@ngxsp/core 0.3.0 → 0.3.1-next.555

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.
@@ -6,20 +6,39 @@
6
6
  export declare const MEDIA_LIBRARY_MODEL_VERSION = 3;
7
7
  export type MediaLibraryKind = 'audio' | 'video';
8
8
  export type AudioInferredField = 'title' | 'artist' | 'albumArtist' | 'album' | 'trackNo';
9
- /** The subset of music-metadata results the model reads. */
9
+ /**
10
+ * The subset of music-metadata results the model reads, in both spellings on purpose.
11
+ *
12
+ * music-metadata 13 camel-cased the common tag properties: 71 of its 124 keys were renamed, four of
13
+ * them ones read here — `albumartist` became `albumArtist`, `genre` became `genres`, and the
14
+ * `track`/`disk` objects became the plain numbers `trackNumber`/`discNumber`. These fields are
15
+ * redeclared rather than imported, so nothing type-checks against the package and a renamed tag is
16
+ * not an error anywhere: it reads as `undefined`, and the library quietly loses the album artist,
17
+ * the genre and the track order while every test stays green.
18
+ *
19
+ * Reading both spellings keeps either version usable, which is what the apps need — each one ships
20
+ * its own copy of music-metadata, and they do not move at the same time.
21
+ */
10
22
  export interface MediaTags {
11
23
  title?: string;
12
24
  artist?: string;
13
25
  artists?: string[];
26
+ /** `albumartist` up to music-metadata 12, `albumArtist` from 13. */
14
27
  albumartist?: string;
28
+ albumArtist?: string;
15
29
  album?: string;
30
+ /** `genre` up to music-metadata 12, `genres` from 13. */
16
31
  genre?: string | string[];
32
+ genres?: string[];
33
+ /** An object up to music-metadata 12, a plain number from 13. */
17
34
  track?: {
18
35
  no?: number | null;
19
36
  };
37
+ trackNumber?: number;
20
38
  disk?: {
21
39
  no?: number | null;
22
40
  };
41
+ discNumber?: number;
23
42
  year?: number;
24
43
  stik?: number;
25
44
  tvShow?: string;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * What a share button puts on the clipboard, when the media has an address worth handing to
3
+ * someone else.
4
+ *
5
+ * The video player learnt this the hard way: it used to copy `location.href` — the address of the
6
+ * window doing the sharing, `file://` in the packaged application and a localhost port in the
7
+ * browser. That link led back to the sharer's own screen and nowhere for anybody else.
8
+ */
9
+ /**
10
+ * The media's own address when it travels, and nothing when it does not. Only absolute http and
11
+ * https do: a relative address is read against the window it was copied from, a file on the disk
12
+ * and an application's own scheme name a place on this machine, and a loopback address names the
13
+ * reader's.
14
+ */
15
+ export declare function shareableSourceUrl(source: string | undefined | null): string | null;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * A count and the word that agrees with it.
3
+ *
4
+ * The applications used to write "(s)" — "1 titre(s)" — or to pick the plural above one, which is
5
+ * right in French and wrong in English: French keeps the singular at zero ("0 titre"), English does
6
+ * not ("0 tracks"). One rule, so neither application has to remember which.
7
+ */
8
+ /** The word that agrees with a count, in the locale's own rule. */
9
+ export declare function pluralWord(locale: string, count: number, singular: string, plural: string): string;
10
+ /** A count and the word that agrees with it: "1 titre", "3 titres", "0 tracks". */
11
+ export declare function countLabel(locale: string, count: number, singular: string, plural: string): string;
@@ -0,0 +1 @@
1
+ export declare function isSupersededLoad(error: unknown): boolean;
@@ -17,12 +17,6 @@ export interface RemotePlaybackEngineOptions {
17
17
  /** Above the native (0) and adaptive engines, so a session takes every source. */
18
18
  priority?: number;
19
19
  }
20
- /**
21
- * Plays through a remote device (DLNA renderer, Cast device) with the player's own controls. Like a media element,
22
- * loading prepares the media and playing starts it: the device receives it on the first `play`, from the position
23
- * reached until then. The device's position and state come back by polling. A device that refuses a media gets it
24
- * converted when the app can convert it; a converted stream seeks by starting again from the new position.
25
- */
26
20
  export declare function createRemotePlaybackEngineFactory(options: RemotePlaybackEngineOptions): EngineFactory;
27
21
  export declare class RemotePlaybackEngine implements PlaybackEngine {
28
22
  private readonly options;
@@ -24,6 +24,16 @@ export declare class PlayerFacade {
24
24
  private engineFactories;
25
25
  private engineId;
26
26
  private lastNonFatal;
27
+ /**
28
+ * Which load has already had its failure reported.
29
+ *
30
+ * One unreadable file used to be reported three times over, by three doors: the media element's
31
+ * own error event, the rejection of `play()`, and the engine's error event. Three codes, three
32
+ * messages, nothing a host could tell apart from three broken files — so a listener was told
33
+ * three times, and a host that moves on after a failure heard three reasons to move.
34
+ */
35
+ private failureReportedForLoad;
36
+ private loadCount;
27
37
  private mediaDecodingSub;
28
38
  private video?;
29
39
  private engine?;
package/index.cjs CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  var rxjs = require('rxjs');
4
4
 
5
+ // src/types.ts
6
+ function playableDurationSec(reported, announced) {
7
+ if (typeof reported === "number" && Number.isFinite(reported) && reported > 0) return reported;
8
+ if (typeof announced === "number" && Number.isFinite(announced) && announced > 0) return announced;
9
+ return 0;
10
+ }
11
+ function meansSourceNotSupported(code) {
12
+ return code === "SRC_NOT_SUPPORTED" || code === "HTML5_4";
13
+ }
14
+
5
15
  // src/config/default-config.ts
6
16
  var DEFAULT_PROGRESS_CONFIG = {
7
17
  mode: "local",
@@ -96,6 +106,16 @@ function parseRemoteClock(value) {
96
106
  return Number(match[1]) * 3600 + Number(match[2]) * 60 + Number(match[3]) + (match[4] ? Number(`0.${match[4]}`) : 0);
97
107
  }
98
108
 
109
+ // src/domain/superseded-load.ts
110
+ var SHAKA_SUPERSEDED_LOAD_CODES = /* @__PURE__ */ new Set([7e3, 7001, 7003]);
111
+ function isSupersededLoad(error) {
112
+ const candidate = error;
113
+ if (candidate?.name === "AbortError") return true;
114
+ if (SHAKA_SUPERSEDED_LOAD_CODES.has(Number(candidate?.code))) return true;
115
+ const message = String(candidate?.message ?? "").toLowerCase();
116
+ return message.includes("interrupted by a new load request") || message.includes("operation was aborted");
117
+ }
118
+
99
119
  // src/engine/engine-factory.ts
100
120
  function selectEngine(config, factories, caps) {
101
121
  const candidates = (factories ?? []).filter((f) => {
@@ -331,10 +351,11 @@ function applyEngineProfileToSource(source, profile) {
331
351
  profile: p
332
352
  };
333
353
  if (Object.keys(abrOut).length) out.abr = abrOut;
334
- if (hints.shakaStreaming) {
354
+ const streamingIn = { ...anySrc._shakaStreaming ?? {}, ...anySrc.streaming ?? {} };
355
+ if (hints.shakaStreaming || Object.keys(streamingIn).length) {
335
356
  out._shakaStreaming = {
336
- ...anySrc._shakaStreaming ?? {},
337
- ...hints.shakaStreaming
357
+ ...hints.shakaStreaming ?? {},
358
+ ...streamingIn
338
359
  };
339
360
  }
340
361
  return out;
@@ -631,6 +652,16 @@ var PlayerFacade = class {
631
652
  engineFactories = [createNativeEngineFactory()];
632
653
  engineId = "native";
633
654
  lastNonFatal = null;
655
+ /**
656
+ * Which load has already had its failure reported.
657
+ *
658
+ * One unreadable file used to be reported three times over, by three doors: the media element's
659
+ * own error event, the rejection of `play()`, and the engine's error event. Three codes, three
660
+ * messages, nothing a host could tell apart from three broken files — so a listener was told
661
+ * three times, and a host that moves on after a failure heard three reasons to move.
662
+ */
663
+ failureReportedForLoad = -1;
664
+ loadCount = 0;
634
665
  // Optional MediaCapabilities decoding probes (async, best-effort)
635
666
  mediaDecodingSub = new rxjs.BehaviorSubject(null);
636
667
  video;
@@ -690,6 +721,8 @@ var PlayerFacade = class {
690
721
  async load(config, opts) {
691
722
  if (!this.video) throw new Error("PlayerFacade not attached");
692
723
  if (!this.ctx) throw new Error("PlayerFacade context missing");
724
+ this.loadCount += 1;
725
+ const loadId = this.loadCount;
693
726
  const rc = await applyRemoteConfig(config, this.ports);
694
727
  if (rc.applied) {
695
728
  this.ports.telemetry?.add?.({
@@ -774,6 +807,11 @@ var PlayerFacade = class {
774
807
  this.stateSub.next({ kind: "paused" });
775
808
  this.emitTelemetry("player:load_ok", "info");
776
809
  } catch (err) {
810
+ const replaced = this.loadCount !== loadId || this.engine !== engine;
811
+ if (replaced && isSupersededLoad(err)) {
812
+ this.emitTelemetry("player:load_superseded", "info", {}, err?.message);
813
+ throw err;
814
+ }
777
815
  this.emitTelemetry("player:load_fail", "error", {}, err?.message);
778
816
  this.emitFatal(err, "UNKNOWN");
779
817
  throw err;
@@ -852,6 +890,17 @@ var PlayerFacade = class {
852
890
  emitFatal(err, code = "UNKNOWN") {
853
891
  const pe = this.toPlayerError(err, true, code);
854
892
  this.emitTelemetry("player:error_fatal", "error", { code: pe.code }, pe.message);
893
+ if (this.failureReportedForLoad === this.loadCount) {
894
+ this.errorSub.next(pe);
895
+ if (this.ctx) for (const p of this.plugins) {
896
+ try {
897
+ void p.onError?.(this.ctx, pe);
898
+ } catch {
899
+ }
900
+ }
901
+ return;
902
+ }
903
+ this.failureReportedForLoad = this.loadCount;
855
904
  this.stateSub.next({ kind: "error", error: pe });
856
905
  this.errorSub.next(pe);
857
906
  if (this.ctx) {
@@ -982,6 +1031,7 @@ var PlayerFacade = class {
982
1031
  }
983
1032
  async play() {
984
1033
  this.emitTelemetry("player:play_request", "info");
1034
+ this.failureReportedForLoad = -1;
985
1035
  try {
986
1036
  await this.engine?.play();
987
1037
  this.emitTelemetry("player:play_ok", "info");
@@ -994,6 +1044,9 @@ var PlayerFacade = class {
994
1044
  if (name === "NotAllowedError") {
995
1045
  this.emitNonFatal(err, "AUTOPLAY_BLOCKED");
996
1046
  this.emitTelemetry("player:play_fail", "warn", { code: "AUTOPLAY_BLOCKED" }, err?.message);
1047
+ } else if (name === "NotSupportedError") {
1048
+ this.emitFatal(err, "SRC_NOT_SUPPORTED");
1049
+ this.emitTelemetry("player:play_fail", "error", { code: "SRC_NOT_SUPPORTED" }, err?.message);
997
1050
  } else if (name === "RemotePlaybackError") {
998
1051
  const code = remotePlaybackErrorCode(err.code);
999
1052
  this.emitFatal(err, code);
@@ -1193,7 +1246,10 @@ var PlayerFacade = class {
1193
1246
  }
1194
1247
  if (ev.type === "error") {
1195
1248
  const pe = { code: ev.error.code, message: ev.error.message, fatal: ev.error.fatal, details: ev.error.details };
1196
- this.stateSub.next({ kind: "error", error: pe });
1249
+ if (this.failureReportedForLoad !== this.loadCount) {
1250
+ this.failureReportedForLoad = this.loadCount;
1251
+ this.stateSub.next({ kind: "error", error: pe });
1252
+ }
1197
1253
  this.errorSub.next(pe);
1198
1254
  try {
1199
1255
  this.ctx?.ports.telemetry.add({ t: Date.now(), kind: "error", code: pe.code, fatal: !!pe.fatal });
@@ -1587,6 +1643,7 @@ function createSsaiManifestRewritePlugin() {
1587
1643
  }
1588
1644
 
1589
1645
  // src/engine/remote-playback.engine.ts
1646
+ var DURATION_SLACK_SEC = 1;
1590
1647
  function createRemotePlaybackEngineFactory(options) {
1591
1648
  return {
1592
1649
  id: "remote",
@@ -1728,9 +1785,10 @@ var RemotePlaybackEngine = class {
1728
1785
  const status = await this.session.status();
1729
1786
  if (this.destroyed) return;
1730
1787
  this.failures = 0;
1731
- if (status.durationSec && !this.media?.conversion) this.durationSec = status.durationSec;
1788
+ if (status.durationSec && !this.media?.conversion && !this.media?.durationSec) this.durationSec = status.durationSec;
1732
1789
  if (status.positionSec !== void 0) this.positionSec = this.offsetSec + status.positionSec;
1733
1790
  this.furthestSec = Math.max(this.furthestSec, this.positionSec - this.offsetSec);
1791
+ if (this.durationSec > 0 && this.positionSec > this.durationSec + DURATION_SLACK_SEC) this.durationSec = 0;
1734
1792
  const wasPlaying = this.lastState === "playing" || this.lastState === "buffering";
1735
1793
  const refused = (status.ended || status.state === "stopped") && this.furthestSec < 1 && !this.source?.live && (status.ended || wasPlaying);
1736
1794
  if ((refused || status.error) && this.convertible(this.media)) {
@@ -2538,23 +2596,27 @@ function audioFieldsFromTags({ relativePath, common = {}, format = {} }) {
2538
2596
  const numbered = LEADING_TRACK_NUMBER.exec(stem);
2539
2597
  const ancestors = ancestorNames(relativePath);
2540
2598
  const artists = Array.isArray(common.artists) ? common.artists.filter(Boolean) : [];
2541
- const genre = Array.isArray(common.genre) ? common.genre.find(Boolean) : common.genre;
2542
- const taggedArtist = nonEmpty(common.artist) ?? nonEmpty(artists.join(", ")) ?? nonEmpty(common.albumartist);
2599
+ const genreTag = common.genres ?? common.genre;
2600
+ const genre = Array.isArray(genreTag) ? genreTag.find(Boolean) : genreTag;
2601
+ const albumArtistTag = nonEmpty(common.albumArtist) ?? nonEmpty(common.albumartist);
2602
+ const trackNoTag = positiveInteger(common.trackNumber) ?? positiveInteger(common.track?.no);
2603
+ const discNoTag = positiveInteger(common.discNumber) ?? positiveInteger(common.disk?.no);
2604
+ const taggedArtist = nonEmpty(common.artist) ?? nonEmpty(artists.join(", ")) ?? albumArtistTag;
2543
2605
  const inferredFields = [
2544
2606
  !nonEmpty(common.title) && "title",
2545
2607
  !taggedArtist && "artist",
2546
- !nonEmpty(common.albumartist) && !nonEmpty(common.artist) && "albumArtist",
2608
+ !albumArtistTag && !nonEmpty(common.artist) && "albumArtist",
2547
2609
  !nonEmpty(common.album) && "album",
2548
- !positiveInteger(common.track?.no) && numbered && "trackNo"
2610
+ !trackNoTag && numbered && "trackNo"
2549
2611
  ].filter((field) => typeof field === "string");
2550
2612
  return {
2551
2613
  title: nonEmpty(common.title) ?? cleanMediaTitle(numbered ? numbered[2] : stem),
2552
2614
  artist: taggedArtist ?? (ancestors[1] ? tidy2(ancestors[1]) : void 0),
2553
- albumArtist: nonEmpty(common.albumartist) ?? nonEmpty(common.artist) ?? (ancestors[1] ? tidy2(ancestors[1]) : void 0),
2615
+ albumArtist: albumArtistTag ?? nonEmpty(common.artist) ?? (ancestors[1] ? tidy2(ancestors[1]) : void 0),
2554
2616
  album: nonEmpty(common.album) ?? (ancestors[0] ? tidy2(ancestors[0]) : void 0),
2555
2617
  genre: nonEmpty(genre),
2556
- trackNo: positiveInteger(common.track?.no) ?? (numbered ? positiveInteger(numbered[1]) : void 0),
2557
- discNo: positiveInteger(common.disk?.no),
2618
+ trackNo: trackNoTag ?? (numbered ? positiveInteger(numbered[1]) : void 0),
2619
+ discNo: discNoTag,
2558
2620
  year: positiveInteger(common.year),
2559
2621
  durationSec: durationOf(format),
2560
2622
  inferredFields: inferredFields.length ? inferredFields : void 0
@@ -2750,6 +2812,29 @@ function writeText(view, offset, text6) {
2750
2812
  for (let index = 0; index < text6.length; index += 1) view.setUint8(offset + index, text6.charCodeAt(index));
2751
2813
  }
2752
2814
 
2815
+ // src/domain/media-share.ts
2816
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
2817
+ function shareableSourceUrl(source) {
2818
+ if (!source) return null;
2819
+ let url;
2820
+ try {
2821
+ url = new URL(source);
2822
+ } catch {
2823
+ return null;
2824
+ }
2825
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
2826
+ if (LOOPBACK_HOSTS.has(url.hostname.toLowerCase())) return null;
2827
+ return url.href;
2828
+ }
2829
+
2830
+ // src/domain/plural.ts
2831
+ function pluralWord(locale, count, singular, plural) {
2832
+ return (locale === "fr" ? count > 1 : count !== 1) ? plural : singular;
2833
+ }
2834
+ function countLabel(locale, count, singular, plural) {
2835
+ return `${count} ${pluralWord(locale, count, singular, plural)}`;
2836
+ }
2837
+
2753
2838
  // src/domain/shake.ts
2754
2839
  var DEFAULTS = {
2755
2840
  force: 12,
@@ -4217,6 +4302,8 @@ var NGXSP_SERVICE_TYPE = "_ngxsp._tcp.local";
4217
4302
  var PLAYBACK_TRANSFER_PATH = "/ngxsp/transfer";
4218
4303
  var PLAYBACK_TRANSFER_VERSION = 1;
4219
4304
  var PLAYBACK_TRANSFER_PROMPT_MS = 6e4;
4305
+ var MAX_PAGE = 200;
4306
+ var DEFAULT_PAGE = 50;
4220
4307
  var MAX_ITEMS = 200;
4221
4308
  var MAX_TEXT = 300;
4222
4309
  function ngxspTxt(identity) {
@@ -4264,6 +4351,9 @@ function readPlaybackTransfer(value) {
4264
4351
  playing: input["playing"] !== false
4265
4352
  };
4266
4353
  }
4354
+ function readPlaybackTransferItem(value) {
4355
+ return readItem(value);
4356
+ }
4267
4357
  function readItem(value) {
4268
4358
  if (!value || typeof value !== "object") return null;
4269
4359
  const input = value;
@@ -4284,6 +4374,78 @@ function readItem(value) {
4284
4374
  function text2(value, max = MAX_TEXT) {
4285
4375
  return typeof value === "string" ? value.replace(/[\u0000-\u001f]/g, " ").trim().slice(0, max) : "";
4286
4376
  }
4377
+ function readPlaybackPull(value) {
4378
+ if (!value || typeof value !== "object") return null;
4379
+ const input = value;
4380
+ const want = input["want"];
4381
+ if (want !== "playback" && want !== "converted" && want !== "library" && want !== "item") return null;
4382
+ const from = input["from"];
4383
+ const app = from?.["app"];
4384
+ if (input["version"] !== PLAYBACK_TRANSFER_VERSION || !from || typeof from["id"] !== "string" || !from["id"] || app !== "audio" && app !== "video") return null;
4385
+ const url = text2(input["url"], 4e3);
4386
+ if (want === "converted" && !/^https?:\/\//i.test(url)) return null;
4387
+ const id = text2(input["id"], 200);
4388
+ if (want === "item" && !id) return null;
4389
+ const offset = Number(input["offset"]);
4390
+ const limit = Number(input["limit"]);
4391
+ return {
4392
+ version: PLAYBACK_TRANSFER_VERSION,
4393
+ from: { id: text2(from["id"]).slice(0, 64), name: text2(from["name"]) || text2(from["id"]).slice(0, 8), app },
4394
+ want,
4395
+ ...want === "converted" ? { url } : {},
4396
+ ...want === "item" ? { id } : {},
4397
+ // Whatever is asked for, the slice is this app's to bound: a peer does not get to ask for
4398
+ // ten thousand entries in one reply.
4399
+ ...want === "library" ? {
4400
+ ...text2(input["query"]) ? { query: text2(input["query"]) } : {},
4401
+ offset: Number.isInteger(offset) && offset > 0 ? offset : 0,
4402
+ limit: Number.isInteger(limit) && limit > 0 ? Math.min(limit, MAX_PAGE) : DEFAULT_PAGE
4403
+ } : {}
4404
+ };
4405
+ }
4406
+ function readPlaybackLibraryPage(value) {
4407
+ if (!value || typeof value !== "object") return null;
4408
+ const input = value;
4409
+ if (!Array.isArray(input["entries"])) return null;
4410
+ const entries = input["entries"].slice(0, MAX_PAGE).flatMap((entry) => {
4411
+ const read = readLibraryEntry(entry);
4412
+ return read ? [read] : [];
4413
+ });
4414
+ const total = Number(input["total"]);
4415
+ const offset = Number(input["offset"]);
4416
+ return {
4417
+ entries,
4418
+ total: Number.isInteger(total) && total >= 0 ? total : entries.length,
4419
+ offset: Number.isInteger(offset) && offset > 0 ? offset : 0
4420
+ };
4421
+ }
4422
+ function readLibraryEntry(value) {
4423
+ if (!value || typeof value !== "object") return null;
4424
+ const input = value;
4425
+ const id = text2(input["id"], 200);
4426
+ const title = text2(input["title"]);
4427
+ if (!id || !title) return null;
4428
+ const whole = (key, max) => {
4429
+ const read = Number(input[key]);
4430
+ return Number.isInteger(read) && read >= 0 && read <= max ? read : void 0;
4431
+ };
4432
+ const durationSec = Number(input["durationSec"]);
4433
+ return {
4434
+ id,
4435
+ title,
4436
+ ...text2(input["category"], 40) ? { category: text2(input["category"], 40) } : {},
4437
+ ...text2(input["artist"]) ? { artist: text2(input["artist"]) } : {},
4438
+ ...text2(input["album"]) ? { album: text2(input["album"]) } : {},
4439
+ ...text2(input["series"]) ? { series: text2(input["series"]) } : {},
4440
+ ...whole("season", 9999) !== void 0 ? { season: whole("season", 9999) } : {},
4441
+ ...whole("episode", 99999) !== void 0 ? { episode: whole("episode", 99999) } : {},
4442
+ ...whole("year", 9999) !== void 0 ? { year: whole("year", 9999) } : {},
4443
+ ...Number.isFinite(durationSec) && durationSec > 0 ? { durationSec } : {},
4444
+ ...text2(input["description"], 2e3) ? { description: text2(input["description"], 2e3) } : {},
4445
+ ...text2(input["fileName"]) ? { fileName: text2(input["fileName"]) } : {},
4446
+ ...input["artwork"] === true ? { artwork: true } : {}
4447
+ };
4448
+ }
4287
4449
  function createPlaybackTransferReceiver(options) {
4288
4450
  let asking = false;
4289
4451
  async function isTrusted(from, authorization) {
@@ -4291,41 +4453,87 @@ function createPlaybackTransferReceiver(options) {
4291
4453
  const sender = options.trusted().find((entry) => entry.id === from.id);
4292
4454
  return !!token && !!sender && await options.sha256Hex(token) === sender.tokenHash;
4293
4455
  }
4294
- async function handle(request2) {
4295
- if (request2.method.toUpperCase() !== "POST") return { status: 405, body: { accepted: false, reason: "invalid" } };
4296
- if (!options.enabled()) return { status: 403, body: { accepted: false, reason: "disabled" } };
4297
- let transfer = null;
4298
- try {
4299
- transfer = readPlaybackTransfer(JSON.parse(request2.body));
4300
- } catch {
4301
- transfer = null;
4302
- }
4303
- if (!transfer) return { status: 400, body: { accepted: false, reason: "invalid" } };
4304
- if (transfer.from.app !== options.app) return { status: 422, body: { accepted: false, reason: "other-app" } };
4305
- if (await isTrusted(transfer.from, request2.authorization)) {
4306
- const from = transfer.from;
4456
+ async function admit(from, authorization, want) {
4457
+ if (await isTrusted(from, authorization)) {
4307
4458
  options.saveTrusted(options.trusted().map((entry) => entry.id === from.id ? { ...entry, name: from.name } : entry));
4308
- options.apply(transfer);
4309
- return { status: 200, body: { accepted: true } };
4459
+ return { allowed: true };
4310
4460
  }
4311
4461
  if (asking) return { status: 409, body: { accepted: false, reason: "busy" } };
4312
4462
  asking = true;
4313
4463
  let allowed;
4464
+ const expired = new AbortController();
4314
4465
  try {
4315
4466
  allowed = await Promise.race([
4316
- options.ask(transfer.from),
4467
+ options.ask(from, want, expired.signal),
4317
4468
  new Promise((resolve) => setTimeout(() => resolve("timeout"), options.promptMs ?? PLAYBACK_TRANSFER_PROMPT_MS))
4318
4469
  ]);
4319
4470
  } finally {
4320
4471
  asking = false;
4472
+ expired.abort();
4321
4473
  }
4322
4474
  if (allowed === "timeout") return { status: 408, body: { accepted: false, reason: "timeout" } };
4323
4475
  if (!allowed) return { status: 403, body: { accepted: false, reason: "refused" } };
4324
4476
  const token = options.randomToken();
4325
- const sender = { id: transfer.from.id, name: transfer.from.name, tokenHash: await options.sha256Hex(token), since: Date.now() };
4477
+ const sender = { id: from.id, name: from.name, tokenHash: await options.sha256Hex(token), since: Date.now() };
4326
4478
  options.saveTrusted([...options.trusted().filter((entry) => entry.id !== sender.id), sender]);
4479
+ return { allowed: true, token };
4480
+ }
4481
+ async function answerPull(pull, request2) {
4482
+ if (pull.from.app !== options.app) return { status: 422, body: { accepted: false, reason: "other-app" } };
4483
+ const answers = { playback: options.offer, converted: options.convert, library: options.browse, item: options.item }[pull.want];
4484
+ if (!answers) return { status: 501, body: { accepted: false, reason: "disabled" } };
4485
+ const verdict = await admit(pull.from, request2.authorization, pull.want);
4486
+ if (!("allowed" in verdict)) return verdict;
4487
+ const token = verdict.token ? { token: verdict.token } : {};
4488
+ const address = text2(request2.address, 60);
4489
+ try {
4490
+ if (pull.want === "playback") {
4491
+ const transfer = await options.offer(pull.from, address);
4492
+ if (!transfer) return { status: 404, body: { accepted: false, reason: "nothing", ...token } };
4493
+ return { status: 200, body: { accepted: true, transfer, ...token } };
4494
+ }
4495
+ if (pull.want === "library") {
4496
+ const page = await options.browse(pull.from, address, {
4497
+ ...pull.query ? { query: pull.query } : {},
4498
+ offset: pull.offset ?? 0,
4499
+ limit: pull.limit ?? DEFAULT_PAGE
4500
+ });
4501
+ if (!page) return { status: 404, body: { accepted: false, reason: "nothing", ...token } };
4502
+ return { status: 200, body: { accepted: true, page, ...token } };
4503
+ }
4504
+ if (pull.want === "item") {
4505
+ const item = await options.item(pull.from, address, pull.id);
4506
+ if (!item) return { status: 404, body: { accepted: false, reason: "nothing", ...token } };
4507
+ return { status: 200, body: { accepted: true, item, ...token } };
4508
+ }
4509
+ const converted = await options.convert(pull.url, pull.from, address);
4510
+ if (!converted) return { status: 404, body: { accepted: false, reason: "nothing", ...token } };
4511
+ return {
4512
+ status: 200,
4513
+ body: { accepted: true, url: converted.url, ...converted.durationSec ? { durationSec: converted.durationSec } : {}, ...token }
4514
+ };
4515
+ } catch {
4516
+ return { status: 404, body: { accepted: false, reason: "nothing", ...token } };
4517
+ }
4518
+ }
4519
+ async function handle(request2) {
4520
+ if (request2.method.toUpperCase() !== "POST") return { status: 405, body: { accepted: false, reason: "invalid" } };
4521
+ if (!options.enabled()) return { status: 403, body: { accepted: false, reason: "disabled" } };
4522
+ let parsed = null;
4523
+ try {
4524
+ parsed = JSON.parse(request2.body);
4525
+ } catch {
4526
+ return { status: 400, body: { accepted: false, reason: "invalid" } };
4527
+ }
4528
+ const pull = readPlaybackPull(parsed);
4529
+ if (pull) return answerPull(pull, request2);
4530
+ const transfer = readPlaybackTransfer(parsed);
4531
+ if (!transfer) return { status: 400, body: { accepted: false, reason: "invalid" } };
4532
+ if (transfer.from.app !== options.app) return { status: 422, body: { accepted: false, reason: "other-app" } };
4533
+ const verdict = await admit(transfer.from, request2.authorization);
4534
+ if (!("allowed" in verdict)) return verdict;
4327
4535
  options.apply(transfer);
4328
- return { status: 200, body: { accepted: true, token } };
4536
+ return { status: 200, body: { accepted: true, ...verdict.token ? { token: verdict.token } : {} } };
4329
4537
  }
4330
4538
  return { handle };
4331
4539
  }
@@ -4356,6 +4564,55 @@ async function sendPlaybackTransfer(http, peer, transfer, token) {
4356
4564
  const reason = reasons.find((entry) => entry === body["reason"]);
4357
4565
  return { accepted: false, reason: reason ?? "unreachable" };
4358
4566
  }
4567
+ async function pullFromPeer(http, peer, pull, token) {
4568
+ let response;
4569
+ try {
4570
+ response = await http.send({
4571
+ url: `http://${peer.address}:${peer.port}${PLAYBACK_TRANSFER_PATH}`,
4572
+ method: "POST",
4573
+ headers: { "Content-Type": "application/json", ...token ? { Authorization: `NGXSP ${token}` } : {} },
4574
+ body: JSON.stringify(pull),
4575
+ // The other device may be waiting for its user, and a conversion starts with a probe.
4576
+ timeoutMs: PLAYBACK_TRANSFER_PROMPT_MS + 15e3
4577
+ });
4578
+ } catch {
4579
+ return { got: false, reason: "unreachable" };
4580
+ }
4581
+ let body = {};
4582
+ try {
4583
+ body = JSON.parse(await response.text());
4584
+ } catch {
4585
+ body = {};
4586
+ }
4587
+ const given = typeof body["token"] === "string" ? { token: body["token"] } : {};
4588
+ if (response.status === 200 && body["accepted"] === true) {
4589
+ if (pull.want === "playback") {
4590
+ const transfer = readPlaybackTransfer(body["transfer"]);
4591
+ return transfer ? { got: true, want: "playback", transfer, ...given } : { got: false, reason: "invalid" };
4592
+ }
4593
+ if (pull.want === "library") {
4594
+ const page = readPlaybackLibraryPage(body["page"]);
4595
+ return page ? { got: true, want: "library", page, ...given } : { got: false, reason: "invalid" };
4596
+ }
4597
+ if (pull.want === "item") {
4598
+ const item = readPlaybackTransferItem(body["item"]);
4599
+ return item ? { got: true, want: "item", item, ...given } : { got: false, reason: "invalid" };
4600
+ }
4601
+ const url = typeof body["url"] === "string" ? body["url"] : "";
4602
+ if (!/^https?:\/\//i.test(url)) return { got: false, reason: "invalid" };
4603
+ const durationSec = Number(body["durationSec"]);
4604
+ return {
4605
+ got: true,
4606
+ want: "converted",
4607
+ url,
4608
+ ...Number.isFinite(durationSec) && durationSec > 0 ? { durationSec } : {},
4609
+ ...given
4610
+ };
4611
+ }
4612
+ const reasons = ["refused", "busy", "timeout", "disabled", "other-app", "invalid", "nothing"];
4613
+ const reason = reasons.find((entry) => entry === body["reason"]);
4614
+ return { got: false, reason: reason ?? "unreachable" };
4615
+ }
4359
4616
 
4360
4617
  // src/online/md5.ts
4361
4618
  function md5Hex(input) {
@@ -5258,7 +5515,7 @@ async function fetchLrclibLyrics(query, options = {}) {
5258
5515
  const exact = await http.getJson(buildLrclibGetUrl({ ...query, title }, options.origin), request2).catch(() => null);
5259
5516
  const direct = lyricsFromRecord(exact);
5260
5517
  if (direct) return direct;
5261
- const results = await http.getJson(buildLrclibSearchUrl({ ...query, title }, options.origin), request2).catch(() => null);
5518
+ const results = await http.getJson(buildLrclibSearchUrl({ ...query, title }, options.origin), request2);
5262
5519
  if (!Array.isArray(results)) return null;
5263
5520
  const best = bestLrclibMatch(results, { ...query, title });
5264
5521
  return best ? lyricsFromRecord(best) : null;
@@ -5418,6 +5675,7 @@ exports.connectDlna = connectDlna;
5418
5675
  exports.connectJellyfin = connectJellyfin;
5419
5676
  exports.connectSubsonic = connectSubsonic;
5420
5677
  exports.connectWebDav = connectWebDav;
5678
+ exports.countLabel = countLabel;
5421
5679
  exports.createAudioLibrarySnapshot = createAudioLibrarySnapshot;
5422
5680
  exports.createCapabilityReport = createCapabilityReport;
5423
5681
  exports.createCastSession = createCastSession;
@@ -5475,6 +5733,7 @@ exports.matchFingerprintedRecording = matchFingerprintedRecording;
5475
5733
  exports.matchMusicBrainzRecording = matchMusicBrainzRecording;
5476
5734
  exports.md5Hex = md5Hex;
5477
5735
  exports.mdnsServices = mdnsServices;
5736
+ exports.meansSourceNotSupported = meansSourceNotSupported;
5478
5737
  exports.mediaContentType = mediaContentType;
5479
5738
  exports.mediaFileExtension = mediaFileExtension;
5480
5739
  exports.mediaMetadataKey = mediaMetadataKey;
@@ -5502,9 +5761,15 @@ exports.parseUpnpDeviceDescription = parseUpnpDeviceDescription;
5502
5761
  exports.parseWebDavMultistatus = parseWebDavMultistatus;
5503
5762
  exports.pickAcoustIdRecording = pickAcoustIdRecording;
5504
5763
  exports.planMediaCacheEviction = planMediaCacheEviction;
5764
+ exports.playableDurationSec = playableDurationSec;
5765
+ exports.pluralWord = pluralWord;
5766
+ exports.pullFromPeer = pullFromPeer;
5505
5767
  exports.readDlnaRenderer = readDlnaRenderer;
5506
5768
  exports.readJellyfinLyrics = readJellyfinLyrics;
5769
+ exports.readPlaybackLibraryPage = readPlaybackLibraryPage;
5770
+ exports.readPlaybackPull = readPlaybackPull;
5507
5771
  exports.readPlaybackTransfer = readPlaybackTransfer;
5772
+ exports.readPlaybackTransferItem = readPlaybackTransferItem;
5508
5773
  exports.readWebDavLyrics = readWebDavLyrics;
5509
5774
  exports.reduceDevicePlaybackState = reduceDevicePlaybackState;
5510
5775
  exports.remotePlaybackErrorCode = remotePlaybackErrorCode;
@@ -5518,6 +5783,7 @@ exports.searchRadioStations = searchRadioStations;
5518
5783
  exports.selectEngine = selectEngine;
5519
5784
  exports.selectInternetArchiveVideo = selectInternetArchiveVideo;
5520
5785
  exports.sendPlaybackTransfer = sendPlaybackTransfer;
5786
+ exports.shareableSourceUrl = shareableSourceUrl;
5521
5787
  exports.subsonicCoverUrl = subsonicCoverUrl;
5522
5788
  exports.subsonicStreamUrl = subsonicStreamUrl;
5523
5789
  exports.subtitleTextToVtt = subtitleTextToVtt;