electron-cast 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,7 +34,7 @@ export function installChromeCast(bridgeKey) {
34
34
  const SenderPlatform = { CHROME: "chrome", IOS: "ios", ANDROID: "android" };
35
35
  const SessionStatus = { CONNECTED: "connected", DISCONNECTED: "disconnected", STOPPED: "stopped" };
36
36
  const VolumeControlType = { ATTENUATION: "attenuation", FIXED: "fixed", MASTER: "master" };
37
- const media = { DEFAULT_MEDIA_RECEIVER_APP_ID: "CC1AD845" };
37
+ const MEDIA_NAMESPACE = "urn:x-cast:com.google.cast.media";
38
38
  class Timeout {
39
39
  requestSession = 60000;
40
40
  leaveSession = 3000;
@@ -158,6 +158,676 @@ export function installChromeCast(bridgeKey) {
158
158
  this.credentials = credentials;
159
159
  }
160
160
  }
161
+ const PlayerState = { IDLE: "IDLE", PLAYING: "PLAYING", PAUSED: "PAUSED", BUFFERING: "BUFFERING" };
162
+ const MediaCommand = { PAUSE: "pause", SEEK: "seek", STREAM_VOLUME: "stream_volume", STREAM_MUTE: "stream_mute" };
163
+ const MetadataType = { GENERIC: 0, MOVIE: 1, TV_SHOW: 2, MUSIC_TRACK: 3, PHOTO: 4 };
164
+ const RepeatMode = { OFF: "REPEAT_OFF", ALL: "REPEAT_ALL", SINGLE: "REPEAT_SINGLE", ALL_AND_SHUFFLE: "REPEAT_ALL_AND_SHUFFLE" };
165
+ const ResumeState = { PLAYBACK_START: "PLAYBACK_START", PLAYBACK_PAUSE: "PLAYBACK_PAUSE" };
166
+ const StreamType = { BUFFERED: "BUFFERED", LIVE: "LIVE", OTHER: "OTHER" };
167
+ const IdleReason = { CANCELLED: "CANCELLED", INTERRUPTED: "INTERRUPTED", FINISHED: "FINISHED", ERROR: "ERROR" };
168
+ const TrackType = { TEXT: "TEXT", AUDIO: "AUDIO", VIDEO: "VIDEO" };
169
+ const TextTrackType = { SUBTITLES: "SUBTITLES", CAPTIONS: "CAPTIONS", DESCRIPTIONS: "DESCRIPTIONS", CHAPTERS: "CHAPTERS", METADATA: "METADATA" };
170
+ const TextTrackEdgeType = { NONE: "NONE", OUTLINE: "OUTLINE", DROP_SHADOW: "DROP_SHADOW", RAISED: "RAISED", DEPRESSED: "DEPRESSED" };
171
+ const TextTrackWindowType = { NONE: "NONE", NORMAL: "NORMAL", ROUNDED_CORNERS: "ROUNDED_CORNERS" };
172
+ const TextTrackFontGenericFamily = { SANS_SERIF: "SANS_SERIF", MONOSPACED_SANS_SERIF: "MONOSPACED_SANS_SERIF", SERIF: "SERIF", MONOSPACED_SERIF: "MONOSPACED_SERIF", CASUAL: "CASUAL", CURSIVE: "CURSIVE", SMALL_CAPITALS: "SMALL_CAPITALS" };
173
+ const TextTrackFontStyle = { NORMAL: "NORMAL", BOLD: "BOLD", BOLD_ITALIC: "BOLD_ITALIC", ITALIC: "ITALIC" };
174
+ class MediaInfo {
175
+ contentId;
176
+ streamType;
177
+ contentType;
178
+ metadata;
179
+ duration;
180
+ tracks;
181
+ textTrackStyle;
182
+ customData;
183
+ constructor(contentId, contentType) {
184
+ this.contentId = contentId;
185
+ this.streamType = "BUFFERED";
186
+ this.contentType = contentType;
187
+ this.metadata = null;
188
+ this.duration = null;
189
+ this.tracks = null;
190
+ this.textTrackStyle = null;
191
+ this.customData = null;
192
+ }
193
+ }
194
+ class LoadRequest {
195
+ type;
196
+ requestId;
197
+ sessionId;
198
+ media;
199
+ activeTrackIds;
200
+ autoplay;
201
+ currentTime;
202
+ customData;
203
+ constructor(media) {
204
+ this.type = "LOAD";
205
+ this.requestId = 0;
206
+ this.sessionId = null;
207
+ this.media = media;
208
+ this.activeTrackIds = null;
209
+ this.autoplay = true;
210
+ this.currentTime = null;
211
+ this.customData = null;
212
+ }
213
+ }
214
+ class QueueItem {
215
+ itemId;
216
+ media;
217
+ autoplay;
218
+ startTime;
219
+ playbackDuration;
220
+ preloadTime;
221
+ activeTrackIds;
222
+ customData;
223
+ constructor(media) {
224
+ this.itemId = null;
225
+ this.media = media;
226
+ this.autoplay = true;
227
+ this.startTime = 0;
228
+ this.playbackDuration = null;
229
+ this.preloadTime = 0;
230
+ this.activeTrackIds = null;
231
+ this.customData = null;
232
+ }
233
+ }
234
+ class QueueLoadRequest {
235
+ type;
236
+ requestId;
237
+ sessionId;
238
+ items;
239
+ startIndex;
240
+ repeatMode;
241
+ customData;
242
+ constructor(items) {
243
+ this.type = "QUEUE_LOAD";
244
+ this.requestId = null;
245
+ this.sessionId = null;
246
+ this.items = items;
247
+ this.startIndex = 0;
248
+ this.repeatMode = "REPEAT_OFF";
249
+ this.customData = null;
250
+ }
251
+ }
252
+ class QueueInsertItemsRequest {
253
+ type;
254
+ requestId;
255
+ sessionId;
256
+ items;
257
+ insertBefore;
258
+ customData;
259
+ constructor(items) {
260
+ this.type = "QUEUE_INSERT";
261
+ this.requestId = null;
262
+ this.sessionId = null;
263
+ this.items = items;
264
+ this.insertBefore = null;
265
+ this.customData = null;
266
+ }
267
+ }
268
+ class QueueRemoveItemsRequest {
269
+ type;
270
+ requestId;
271
+ sessionId;
272
+ itemIds;
273
+ customData;
274
+ constructor(itemIds) {
275
+ this.type = "QUEUE_REMOVE";
276
+ this.requestId = null;
277
+ this.sessionId = null;
278
+ this.itemIds = itemIds;
279
+ this.customData = null;
280
+ }
281
+ }
282
+ class QueueReorderItemsRequest {
283
+ type;
284
+ requestId;
285
+ sessionId;
286
+ itemIds;
287
+ insertBefore;
288
+ customData;
289
+ constructor(itemIds) {
290
+ this.type = "QUEUE_REORDER";
291
+ this.requestId = null;
292
+ this.sessionId = null;
293
+ this.itemIds = itemIds;
294
+ this.insertBefore = null;
295
+ this.customData = null;
296
+ }
297
+ }
298
+ class QueueUpdateItemsRequest {
299
+ type;
300
+ requestId;
301
+ sessionId;
302
+ items;
303
+ customData;
304
+ constructor(items) {
305
+ this.type = "QUEUE_UPDATE";
306
+ this.requestId = null;
307
+ this.sessionId = null;
308
+ this.items = items;
309
+ this.customData = null;
310
+ }
311
+ }
312
+ class QueueSetPropertiesRequest {
313
+ type;
314
+ requestId;
315
+ sessionId;
316
+ repeatMode;
317
+ customData;
318
+ constructor() {
319
+ this.type = "QUEUE_UPDATE";
320
+ this.requestId = null;
321
+ this.sessionId = null;
322
+ this.repeatMode = null;
323
+ this.customData = null;
324
+ }
325
+ }
326
+ class QueueJumpRequest {
327
+ type;
328
+ requestId;
329
+ sessionId;
330
+ currentItemId;
331
+ jump;
332
+ customData;
333
+ constructor() {
334
+ this.type = "QUEUE_UPDATE";
335
+ this.requestId = null;
336
+ this.sessionId = null;
337
+ this.currentItemId = null;
338
+ this.jump = null;
339
+ this.customData = null;
340
+ }
341
+ }
342
+ class SeekRequest {
343
+ currentTime;
344
+ resumeState;
345
+ customData;
346
+ constructor() {
347
+ this.currentTime = null;
348
+ this.resumeState = null;
349
+ this.customData = null;
350
+ }
351
+ }
352
+ class VolumeRequest {
353
+ volume;
354
+ customData;
355
+ constructor(volume) {
356
+ this.volume = volume;
357
+ this.customData = null;
358
+ }
359
+ }
360
+ class PlayRequest {
361
+ customData;
362
+ constructor() {
363
+ this.customData = null;
364
+ }
365
+ }
366
+ class PauseRequest {
367
+ customData;
368
+ constructor() {
369
+ this.customData = null;
370
+ }
371
+ }
372
+ class StopRequest {
373
+ customData;
374
+ constructor() {
375
+ this.customData = null;
376
+ }
377
+ }
378
+ class GetStatusRequest {
379
+ customData;
380
+ constructor() {
381
+ this.customData = null;
382
+ }
383
+ }
384
+ class EditTracksInfoRequest {
385
+ requestId;
386
+ activeTrackIds;
387
+ textTrackStyle;
388
+ constructor(activeTrackIds, textTrackStyle) {
389
+ this.requestId = 0;
390
+ this.activeTrackIds = activeTrackIds ?? null;
391
+ this.textTrackStyle = textTrackStyle ?? null;
392
+ }
393
+ }
394
+ class Track {
395
+ trackId;
396
+ trackContentId;
397
+ trackContentType;
398
+ type;
399
+ name;
400
+ language;
401
+ subtype;
402
+ customData;
403
+ constructor(trackId, type) {
404
+ this.trackId = trackId;
405
+ this.trackContentId = null;
406
+ this.trackContentType = null;
407
+ this.type = type;
408
+ this.name = null;
409
+ this.language = null;
410
+ this.subtype = null;
411
+ this.customData = null;
412
+ }
413
+ }
414
+ class TextTrackStyle {
415
+ foregroundColor;
416
+ backgroundColor;
417
+ edgeType;
418
+ edgeColor;
419
+ windowType;
420
+ windowColor;
421
+ windowRoundedCornerRadius;
422
+ fontScale;
423
+ fontFamily;
424
+ fontGenericFamily;
425
+ fontStyle;
426
+ customData;
427
+ constructor() {
428
+ this.foregroundColor = null;
429
+ this.backgroundColor = null;
430
+ this.edgeType = null;
431
+ this.edgeColor = null;
432
+ this.windowType = null;
433
+ this.windowColor = null;
434
+ this.windowRoundedCornerRadius = null;
435
+ this.fontScale = null;
436
+ this.fontFamily = null;
437
+ this.fontGenericFamily = null;
438
+ this.fontStyle = null;
439
+ this.customData = null;
440
+ }
441
+ }
442
+ class GenericMediaMetadata {
443
+ type;
444
+ metadataType;
445
+ title;
446
+ subtitle;
447
+ images;
448
+ releaseYear;
449
+ releaseDate;
450
+ constructor() {
451
+ this.type = 0;
452
+ this.metadataType = 0;
453
+ this.title = null;
454
+ this.subtitle = null;
455
+ this.images = null;
456
+ this.releaseYear = null;
457
+ this.releaseDate = null;
458
+ }
459
+ }
460
+ class MovieMediaMetadata {
461
+ type;
462
+ metadataType;
463
+ title;
464
+ studio;
465
+ subtitle;
466
+ images;
467
+ releaseYear;
468
+ releaseDate;
469
+ constructor() {
470
+ this.type = 1;
471
+ this.metadataType = 1;
472
+ this.title = null;
473
+ this.studio = null;
474
+ this.subtitle = null;
475
+ this.images = null;
476
+ this.releaseYear = null;
477
+ this.releaseDate = null;
478
+ }
479
+ }
480
+ class TvShowMediaMetadata {
481
+ type;
482
+ metadataType;
483
+ seriesTitle;
484
+ title;
485
+ episodeTitle;
486
+ seasonNumber;
487
+ season;
488
+ episodeNumber;
489
+ episode;
490
+ images;
491
+ releaseYear;
492
+ originalAirdate;
493
+ constructor() {
494
+ this.type = 2;
495
+ this.metadataType = 2;
496
+ this.seriesTitle = null;
497
+ this.title = null;
498
+ this.episodeTitle = null;
499
+ this.seasonNumber = null;
500
+ this.season = null;
501
+ this.episodeNumber = null;
502
+ this.episode = null;
503
+ this.images = null;
504
+ this.releaseYear = null;
505
+ this.originalAirdate = null;
506
+ }
507
+ }
508
+ class MusicTrackMediaMetadata {
509
+ type;
510
+ metadataType;
511
+ albumName;
512
+ title;
513
+ albumArtist;
514
+ artist;
515
+ composer;
516
+ songName;
517
+ artistName;
518
+ trackNumber;
519
+ discNumber;
520
+ images;
521
+ releaseYear;
522
+ releaseDate;
523
+ constructor() {
524
+ this.type = 3;
525
+ this.metadataType = 3;
526
+ this.albumName = null;
527
+ this.title = null;
528
+ this.albumArtist = null;
529
+ this.artist = null;
530
+ this.composer = null;
531
+ this.songName = null;
532
+ this.artistName = null;
533
+ this.trackNumber = null;
534
+ this.discNumber = null;
535
+ this.images = null;
536
+ this.releaseYear = null;
537
+ this.releaseDate = null;
538
+ }
539
+ }
540
+ class PhotoMediaMetadata {
541
+ type;
542
+ metadataType;
543
+ title;
544
+ artist;
545
+ location;
546
+ images;
547
+ latitude;
548
+ longitude;
549
+ width;
550
+ height;
551
+ creationDateTime;
552
+ constructor() {
553
+ this.type = 4;
554
+ this.metadataType = 4;
555
+ this.title = null;
556
+ this.artist = null;
557
+ this.location = null;
558
+ this.images = null;
559
+ this.latitude = null;
560
+ this.longitude = null;
561
+ this.width = null;
562
+ this.height = null;
563
+ this.creationDateTime = null;
564
+ }
565
+ }
566
+ class Media {
567
+ sessionId;
568
+ mediaSessionId;
569
+ media;
570
+ playbackRate;
571
+ playerState;
572
+ currentTime;
573
+ supportedMediaCommands;
574
+ volume;
575
+ idleReason;
576
+ activeTrackIds;
577
+ customData;
578
+ currentItemId;
579
+ loadingItemId;
580
+ preloadedItemId;
581
+ items;
582
+ repeatMode;
583
+ liveSeekableRange;
584
+ breakStatus;
585
+ videoInfo;
586
+ queueData;
587
+ _updateListeners;
588
+ _lastUpdate;
589
+ _announced;
590
+ constructor(sessionId, mediaSessionId) {
591
+ this.sessionId = sessionId;
592
+ this.mediaSessionId = mediaSessionId;
593
+ this.media = null;
594
+ this.playbackRate = 1;
595
+ this.playerState = "IDLE";
596
+ this.currentTime = 0;
597
+ this.supportedMediaCommands = [];
598
+ this.volume = new Volume();
599
+ this.idleReason = null;
600
+ this.activeTrackIds = null;
601
+ this.customData = null;
602
+ this.currentItemId = null;
603
+ this.loadingItemId = null;
604
+ this.preloadedItemId = null;
605
+ this.items = null;
606
+ this.repeatMode = "REPEAT_OFF";
607
+ this.liveSeekableRange = null;
608
+ this.breakStatus = null;
609
+ this.videoInfo = null;
610
+ this.queueData = null;
611
+ this._updateListeners = [];
612
+ this._lastUpdate = 0;
613
+ this._announced = false;
614
+ }
615
+ addUpdateListener(fn) {
616
+ if (typeof fn === "function" && !this._updateListeners.includes(fn))
617
+ this._updateListeners.push(fn);
618
+ }
619
+ removeUpdateListener(fn) {
620
+ const i = this._updateListeners.indexOf(fn);
621
+ if (i >= 0)
622
+ this._updateListeners.splice(i, 1);
623
+ }
624
+ supportsCommand(cmd) {
625
+ return this.supportedMediaCommands.includes(cmd);
626
+ }
627
+ getEstimatedTime() {
628
+ if (this.playerState === "PLAYING") {
629
+ let t = this.currentTime + this.playbackRate * (Date.now() - this._lastUpdate) / 1000;
630
+ const duration = this.media && this.media.duration;
631
+ if (typeof duration === "number")
632
+ t = Math.min(t, duration);
633
+ return t;
634
+ }
635
+ return this.currentTime;
636
+ }
637
+ getEstimatedBreakTime() {
638
+ const base = this.breakStatus && this.breakStatus.currentBreakTime;
639
+ if (typeof base !== "number")
640
+ return undefined;
641
+ return base + this._estimateElapsed();
642
+ }
643
+ getEstimatedBreakClipTime() {
644
+ const base = this.breakStatus && this.breakStatus.currentBreakClipTime;
645
+ if (typeof base !== "number")
646
+ return undefined;
647
+ return base + this._estimateElapsed();
648
+ }
649
+ getEstimatedLiveSeekableRange() {
650
+ const r = this.liveSeekableRange;
651
+ if (r == null)
652
+ return undefined;
653
+ const elapsed = this._estimateElapsed();
654
+ const out = {
655
+ start: r.start,
656
+ end: r.end,
657
+ isMovingWindow: r.isMovingWindow,
658
+ isLiveDone: r.isLiveDone,
659
+ };
660
+ if (r.isLiveDone !== true) {
661
+ if (typeof out.end === "number")
662
+ out.end += elapsed;
663
+ if (r.isMovingWindow === true && typeof out.start === "number")
664
+ out.start += elapsed;
665
+ }
666
+ return out;
667
+ }
668
+ /** Seconds advanced since the last status update: playbackRate * elapsed while PLAYING, else 0. */
669
+ _estimateElapsed() {
670
+ if (this.playerState !== "PLAYING")
671
+ return 0;
672
+ return this.playbackRate * (Date.now() - this._lastUpdate) / 1000;
673
+ }
674
+ /** Send a command on the media namespace; resolves with no arguments on the matching MEDIA_STATUS. */
675
+ sendCommand(type, extra, success, error) {
676
+ const sess = sessions.get(this.sessionId);
677
+ if (!sess || sess.status !== "connected") {
678
+ fail(error, "session_error");
679
+ return;
680
+ }
681
+ const requestId = nextRequestId();
682
+ const message = stripNulls({ type, requestId, mediaSessionId: this.mediaSessionId, ...extra });
683
+ sendMediaRequest(sess, requestId, message, MEDIA_TIMEOUT_KEYS[type] ?? "getStatus", success, error);
684
+ }
685
+ getStatus(req, success, error) {
686
+ this.sendCommand("GET_STATUS", { customData: req?.customData ?? null }, success, error);
687
+ }
688
+ play(req, success, error) {
689
+ this.sendCommand("PLAY", { customData: req?.customData ?? null }, success, error);
690
+ }
691
+ pause(req, success, error) {
692
+ this.sendCommand("PAUSE", { customData: req?.customData ?? null }, success, error);
693
+ }
694
+ seek(seekRequest, success, error) {
695
+ this.sendCommand("SEEK", {
696
+ currentTime: seekRequest?.currentTime ?? null,
697
+ resumeState: seekRequest?.resumeState ?? null,
698
+ customData: seekRequest?.customData ?? null,
699
+ }, success, error);
700
+ }
701
+ stop(req, success, error) {
702
+ this.sendCommand("STOP", { customData: req?.customData ?? null }, success, error);
703
+ }
704
+ setVolume(volumeRequest, success, error) {
705
+ const vol = volumeRequest?.volume;
706
+ this.sendCommand("SET_VOLUME", {
707
+ volume: vol ? { level: vol.level ?? null, muted: vol.muted ?? null } : null,
708
+ customData: volumeRequest?.customData ?? null,
709
+ }, success, error);
710
+ }
711
+ editTracksInfo(req, success, error) {
712
+ this.sendCommand("EDIT_TRACKS_INFO", {
713
+ activeTrackIds: req?.activeTrackIds ?? null,
714
+ textTrackStyle: req?.textTrackStyle ?? null,
715
+ }, success, error);
716
+ }
717
+ queueInsertItems(req, success, error) {
718
+ this.sendCommand("QUEUE_INSERT", {
719
+ items: req?.items ?? null,
720
+ insertBefore: req?.insertBefore ?? null,
721
+ customData: req?.customData ?? null,
722
+ }, success, error);
723
+ }
724
+ queueAppendItem(item, success, error) {
725
+ this.sendCommand("QUEUE_INSERT", { items: [item] }, success, error);
726
+ }
727
+ queueUpdateItems(req, success, error) {
728
+ this.sendCommand("QUEUE_UPDATE", {
729
+ items: req?.items ?? null,
730
+ customData: req?.customData ?? null,
731
+ }, success, error);
732
+ }
733
+ queueJumpToItem(itemId, success, error) {
734
+ this.sendCommand("QUEUE_UPDATE", { currentItemId: itemId }, success, error);
735
+ }
736
+ queueNext(success, error) {
737
+ this.sendCommand("QUEUE_UPDATE", { jump: 1 }, success, error);
738
+ }
739
+ queuePrev(success, error) {
740
+ this.sendCommand("QUEUE_UPDATE", { jump: -1 }, success, error);
741
+ }
742
+ queueSetRepeatMode(mode, success, error) {
743
+ this.sendCommand("QUEUE_UPDATE", { repeatMode: mode }, success, error);
744
+ }
745
+ queueRemoveItems(req, success, error) {
746
+ this.sendCommand("QUEUE_REMOVE", {
747
+ itemIds: req?.itemIds ?? null,
748
+ customData: req?.customData ?? null,
749
+ }, success, error);
750
+ }
751
+ queueRemoveItem(itemId, success, error) {
752
+ this.sendCommand("QUEUE_REMOVE", { itemIds: [itemId] }, success, error);
753
+ }
754
+ queueReorderItems(req, success, error) {
755
+ this.sendCommand("QUEUE_REORDER", {
756
+ itemIds: req?.itemIds ?? null,
757
+ insertBefore: req?.insertBefore ?? null,
758
+ customData: req?.customData ?? null,
759
+ }, success, error);
760
+ }
761
+ queueMoveItemToNewIndex(itemId, newIndex, success, error) {
762
+ const items = Array.isArray(this.items) ? this.items : null;
763
+ if (!items || !items.some((i) => i && i.itemId === itemId) || !Number.isInteger(newIndex) || newIndex < 0) {
764
+ fail(error, "invalid_parameter");
765
+ return;
766
+ }
767
+ const remaining = items.map((i) => i.itemId).filter((id) => id !== itemId);
768
+ const extra = newIndex >= remaining.length
769
+ ? { itemIds: [itemId] }
770
+ : { itemIds: [itemId], insertBefore: remaining[newIndex] };
771
+ this.sendCommand("QUEUE_REORDER", extra, success, error);
772
+ }
773
+ }
774
+ const media = {
775
+ DEFAULT_MEDIA_RECEIVER_APP_ID: "CC1AD845",
776
+ PlayerState,
777
+ MediaCommand,
778
+ MetadataType,
779
+ RepeatMode,
780
+ ResumeState,
781
+ StreamType,
782
+ IdleReason,
783
+ TrackType,
784
+ TextTrackType,
785
+ TextTrackEdgeType,
786
+ TextTrackWindowType,
787
+ TextTrackFontGenericFamily,
788
+ TextTrackFontStyle,
789
+ timeout: { load: 15000, getStatus: 15000, play: 15000, pause: 15000, seek: 15000, stop: 15000, setVolume: 15000, editTracksInfo: 15000, queue: 15000 },
790
+ MediaInfo,
791
+ LoadRequest,
792
+ QueueItem,
793
+ QueueLoadRequest,
794
+ QueueInsertItemsRequest,
795
+ QueueRemoveItemsRequest,
796
+ QueueReorderItemsRequest,
797
+ QueueUpdateItemsRequest,
798
+ QueueSetPropertiesRequest,
799
+ QueueJumpRequest,
800
+ SeekRequest,
801
+ VolumeRequest,
802
+ PlayRequest,
803
+ PauseRequest,
804
+ StopRequest,
805
+ GetStatusRequest,
806
+ EditTracksInfoRequest,
807
+ Track,
808
+ TextTrackStyle,
809
+ GenericMediaMetadata,
810
+ MovieMediaMetadata,
811
+ TvShowMediaMetadata,
812
+ MusicTrackMediaMetadata,
813
+ PhotoMediaMetadata,
814
+ Media,
815
+ };
816
+ const MEDIA_TIMEOUT_KEYS = {
817
+ LOAD: "load",
818
+ GET_STATUS: "getStatus",
819
+ PLAY: "play",
820
+ PAUSE: "pause",
821
+ SEEK: "seek",
822
+ STOP: "stop",
823
+ SET_VOLUME: "setVolume",
824
+ EDIT_TRACKS_INFO: "editTracksInfo",
825
+ QUEUE_LOAD: "queue",
826
+ QUEUE_INSERT: "queue",
827
+ QUEUE_REMOVE: "queue",
828
+ QUEUE_REORDER: "queue",
829
+ QUEUE_UPDATE: "queue",
830
+ };
161
831
  function safe(fn, ...args) {
162
832
  if (typeof fn !== "function")
163
833
  return;
@@ -171,6 +841,203 @@ export function installChromeCast(bridgeKey) {
171
841
  function fail(error, code, description) {
172
842
  setTimeout(() => safe(error, new CastError(code, description ?? null)), 0);
173
843
  }
844
+ const REQ_ID_MAX = 2 ** 30;
845
+ let requestIdCounter = Math.floor(Math.random() * (REQ_ID_MAX - 1)) + 1;
846
+ /** Positive integer requestIds, unique within the page, starting at a random value in [1, 2^30). */
847
+ function nextRequestId() {
848
+ const id = requestIdCounter;
849
+ requestIdCounter += 1;
850
+ if (requestIdCounter >= REQ_ID_MAX)
851
+ requestIdCounter = 1;
852
+ return id;
853
+ }
854
+ /** A timer that does not keep a Node test process alive; plain in the browser. */
855
+ function later(ms, fn) {
856
+ const t = setTimeout(fn, ms);
857
+ if (t && typeof t.unref === "function")
858
+ t.unref();
859
+ return t;
860
+ }
861
+ /** Remove every key whose value is null or undefined, recursively through objects and arrays. */
862
+ function stripNulls(value) {
863
+ if (Array.isArray(value))
864
+ return value.map(stripNulls).filter((v) => v !== null && v !== undefined);
865
+ if (value && typeof value === "object") {
866
+ const out = {};
867
+ for (const key of Object.keys(value)) {
868
+ const v = value[key];
869
+ if (v === null || v === undefined)
870
+ continue;
871
+ out[key] = stripNulls(v);
872
+ }
873
+ return out;
874
+ }
875
+ return value;
876
+ }
877
+ function settlePendingMedia(sess, requestId, outcome) {
878
+ const p = sess._pendingMedia.get(requestId);
879
+ if (!p)
880
+ return;
881
+ sess._pendingMedia.delete(requestId);
882
+ if (p.timer)
883
+ clearTimeout(p.timer);
884
+ outcome();
885
+ }
886
+ /** Send one media-namespace message and track it until its reply (or timeout) arrives. */
887
+ function sendMediaRequest(sess, requestId, message, timeoutKey, success, error) {
888
+ const pending = { kind: message.type, success, error, timer: null };
889
+ const timeoutMs = media.timeout[timeoutKey];
890
+ if (typeof timeoutMs === "number" && timeoutMs > 0) {
891
+ pending.timer = later(timeoutMs, () => settlePendingMedia(sess, requestId, () => fail(error, "timeout")));
892
+ }
893
+ sess._pendingMedia.set(requestId, pending);
894
+ bridge.call("sendMessage", { sessionId: sess.sessionId, namespace: MEDIA_NAMESPACE, message: JSON.stringify(message) })
895
+ .then((res) => {
896
+ if (!res.ok)
897
+ settlePendingMedia(sess, requestId, () => fail(error, res.code, res.description));
898
+ })
899
+ .catch((e) => settlePendingMedia(sess, requestId, () => fail(error, "session_error", String(e))));
900
+ }
901
+ /** Kill every Media of the session (update listeners get false) without touching pending requests. */
902
+ function killAllMedia(sess) {
903
+ for (const m of [...sess.media]) {
904
+ for (const fn of [...m._updateListeners])
905
+ safe(fn, false);
906
+ }
907
+ sess.media = [];
908
+ }
909
+ /** The session is gone: kill its media and fail every pending media request with session_error. */
910
+ function killSessionMedia(sess) {
911
+ killAllMedia(sess);
912
+ for (const p of [...sess._pendingMedia.values()]) {
913
+ if (p.timer)
914
+ clearTimeout(p.timer);
915
+ fail(p.error, "session_error");
916
+ }
917
+ sess._pendingMedia.clear();
918
+ }
919
+ function applyMediaStatus(sess, msg) {
920
+ const entries = Array.isArray(msg.status) ? msg.status : msg.status && typeof msg.status === "object" ? [msg.status] : [];
921
+ if (entries.length === 0) {
922
+ killAllMedia(sess);
923
+ return;
924
+ }
925
+ const pending = typeof msg.requestId === "number" ? sess._pendingMedia.get(msg.requestId) : undefined;
926
+ const suppressAnnounce = !!pending && (pending.kind === "LOAD" || pending.kind === "QUEUE_LOAD");
927
+ for (const e of entries) {
928
+ if (!e || typeof e !== "object" || e.mediaSessionId == null)
929
+ continue;
930
+ let m = sess.media.find((x) => x.mediaSessionId === e.mediaSessionId);
931
+ const isNew = !m;
932
+ if (isNew) {
933
+ m = new Media(sess.sessionId, e.mediaSessionId);
934
+ sess.media.push(m);
935
+ }
936
+ if (e.media != null)
937
+ m.media = e.media;
938
+ if (e.playbackRate != null)
939
+ m.playbackRate = e.playbackRate;
940
+ if (e.playerState != null)
941
+ m.playerState = e.playerState;
942
+ if (e.currentTime != null)
943
+ m.currentTime = e.currentTime;
944
+ if (e.activeTrackIds != null)
945
+ m.activeTrackIds = e.activeTrackIds;
946
+ if (e.customData != null)
947
+ m.customData = e.customData;
948
+ if (e.currentItemId != null)
949
+ m.currentItemId = e.currentItemId;
950
+ if (e.loadingItemId != null)
951
+ m.loadingItemId = e.loadingItemId;
952
+ if (e.preloadedItemId != null)
953
+ m.preloadedItemId = e.preloadedItemId;
954
+ if (e.items != null)
955
+ m.items = e.items;
956
+ if (e.repeatMode != null)
957
+ m.repeatMode = e.repeatMode;
958
+ // A MEDIA_STATUS entry is the receiver's full status except that unchanged fields may be left out:
959
+ // an ad break that ended, or a stream that is no longer live, drops the field, so these default to null.
960
+ m.liveSeekableRange = e.liveSeekableRange ?? null;
961
+ m.breakStatus = e.breakStatus ?? null;
962
+ if (e.videoInfo != null)
963
+ m.videoInfo = e.videoInfo;
964
+ if (e.queueData != null)
965
+ m.queueData = e.queueData;
966
+ m.idleReason = e.idleReason ?? null;
967
+ if (e.volume != null)
968
+ m.volume = new Volume(e.volume.level ?? null, e.volume.muted ?? null);
969
+ if (e.supportedMediaCommands != null) {
970
+ const bits = [MediaCommand.PAUSE, MediaCommand.SEEK, MediaCommand.STREAM_VOLUME, MediaCommand.STREAM_MUTE];
971
+ m.supportedMediaCommands = bits.filter((_, i) => (e.supportedMediaCommands & (1 << i)) !== 0);
972
+ }
973
+ m._lastUpdate = Date.now();
974
+ const alive = !(m.playerState === PlayerState.IDLE && m.idleReason !== null);
975
+ for (const fn of [...m._updateListeners])
976
+ safe(fn, alive);
977
+ if (!alive) {
978
+ const i = sess.media.indexOf(m);
979
+ if (i >= 0)
980
+ sess.media.splice(i, 1);
981
+ }
982
+ else if (isNew && !m._announced) {
983
+ m._announced = true;
984
+ if (!suppressAnnounce)
985
+ for (const fn of [...sess._mediaListeners])
986
+ safe(fn, m);
987
+ }
988
+ }
989
+ }
990
+ /** Resolve a pending media request from a reply on the media namespace. */
991
+ function resolveMediaReply(sess, msg) {
992
+ if (!msg || typeof msg !== "object" || typeof msg.requestId !== "number")
993
+ return;
994
+ const p = sess._pendingMedia.get(msg.requestId);
995
+ if (!p)
996
+ return;
997
+ switch (msg.type) {
998
+ case "MEDIA_STATUS": {
999
+ if (p.kind === "LOAD" || p.kind === "QUEUE_LOAD") {
1000
+ // Some receivers (a Nest Hub) answer a LOAD with an interim MEDIA_STATUS whose entry still
1001
+ // reports extendedStatus.playerState "LOADING"; keep waiting for the final status.
1002
+ const entries = Array.isArray(msg.status) ? msg.status : msg.status && typeof msg.status === "object" ? [msg.status] : [];
1003
+ const interim = entries.some((e) => e && e.extendedStatus && e.extendedStatus.playerState === "LOADING");
1004
+ if (interim)
1005
+ return;
1006
+ const first = Array.isArray(msg.status) ? msg.status[0] : msg.status;
1007
+ const m = first && sess.media.find((x) => x.mediaSessionId === first.mediaSessionId);
1008
+ settlePendingMedia(sess, msg.requestId, () => (m ? safe(p.success, m) : fail(p.error, "load_media_failed")));
1009
+ }
1010
+ else {
1011
+ settlePendingMedia(sess, msg.requestId, () => safe(p.success));
1012
+ }
1013
+ return;
1014
+ }
1015
+ case "LOAD_FAILED":
1016
+ settlePendingMedia(sess, msg.requestId, () => fail(p.error, "load_media_failed"));
1017
+ return;
1018
+ case "LOAD_CANCELLED":
1019
+ settlePendingMedia(sess, msg.requestId, () => fail(p.error, "cancel"));
1020
+ return;
1021
+ case "INVALID_REQUEST":
1022
+ case "INVALID_PLAYER_STATE":
1023
+ settlePendingMedia(sess, msg.requestId, () => fail(p.error, "session_error", msg.reason));
1024
+ return;
1025
+ }
1026
+ }
1027
+ function handleMediaMessage(sess, raw) {
1028
+ let msg;
1029
+ try {
1030
+ msg = typeof raw === "string" ? JSON.parse(raw) : raw;
1031
+ }
1032
+ catch {
1033
+ return;
1034
+ }
1035
+ if (!msg || typeof msg !== "object")
1036
+ return;
1037
+ if (msg.type === "MEDIA_STATUS")
1038
+ applyMediaStatus(sess, msg);
1039
+ resolveMediaReply(sess, msg);
1040
+ }
174
1041
  function toImage(img) {
175
1042
  const out = new Image(img.url);
176
1043
  if (img.height != null)
@@ -229,6 +1096,8 @@ export function installChromeCast(bridgeKey) {
229
1096
  transportId;
230
1097
  updateListeners;
231
1098
  messageListeners;
1099
+ _mediaListeners;
1100
+ _pendingMedia;
232
1101
  constructor(sessionId, appId, displayName, appImages, receiver) {
233
1102
  this.sessionId = sessionId;
234
1103
  this.appId = appId;
@@ -243,6 +1112,8 @@ export function installChromeCast(bridgeKey) {
243
1112
  this.transportId = sessionId;
244
1113
  this.updateListeners = [];
245
1114
  this.messageListeners = new Map();
1115
+ this._mediaListeners = [];
1116
+ this._pendingMedia = new Map();
246
1117
  }
247
1118
  sendMessage(namespace, message, success, error) {
248
1119
  const payload = typeof message === "string" ? message : JSON.stringify(message);
@@ -282,17 +1153,22 @@ export function installChromeCast(bridgeKey) {
282
1153
  if (i >= 0)
283
1154
  this.updateListeners.splice(i, 1);
284
1155
  }
285
- addMediaListener(_fn) { }
286
- removeMediaListener(_fn) { }
1156
+ addMediaListener(fn) {
1157
+ if (typeof fn === "function" && !this._mediaListeners.includes(fn))
1158
+ this._mediaListeners.push(fn);
1159
+ }
1160
+ removeMediaListener(fn) {
1161
+ const i = this._mediaListeners.indexOf(fn);
1162
+ if (i >= 0)
1163
+ this._mediaListeners.splice(i, 1);
1164
+ }
287
1165
  stop(success, error) {
288
1166
  bridge.call("stopSession", { sessionId: this.sessionId }).then((res) => {
289
1167
  if (!res.ok) {
290
1168
  fail(error, res.code, res.description);
291
1169
  return;
292
1170
  }
293
- this.status = "stopped";
294
- for (const fn of [...this.updateListeners])
295
- safe(fn, false);
1171
+ endSession(this, "stopped");
296
1172
  safe(success);
297
1173
  }).catch((e) => fail(error, "session_error", String(e)));
298
1174
  }
@@ -302,9 +1178,7 @@ export function installChromeCast(bridgeKey) {
302
1178
  fail(error, res.code, res.description);
303
1179
  return;
304
1180
  }
305
- this.status = "disconnected";
306
- for (const fn of [...this.updateListeners])
307
- safe(fn, false);
1181
+ endSession(this, "disconnected");
308
1182
  safe(success);
309
1183
  }).catch((e) => fail(error, "session_error", String(e)));
310
1184
  }
@@ -330,21 +1204,90 @@ export function installChromeCast(bridgeKey) {
330
1204
  fail(error, res.code, res.description);
331
1205
  }).catch((e) => fail(error, "session_error", String(e)));
332
1206
  }
333
- loadMedia(_req, _success, error) {
334
- fail(error, "session_error", "Media is not supported yet");
1207
+ loadMedia(req, success, error) {
1208
+ if (!req || typeof req !== "object" || !req.media) {
1209
+ fail(error, "invalid_parameter");
1210
+ return;
1211
+ }
1212
+ if (this.status !== "connected") {
1213
+ fail(error, "session_error");
1214
+ return;
1215
+ }
1216
+ const requestId = nextRequestId();
1217
+ const message = stripNulls({
1218
+ type: "LOAD",
1219
+ requestId,
1220
+ sessionId: this.sessionId,
1221
+ media: req.media,
1222
+ autoplay: req.autoplay ?? true,
1223
+ currentTime: req.currentTime ?? null,
1224
+ activeTrackIds: req.activeTrackIds ?? null,
1225
+ customData: req.customData ?? null,
1226
+ });
1227
+ sendMediaRequest(this, requestId, message, "load", success, error);
335
1228
  }
336
- queueLoad(_req, _success, error) {
337
- fail(error, "session_error", "Media is not supported yet");
1229
+ queueLoad(req, success, error) {
1230
+ if (!req || typeof req !== "object" || !Array.isArray(req.items)) {
1231
+ fail(error, "invalid_parameter");
1232
+ return;
1233
+ }
1234
+ if (this.status !== "connected") {
1235
+ fail(error, "session_error");
1236
+ return;
1237
+ }
1238
+ const requestId = nextRequestId();
1239
+ const message = stripNulls({
1240
+ type: "QUEUE_LOAD",
1241
+ requestId,
1242
+ sessionId: this.sessionId,
1243
+ items: req.items,
1244
+ startIndex: req.startIndex ?? 0,
1245
+ repeatMode: req.repeatMode ?? "REPEAT_OFF",
1246
+ customData: req.customData ?? null,
1247
+ });
1248
+ sendMediaRequest(this, requestId, message, "queue", success, error);
338
1249
  }
339
1250
  }
340
1251
  const sessions = new Map();
1252
+ /** End a session: notify, then drop it from the session map so later events for it are ignored. */
1253
+ function endSession(sess, status) {
1254
+ sess.status = status;
1255
+ killSessionMedia(sess);
1256
+ notifyUpdate(sess, false);
1257
+ sessions.delete(sess.sessionId);
1258
+ }
1259
+ /**
1260
+ * Report a session to a sessionListener function at most once: remember, per listener function, the
1261
+ * session ids already announced to it, so a second initialize (or a requestSessionById) does not
1262
+ * re-announce a session that function already got.
1263
+ */
1264
+ const announcedTo = new WeakMap();
1265
+ function announce(sess, listener) {
1266
+ if (!sess || typeof listener !== "function")
1267
+ return;
1268
+ let set = announcedTo.get(listener);
1269
+ if (!set) {
1270
+ set = new Set();
1271
+ announcedTo.set(listener, set);
1272
+ }
1273
+ if (set.has(sess.sessionId))
1274
+ return;
1275
+ set.add(sess.sessionId);
1276
+ safe(listener, sess);
1277
+ }
341
1278
  function upsertSession(snap) {
342
1279
  let sess = sessions.get(snap.sessionId);
343
- if (!sess) {
1280
+ const created = !sess;
1281
+ if (created) {
344
1282
  sess = new Session(snap.sessionId, snap.appId, snap.displayName, [], toReceiver(snap.receiver));
345
1283
  sessions.set(snap.sessionId, sess);
346
1284
  }
347
1285
  applySnapshot(sess, snap);
1286
+ if (created && sess.namespaces.some((n) => n.name === MEDIA_NAMESPACE)) {
1287
+ // Discover media the receiver already has; its failure is ignored.
1288
+ const requestId = nextRequestId();
1289
+ sendMediaRequest(sess, requestId, { type: "GET_STATUS", requestId }, "getStatus", () => { }, () => { });
1290
+ }
348
1291
  return sess;
349
1292
  }
350
1293
  let initialized = false;
@@ -379,8 +1322,16 @@ export function installChromeCast(bridgeKey) {
379
1322
  const sess = sessions.get(event.sessionId);
380
1323
  if (!sess)
381
1324
  return;
382
- sess.status = event.status;
383
- notifyUpdate(sess, false);
1325
+ endSession(sess, event.status);
1326
+ return;
1327
+ }
1328
+ case "receiverAction": {
1329
+ // A live session only: unknown ids and sessions that already ended are ignored.
1330
+ const sess = sessions.get(event.sessionId);
1331
+ if (!sess)
1332
+ return;
1333
+ for (const fn of [...receiverActionListeners])
1334
+ safe(fn, sess.receiver, ReceiverAction.STOP);
384
1335
  return;
385
1336
  }
386
1337
  case "message": {
@@ -390,6 +1341,8 @@ export function installChromeCast(bridgeKey) {
390
1341
  const fns = sess.messageListeners.get(event.namespace) ?? [];
391
1342
  for (const fn of [...fns])
392
1343
  safe(fn, event.namespace, event.message);
1344
+ if (event.namespace === MEDIA_NAMESPACE)
1345
+ handleMediaMessage(sess, event.message);
393
1346
  return;
394
1347
  }
395
1348
  }
@@ -419,7 +1372,7 @@ export function installChromeCast(bridgeKey) {
419
1372
  safe(success);
420
1373
  safe(apiCfg.receiverListener, availability);
421
1374
  for (const snap of value.sessions ?? [])
422
- safe(apiCfg.sessionListener, upsertSession(snap));
1375
+ announce(upsertSession(snap), apiCfg.sessionListener);
423
1376
  }).catch((e) => fail(error, "session_error", String(e)));
424
1377
  }
425
1378
  function requestSession(success, error, optSessionRequest) {
@@ -458,7 +1411,7 @@ export function installChromeCast(bridgeKey) {
458
1411
  return;
459
1412
  const sess = upsertSession(res.value);
460
1413
  if (apiConfig)
461
- safe(apiConfig.sessionListener, sess);
1414
+ announce(sess, apiConfig.sessionListener);
462
1415
  }).catch((e) => console.error(e));
463
1416
  }
464
1417
  function addReceiverActionListener(fn) {
@@ -525,20 +1478,87 @@ export function installChromeCast(bridgeKey) {
525
1478
  precache,
526
1479
  unescape,
527
1480
  };
1481
+ // Google's cast_sender.js loader (it takes the desktop-Chrome path because Electron exposes
1482
+ // navigator.presentation) injects its own chrome.cast implementations from gstatic/eureka/clank and
1483
+ // from the two Cast extensions. The first one that loads would overwrite this polyfill with an
1484
+ // implementation on the Presentation API, which finds no devices in Electron, so those scripts are
1485
+ // blocked before they can load. A blocked element ends up with no src, so it never fires load or
1486
+ // error and the loader's chain simply stops there.
1487
+ const blockedClankRe = /^(https?:)?\/\/www\.gstatic\.com\/eureka\/clank\/(\d+\/)?cast_sender\.js/i;
1488
+ const blockedExtensionRe = /^chrome-extension:\/\/(pkedcjkdefgpdelpbcmbmeomcjbeemfm|enhhojjnijigcajfphajepfemndkmdlo)\//i;
1489
+ const isBlockedSrc = (value) => {
1490
+ let url;
1491
+ try {
1492
+ url = String(value);
1493
+ }
1494
+ catch {
1495
+ return false;
1496
+ }
1497
+ return blockedClankRe.test(url) || blockedExtensionRe.test(url);
1498
+ };
1499
+ if (typeof HTMLScriptElement === "function") {
1500
+ let proto = HTMLScriptElement.prototype;
1501
+ let srcDesc = proto ? Object.getOwnPropertyDescriptor(proto, "src") : undefined;
1502
+ while (!srcDesc && proto) {
1503
+ proto = Object.getPrototypeOf(proto);
1504
+ if (proto)
1505
+ srcDesc = Object.getOwnPropertyDescriptor(proto, "src");
1506
+ }
1507
+ if (srcDesc && typeof srcDesc.set === "function") {
1508
+ const originalSetSrc = srcDesc.set;
1509
+ Object.defineProperty(HTMLScriptElement.prototype, "src", {
1510
+ configurable: srcDesc.configurable === true,
1511
+ enumerable: srcDesc.enumerable === true,
1512
+ get: srcDesc.get,
1513
+ set(v) {
1514
+ if (isBlockedSrc(v))
1515
+ return;
1516
+ originalSetSrc.call(this, v);
1517
+ },
1518
+ });
1519
+ }
1520
+ }
1521
+ if (typeof Element === "function" && typeof Element.prototype.setAttribute === "function") {
1522
+ const originalSetAttribute = Element.prototype.setAttribute;
1523
+ Element.prototype.setAttribute = function (name, value) {
1524
+ if (typeof HTMLScriptElement === "function"
1525
+ && this instanceof HTMLScriptElement
1526
+ && typeof name === "string"
1527
+ && name.toLowerCase() === "src"
1528
+ && isBlockedSrc(value)) {
1529
+ return undefined;
1530
+ }
1531
+ return originalSetAttribute.call(this, name, value);
1532
+ };
1533
+ }
1534
+ // While the document is still loading, a page assigns its __onGCastApiAvailable callback and then the
1535
+ // parser loads cast_sender.js; calling the callback on a timer would run it before the page's scripts
1536
+ // (and cast.framework) exist. So until DOMContentLoaded only store the callback, then call whatever is
1537
+ // stored at that moment. With Google's loader that is its counter wrapper, which stands in for the
1538
+ // second report-in and fires the page's callback once the framework has loaded as well.
1539
+ const docIsLoading = () => typeof document !== "undefined" && document.readyState === "loading";
528
1540
  let onGCastApiAvailable = g.__onGCastApiAvailable;
529
- const notifyGCastApiAvailable = () => {
530
- setTimeout(() => safe(onGCastApiAvailable, true), 0);
1541
+ const notifiedCallbacks = new WeakSet();
1542
+ const notifyGCastApiAvailable = (fn) => {
1543
+ if (typeof fn !== "function" || notifiedCallbacks.has(fn))
1544
+ return;
1545
+ notifiedCallbacks.add(fn);
1546
+ setTimeout(() => safe(fn, true), 0);
531
1547
  };
532
- if (typeof onGCastApiAvailable === "function")
533
- notifyGCastApiAvailable();
1548
+ if (docIsLoading() && typeof document.addEventListener === "function") {
1549
+ document.addEventListener("DOMContentLoaded", () => notifyGCastApiAvailable(onGCastApiAvailable));
1550
+ }
1551
+ else {
1552
+ notifyGCastApiAvailable(onGCastApiAvailable);
1553
+ }
534
1554
  Object.defineProperty(g, "__onGCastApiAvailable", {
535
1555
  configurable: true,
536
1556
  enumerable: true,
537
1557
  get: () => onGCastApiAvailable,
538
1558
  set: (v) => {
539
1559
  onGCastApiAvailable = v;
540
- if (typeof v === "function")
541
- notifyGCastApiAvailable();
1560
+ if (typeof v === "function" && !docIsLoading())
1561
+ notifyGCastApiAvailable(v);
542
1562
  },
543
1563
  });
544
1564
  return true;