@dominevo/addon-media-library 0.1.13 → 0.1.14

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.
@@ -633,8 +633,7 @@ var $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, d
633
633
  const origin = numericOriginMap[typeof def.value];
634
634
  inst._zod.onattach.push((inst) => {
635
635
  const bag = inst._zod.bag;
636
- const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
637
- if (def.value < curr) if (def.inclusive) bag.maximum = def.value;
636
+ if (def.value < ((def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY)) if (def.inclusive) bag.maximum = def.value;
638
637
  else bag.exclusiveMaximum = def.value;
639
638
  });
640
639
  inst._zod.check = (payload) => {
@@ -655,8 +654,7 @@ var $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (i
655
654
  const origin = numericOriginMap[typeof def.value];
656
655
  inst._zod.onattach.push((inst) => {
657
656
  const bag = inst._zod.bag;
658
- const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
659
- if (def.value > curr) if (def.inclusive) bag.minimum = def.value;
657
+ if (def.value > ((def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY)) if (def.inclusive) bag.minimum = def.value;
660
658
  else bag.exclusiveMinimum = def.value;
661
659
  });
662
660
  inst._zod.check = (payload) => {
@@ -770,8 +768,7 @@ var $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst,
770
768
  return !nullish(val) && val.length !== void 0;
771
769
  });
772
770
  inst._zod.onattach.push((inst) => {
773
- const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
774
- if (def.maximum < curr) inst._zod.bag.maximum = def.maximum;
771
+ if (def.maximum < (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY)) inst._zod.bag.maximum = def.maximum;
775
772
  });
776
773
  inst._zod.check = (payload) => {
777
774
  const input = payload.value;
@@ -796,8 +793,7 @@ var $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst,
796
793
  return !nullish(val) && val.length !== void 0;
797
794
  });
798
795
  inst._zod.onattach.push((inst) => {
799
- const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
800
- if (def.minimum > curr) inst._zod.bag.minimum = def.minimum;
796
+ if (def.minimum > (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY)) inst._zod.bag.minimum = def.minimum;
801
797
  });
802
798
  inst._zod.check = (payload) => {
803
799
  const input = payload.value;
@@ -832,10 +828,9 @@ var $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals",
832
828
  const length = input.length;
833
829
  if (length === def.length) return;
834
830
  const origin = getLengthableOrigin(input);
835
- const tooBig = length > def.length;
836
831
  payload.issues.push({
837
832
  origin,
838
- ...tooBig ? {
833
+ ...length > def.length ? {
839
834
  code: "too_big",
840
835
  maximum: def.length
841
836
  } : {
@@ -1475,9 +1470,8 @@ var $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => {
1475
1470
  payload.value = Array(input.length);
1476
1471
  const proms = [];
1477
1472
  for (let i = 0; i < input.length; i++) {
1478
- const item = input[i];
1479
1473
  const result = def.element._zod.run({
1480
- value: item,
1474
+ value: input[i],
1481
1475
  issues: []
1482
1476
  }, ctx);
1483
1477
  if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i)));
@@ -5600,7 +5594,6 @@ function createEvent(category, source, data) {
5600
5594
  * coordinate.
5601
5595
  */
5602
5596
  function emitReadiness(bus, params) {
5603
- const ts = params.ts ?? Date.now();
5604
5597
  bus.emit(createEvent("system.ready-state", {
5605
5598
  type: "capability",
5606
5599
  id: params.capName,
@@ -5611,7 +5604,7 @@ function emitReadiness(bus, params) {
5611
5604
  state: params.state,
5612
5605
  generation: params.generation,
5613
5606
  sourceNodeId: params.sourceNodeId,
5614
- ts
5607
+ ts: params.ts ?? Date.now()
5615
5608
  }));
5616
5609
  }
5617
5610
  //#endregion
@@ -8713,22 +8706,21 @@ var AppReachSchema = /* @__PURE__ */ discriminatedUnion("kind", [
8713
8706
  ]);
8714
8707
  /** The role an app is offered to. */
8715
8708
  var AppRoleSchema = /* @__PURE__ */ _enum(["admin", "user"]);
8716
- var AppNavItemSchema = /* @__PURE__ */ object({
8717
- id: /* @__PURE__ */ string(),
8718
- label: AppLabelSchema,
8719
- /** A lucide icon name. */
8720
- icon: /* @__PURE__ */ string(),
8721
- path: /* @__PURE__ */ string(),
8722
- adminOnly: /* @__PURE__ */ boolean().optional(),
8723
- keywords: /* @__PURE__ */ array(/* @__PURE__ */ string()).optional(),
8724
- badgeKey: /* @__PURE__ */ string().optional(),
8725
- /** Interpreted by the shell (phase 4): the item is hidden while the capability is absent. */
8726
- requiresCapability: /* @__PURE__ */ string().optional()
8727
- });
8728
8709
  var AppNavSectionSchema = /* @__PURE__ */ object({
8729
8710
  id: /* @__PURE__ */ string(),
8730
8711
  label: /* @__PURE__ */ AppLabelSchema.nullable(),
8731
- items: /* @__PURE__ */ array(AppNavItemSchema)
8712
+ items: /* @__PURE__ */ array(/* @__PURE__ */ object({
8713
+ id: /* @__PURE__ */ string(),
8714
+ label: AppLabelSchema,
8715
+ /** A lucide icon name. */
8716
+ icon: /* @__PURE__ */ string(),
8717
+ path: /* @__PURE__ */ string(),
8718
+ adminOnly: /* @__PURE__ */ boolean().optional(),
8719
+ keywords: /* @__PURE__ */ array(/* @__PURE__ */ string()).optional(),
8720
+ badgeKey: /* @__PURE__ */ string().optional(),
8721
+ /** Interpreted by the shell (phase 4): the item is hidden while the capability is absent. */
8722
+ requiresCapability: /* @__PURE__ */ string().optional()
8723
+ }))
8732
8724
  });
8733
8725
  var appSourceCapability = {
8734
8726
  name: "app-source",
@@ -9342,629 +9334,119 @@ function withOptionalId(record) {
9342
9334
  };
9343
9335
  }
9344
9336
  //#endregion
9345
- //#region src/settings.ts
9346
- /** The capability that owns the cluster-scoped settings (D986). */
9347
- var SETTINGS_CAP = "media-library";
9348
- /** An http(s) base URL without credentials, query or trailing slash; `''` is "not configured"; `null` is invalid. */
9349
- function normalizeBaseUrl(raw) {
9350
- const text = raw.trim();
9351
- if (text === "") return "";
9352
- let url;
9337
+ //#region src/servable.ts
9338
+ /**
9339
+ * A file is servable only when its REAL path (symlinks resolved) is inside a configured root.
9340
+ * The path itself comes from the catalogue by item id; this is the second lock on the same door,
9341
+ * so a catalogue row that names `/etc/passwd`, or a symlink that points out of the library, serves nothing.
9342
+ */
9343
+ async function resolveServable(path, roots) {
9344
+ if (!isAbsolute(path) || path.includes("\0")) return null;
9345
+ let real;
9353
9346
  try {
9354
- url = new URL(text);
9347
+ real = await realpath(path);
9355
9348
  } catch {
9356
9349
  return null;
9357
9350
  }
9358
- if (url.protocol !== "http:" && url.protocol !== "https:") return null;
9359
- if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") return null;
9360
- return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
9361
- }
9362
- var BaseUrlSchema = string().transform((value, ctx) => {
9363
- const normalized = normalizeBaseUrl(value);
9364
- if (normalized === null) {
9365
- ctx.addIssue({
9366
- code: "custom",
9367
- message: "expected an http(s) URL"
9368
- });
9369
- return NEVER;
9351
+ for (const root of roots) {
9352
+ if (root === "") continue;
9353
+ let realRoot;
9354
+ try {
9355
+ realRoot = await realpath(root);
9356
+ } catch {
9357
+ continue;
9358
+ }
9359
+ const prefix = realRoot.endsWith(sep) ? realRoot : `${realRoot}${sep}`;
9360
+ if (real.startsWith(prefix)) return real;
9370
9361
  }
9371
- return normalized;
9372
- });
9373
- /** The metadata steps, in the order they answer by default: files, the arr app, then online (each needs its key or switch), pictures last. */
9374
- var METADATA_STEPS = [
9375
- "local",
9376
- "arr",
9377
- "tmdb",
9378
- "tvmaze",
9379
- "tvdb",
9380
- "omdb",
9381
- "anilist",
9382
- "fanart"
9383
- ];
9384
- var DEFAULT_METADATA_ORDER = METADATA_STEPS;
9385
- /** The steps that cannot answer without the installation's own key. */
9386
- var KEYED_STEPS = [
9387
- "tmdb",
9388
- "tvdb",
9389
- "omdb",
9390
- "fanart"
9391
- ];
9392
- function isStep(value) {
9393
- return METADATA_STEPS.some((step) => step === value);
9362
+ return null;
9394
9363
  }
9395
- function isKeyedStep(step) {
9396
- return KEYED_STEPS.some((keyed) => keyed === step);
9364
+ //#endregion
9365
+ //#region src/naming.ts
9366
+ /** Case- and accent-insensitive form of a title, for search and ordering. */
9367
+ function foldTitle(title) {
9368
+ return title.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().trim();
9397
9369
  }
9398
- /** What the settings list shows for each step. */
9399
- var STEP_NAMES = {
9400
- local: "Local files",
9401
- arr: "Sonarr and Radarr",
9402
- tmdb: "TMDB",
9403
- tvmaze: "TVmaze",
9404
- tvdb: "TheTVDB",
9405
- omdb: "OMDb",
9406
- anilist: "AniList",
9407
- fanart: "Fanart.tv"
9408
- };
9409
- /** One row of the metadata chain: the row order is the order the steps answer in (D1125). */
9410
- var MetadataProviderRowSchema = object({
9411
- /** The step this row is; stable, it addresses the row's secret. */
9412
- id: string(),
9413
- /** The step's display name, stamped by the addon for the row title. */
9414
- name: string().default(""),
9415
- enabled: boolean().default(true),
9416
- /** The installation's own key or token, for a keyed step; unused by the others. */
9417
- apiKey: string().meta({ secret: true }).default("")
9418
- });
9419
- /** A row for `step`; AniList needs no account but sends titles out, so it starts off. */
9420
- function providerRow(step, patch = {}) {
9421
- return {
9422
- id: step,
9423
- name: STEP_NAMES[step],
9424
- enabled: step !== "anilist",
9425
- apiKey: "",
9426
- ...patch
9427
- };
9370
+ /** The ordering key: the folded title without a leading article. */
9371
+ function sortKey(title) {
9372
+ return foldTitle(title).replace(/^(the|a|an|il|lo|la|le|i|gli|un|una)\s+/, "");
9428
9373
  }
9429
- /** The list a fresh installation starts from: every step, in the default order. */
9430
- function defaultProviderRows() {
9431
- return DEFAULT_METADATA_ORDER.map((step) => providerRow(step));
9374
+ /** A stable short id for a thing that has no id of its own (a folder-found file or show). */
9375
+ function hashKey(text) {
9376
+ return createHash("sha1").update(text).digest("hex").slice(0, 16);
9432
9377
  }
9433
- /** A keyed row answers only with a key; the other steps need none. */
9434
- function rowAnswers(row, step) {
9435
- return row.enabled && (!isKeyedStep(step) || row.apiKey.trim() !== "");
9378
+ function itemId(sourceId, letter, key) {
9379
+ return `${sourceId}:${letter}:${key}`;
9436
9380
  }
9437
- /** The steps that are on, in the list's order; a step with no row is off, an unknown id is ignored, a keyed row without its key is skipped. */
9438
- function resolveMetadataSteps(settings) {
9439
- const out = [];
9440
- for (const row of settings.metadataProviders) {
9441
- const step = row.id.toLowerCase();
9442
- if (isStep(step) && rowAnswers(row, step) && !out.includes(step)) out.push(step);
9443
- }
9444
- return out;
9381
+ var ID_PATTERN = /^[a-z-]+:[sme]:[A-Za-z0-9]+$/;
9382
+ /** An item id as a client may send it: the shape this module mints, nothing else. */
9383
+ function isItemId(candidate) {
9384
+ return ID_PATTERN.test(candidate);
9445
9385
  }
9446
- /** The key of a keyed step, or `''` when the step is not answering. */
9447
- function keyOf(settings, step) {
9448
- if (!resolveMetadataSteps(settings).includes(step)) return "";
9449
- return settings.metadataProviders.find((candidate) => candidate.id.toLowerCase() === step)?.apiKey.trim() ?? "";
9386
+ /** Apply a path-prefix mapping (arr path → local path). A path outside the prefix is returned unchanged. */
9387
+ function mapPath(path, from, to) {
9388
+ if (from === "" || to === "") return path;
9389
+ const prefix = from.replace(/\/+$/, "");
9390
+ if (path === prefix) return to.replace(/\/+$/, "");
9391
+ if (path.startsWith(`${prefix}/`)) return `${to.replace(/\/+$/, "")}${path.slice(prefix.length)}`;
9392
+ return path;
9450
9393
  }
9451
- var PROVIDERS_GUIDE_EN = "<p>Each online provider needs a key of your own account; no key ships with Dominevo. Titles and ids of your library are sent to a provider to look them up. A row that needs a key and has none is skipped.</p><ul><li><strong>TMDB</strong>: <a href=\"https://www.themoviedb.org/signup\">themoviedb.org</a>, then Settings, API: request a Developer key (personal use) and copy the <strong>API Read Access Token</strong> (the long one, not the short API Key).</li><li><strong>TheTVDB</strong>: <a href=\"https://thetvdb.com/\">thetvdb.com</a>, then your dashboard: create a v4 API key (free for personal use).</li><li><strong>OMDb</strong>: <a href=\"https://www.omdbapi.com/apikey.aspx\">omdbapi.com/apikey.aspx</a>: the free key allows 1,000 requests a day.</li><li><strong>Fanart.tv</strong>: <a href=\"https://fanart.tv/\">fanart.tv</a>, then your profile: copy the personal API key. It only adds posters and backgrounds.</li></ul>Local files, Sonarr and Radarr, TVmaze and AniList need no key.";
9452
- var MediaLibrarySettingsSchema = object({
9453
- seriesArrUrl: BaseUrlSchema.default(""),
9454
- seriesArrKey: string().default(""),
9455
- /** Where the series app sees the library, and where this node mounts it. */
9456
- seriesPathFrom: string().default(""),
9457
- seriesPathTo: string().default(""),
9458
- moviesArrUrl: BaseUrlSchema.default(""),
9459
- moviesArrKey: string().default(""),
9460
- moviesPathFrom: string().default(""),
9461
- moviesPathTo: string().default(""),
9462
- /** Plain folders walked for files the arr apps do not know, one absolute path per line. */
9463
- folderRoots: string().default(""),
9464
- rescanMinutes: number().int().min(0).default(60),
9465
- /** Scrub thumbnails, generated in the background with ffmpeg and cached under the addon's data dir. */
9466
- trickplay: boolean().default(true),
9467
- /** The metadata chain, one row per step in the order they answer; the first answer to a field wins (D1125). */
9468
- metadataProviders: array(MetadataProviderRowSchema).default(defaultProviderRows),
9469
- /** The Plex import (a one-shot, re-runnable action): the server, a token, and how paths and users line up. */
9470
- plexUrl: BaseUrlSchema.default(""),
9471
- plexToken: string().meta({ secret: true }).default(""),
9472
- plexPathFrom: string().default(""),
9473
- plexPathTo: string().default(""),
9474
- plexUserMap: string().default("")
9475
- });
9476
- /** A source is on only when both its URL and key are set; a half-filled one is off, not guessed. */
9477
- function resolveSources(settings) {
9478
- const pick = (baseUrl, apiKey, pathFrom, pathTo) => baseUrl === "" || apiKey === "" ? null : {
9479
- baseUrl,
9480
- apiKey,
9481
- pathFrom: pathFrom.trim(),
9482
- pathTo: pathTo.trim()
9483
- };
9394
+ function cleanName(raw) {
9395
+ return raw.replace(/[._]+/g, " ").replace(/\s+/g, " ").replace(/[\s-]+$/, "").trim();
9396
+ }
9397
+ /** Guess what a file nobody catalogued is, from its name: `Show.S01E02…` is an episode, anything else a movie. */
9398
+ function guessFromFilename(fileName, parentDir) {
9399
+ const base = fileName.replace(/\.[A-Za-z0-9]+$/, "");
9400
+ const episode = /^(.*?)[\s._-]*S(\d{1,2})E(\d{1,3})/i.exec(base);
9401
+ if (episode?.[2] !== void 0 && episode[3] !== void 0) {
9402
+ const named = cleanName(episode[1] ?? "");
9403
+ return {
9404
+ kind: "episode",
9405
+ title: named === "" ? cleanName(parentDir) : named,
9406
+ year: null,
9407
+ seasonNumber: Number(episode[2]),
9408
+ episodeNumber: Number(episode[3])
9409
+ };
9410
+ }
9411
+ const year = /[([.\s_-]((?:19|20)\d{2})[)\].\s_-]/.exec(`${base} `);
9412
+ const title = cleanName(year ? base.slice(0, year.index) : base);
9484
9413
  return {
9485
- series: pick(settings.seriesArrUrl, settings.seriesArrKey, settings.seriesPathFrom, settings.seriesPathTo),
9486
- movies: pick(settings.moviesArrUrl, settings.moviesArrKey, settings.moviesPathFrom, settings.moviesPathTo),
9487
- folderRoots: settings.folderRoots.split("\n").map((line) => line.trim()).filter((line) => line !== ""),
9488
- metadataSteps: resolveMetadataSteps(settings),
9489
- tmdbToken: keyOf(settings, "tmdb"),
9490
- tvdbApiKey: keyOf(settings, "tvdb"),
9491
- fanartApiKey: keyOf(settings, "fanart"),
9492
- omdbApiKey: keyOf(settings, "omdb")
9414
+ kind: "movie",
9415
+ title: title === "" ? cleanName(base) : title,
9416
+ year: year?.[1] !== void 0 ? Number(year[1]) : null,
9417
+ seasonNumber: null,
9418
+ episodeNumber: null
9493
9419
  };
9494
9420
  }
9495
- /** The import is configured only when both the server URL and the token are set. */
9496
- function resolvePlex(settings) {
9497
- if (settings.plexUrl === "" || settings.plexToken === "") return null;
9421
+ //#endregion
9422
+ //#region src/file-plane.ts
9423
+ /**
9424
+ * Parse one `Range: bytes=…` header against a file of `size` bytes. A header this server does not
9425
+ * understand, and a multi-range one, is served as the whole file (200), which RFC 9110 allows.
9426
+ */
9427
+ function parseRange(header, size) {
9428
+ if (header === void 0) return { kind: "full" };
9429
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
9430
+ if (match === null) return { kind: "full" };
9431
+ const [, first = "", last = ""] = match;
9432
+ if (first === "" && last === "") return { kind: "full" };
9433
+ if (first === "") {
9434
+ const suffix = Number(last);
9435
+ if (suffix === 0 || size === 0) return { kind: "unsatisfiable" };
9436
+ return {
9437
+ kind: "range",
9438
+ start: Math.max(0, size - suffix),
9439
+ end: size - 1
9440
+ };
9441
+ }
9442
+ const start = Number(first);
9443
+ if (start >= size) return { kind: "unsatisfiable" };
9444
+ const end = last === "" ? size - 1 : Math.min(Number(last), size - 1);
9445
+ if (end < start) return { kind: "full" };
9498
9446
  return {
9499
- baseUrl: settings.plexUrl,
9500
- token: settings.plexToken,
9501
- pathFrom: settings.plexPathFrom.trim(),
9502
- pathTo: settings.plexPathTo.trim(),
9503
- userMap: settings.plexUserMap
9504
- };
9505
- }
9506
- var MEDIA_LIBRARY_CLUSTER_SCHEMA = { sections: [
9507
- {
9508
- id: "series",
9509
- title: "Series source",
9510
- titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.title",
9511
- fields: [
9512
- {
9513
- type: "text",
9514
- key: "seriesArrUrl",
9515
- label: "Sonarr URL",
9516
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrUrl.label",
9517
- description: "Address of the series app, for example http://192.168.1.20:8989. Empty turns the source off.",
9518
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrUrl.description"
9519
- },
9520
- {
9521
- type: "password",
9522
- key: "seriesArrKey",
9523
- label: "Sonarr API key",
9524
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrKey.label"
9525
- },
9526
- {
9527
- type: "text",
9528
- key: "seriesPathFrom",
9529
- label: "Path in Sonarr",
9530
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathFrom.label",
9531
- description: "The library folder as the series app sees it, for example /tv.",
9532
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathFrom.description"
9533
- },
9534
- {
9535
- type: "text",
9536
- key: "seriesPathTo",
9537
- label: "Path on this hub",
9538
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathTo.label",
9539
- description: "Where the same folder is mounted on this hub.",
9540
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathTo.description"
9541
- }
9542
- ]
9543
- },
9544
- {
9545
- id: "movies",
9546
- title: "Movies source",
9547
- titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.title",
9548
- fields: [
9549
- {
9550
- type: "text",
9551
- key: "moviesArrUrl",
9552
- label: "Radarr URL",
9553
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrUrl.label",
9554
- description: "Address of the movies app, for example http://192.168.1.20:7878. Empty turns the source off.",
9555
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrUrl.description"
9556
- },
9557
- {
9558
- type: "password",
9559
- key: "moviesArrKey",
9560
- label: "Radarr API key",
9561
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrKey.label"
9562
- },
9563
- {
9564
- type: "text",
9565
- key: "moviesPathFrom",
9566
- label: "Path in Radarr",
9567
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathFrom.label",
9568
- description: "The library folder as the movies app sees it, for example /movies.",
9569
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathFrom.description"
9570
- },
9571
- {
9572
- type: "text",
9573
- key: "moviesPathTo",
9574
- label: "Path on this hub",
9575
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathTo.label",
9576
- description: "Where the same folder is mounted on this hub.",
9577
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathTo.description"
9578
- }
9579
- ]
9580
- },
9581
- {
9582
- id: "folders",
9583
- title: "Folders",
9584
- titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.title",
9585
- fields: [
9586
- {
9587
- type: "textarea",
9588
- key: "folderRoots",
9589
- label: "Folders to walk",
9590
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.label",
9591
- description: "One absolute path per line. Files the arr apps do not know are added from here.",
9592
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.description"
9593
- },
9594
- {
9595
- type: "number",
9596
- key: "rescanMinutes",
9597
- label: "Rescan every (minutes)",
9598
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.label",
9599
- description: "0 scans only when asked.",
9600
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
9601
- min: 0
9602
- },
9603
- {
9604
- type: "boolean",
9605
- key: "trickplay",
9606
- label: "Scrub thumbnails",
9607
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.label",
9608
- description: "Generate preview pictures for the seek bar in the background, one ffmpeg at a time at low priority.",
9609
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.description"
9610
- }
9611
- ]
9612
- },
9613
- {
9614
- id: "metadata",
9615
- title: "Metadata",
9616
- titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.title",
9617
- fields: [{
9618
- type: "info",
9619
- key: "providersGuide",
9620
- label: "How to get the keys",
9621
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.providersGuide.label",
9622
- format: "html",
9623
- content: PROVIDERS_GUIDE_EN,
9624
- contentKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.providersGuide.content"
9625
- }, {
9626
- type: "editable-array",
9627
- key: "metadataProviders",
9628
- label: "Metadata providers",
9629
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.label",
9630
- description: "Asked from the top down: the first answer to a field wins. Move a row to change the order. A provider that needs a key and has none is skipped.",
9631
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.description",
9632
- default: defaultProviderRows(),
9633
- reorderable: true,
9634
- fixedRows: true,
9635
- itemIdKey: "id",
9636
- rowTitleTemplate: "{name}",
9637
- itemFields: [
9638
- {
9639
- type: "text",
9640
- key: "id",
9641
- label: "Provider",
9642
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.id.label",
9643
- showWhen: {
9644
- field: "id",
9645
- equals: ""
9646
- }
9647
- },
9648
- {
9649
- type: "text",
9650
- key: "name",
9651
- label: "Name",
9652
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.name.label",
9653
- showWhen: {
9654
- field: "id",
9655
- equals: ""
9656
- }
9657
- },
9658
- {
9659
- type: "boolean",
9660
- key: "enabled",
9661
- label: "Use this provider",
9662
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.enabled.label"
9663
- },
9664
- {
9665
- type: "password",
9666
- key: "apiKey",
9667
- label: "API key or token",
9668
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.apiKey.label",
9669
- description: "The key of your own account, stored in the keychain. Without it this provider is skipped.",
9670
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.apiKey.description",
9671
- showWhen: {
9672
- field: "id",
9673
- in: [...KEYED_STEPS]
9674
- }
9675
- }
9676
- ]
9677
- }]
9678
- },
9679
- {
9680
- id: "plex",
9681
- title: "Import from Plex",
9682
- titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.title",
9683
- fields: [
9684
- {
9685
- type: "text",
9686
- key: "plexUrl",
9687
- label: "Plex server URL",
9688
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUrl.label",
9689
- description: "Address of the Plex Media Server, for example http://192.168.1.20:32400. Used only when you press Preview or Import: nothing is linked or kept in sync.",
9690
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUrl.description"
9691
- },
9692
- {
9693
- type: "password",
9694
- key: "plexToken",
9695
- label: "Plex token",
9696
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexToken.label",
9697
- description: "The server owner's X-Plex-Token. Stored in the keychain.",
9698
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexToken.description"
9699
- },
9700
- {
9701
- type: "text",
9702
- key: "plexPathFrom",
9703
- label: "Path in Plex",
9704
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathFrom.label",
9705
- description: "The library folder as Plex sees it, for example /data/movies. Used to match files by path when the ids do not match.",
9706
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathFrom.description"
9707
- },
9708
- {
9709
- type: "text",
9710
- key: "plexPathTo",
9711
- label: "Path on this hub",
9712
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathTo.label",
9713
- description: "Where the same folder is mounted on this hub.",
9714
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathTo.description"
9715
- },
9716
- {
9717
- type: "textarea",
9718
- key: "plexUserMap",
9719
- label: "Plex user to Dominevo user",
9720
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUserMap.label",
9721
- description: "One \"plexName = dominevoUsername\" per line. Without a line a Plex user is matched by username, title or email.",
9722
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUserMap.description"
9723
- },
9724
- {
9725
- type: "addon-action-button",
9726
- addonId: "media-library",
9727
- key: "__plex-import-preview",
9728
- label: "Preview the Plex import",
9729
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-preview.label",
9730
- description: "Reads Plex and works out what would be imported per user. Writes nothing. Save the settings first.",
9731
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-preview.description",
9732
- buttonLabel: "Preview",
9733
- action: "plexImportPreview",
9734
- successMessage: "{message}"
9735
- },
9736
- {
9737
- type: "addon-action-button",
9738
- addonId: "media-library",
9739
- key: "__plex-import-run",
9740
- label: "Import from Plex",
9741
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-run.label",
9742
- description: "Imports watched state, resume positions and Plex's TMDB/TVDB/IMDb ids. Safe to run again: a newer Dominevo position is never overwritten.",
9743
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-run.description",
9744
- buttonLabel: "Import",
9745
- action: "plexImportRun",
9746
- variant: "primary",
9747
- confirmMessage: "Import watch history and ids from Plex now?",
9748
- successMessage: "{message}"
9749
- }
9750
- ]
9751
- }
9752
- ] };
9753
- //#endregion
9754
- //#region src/settings-migration.ts
9755
- /** The settings the provider list replaced; stored by installations that saved before it. */
9756
- var LEGACY_PROVIDER_KEYS = [
9757
- "metadataOrder",
9758
- "metadataLocalEnabled",
9759
- "metadataArrEnabled",
9760
- "metadataTvmazeEnabled",
9761
- "metadataAnilistEnabled",
9762
- "tmdbToken",
9763
- "tvdbApiKey",
9764
- "omdbApiKey",
9765
- "fanartApiKey"
9766
- ];
9767
- /** The old keys that held a credential. */
9768
- var LEGACY_SECRET_KEYS = [
9769
- "tmdbToken",
9770
- "tvdbApiKey",
9771
- "omdbApiKey",
9772
- "fanartApiKey"
9773
- ];
9774
- var LEGACY_KEY_OF_STEP = {
9775
- tmdb: "tmdbToken",
9776
- tvdb: "tvdbApiKey",
9777
- omdb: "omdbApiKey",
9778
- fanart: "fanartApiKey"
9779
- };
9780
- /** Orders saved by the defaults of earlier versions (TVmaze first, with or without TMDB): they mean "the default". */
9781
- var LEGACY_DEFAULT_ORDER = /^local[\s,]+arr[\s,]+tvmaze(?:[\s,]+tmdb)?$/i;
9782
- function text$4(value) {
9783
- return typeof value === "string" ? value : "";
9784
- }
9785
- function flag(value, fallback) {
9786
- return typeof value === "boolean" ? value : fallback;
9787
- }
9788
- /** The old order, then every step it left out (those were off). */
9789
- function legacyOrder(raw) {
9790
- const trimmed = raw.trim();
9791
- if (trimmed === "" || LEGACY_DEFAULT_ORDER.test(trimmed)) return {
9792
- order: [...DEFAULT_METADATA_ORDER],
9793
- named: new Set(DEFAULT_METADATA_ORDER)
9794
- };
9795
- const named = /* @__PURE__ */ new Set();
9796
- const order = [];
9797
- for (const name of trimmed.split(/[\s,]+/)) {
9798
- const step = name.toLowerCase();
9799
- if (isStep(step) && !named.has(step)) {
9800
- named.add(step);
9801
- order.push(step);
9802
- }
9803
- }
9804
- for (const step of DEFAULT_METADATA_ORDER) if (!named.has(step)) order.push(step);
9805
- return {
9806
- order,
9807
- named
9808
- };
9809
- }
9810
- function hasLegacyProviderKeys(stored) {
9811
- return LEGACY_PROVIDER_KEYS.some((key) => stored[key] !== void 0);
9812
- }
9813
- /**
9814
- * The provider list the old settings meant. `stored` holds RESOLVED values (the keys are plain
9815
- * strings here, moved on into the keychain by the write that stores the rows). A step the old
9816
- * order did not name is off, as it was; a keyed step is on when its key was set.
9817
- */
9818
- function providerRowsFromLegacy(stored) {
9819
- const { order, named } = legacyOrder(text$4(stored["metadataOrder"]));
9820
- const flags = {
9821
- local: flag(stored["metadataLocalEnabled"], true),
9822
- arr: flag(stored["metadataArrEnabled"], true),
9823
- tvmaze: flag(stored["metadataTvmazeEnabled"], true),
9824
- anilist: flag(stored["metadataAnilistEnabled"], false)
9825
- };
9826
- return order.map((step) => {
9827
- if (step === "local" || step === "arr" || step === "tvmaze" || step === "anilist") return providerRow(step, { enabled: named.has(step) && flags[step] });
9828
- const apiKey = text$4(stored[LEGACY_KEY_OF_STEP[step]]);
9829
- return providerRow(step, {
9830
- enabled: named.has(step) && apiKey !== "",
9831
- apiKey
9832
- });
9833
- });
9834
- }
9835
- /** The old secret key a step's row replaced. */
9836
- function legacyKeyOfStep(step) {
9837
- return isStep(step) && isKeyedStep(step) ? LEGACY_KEY_OF_STEP[step] : void 0;
9838
- }
9839
- /** Whether the stored row of the step `legacyKey` belonged to holds a key (a marker counts). */
9840
- function rowHoldsKey(rows, legacyKey) {
9841
- return rows.some((row) => legacyKeyOfStep(row.id) === legacyKey && row.apiKey.trim() !== "");
9842
- }
9843
- /** A stored list whose keyed row is empty takes the old key of that step; nothing else changes. */
9844
- function fillMissingKeys(rows, stored) {
9845
- return rows.map((row) => {
9846
- const legacy = legacyKeyOfStep(row.id);
9847
- const key = legacy === void 0 ? "" : text$4(stored[legacy]);
9848
- return row.apiKey.trim() === "" && key !== "" ? {
9849
- ...row,
9850
- apiKey: key
9851
- } : row;
9852
- });
9853
- }
9854
- //#endregion
9855
- //#region src/servable.ts
9856
- /**
9857
- * A file is servable only when its REAL path (symlinks resolved) is inside a configured root.
9858
- * The path itself comes from the catalogue by item id; this is the second lock on the same door,
9859
- * so a catalogue row that names `/etc/passwd`, or a symlink that points out of the library, serves nothing.
9860
- */
9861
- async function resolveServable(path, roots) {
9862
- if (!isAbsolute(path) || path.includes("\0")) return null;
9863
- let real;
9864
- try {
9865
- real = await realpath(path);
9866
- } catch {
9867
- return null;
9868
- }
9869
- for (const root of roots) {
9870
- if (root === "") continue;
9871
- let realRoot;
9872
- try {
9873
- realRoot = await realpath(root);
9874
- } catch {
9875
- continue;
9876
- }
9877
- const prefix = realRoot.endsWith(sep) ? realRoot : `${realRoot}${sep}`;
9878
- if (real.startsWith(prefix)) return real;
9879
- }
9880
- return null;
9881
- }
9882
- //#endregion
9883
- //#region src/naming.ts
9884
- /** Case- and accent-insensitive form of a title, for search and ordering. */
9885
- function foldTitle(title) {
9886
- return title.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().trim();
9887
- }
9888
- /** The ordering key: the folded title without a leading article. */
9889
- function sortKey(title) {
9890
- return foldTitle(title).replace(/^(the|a|an|il|lo|la|le|i|gli|un|una)\s+/, "");
9891
- }
9892
- /** A stable short id for a thing that has no id of its own (a folder-found file or show). */
9893
- function hashKey(text) {
9894
- return createHash("sha1").update(text).digest("hex").slice(0, 16);
9895
- }
9896
- function itemId(sourceId, letter, key) {
9897
- return `${sourceId}:${letter}:${key}`;
9898
- }
9899
- var ID_PATTERN = /^[a-z-]+:[sme]:[A-Za-z0-9]+$/;
9900
- /** An item id as a client may send it: the shape this module mints, nothing else. */
9901
- function isItemId(candidate) {
9902
- return ID_PATTERN.test(candidate);
9903
- }
9904
- /** Apply a path-prefix mapping (arr path → local path). A path outside the prefix is returned unchanged. */
9905
- function mapPath(path, from, to) {
9906
- if (from === "" || to === "") return path;
9907
- const prefix = from.replace(/\/+$/, "");
9908
- if (path === prefix) return to.replace(/\/+$/, "");
9909
- if (path.startsWith(`${prefix}/`)) return `${to.replace(/\/+$/, "")}${path.slice(prefix.length)}`;
9910
- return path;
9911
- }
9912
- function cleanName(raw) {
9913
- return raw.replace(/[._]+/g, " ").replace(/\s+/g, " ").replace(/[\s-]+$/, "").trim();
9914
- }
9915
- /** Guess what a file nobody catalogued is, from its name: `Show.S01E02…` is an episode, anything else a movie. */
9916
- function guessFromFilename(fileName, parentDir) {
9917
- const base = fileName.replace(/\.[A-Za-z0-9]+$/, "");
9918
- const episode = /^(.*?)[\s._-]*S(\d{1,2})E(\d{1,3})/i.exec(base);
9919
- if (episode?.[2] !== void 0 && episode[3] !== void 0) {
9920
- const named = cleanName(episode[1] ?? "");
9921
- return {
9922
- kind: "episode",
9923
- title: named === "" ? cleanName(parentDir) : named,
9924
- year: null,
9925
- seasonNumber: Number(episode[2]),
9926
- episodeNumber: Number(episode[3])
9927
- };
9928
- }
9929
- const year = /[([.\s_-]((?:19|20)\d{2})[)\].\s_-]/.exec(`${base} `);
9930
- const title = cleanName(year ? base.slice(0, year.index) : base);
9931
- return {
9932
- kind: "movie",
9933
- title: title === "" ? cleanName(base) : title,
9934
- year: year?.[1] !== void 0 ? Number(year[1]) : null,
9935
- seasonNumber: null,
9936
- episodeNumber: null
9937
- };
9938
- }
9939
- //#endregion
9940
- //#region src/file-plane.ts
9941
- /**
9942
- * Parse one `Range: bytes=…` header against a file of `size` bytes. A header this server does not
9943
- * understand, and a multi-range one, is served as the whole file (200), which RFC 9110 allows.
9944
- */
9945
- function parseRange(header, size) {
9946
- if (header === void 0) return { kind: "full" };
9947
- const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
9948
- if (match === null) return { kind: "full" };
9949
- const [, first = "", last = ""] = match;
9950
- if (first === "" && last === "") return { kind: "full" };
9951
- if (first === "") {
9952
- const suffix = Number(last);
9953
- if (suffix === 0 || size === 0) return { kind: "unsatisfiable" };
9954
- return {
9955
- kind: "range",
9956
- start: Math.max(0, size - suffix),
9957
- end: size - 1
9958
- };
9959
- }
9960
- const start = Number(first);
9961
- if (start >= size) return { kind: "unsatisfiable" };
9962
- const end = last === "" ? size - 1 : Math.min(Number(last), size - 1);
9963
- if (end < start) return { kind: "full" };
9964
- return {
9965
- kind: "range",
9966
- start,
9967
- end
9447
+ kind: "range",
9448
+ start,
9449
+ end
9968
9450
  };
9969
9451
  }
9970
9452
  var CONTENT_TYPES = new Map([
@@ -14021,702 +13503,1110 @@ function createTmdbProvider(deps) {
14021
13503
  return hit === void 0 ? null : detailsOf(kind, hit.id);
14022
13504
  },
14023
13505
  async lookup(kind, ids) {
14024
- if (ids.tmdbId !== null) return detailsOf(kind, ids.tmdbId);
14025
- const external = ids.imdbId !== null ? {
14026
- source: "imdb_id",
14027
- value: ids.imdbId
14028
- } : ids.tvdbId !== null ? {
14029
- source: "tvdb_id",
14030
- value: String(ids.tvdbId)
14031
- } : null;
13506
+ if (ids.tmdbId !== null) return detailsOf(kind, ids.tmdbId);
13507
+ const external = ids.imdbId !== null ? {
13508
+ source: "imdb_id",
13509
+ value: ids.imdbId
13510
+ } : ids.tvdbId !== null ? {
13511
+ source: "tvdb_id",
13512
+ value: String(ids.tvdbId)
13513
+ } : null;
13514
+ if (external === null) return null;
13515
+ const found = FindSchema.parse(await call(`/find/${encodeURIComponent(external.value)}`, { external_source: external.source }));
13516
+ const id = (kind === "movie" ? found.movie_results : found.tv_results)[0]?.id;
13517
+ return id === void 0 ? null : detailsOf(kind, id);
13518
+ },
13519
+ async episodes(match) {
13520
+ const base = `/tv/${encodeURIComponent(match.remoteId)}`;
13521
+ const show = DetailsSchema.parse(await call(base));
13522
+ const out = [];
13523
+ for (const season of show.seasons ?? []) {
13524
+ const list = SeasonSchema.parse(await call(`${base}/season/${season.season_number}`));
13525
+ for (const entry of list.episodes) out.push({
13526
+ season: entry.season_number,
13527
+ episode: entry.episode_number,
13528
+ title: text(entry.name),
13529
+ overview: text(entry.overview),
13530
+ still: image("w300", entry.still_path),
13531
+ details: {
13532
+ genres: {},
13533
+ runtimeMinutes: positive(entry.runtime),
13534
+ certification: null,
13535
+ creators: [],
13536
+ directors: personsOf(entry.crew, DIRECTOR_JOBS),
13537
+ writers: personsOf(entry.crew, WRITER_JOBS),
13538
+ cast: [],
13539
+ guestStars: castOf(entry.guest_stars)
13540
+ }
13541
+ });
13542
+ }
13543
+ return out;
13544
+ }
13545
+ };
13546
+ }
13547
+ //#endregion
13548
+ //#region src/tvdb.ts
13549
+ var TVDB_ID = "tvdb";
13550
+ var API$1 = "https://api4.thetvdb.com/v4";
13551
+ /** Said once per scan, never with the key. */
13552
+ var TVDB_REJECTED = "TheTVDB key rejected: check the API key in the settings";
13553
+ /** Artwork type ids: series poster / background, movie poster / background. */
13554
+ var ARTWORK = {
13555
+ series: {
13556
+ poster: 2,
13557
+ fanart: 3
13558
+ },
13559
+ movie: {
13560
+ poster: 14,
13561
+ fanart: 15
13562
+ }
13563
+ };
13564
+ var MAX_EPISODE_PAGES = 50;
13565
+ /** The login answer; the bearer is read by name below, it is a response, not a setting. */
13566
+ var LoginSchema = object({ data: record(string(), string()) });
13567
+ var SearchSchema$1 = object({ data: array(object({
13568
+ tvdb_id: union([string(), number()]),
13569
+ name: string().nullish(),
13570
+ year: union([string(), number()]).nullish()
13571
+ })).nullish() });
13572
+ var RemoteIdSchema = object({
13573
+ id: union([string(), number()]),
13574
+ sourceName: string()
13575
+ });
13576
+ var ExtendedSchema = object({ data: object({
13577
+ id: number().int(),
13578
+ name: string().nullish(),
13579
+ year: union([string(), number()]).nullish(),
13580
+ firstAired: string().nullish(),
13581
+ overview: string().nullish(),
13582
+ image: string().nullish(),
13583
+ remoteIds: array(RemoteIdSchema).nullish(),
13584
+ artworks: array(object({
13585
+ image: string(),
13586
+ type: number().int(),
13587
+ score: number().nullish()
13588
+ })).nullish()
13589
+ }) });
13590
+ var RemoteSearchSchema = object({ data: array(object({
13591
+ series: object({ id: number().int() }).nullish(),
13592
+ movie: object({ id: number().int() }).nullish()
13593
+ })).nullish() });
13594
+ var EpisodesSchema = object({
13595
+ data: object({ episodes: array(object({
13596
+ seasonNumber: number().int(),
13597
+ number: number().int(),
13598
+ name: string().nullish(),
13599
+ overview: string().nullish(),
13600
+ image: string().nullish()
13601
+ })) }),
13602
+ links: object({ next: number().int().nullish() }).nullish()
13603
+ });
13604
+ function bestArtwork(extended, type) {
13605
+ return (extended.artworks ?? []).filter((art) => art.type === type).sort((a, b) => (b.score ?? 0) - (a.score ?? 0))[0]?.image ?? null;
13606
+ }
13607
+ function remoteId(extended, source) {
13608
+ return extended.remoteIds?.find((entry) => source.test(entry.sourceName))?.id.toString() ?? null;
13609
+ }
13610
+ /** TheTVDB v4: series and movies; a bearer token from the key is held for the provider's lifetime. */
13611
+ function createTvdbProvider(deps) {
13612
+ let token = null;
13613
+ const login = async () => {
13614
+ try {
13615
+ const bytes = await deps.fetch(`${API$1}/login`, {
13616
+ headers: {
13617
+ "Content-Type": "application/json",
13618
+ Accept: "application/json"
13619
+ },
13620
+ body: JSON.stringify({ apikey: deps.apiKey })
13621
+ });
13622
+ const bearer = LoginSchema.parse(JSON.parse(bytes.toString("utf8"))).data["token"];
13623
+ if (bearer === void 0) throw new Error("TheTVDB login answered without a bearer");
13624
+ token = bearer;
13625
+ return bearer;
13626
+ } catch (error) {
13627
+ if (isHttp(error, 401)) throw new ProviderAuthError(TVDB_REJECTED);
13628
+ throw error;
13629
+ }
13630
+ };
13631
+ const call = async (path, query = {}) => {
13632
+ const params = new URLSearchParams(query).toString();
13633
+ const url = `${API$1}${path}${params === "" ? "" : `?${params}`}`;
13634
+ const send = async (bearer) => JSON.parse((await deps.fetch(url, { headers: {
13635
+ Authorization: `Bearer ${bearer}`,
13636
+ Accept: "application/json"
13637
+ } })).toString("utf8"));
13638
+ try {
13639
+ return await send(token ?? await login());
13640
+ } catch (error) {
13641
+ if (!isHttp(error, 401)) throw error;
13642
+ }
13643
+ try {
13644
+ return await send(await login());
13645
+ } catch (error) {
13646
+ if (isHttp(error, 401)) throw new ProviderAuthError(TVDB_REJECTED);
13647
+ throw error;
13648
+ }
13649
+ };
13650
+ const extendedPath = (kind, id) => `/${kind === "movie" ? "movies" : "series"}/${id}/extended`;
13651
+ const detailsOf = async (kind, id) => {
13652
+ try {
13653
+ const { data } = ExtendedSchema.parse(await call(extendedPath(kind, id)));
13654
+ const imdb = remoteId(data, /imdb/i);
13655
+ const tmdb = remoteId(data, /themoviedb|tmdb/i);
13656
+ return {
13657
+ providerId: TVDB_ID,
13658
+ remoteId: String(data.id),
13659
+ title: data.name ?? "",
13660
+ year: yearOf$2(data.year) ?? yearOf$2(data.firstAired),
13661
+ overview: text$1(data.overview),
13662
+ tvdbId: data.id,
13663
+ tmdbId: tmdb === null || !/^\d+$/.test(tmdb) ? null : Number(tmdb),
13664
+ imdbId: imdb,
13665
+ poster: bestArtwork(data, ARTWORK[kind].poster) ?? text$1(data.image),
13666
+ fanart: bestArtwork(data, ARTWORK[kind].fanart)
13667
+ };
13668
+ } catch (error) {
13669
+ if (isHttp(error, 404)) return null;
13670
+ throw error;
13671
+ }
13672
+ };
13673
+ return {
13674
+ id: TVDB_ID,
13675
+ kinds: ["movie", "series"],
13676
+ lookupBy: [
13677
+ "tvdbId",
13678
+ "imdbId",
13679
+ "tmdbId"
13680
+ ],
13681
+ async identify(kind, title, year) {
13682
+ const exact = (SearchSchema$1.parse(await call("/search", {
13683
+ query: title,
13684
+ type: kind,
13685
+ ...year === null ? {} : { year: String(year) }
13686
+ })).data ?? []).filter((entry) => foldTitle(entry.name ?? "") === foldTitle(title));
13687
+ const sameYear = year === null ? [] : exact.filter((entry) => yearOf$2(entry.year) === year);
13688
+ const ids = new Set((sameYear.length > 0 ? sameYear : exact).map((entry) => Number(entry.tvdb_id)));
13689
+ const [id] = [...ids];
13690
+ return ids.size === 1 && id !== void 0 && Number.isInteger(id) ? detailsOf(kind, id) : null;
13691
+ },
13692
+ async lookup(kind, ids) {
13693
+ if (ids.tvdbId !== null) return detailsOf(kind, ids.tvdbId);
13694
+ const external = ids.imdbId ?? (ids.tmdbId === null ? null : String(ids.tmdbId));
14032
13695
  if (external === null) return null;
14033
- const found = FindSchema.parse(await call(`/find/${encodeURIComponent(external.value)}`, { external_source: external.source }));
14034
- const id = (kind === "movie" ? found.movie_results : found.tv_results)[0]?.id;
14035
- return id === void 0 ? null : detailsOf(kind, id);
13696
+ let found;
13697
+ try {
13698
+ found = RemoteSearchSchema.parse(await call(`/search/remoteid/${encodeURIComponent(external)}`));
13699
+ } catch (error) {
13700
+ if (isHttp(error, 404)) return null;
13701
+ throw error;
13702
+ }
13703
+ const hit = (found.data ?? []).map((entry) => kind === "movie" ? entry.movie : entry.series).find((entry) => entry !== null && entry !== void 0);
13704
+ return hit === void 0 || hit === null ? null : detailsOf(kind, hit.id);
14036
13705
  },
14037
13706
  async episodes(match) {
14038
- const base = `/tv/${encodeURIComponent(match.remoteId)}`;
14039
- const show = DetailsSchema.parse(await call(base));
14040
13707
  const out = [];
14041
- for (const season of show.seasons ?? []) {
14042
- const list = SeasonSchema.parse(await call(`${base}/season/${season.season_number}`));
14043
- for (const entry of list.episodes) out.push({
14044
- season: entry.season_number,
14045
- episode: entry.episode_number,
14046
- title: text(entry.name),
14047
- overview: text(entry.overview),
14048
- still: image("w300", entry.still_path),
14049
- details: {
14050
- genres: {},
14051
- runtimeMinutes: positive(entry.runtime),
14052
- certification: null,
14053
- creators: [],
14054
- directors: personsOf(entry.crew, DIRECTOR_JOBS),
14055
- writers: personsOf(entry.crew, WRITER_JOBS),
14056
- cast: [],
14057
- guestStars: castOf(entry.guest_stars)
14058
- }
13708
+ let page = 0;
13709
+ for (let guard = 0; page !== null && guard < MAX_EPISODE_PAGES; guard += 1) {
13710
+ const list = EpisodesSchema.parse(await call(`/series/${encodeURIComponent(match.remoteId)}/episodes/default`, { page: String(page) }));
13711
+ for (const entry of list.data.episodes) out.push({
13712
+ season: entry.seasonNumber,
13713
+ episode: entry.number,
13714
+ title: text$1(entry.name),
13715
+ overview: text$1(entry.overview),
13716
+ still: text$1(entry.image)
14059
13717
  });
13718
+ page = list.links?.next ?? null;
14060
13719
  }
14061
13720
  return out;
14062
13721
  }
14063
13722
  };
14064
13723
  }
14065
13724
  //#endregion
14066
- //#region src/tvdb.ts
14067
- var TVDB_ID = "tvdb";
14068
- var API$1 = "https://api4.thetvdb.com/v4";
14069
- /** Said once per scan, never with the key. */
14070
- var TVDB_REJECTED = "TheTVDB key rejected: check the API key in the settings";
14071
- /** Artwork type ids: series poster / background, movie poster / background. */
14072
- var ARTWORK = {
14073
- series: {
14074
- poster: 2,
14075
- fanart: 3
14076
- },
14077
- movie: {
14078
- poster: 14,
14079
- fanart: 15
14080
- }
14081
- };
14082
- var MAX_EPISODE_PAGES = 50;
14083
- /** The login answer; the bearer is read by name below, it is a response, not a setting. */
14084
- var LoginSchema = object({ data: record(string(), string()) });
14085
- var SearchSchema$1 = object({ data: array(object({
14086
- tvdb_id: union([string(), number()]),
14087
- name: string().nullish(),
14088
- year: union([string(), number()]).nullish()
14089
- })).nullish() });
14090
- var RemoteIdSchema = object({
14091
- id: union([string(), number()]),
14092
- sourceName: string()
14093
- });
14094
- var ExtendedSchema = object({ data: object({
13725
+ //#region src/tvmaze.ts
13726
+ var TVMAZE_ID = "tvmaze";
13727
+ var API = "https://api.tvmaze.com";
13728
+ var ImageSchema = object({
13729
+ medium: string().nullish(),
13730
+ original: string().nullish()
13731
+ }).nullish();
13732
+ var ShowSchema = object({
14095
13733
  id: number().int(),
13734
+ name: string(),
13735
+ premiered: string().nullish(),
13736
+ summary: string().nullish(),
13737
+ image: ImageSchema,
13738
+ externals: object({
13739
+ thetvdb: number().int().nullish(),
13740
+ imdb: string().nullish()
13741
+ }).nullish()
13742
+ });
13743
+ var SearchSchema = array(object({
13744
+ score: number(),
13745
+ show: ShowSchema
13746
+ }));
13747
+ var EpisodeSchema = object({
14096
13748
  name: string().nullish(),
14097
- year: union([string(), number()]).nullish(),
14098
- firstAired: string().nullish(),
14099
- overview: string().nullish(),
14100
- image: string().nullish(),
14101
- remoteIds: array(RemoteIdSchema).nullish(),
14102
- artworks: array(object({
14103
- image: string(),
14104
- type: number().int(),
14105
- score: number().nullish()
14106
- })).nullish()
14107
- }) });
14108
- var RemoteSearchSchema = object({ data: array(object({
14109
- series: object({ id: number().int() }).nullish(),
14110
- movie: object({ id: number().int() }).nullish()
14111
- })).nullish() });
14112
- var EpisodesSchema = object({
14113
- data: object({ episodes: array(object({
14114
- seasonNumber: number().int(),
14115
- number: number().int(),
14116
- name: string().nullish(),
14117
- overview: string().nullish(),
14118
- image: string().nullish()
14119
- })) }),
14120
- links: object({ next: number().int().nullish() }).nullish()
13749
+ season: number().int(),
13750
+ number: number().int().nullish(),
13751
+ summary: string().nullish(),
13752
+ image: ImageSchema
14121
13753
  });
14122
- function bestArtwork(extended, type) {
14123
- return (extended.artworks ?? []).filter((art) => art.type === type).sort((a, b) => (b.score ?? 0) - (a.score ?? 0))[0]?.image ?? null;
13754
+ /** The summary field is HTML; keep the text. */
13755
+ function plain(html) {
13756
+ if (html === null || html === void 0) return null;
13757
+ const text = html.replace(/<[^>]*>/g, " ").replace(/&#(\d{1,6});|&#x([0-9a-f]{1,6});/gi, (_whole, dec, hex) => {
13758
+ const code = typeof dec === "string" ? Number(dec) : Number.parseInt(String(hex), 16);
13759
+ return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : "";
13760
+ }).replace(/&apos;/g, "'").replace(/&quot;/g, "\"").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/\s+/g, " ").trim();
13761
+ return text === "" ? null : text;
13762
+ }
13763
+ function imageOf(image) {
13764
+ const url = image?.original ?? image?.medium ?? null;
13765
+ return url !== null && url.startsWith("https://") ? url : null;
13766
+ }
13767
+ function yearOf(premiered) {
13768
+ const match = /^(\d{4})/.exec(premiered ?? "");
13769
+ return match?.[1] === void 0 ? null : Number(match[1]);
13770
+ }
13771
+ /** TVmaze: keyless, series only. Every call goes through the shared remote fetch and one spaced queue. */
13772
+ function createTvmazeProvider(deps) {
13773
+ const sleep = deps.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
13774
+ const now = deps.now ?? Date.now;
13775
+ const gap = deps.minGapMs ?? 600;
13776
+ let tail = Promise.resolve();
13777
+ let lastCallAt = Number.NEGATIVE_INFINITY;
13778
+ const call = (path) => {
13779
+ const run = async () => {
13780
+ const wait = lastCallAt + gap - now();
13781
+ if (wait > 0) await sleep(wait);
13782
+ lastCallAt = now();
13783
+ const bytes = await deps.fetch(`${API}${path}`);
13784
+ return JSON.parse(bytes.toString("utf8"));
13785
+ };
13786
+ const result = tail.then(run, run);
13787
+ tail = result.catch(() => void 0);
13788
+ return result;
13789
+ };
13790
+ const matchOf = (show) => ({
13791
+ providerId: TVMAZE_ID,
13792
+ remoteId: String(show.id),
13793
+ title: show.name,
13794
+ year: yearOf(show.premiered),
13795
+ overview: plain(show.summary),
13796
+ tvdbId: show.externals?.thetvdb ?? null,
13797
+ tmdbId: null,
13798
+ imdbId: show.externals?.imdb ?? null,
13799
+ poster: imageOf(show.image),
13800
+ fanart: null
13801
+ });
13802
+ return {
13803
+ id: TVMAZE_ID,
13804
+ kinds: ["series"],
13805
+ async lookup(_kind, ids) {
13806
+ const query = ids.tvdbId !== null ? `thetvdb=${ids.tvdbId}` : ids.imdbId !== null ? `imdb=${encodeURIComponent(ids.imdbId)}` : null;
13807
+ if (query === null) return null;
13808
+ try {
13809
+ return matchOf(ShowSchema.parse(await call(`/lookup/shows?${query}`)));
13810
+ } catch (error) {
13811
+ if (error instanceof Error && /\b404\b/.test(error.message)) return null;
13812
+ throw error;
13813
+ }
13814
+ },
13815
+ async identify(_kind, title, year) {
13816
+ const found = SearchSchema.parse(await call(`/search/shows?q=${encodeURIComponent(title)}`));
13817
+ const sameYear = year === null ? void 0 : found.find((entry) => yearOf(entry.show.premiered) === year);
13818
+ const top = found[0];
13819
+ const hit = sameYear ?? (year === null || top !== void 0 && foldTitle(top.show.name) === foldTitle(title) ? top : void 0);
13820
+ if (hit === void 0) return null;
13821
+ const show = hit.show;
13822
+ return {
13823
+ providerId: TVMAZE_ID,
13824
+ remoteId: String(show.id),
13825
+ title: show.name,
13826
+ year: yearOf(show.premiered),
13827
+ overview: plain(show.summary),
13828
+ tvdbId: show.externals?.thetvdb ?? null,
13829
+ tmdbId: null,
13830
+ imdbId: show.externals?.imdb ?? null,
13831
+ poster: imageOf(show.image),
13832
+ fanart: null
13833
+ };
13834
+ },
13835
+ async episodes(match) {
13836
+ return array(EpisodeSchema).parse(await call(`/shows/${encodeURIComponent(match.remoteId)}/episodes?specials=1`)).flatMap((entry) => entry.number === null || entry.number === void 0 ? [] : [{
13837
+ season: entry.season,
13838
+ episode: entry.number,
13839
+ title: entry.name ?? null,
13840
+ overview: plain(entry.summary),
13841
+ still: imageOf(entry.image)
13842
+ }]);
13843
+ }
13844
+ };
13845
+ }
13846
+ //#endregion
13847
+ //#region src/img-plane.ts
13848
+ var FAILED_GRAB_TTL_MS = 30 * 6e4;
13849
+ var FAILED_GRAB_MAX = 500;
13850
+ /** The real fetch: the key travels in a header, a redirect is never followed, the body is size-capped as it streams. */
13851
+ var httpImageFetch = async (url, apiKey) => {
13852
+ const response = await fetch(url, {
13853
+ headers: { "X-Api-Key": apiKey },
13854
+ redirect: "manual",
13855
+ signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
13856
+ });
13857
+ if (response.status >= 300 && response.status < 400) throw new Error(`redirect refused (HTTP ${response.status}): the key is never sent to another URL`);
13858
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
13859
+ return readCapped(response, MAX_IMAGE_BYTES);
13860
+ };
13861
+ function typeOf(bytes) {
13862
+ if (bytes.length > 3 && bytes[0] === 255 && bytes[1] === 216) return "image/jpeg";
13863
+ if (bytes.length > 8 && bytes.subarray(1, 4).toString("latin1") === "PNG") return "image/png";
13864
+ if (bytes.length > 12 && bytes.subarray(8, 12).toString("latin1") === "WEBP") return "image/webp";
13865
+ return null;
13866
+ }
13867
+ /**
13868
+ * The remote URL of an arr cover: a path on the arr's own origin, or an absolute URL that already
13869
+ * IS on that origin (the arr app answers plain http on a LAN). Never another host, port or scheme,
13870
+ * and never a URL that carries credentials.
13871
+ */
13872
+ function coverUrl(source, path) {
13873
+ if (/^https?:\/\//i.test(path)) {
13874
+ const absolute = URL.canParse(path) ? new URL(path) : null;
13875
+ const own = new URL(source.baseUrl);
13876
+ return absolute !== null && absolute.origin === own.origin && absolute.username === "" && absolute.password === "" ? absolute.toString() : null;
13877
+ }
13878
+ if (!path.startsWith("/") || path.startsWith("//")) return null;
13879
+ const base = new URL(source.baseUrl);
13880
+ const url = new URL(`${source.baseUrl}${path}`);
13881
+ return url.origin === base.origin ? url.toString() : null;
14124
13882
  }
14125
- function remoteId(extended, source) {
14126
- return extended.remoteIds?.find((entry) => source.test(entry.sourceName))?.id.toString() ?? null;
13883
+ function end(res, status) {
13884
+ res.writeHead(status, { "Content-Length": 0 });
13885
+ res.end();
14127
13886
  }
14128
- /** TheTVDB v4: series and movies; a bearer token from the key is held for the provider's lifetime. */
14129
- function createTvdbProvider(deps) {
14130
- let token = null;
14131
- const login = async () => {
14132
- try {
14133
- const bytes = await deps.fetch(`${API$1}/login`, {
14134
- headers: {
14135
- "Content-Type": "application/json",
14136
- Accept: "application/json"
14137
- },
14138
- body: JSON.stringify({ apikey: deps.apiKey })
13887
+ /** The `img` plane: `GET /<itemId>/poster|fanart`, fetched from the arr once and cached on disk. */
13888
+ function createImagePlaneHandler(deps) {
13889
+ const inFlight = /* @__PURE__ */ new Map();
13890
+ const now = deps.now ?? Date.now;
13891
+ /** key → when the failure is forgotten: a transient failure retries, and the set is bounded. */
13892
+ const failedGrabs = /* @__PURE__ */ new Map();
13893
+ const hasFailed = (key) => {
13894
+ const until = failedGrabs.get(key);
13895
+ if (until === void 0) return false;
13896
+ if (until > now()) return true;
13897
+ failedGrabs.delete(key);
13898
+ return false;
13899
+ };
13900
+ const rememberFailure = (key) => {
13901
+ failedGrabs.delete(key);
13902
+ failedGrabs.set(key, now() + FAILED_GRAB_TTL_MS);
13903
+ for (const oldest of failedGrabs.keys()) {
13904
+ if (failedGrabs.size <= FAILED_GRAB_MAX) break;
13905
+ failedGrabs.delete(oldest);
13906
+ }
13907
+ };
13908
+ const limitGrabs = createLimiter(deps.grabConcurrency ?? 2, deps.grabQueueLimit ?? 32);
13909
+ /** A sidecar image is read only from inside a configured root, symlinks resolved, and only up to the size cap. */
13910
+ const readLocal = async (path, tags) => {
13911
+ const real = await resolveServable(path, await deps.roots?.() ?? []);
13912
+ if (real === null) {
13913
+ deps.logger.warn("image refused: outside the configured folders", {
13914
+ tags,
13915
+ meta: { reason: "outside-roots" }
14139
13916
  });
14140
- const bearer = LoginSchema.parse(JSON.parse(bytes.toString("utf8"))).data["token"];
14141
- if (bearer === void 0) throw new Error("TheTVDB login answered without a bearer");
14142
- token = bearer;
14143
- return bearer;
14144
- } catch (error) {
14145
- if (isHttp(error, 401)) throw new ProviderAuthError(TVDB_REJECTED);
14146
- throw error;
13917
+ return null;
14147
13918
  }
13919
+ if ((await stat(real)).size > 10485760) throw new Error("image too large");
13920
+ return readFile(real);
14148
13921
  };
14149
- const call = async (path, query = {}) => {
14150
- const params = new URLSearchParams(query).toString();
14151
- const url = `${API$1}${path}${params === "" ? "" : `?${params}`}`;
14152
- const send = async (bearer) => JSON.parse((await deps.fetch(url, { headers: {
14153
- Authorization: `Bearer ${bearer}`,
14154
- Accept: "application/json"
14155
- } })).toString("utf8"));
14156
- try {
14157
- return await send(token ?? await login());
13922
+ const produce = async (found, tags) => {
13923
+ if (found.kind === "frame") return limitGrabs(() => deps.grabFrame(found.filePath, found.durationMs));
13924
+ if (found.kind === "remote") return deps.fetchRemote(found.url);
13925
+ const arr = await deps.arrSource(found.sourceId);
13926
+ const url = arr === null ? null : coverUrl(arr, found.path);
13927
+ if (arr === null || url === null) {
13928
+ deps.logger.warn("image skipped: no usable source", {
13929
+ tags,
13930
+ meta: { reason: arr === null ? "source-off" : "foreign-origin" }
13931
+ });
13932
+ return null;
13933
+ }
13934
+ return deps.fetchImage(url, arr.apiKey);
13935
+ };
13936
+ const load = async (itemId, which) => {
13937
+ for (const found of await deps.source(itemId, which)) {
13938
+ const bytes = await loadOne(itemId, which, found);
13939
+ if (bytes !== null) return bytes;
13940
+ }
13941
+ return null;
13942
+ };
13943
+ const loadOne = async (itemId, which, found) => {
13944
+ const tags = { itemId };
13945
+ const origin = found.kind === "arr" ? found.path : found.kind === "remote" ? found.url : found.kind === "local" ? found.path : `frame:${found.filePath}`;
13946
+ if (found.kind === "local") try {
13947
+ const bytes = await readLocal(found.path, tags);
13948
+ return bytes !== null && typeOf(bytes) !== null ? bytes : null;
14158
13949
  } catch (error) {
14159
- if (!isHttp(error, 401)) throw error;
13950
+ deps.logger.warn("image fetch failed", {
13951
+ tags,
13952
+ meta: {
13953
+ reason: "read-failed",
13954
+ error: error instanceof Error ? error.message : String(error)
13955
+ }
13956
+ });
13957
+ return null;
14160
13958
  }
13959
+ const key = hashKey(`${itemId}:${which}:${origin}`);
13960
+ if (hasFailed(key)) return null;
13961
+ const cached = join(deps.cacheDir, key);
14161
13962
  try {
14162
- return await send(await login());
13963
+ const onDisk = await readFile(cached);
13964
+ if (typeOf(onDisk) !== null) return onDisk;
13965
+ deps.logger.warn("cached image is not an image: dropped and fetched again", {
13966
+ tags,
13967
+ meta: { reason: "cache-corrupt" }
13968
+ });
13969
+ await unlink(cached);
13970
+ } catch {}
13971
+ try {
13972
+ const bytes = await produce(found, tags);
13973
+ if (bytes === null) return null;
13974
+ if (typeOf(bytes) === null) throw new Error("not an image");
13975
+ await mkdir(deps.cacheDir, { recursive: true });
13976
+ await writeFile(`${cached}.tmp`, bytes);
13977
+ await rename(`${cached}.tmp`, cached);
13978
+ return bytes;
14163
13979
  } catch (error) {
14164
- if (isHttp(error, 401)) throw new ProviderAuthError(TVDB_REJECTED);
14165
- throw error;
13980
+ if (error instanceof LimiterFullError) {
13981
+ deps.logger.warn("frame grab refused", {
13982
+ tags,
13983
+ meta: { reason: "queue-full" }
13984
+ });
13985
+ return null;
13986
+ }
13987
+ if (found.kind === "frame") rememberFailure(key);
13988
+ deps.logger.warn(found.kind === "frame" ? "frame grab failed" : "image fetch failed", {
13989
+ tags,
13990
+ meta: {
13991
+ reason: found.kind === "frame" ? "grab-failed" : "fetch-failed",
13992
+ error: error instanceof Error ? error.message : String(error)
13993
+ }
13994
+ });
13995
+ return null;
14166
13996
  }
14167
13997
  };
14168
- const extendedPath = (kind, id) => `/${kind === "movie" ? "movies" : "series"}/${id}/extended`;
14169
- const detailsOf = async (kind, id) => {
13998
+ return async (req, res) => {
13999
+ if (req.method !== "GET" && req.method !== "HEAD") return end(res, 405);
14000
+ const parts = ((req.url ?? "/").split("?")[0] ?? "/").replace(/^\//, "").split("/");
14001
+ const [rawId, which] = parts;
14002
+ let itemId = "";
14170
14003
  try {
14171
- const { data } = ExtendedSchema.parse(await call(extendedPath(kind, id)));
14172
- const imdb = remoteId(data, /imdb/i);
14173
- const tmdb = remoteId(data, /themoviedb|tmdb/i);
14174
- return {
14175
- providerId: TVDB_ID,
14176
- remoteId: String(data.id),
14177
- title: data.name ?? "",
14178
- year: yearOf$2(data.year) ?? yearOf$2(data.firstAired),
14179
- overview: text$1(data.overview),
14180
- tvdbId: data.id,
14181
- tmdbId: tmdb === null || !/^\d+$/.test(tmdb) ? null : Number(tmdb),
14182
- imdbId: imdb,
14183
- poster: bestArtwork(data, ARTWORK[kind].poster) ?? text$1(data.image),
14184
- fanart: bestArtwork(data, ARTWORK[kind].fanart)
14185
- };
14186
- } catch (error) {
14187
- if (isHttp(error, 404)) return null;
14188
- throw error;
14004
+ itemId = decodeURIComponent(rawId ?? "");
14005
+ } catch {
14006
+ return end(res, 404);
14189
14007
  }
14190
- };
14191
- return {
14192
- id: TVDB_ID,
14193
- kinds: ["movie", "series"],
14194
- lookupBy: [
14195
- "tvdbId",
14196
- "imdbId",
14197
- "tmdbId"
14198
- ],
14199
- async identify(kind, title, year) {
14200
- const exact = (SearchSchema$1.parse(await call("/search", {
14201
- query: title,
14202
- type: kind,
14203
- ...year === null ? {} : { year: String(year) }
14204
- })).data ?? []).filter((entry) => foldTitle(entry.name ?? "") === foldTitle(title));
14205
- const sameYear = year === null ? [] : exact.filter((entry) => yearOf$2(entry.year) === year);
14206
- const pool = sameYear.length > 0 ? sameYear : exact;
14207
- const ids = new Set(pool.map((entry) => Number(entry.tvdb_id)));
14208
- const [id] = [...ids];
14209
- return ids.size === 1 && id !== void 0 && Number.isInteger(id) ? detailsOf(kind, id) : null;
14210
- },
14211
- async lookup(kind, ids) {
14212
- if (ids.tvdbId !== null) return detailsOf(kind, ids.tvdbId);
14213
- const external = ids.imdbId ?? (ids.tmdbId === null ? null : String(ids.tmdbId));
14214
- if (external === null) return null;
14215
- let found;
14216
- try {
14217
- found = RemoteSearchSchema.parse(await call(`/search/remoteid/${encodeURIComponent(external)}`));
14218
- } catch (error) {
14219
- if (isHttp(error, 404)) return null;
14220
- throw error;
14221
- }
14222
- const hit = (found.data ?? []).map((entry) => kind === "movie" ? entry.movie : entry.series).find((entry) => entry !== null && entry !== void 0);
14223
- return hit === void 0 || hit === null ? null : detailsOf(kind, hit.id);
14224
- },
14225
- async episodes(match) {
14226
- const out = [];
14227
- let page = 0;
14228
- for (let guard = 0; page !== null && guard < MAX_EPISODE_PAGES; guard += 1) {
14229
- const list = EpisodesSchema.parse(await call(`/series/${encodeURIComponent(match.remoteId)}/episodes/default`, { page: String(page) }));
14230
- for (const entry of list.data.episodes) out.push({
14231
- season: entry.seasonNumber,
14232
- episode: entry.number,
14233
- title: text$1(entry.name),
14234
- overview: text$1(entry.overview),
14235
- still: text$1(entry.image)
14236
- });
14237
- page = list.links?.next ?? null;
14238
- }
14239
- return out;
14008
+ if (parts.length !== 2 || !isItemId(itemId) || !isImageKind(which)) {
14009
+ deps.logger.warn("image request refused", { meta: { reason: "bad-request" } });
14010
+ return end(res, 404);
14011
+ }
14012
+ const flightKey = `${itemId}:${which}`;
14013
+ const pending = inFlight.get(flightKey) ?? load(itemId, which);
14014
+ inFlight.set(flightKey, pending);
14015
+ let bytes;
14016
+ try {
14017
+ bytes = await pending;
14018
+ } finally {
14019
+ inFlight.delete(flightKey);
14240
14020
  }
14021
+ const contentType = bytes === null ? null : typeOf(bytes);
14022
+ if (bytes === null || contentType === null) return end(res, 404);
14023
+ res.writeHead(200, {
14024
+ "Content-Type": contentType,
14025
+ "Content-Length": bytes.length,
14026
+ "Cache-Control": "private, max-age=86400"
14027
+ });
14028
+ res.end(req.method === "HEAD" ? void 0 : bytes);
14241
14029
  };
14242
14030
  }
14243
- //#endregion
14244
- //#region src/tvmaze.ts
14245
- var TVMAZE_ID = "tvmaze";
14246
- var API = "https://api.tvmaze.com";
14247
- var ImageSchema = object({
14248
- medium: string().nullish(),
14249
- original: string().nullish()
14250
- }).nullish();
14251
- var ShowSchema = object({
14252
- id: number().int(),
14253
- name: string(),
14254
- premiered: string().nullish(),
14255
- summary: string().nullish(),
14256
- image: ImageSchema,
14257
- externals: object({
14258
- thetvdb: number().int().nullish(),
14259
- imdb: string().nullish()
14260
- }).nullish()
14261
- });
14262
- var SearchSchema = array(object({
14263
- score: number(),
14264
- show: ShowSchema
14265
- }));
14266
- var EpisodeSchema = object({
14267
- name: string().nullish(),
14268
- season: number().int(),
14269
- number: number().int().nullish(),
14270
- summary: string().nullish(),
14271
- image: ImageSchema
14272
- });
14273
- /** The summary field is HTML; keep the text. */
14274
- function plain(html) {
14275
- if (html === null || html === void 0) return null;
14276
- const text = html.replace(/<[^>]*>/g, " ").replace(/&#(\d{1,6});|&#x([0-9a-f]{1,6});/gi, (_whole, dec, hex) => {
14277
- const code = typeof dec === "string" ? Number(dec) : Number.parseInt(String(hex), 16);
14278
- return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : "";
14279
- }).replace(/&apos;/g, "'").replace(/&quot;/g, "\"").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/\s+/g, " ").trim();
14280
- return text === "" ? null : text;
14031
+ //#endregion
14032
+ //#region src/probe.ts
14033
+ var CONTAINER_NAMES = new Map([
14034
+ ["matroska", "mkv"],
14035
+ ["mov", "mp4"],
14036
+ ["avi", "avi"],
14037
+ ["mpegts", "ts"]
14038
+ ]);
14039
+ function containerOf(formats) {
14040
+ const first = formats.split(",")[0]?.trim() ?? formats;
14041
+ return CONTAINER_NAMES.get(first) ?? first;
14042
+ }
14043
+ function languageOf(tag) {
14044
+ if (tag === void 0 || tag === "" || tag === "und") return null;
14045
+ return tag;
14281
14046
  }
14282
- function imageOf(image) {
14283
- const url = image?.original ?? image?.medium ?? null;
14284
- return url !== null && url.startsWith("https://") ? url : null;
14047
+ function bitDepthOf(pixFmt) {
14048
+ if (pixFmt === null) return null;
14049
+ const match = /(?:p|le|be)(9|10|12|14|16)(?:le|be)?$/.exec(pixFmt);
14050
+ if (match?.[1] !== void 0) return Number(match[1]);
14051
+ return /^(yuv|nv|gray|rgb|bgr)/.test(pixFmt) ? 8 : null;
14285
14052
  }
14286
- function yearOf(premiered) {
14287
- const match = /^(\d{4})/.exec(premiered ?? "");
14288
- return match?.[1] === void 0 ? null : Number(match[1]);
14053
+ function hdrOf(line, doviSeen) {
14054
+ if (doviSeen) return "dolby-vision";
14055
+ if (line.includes("smpte2084")) return "hdr10";
14056
+ if (line.includes("arib-std-b67")) return "hlg";
14057
+ return null;
14289
14058
  }
14290
- /** TVmaze: keyless, series only. Every call goes through the shared remote fetch and one spaced queue. */
14291
- function createTvmazeProvider(deps) {
14292
- const sleep = deps.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
14293
- const now = deps.now ?? Date.now;
14294
- const gap = deps.minGapMs ?? 600;
14295
- let tail = Promise.resolve();
14296
- let lastCallAt = Number.NEGATIVE_INFINITY;
14297
- const call = (path) => {
14298
- const run = async () => {
14299
- const wait = lastCallAt + gap - now();
14300
- if (wait > 0) await sleep(wait);
14301
- lastCallAt = now();
14302
- const bytes = await deps.fetch(`${API}${path}`);
14303
- return JSON.parse(bytes.toString("utf8"));
14059
+ function channelsOf(line) {
14060
+ if (/\bmono\b/.test(line)) return 1;
14061
+ if (/\bstereo\b/.test(line)) return 2;
14062
+ const layout = /\b(\d)\.(\d)(?:\([a-z]+\))?/.exec(line);
14063
+ if (layout?.[1] !== void 0 && layout[2] !== void 0) return Number(layout[1]) + Number(layout[2]);
14064
+ const count = /\b(\d+) channels\b/.exec(line);
14065
+ return count?.[1] !== void 0 ? Number(count[1]) : null;
14066
+ }
14067
+ var STREAM_LINE = /^\s*Stream #\d+:(\d+)(?:\[[^\]]*\])?(?:\(([^)]*)\))?[^:]*: (Video|Audio|Subtitle): (.*)$/;
14068
+ var CHAPTER_LINE = /^\s*Chapter #\d+:\d+: start ([\d.]+), end ([\d.]+)/;
14069
+ var CHAPTER_TITLE = /^\s+title\s*:\s*(.*)$/;
14070
+ /** Parse the report `ffmpeg -i <file>` prints on stderr. A report that is not one yields no streams and no duration. */
14071
+ function parseFfmpegReport(report) {
14072
+ const lines = report.split("\n");
14073
+ let container = null;
14074
+ let durationMs = null;
14075
+ const streams = [];
14076
+ const chapters = [];
14077
+ let doviSeenFor = null;
14078
+ let inChapters = false;
14079
+ for (const line of lines) {
14080
+ const input = /^Input #\d+, ([^,]+(?:,[^,]+)*), from /.exec(line);
14081
+ if (input?.[1] !== void 0 && container === null) container = containerOf(input[1]);
14082
+ const duration = /^\s*Duration: (\d+):(\d{2}):(\d{2})\.(\d{2})/.exec(line);
14083
+ if (duration && durationMs === null) durationMs = (Number(duration[1]) * 3600 + Number(duration[2]) * 60 + Number(duration[3])) * 1e3 + Number(duration[4]) * 10;
14084
+ const chapter = CHAPTER_LINE.exec(line);
14085
+ if (chapter?.[1] !== void 0 && chapter[2] !== void 0) {
14086
+ const startSec = Number(chapter[1]);
14087
+ const endSec = Number(chapter[2]);
14088
+ if (Number.isFinite(startSec) && Number.isFinite(endSec) && endSec > startSec) chapters.push({
14089
+ startSec,
14090
+ endSec,
14091
+ title: null
14092
+ });
14093
+ continue;
14094
+ }
14095
+ const titled = CHAPTER_TITLE.exec(line);
14096
+ const last = chapters[chapters.length - 1];
14097
+ if (titled?.[1] !== void 0 && last !== void 0 && last.title === null && inChapters) {
14098
+ if (titled[1].trim() !== "") chapters[chapters.length - 1] = {
14099
+ ...last,
14100
+ title: titled[1].trim()
14101
+ };
14102
+ continue;
14103
+ }
14104
+ if (/^\s*Chapters:/.test(line)) inChapters = true;
14105
+ if (STREAM_LINE.test(line)) inChapters = false;
14106
+ if (/DOVI configuration record/.test(line) && streams.length > 0) {
14107
+ doviSeenFor = streams.length - 1;
14108
+ continue;
14109
+ }
14110
+ const match = STREAM_LINE.exec(line);
14111
+ if (!match) continue;
14112
+ const [, indexText, lang, kindText, rest] = match;
14113
+ if (indexText === void 0 || kindText === void 0 || rest === void 0) continue;
14114
+ const kind = kindText === "Video" ? "video" : kindText === "Audio" ? "audio" : "subtitle";
14115
+ const codecMatch = /^([A-Za-z0-9_]+)(?: \(([^)]*)\))?/.exec(rest);
14116
+ const codec = codecMatch?.[1] ?? "unknown";
14117
+ const rawProfile = codecMatch?.[2];
14118
+ const profile = kind !== "subtitle" && rawProfile !== void 0 && !/ 0x|^(default|forced)$/.test(rawProfile) ? rawProfile : null;
14119
+ const pixFmt = kind === "video" ? /\b(yuv[a-z0-9]*|nv\d+[a-z0-9]*|gray[a-z0-9]*|rgb[a-z0-9]*|bgr[a-z0-9]*)\b/.exec(rest)?.[1] ?? null : null;
14120
+ const size = kind === "video" ? /\b(\d{2,5})x(\d{2,5})\b/.exec(rest) : null;
14121
+ streams.push({
14122
+ index: Number(indexText),
14123
+ kind,
14124
+ codec,
14125
+ profile,
14126
+ language: languageOf(lang),
14127
+ channels: kind === "audio" ? channelsOf(rest) : null,
14128
+ bitDepth: kind === "video" ? bitDepthOf(pixFmt) : null,
14129
+ hdr: kind === "video" ? hdrOf(rest, false) : null,
14130
+ width: size?.[1] !== void 0 ? Number(size[1]) : null,
14131
+ height: size?.[2] !== void 0 ? Number(size[2]) : null,
14132
+ isDefault: /\(default\)/.test(rest),
14133
+ isForced: /\(forced\)/.test(rest)
14134
+ });
14135
+ }
14136
+ if (doviSeenFor !== null) {
14137
+ const target = streams[doviSeenFor];
14138
+ if (target?.kind === "video") streams[doviSeenFor] = {
14139
+ ...target,
14140
+ hdr: "dolby-vision"
14304
14141
  };
14305
- const result = tail.then(run, run);
14306
- tail = result.catch(() => void 0);
14307
- return result;
14142
+ }
14143
+ return {
14144
+ container,
14145
+ durationMs,
14146
+ streams,
14147
+ chapters
14308
14148
  };
14309
- const matchOf = (show) => ({
14310
- providerId: TVMAZE_ID,
14311
- remoteId: String(show.id),
14312
- title: show.name,
14313
- year: yearOf(show.premiered),
14314
- overview: plain(show.summary),
14315
- tvdbId: show.externals?.thetvdb ?? null,
14316
- tmdbId: null,
14317
- imdbId: show.externals?.imdb ?? null,
14318
- poster: imageOf(show.image),
14319
- fanart: null
14149
+ }
14150
+ var PROBE_TIMEOUT_MS = 3e4;
14151
+ var REPORT_MAX_BYTES = 1024 * 1024;
14152
+ /**
14153
+ * ONE ffmpeg per file, reading the input report. ffmpeg exits non-zero with no output file
14154
+ * (the report is on stderr), so a non-zero exit is expected and only a missing report is a failure.
14155
+ */
14156
+ function createFfmpegProber(binaryPath) {
14157
+ return (path) => new Promise((resolve, reject) => {
14158
+ execFile(binaryPath, [
14159
+ "-hide_banner",
14160
+ "-nostdin",
14161
+ "-i",
14162
+ path
14163
+ ], {
14164
+ timeout: PROBE_TIMEOUT_MS,
14165
+ maxBuffer: REPORT_MAX_BYTES,
14166
+ encoding: "utf8"
14167
+ }, (error, _stdout, stderr) => {
14168
+ if (error !== null && (error.killed === true || stderr === "")) {
14169
+ reject(new Error(error.killed === true ? "probe timed out" : error.message));
14170
+ return;
14171
+ }
14172
+ const result = parseFfmpegReport(stderr);
14173
+ if (result.streams.length === 0) reject(/* @__PURE__ */ new Error("no streams in the report"));
14174
+ else resolve(result);
14175
+ });
14320
14176
  });
14177
+ }
14178
+ //#endregion
14179
+ //#region src/provider.ts
14180
+ /** The `media-library` capability over the store. A caller reads and writes only their own progress. */
14181
+ function createMediaLibraryProvider(store, scans) {
14321
14182
  return {
14322
- id: TVMAZE_ID,
14323
- kinds: ["series"],
14324
- async lookup(_kind, ids) {
14325
- const query = ids.tvdbId !== null ? `thetvdb=${ids.tvdbId}` : ids.imdbId !== null ? `imdb=${encodeURIComponent(ids.imdbId)}` : null;
14326
- if (query === null) return null;
14327
- try {
14328
- return matchOf(ShowSchema.parse(await call(`/lookup/shows?${query}`)));
14329
- } catch (error) {
14330
- if (error instanceof Error && /\b404\b/.test(error.message)) return null;
14331
- throw error;
14332
- }
14333
- },
14334
- async identify(_kind, title, year) {
14335
- const found = SearchSchema.parse(await call(`/search/shows?q=${encodeURIComponent(title)}`));
14336
- const sameYear = year === null ? void 0 : found.find((entry) => yearOf(entry.show.premiered) === year);
14337
- const top = found[0];
14338
- const hit = sameYear ?? (year === null || top !== void 0 && foldTitle(top.show.name) === foldTitle(title) ? top : void 0);
14339
- if (hit === void 0) return null;
14340
- const show = hit.show;
14341
- return {
14342
- providerId: TVMAZE_ID,
14343
- remoteId: String(show.id),
14344
- title: show.name,
14345
- year: yearOf(show.premiered),
14346
- overview: plain(show.summary),
14347
- tvdbId: show.externals?.thetvdb ?? null,
14348
- tmdbId: null,
14349
- imdbId: show.externals?.imdb ?? null,
14350
- poster: imageOf(show.image),
14351
- fanart: null
14352
- };
14353
- },
14354
- async episodes(match) {
14355
- return array(EpisodeSchema).parse(await call(`/shows/${encodeURIComponent(match.remoteId)}/episodes?specials=1`)).flatMap((entry) => entry.number === null || entry.number === void 0 ? [] : [{
14356
- season: entry.season,
14357
- episode: entry.number,
14358
- title: entry.name ?? null,
14359
- overview: plain(entry.summary),
14360
- still: imageOf(entry.image)
14361
- }]);
14362
- }
14183
+ listSeries: ({ limit, offset, language, caller }) => store.listSeries(caller.userId, limit, offset, language),
14184
+ listMovies: ({ limit, offset, language, caller }) => store.listMovies(caller.userId, limit, offset, language),
14185
+ listSeasons: ({ seriesId, caller }) => store.listSeasons(caller.userId, seriesId),
14186
+ listEpisodes: ({ seriesId, seasonNumber, language, caller }) => store.listEpisodes(caller.userId, seriesId, seasonNumber, language),
14187
+ getItem: ({ itemId, language, caller }) => store.getItem(caller.userId, itemId, language),
14188
+ search: ({ query, limit, language, caller }) => store.search(caller.userId, query, limit, language),
14189
+ listRecentlyAdded: ({ limit, language, caller }) => store.listRecentlyAdded(caller.userId, limit, language),
14190
+ listWatchlist: ({ limit, offset, language, caller }) => store.listWatchlist(caller.userId, limit, offset, language),
14191
+ setWatchlisted: ({ itemId, on, caller }) => store.setWatchlisted(caller.userId, itemId, on),
14192
+ getItemDetails: ({ itemId, language }) => store.getItemDetails(itemId, language),
14193
+ getProgress: ({ itemId, caller }) => store.getProgress(caller.userId, itemId),
14194
+ setProgress: ({ caller, ...input }) => store.setProgress(caller.userId, input),
14195
+ markWatched: ({ caller, ...input }) => store.markWatched(caller.userId, input),
14196
+ listContinue: ({ limit, language, caller }) => store.listContinue(caller.userId, limit, language),
14197
+ rescan: async () => ({ started: scans.start("manual") }),
14198
+ getScanStatus: async () => scans.status()
14363
14199
  };
14364
14200
  }
14365
14201
  //#endregion
14366
- //#region src/img-plane.ts
14367
- var FAILED_GRAB_TTL_MS = 30 * 6e4;
14368
- var FAILED_GRAB_MAX = 500;
14369
- /** The real fetch: the key travels in a header, a redirect is never followed, the body is size-capped as it streams. */
14370
- var httpImageFetch = async (url, apiKey) => {
14371
- const response = await fetch(url, {
14372
- headers: { "X-Api-Key": apiKey },
14373
- redirect: "manual",
14374
- signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
14375
- });
14376
- if (response.status >= 300 && response.status < 400) throw new Error(`redirect refused (HTTP ${response.status}): the key is never sent to another URL`);
14377
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
14378
- return readCapped(response, MAX_IMAGE_BYTES);
14379
- };
14380
- function typeOf(bytes) {
14381
- if (bytes.length > 3 && bytes[0] === 255 && bytes[1] === 216) return "image/jpeg";
14382
- if (bytes.length > 8 && bytes.subarray(1, 4).toString("latin1") === "PNG") return "image/png";
14383
- if (bytes.length > 12 && bytes.subarray(8, 12).toString("latin1") === "WEBP") return "image/webp";
14384
- return null;
14202
+ //#region src/settings.ts
14203
+ /** The capability that owns the cluster-scoped settings (D986). */
14204
+ var SETTINGS_CAP = "media-library";
14205
+ /** An http(s) base URL without credentials, query or trailing slash; `''` is "not configured"; `null` is invalid. */
14206
+ function normalizeBaseUrl(raw) {
14207
+ const text = raw.trim();
14208
+ if (text === "") return "";
14209
+ let url;
14210
+ try {
14211
+ url = new URL(text);
14212
+ } catch {
14213
+ return null;
14214
+ }
14215
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
14216
+ if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") return null;
14217
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
14385
14218
  }
14386
- /**
14387
- * The remote URL of an arr cover: a path on the arr's own origin, or an absolute URL that already
14388
- * IS on that origin (the arr app answers plain http on a LAN). Never another host, port or scheme,
14389
- * and never a URL that carries credentials.
14390
- */
14391
- function coverUrl(source, path) {
14392
- if (/^https?:\/\//i.test(path)) {
14393
- const absolute = URL.canParse(path) ? new URL(path) : null;
14394
- const own = new URL(source.baseUrl);
14395
- return absolute !== null && absolute.origin === own.origin && absolute.username === "" && absolute.password === "" ? absolute.toString() : null;
14219
+ var BaseUrlSchema = string().transform((value, ctx) => {
14220
+ const normalized = normalizeBaseUrl(value);
14221
+ if (normalized === null) {
14222
+ ctx.addIssue({
14223
+ code: "custom",
14224
+ message: "expected an http(s) URL"
14225
+ });
14226
+ return NEVER;
14396
14227
  }
14397
- if (!path.startsWith("/") || path.startsWith("//")) return null;
14398
- const base = new URL(source.baseUrl);
14399
- const url = new URL(`${source.baseUrl}${path}`);
14400
- return url.origin === base.origin ? url.toString() : null;
14228
+ return normalized;
14229
+ });
14230
+ /** The metadata steps, in the order they answer by default: files, the arr app, then online (each needs its key or switch), pictures last. */
14231
+ var METADATA_STEPS = [
14232
+ "local",
14233
+ "arr",
14234
+ "tmdb",
14235
+ "tvmaze",
14236
+ "tvdb",
14237
+ "omdb",
14238
+ "anilist",
14239
+ "fanart"
14240
+ ];
14241
+ var DEFAULT_METADATA_ORDER = METADATA_STEPS;
14242
+ /** The steps that cannot answer without the installation's own key. */
14243
+ var KEYED_STEPS = [
14244
+ "tmdb",
14245
+ "tvdb",
14246
+ "omdb",
14247
+ "fanart"
14248
+ ];
14249
+ function isStep(value) {
14250
+ return METADATA_STEPS.some((step) => step === value);
14401
14251
  }
14402
- function end(res, status) {
14403
- res.writeHead(status, { "Content-Length": 0 });
14404
- res.end();
14252
+ function isKeyedStep(step) {
14253
+ return KEYED_STEPS.some((keyed) => keyed === step);
14405
14254
  }
14406
- /** The `img` plane: `GET /<itemId>/poster|fanart`, fetched from the arr once and cached on disk. */
14407
- function createImagePlaneHandler(deps) {
14408
- const inFlight = /* @__PURE__ */ new Map();
14409
- const now = deps.now ?? Date.now;
14410
- /** key → when the failure is forgotten: a transient failure retries, and the set is bounded. */
14411
- const failedGrabs = /* @__PURE__ */ new Map();
14412
- const hasFailed = (key) => {
14413
- const until = failedGrabs.get(key);
14414
- if (until === void 0) return false;
14415
- if (until > now()) return true;
14416
- failedGrabs.delete(key);
14417
- return false;
14418
- };
14419
- const rememberFailure = (key) => {
14420
- failedGrabs.delete(key);
14421
- failedGrabs.set(key, now() + FAILED_GRAB_TTL_MS);
14422
- for (const oldest of failedGrabs.keys()) {
14423
- if (failedGrabs.size <= FAILED_GRAB_MAX) break;
14424
- failedGrabs.delete(oldest);
14425
- }
14426
- };
14427
- const limitGrabs = createLimiter(deps.grabConcurrency ?? 2, deps.grabQueueLimit ?? 32);
14428
- /** A sidecar image is read only from inside a configured root, symlinks resolved, and only up to the size cap. */
14429
- const readLocal = async (path, tags) => {
14430
- const real = await resolveServable(path, await deps.roots?.() ?? []);
14431
- if (real === null) {
14432
- deps.logger.warn("image refused: outside the configured folders", {
14433
- tags,
14434
- meta: { reason: "outside-roots" }
14435
- });
14436
- return null;
14437
- }
14438
- if ((await stat(real)).size > 10485760) throw new Error("image too large");
14439
- return readFile(real);
14255
+ /** What the settings list shows for each step. */
14256
+ var STEP_NAMES = {
14257
+ local: "Local files",
14258
+ arr: "Sonarr and Radarr",
14259
+ tmdb: "TMDB",
14260
+ tvmaze: "TVmaze",
14261
+ tvdb: "TheTVDB",
14262
+ omdb: "OMDb",
14263
+ anilist: "AniList",
14264
+ fanart: "Fanart.tv"
14265
+ };
14266
+ /** One row of the metadata chain: the row order is the order the steps answer in (D1125). */
14267
+ var MetadataProviderRowSchema = object({
14268
+ /** The step this row is; stable, it addresses the row's secret. */
14269
+ id: string(),
14270
+ /** The step's display name, stamped by the addon for the row title. */
14271
+ name: string().default(""),
14272
+ enabled: boolean().default(true),
14273
+ /** The installation's own key or token, for a keyed step; unused by the others. */
14274
+ apiKey: string().meta({ secret: true }).default("")
14275
+ });
14276
+ /** A row for `step`; AniList needs no account but sends titles out, so it starts off. */
14277
+ function providerRow(step, patch = {}) {
14278
+ return {
14279
+ id: step,
14280
+ name: STEP_NAMES[step],
14281
+ enabled: step !== "anilist",
14282
+ apiKey: "",
14283
+ ...patch
14440
14284
  };
14441
- const produce = async (found, tags) => {
14442
- if (found.kind === "frame") return limitGrabs(() => deps.grabFrame(found.filePath, found.durationMs));
14443
- if (found.kind === "remote") return deps.fetchRemote(found.url);
14444
- const arr = await deps.arrSource(found.sourceId);
14445
- const url = arr === null ? null : coverUrl(arr, found.path);
14446
- if (arr === null || url === null) {
14447
- deps.logger.warn("image skipped: no usable source", {
14448
- tags,
14449
- meta: { reason: arr === null ? "source-off" : "foreign-origin" }
14450
- });
14451
- return null;
14452
- }
14453
- return deps.fetchImage(url, arr.apiKey);
14285
+ }
14286
+ /** The list a fresh installation starts from: every step, in the default order. */
14287
+ function defaultProviderRows() {
14288
+ return DEFAULT_METADATA_ORDER.map((step) => providerRow(step));
14289
+ }
14290
+ /** A keyed row answers only with a key; the other steps need none. */
14291
+ function rowAnswers(row, step) {
14292
+ return row.enabled && (!isKeyedStep(step) || row.apiKey.trim() !== "");
14293
+ }
14294
+ /** The steps that are on, in the list's order; a step with no row is off, an unknown id is ignored, a keyed row without its key is skipped. */
14295
+ function resolveMetadataSteps(settings) {
14296
+ const out = [];
14297
+ for (const row of settings.metadataProviders) {
14298
+ const step = row.id.toLowerCase();
14299
+ if (isStep(step) && rowAnswers(row, step) && !out.includes(step)) out.push(step);
14300
+ }
14301
+ return out;
14302
+ }
14303
+ /** The key of a keyed step, or `''` when the step is not answering. */
14304
+ function keyOf(settings, step) {
14305
+ if (!resolveMetadataSteps(settings).includes(step)) return "";
14306
+ return settings.metadataProviders.find((candidate) => candidate.id.toLowerCase() === step)?.apiKey.trim() ?? "";
14307
+ }
14308
+ var PROVIDERS_GUIDE_EN = "<p>Each online provider needs a key of your own account; no key ships with Dominevo. Titles and ids of your library are sent to a provider to look them up. A row that needs a key and has none is skipped.</p><ul><li><strong>TMDB</strong>: <a href=\"https://www.themoviedb.org/signup\">themoviedb.org</a>, then Settings, API: request a Developer key (personal use) and copy the <strong>API Read Access Token</strong> (the long one, not the short API Key).</li><li><strong>TheTVDB</strong>: <a href=\"https://thetvdb.com/\">thetvdb.com</a>, then your dashboard: create a v4 API key (free for personal use).</li><li><strong>OMDb</strong>: <a href=\"https://www.omdbapi.com/apikey.aspx\">omdbapi.com/apikey.aspx</a>: the free key allows 1,000 requests a day.</li><li><strong>Fanart.tv</strong>: <a href=\"https://fanart.tv/\">fanart.tv</a>, then your profile: copy the personal API key. It only adds posters and backgrounds.</li></ul>Local files, Sonarr and Radarr, TVmaze and AniList need no key.";
14309
+ var MediaLibrarySettingsSchema = object({
14310
+ seriesArrUrl: BaseUrlSchema.default(""),
14311
+ seriesArrKey: string().default(""),
14312
+ /** Where the series app sees the library, and where this node mounts it. */
14313
+ seriesPathFrom: string().default(""),
14314
+ seriesPathTo: string().default(""),
14315
+ moviesArrUrl: BaseUrlSchema.default(""),
14316
+ moviesArrKey: string().default(""),
14317
+ moviesPathFrom: string().default(""),
14318
+ moviesPathTo: string().default(""),
14319
+ /** Plain folders walked for files the arr apps do not know, one absolute path per line. */
14320
+ folderRoots: string().default(""),
14321
+ rescanMinutes: number().int().min(0).default(60),
14322
+ /** Scrub thumbnails, generated in the background with ffmpeg and cached under the addon's data dir. */
14323
+ trickplay: boolean().default(true),
14324
+ /** The metadata chain, one row per step in the order they answer; the first answer to a field wins (D1125). */
14325
+ metadataProviders: array(MetadataProviderRowSchema).default(defaultProviderRows),
14326
+ /** The Plex import (a one-shot, re-runnable action): the server, a token, and how paths and users line up. */
14327
+ plexUrl: BaseUrlSchema.default(""),
14328
+ plexToken: string().meta({ secret: true }).default(""),
14329
+ plexPathFrom: string().default(""),
14330
+ plexPathTo: string().default(""),
14331
+ plexUserMap: string().default("")
14332
+ });
14333
+ /** A source is on only when both its URL and key are set; a half-filled one is off, not guessed. */
14334
+ function resolveSources(settings) {
14335
+ const pick = (baseUrl, apiKey, pathFrom, pathTo) => baseUrl === "" || apiKey === "" ? null : {
14336
+ baseUrl,
14337
+ apiKey,
14338
+ pathFrom: pathFrom.trim(),
14339
+ pathTo: pathTo.trim()
14454
14340
  };
14455
- const load = async (itemId, which) => {
14456
- for (const found of await deps.source(itemId, which)) {
14457
- const bytes = await loadOne(itemId, which, found);
14458
- if (bytes !== null) return bytes;
14459
- }
14460
- return null;
14341
+ return {
14342
+ series: pick(settings.seriesArrUrl, settings.seriesArrKey, settings.seriesPathFrom, settings.seriesPathTo),
14343
+ movies: pick(settings.moviesArrUrl, settings.moviesArrKey, settings.moviesPathFrom, settings.moviesPathTo),
14344
+ folderRoots: settings.folderRoots.split("\n").map((line) => line.trim()).filter((line) => line !== ""),
14345
+ metadataSteps: resolveMetadataSteps(settings),
14346
+ tmdbToken: keyOf(settings, "tmdb"),
14347
+ tvdbApiKey: keyOf(settings, "tvdb"),
14348
+ fanartApiKey: keyOf(settings, "fanart"),
14349
+ omdbApiKey: keyOf(settings, "omdb")
14461
14350
  };
14462
- const loadOne = async (itemId, which, found) => {
14463
- const tags = { itemId };
14464
- const origin = found.kind === "arr" ? found.path : found.kind === "remote" ? found.url : found.kind === "local" ? found.path : `frame:${found.filePath}`;
14465
- if (found.kind === "local") try {
14466
- const bytes = await readLocal(found.path, tags);
14467
- return bytes !== null && typeOf(bytes) !== null ? bytes : null;
14468
- } catch (error) {
14469
- deps.logger.warn("image fetch failed", {
14470
- tags,
14471
- meta: {
14472
- reason: "read-failed",
14473
- error: error instanceof Error ? error.message : String(error)
14351
+ }
14352
+ /** The import is configured only when both the server URL and the token are set. */
14353
+ function resolvePlex(settings) {
14354
+ if (settings.plexUrl === "" || settings.plexToken === "") return null;
14355
+ return {
14356
+ baseUrl: settings.plexUrl,
14357
+ token: settings.plexToken,
14358
+ pathFrom: settings.plexPathFrom.trim(),
14359
+ pathTo: settings.plexPathTo.trim(),
14360
+ userMap: settings.plexUserMap
14361
+ };
14362
+ }
14363
+ var MEDIA_LIBRARY_CLUSTER_SCHEMA = { sections: [
14364
+ {
14365
+ id: "series",
14366
+ title: "Series source",
14367
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.title",
14368
+ fields: [
14369
+ {
14370
+ type: "text",
14371
+ key: "seriesArrUrl",
14372
+ label: "Sonarr URL",
14373
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrUrl.label",
14374
+ description: "Address of the series app, for example http://192.168.1.20:8989. Empty turns the source off.",
14375
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrUrl.description"
14376
+ },
14377
+ {
14378
+ type: "password",
14379
+ key: "seriesArrKey",
14380
+ label: "Sonarr API key",
14381
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrKey.label"
14382
+ },
14383
+ {
14384
+ type: "text",
14385
+ key: "seriesPathFrom",
14386
+ label: "Path in Sonarr",
14387
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathFrom.label",
14388
+ description: "The library folder as the series app sees it, for example /tv.",
14389
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathFrom.description"
14390
+ },
14391
+ {
14392
+ type: "text",
14393
+ key: "seriesPathTo",
14394
+ label: "Path on this hub",
14395
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathTo.label",
14396
+ description: "Where the same folder is mounted on this hub.",
14397
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathTo.description"
14398
+ }
14399
+ ]
14400
+ },
14401
+ {
14402
+ id: "movies",
14403
+ title: "Movies source",
14404
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.title",
14405
+ fields: [
14406
+ {
14407
+ type: "text",
14408
+ key: "moviesArrUrl",
14409
+ label: "Radarr URL",
14410
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrUrl.label",
14411
+ description: "Address of the movies app, for example http://192.168.1.20:7878. Empty turns the source off.",
14412
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrUrl.description"
14413
+ },
14414
+ {
14415
+ type: "password",
14416
+ key: "moviesArrKey",
14417
+ label: "Radarr API key",
14418
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrKey.label"
14419
+ },
14420
+ {
14421
+ type: "text",
14422
+ key: "moviesPathFrom",
14423
+ label: "Path in Radarr",
14424
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathFrom.label",
14425
+ description: "The library folder as the movies app sees it, for example /movies.",
14426
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathFrom.description"
14427
+ },
14428
+ {
14429
+ type: "text",
14430
+ key: "moviesPathTo",
14431
+ label: "Path on this hub",
14432
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathTo.label",
14433
+ description: "Where the same folder is mounted on this hub.",
14434
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathTo.description"
14435
+ }
14436
+ ]
14437
+ },
14438
+ {
14439
+ id: "folders",
14440
+ title: "Folders",
14441
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.title",
14442
+ fields: [
14443
+ {
14444
+ type: "textarea",
14445
+ key: "folderRoots",
14446
+ label: "Folders to walk",
14447
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.label",
14448
+ description: "One absolute path per line. Files the arr apps do not know are added from here.",
14449
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.description"
14450
+ },
14451
+ {
14452
+ type: "number",
14453
+ key: "rescanMinutes",
14454
+ label: "Rescan every (minutes)",
14455
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.label",
14456
+ description: "0 scans only when asked.",
14457
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
14458
+ min: 0
14459
+ },
14460
+ {
14461
+ type: "boolean",
14462
+ key: "trickplay",
14463
+ label: "Scrub thumbnails",
14464
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.label",
14465
+ description: "Generate preview pictures for the seek bar in the background, one ffmpeg at a time at low priority.",
14466
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.description"
14467
+ }
14468
+ ]
14469
+ },
14470
+ {
14471
+ id: "metadata",
14472
+ title: "Metadata",
14473
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.title",
14474
+ fields: [{
14475
+ type: "info",
14476
+ key: "providersGuide",
14477
+ label: "How to get the keys",
14478
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.providersGuide.label",
14479
+ format: "html",
14480
+ content: PROVIDERS_GUIDE_EN,
14481
+ contentKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.providersGuide.content"
14482
+ }, {
14483
+ type: "editable-array",
14484
+ key: "metadataProviders",
14485
+ label: "Metadata providers",
14486
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.label",
14487
+ description: "Asked from the top down: the first answer to a field wins. Move a row to change the order. A provider that needs a key and has none is skipped.",
14488
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.description",
14489
+ default: defaultProviderRows(),
14490
+ reorderable: true,
14491
+ fixedRows: true,
14492
+ itemIdKey: "id",
14493
+ rowTitleTemplate: "{name}",
14494
+ itemFields: [
14495
+ {
14496
+ type: "text",
14497
+ key: "id",
14498
+ label: "Provider",
14499
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.id.label",
14500
+ showWhen: {
14501
+ field: "id",
14502
+ equals: ""
14503
+ }
14504
+ },
14505
+ {
14506
+ type: "text",
14507
+ key: "name",
14508
+ label: "Name",
14509
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.name.label",
14510
+ showWhen: {
14511
+ field: "id",
14512
+ equals: ""
14513
+ }
14514
+ },
14515
+ {
14516
+ type: "boolean",
14517
+ key: "enabled",
14518
+ label: "Use this provider",
14519
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.enabled.label"
14520
+ },
14521
+ {
14522
+ type: "password",
14523
+ key: "apiKey",
14524
+ label: "API key or token",
14525
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.apiKey.label",
14526
+ description: "The key of your own account, stored in the keychain. Without it this provider is skipped.",
14527
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.apiKey.description",
14528
+ showWhen: {
14529
+ field: "id",
14530
+ in: [...KEYED_STEPS]
14531
+ }
14474
14532
  }
14475
- });
14476
- return null;
14477
- }
14478
- const key = hashKey(`${itemId}:${which}:${origin}`);
14479
- if (hasFailed(key)) return null;
14480
- const cached = join(deps.cacheDir, key);
14481
- try {
14482
- const onDisk = await readFile(cached);
14483
- if (typeOf(onDisk) !== null) return onDisk;
14484
- deps.logger.warn("cached image is not an image: dropped and fetched again", {
14485
- tags,
14486
- meta: { reason: "cache-corrupt" }
14487
- });
14488
- await unlink(cached);
14489
- } catch {}
14490
- try {
14491
- const bytes = await produce(found, tags);
14492
- if (bytes === null) return null;
14493
- if (typeOf(bytes) === null) throw new Error("not an image");
14494
- await mkdir(deps.cacheDir, { recursive: true });
14495
- await writeFile(`${cached}.tmp`, bytes);
14496
- await rename(`${cached}.tmp`, cached);
14497
- return bytes;
14498
- } catch (error) {
14499
- if (error instanceof LimiterFullError) {
14500
- deps.logger.warn("frame grab refused", {
14501
- tags,
14502
- meta: { reason: "queue-full" }
14503
- });
14504
- return null;
14533
+ ]
14534
+ }]
14535
+ },
14536
+ {
14537
+ id: "plex",
14538
+ title: "Import from Plex",
14539
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.title",
14540
+ fields: [
14541
+ {
14542
+ type: "text",
14543
+ key: "plexUrl",
14544
+ label: "Plex server URL",
14545
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUrl.label",
14546
+ description: "Address of the Plex Media Server, for example http://192.168.1.20:32400. Used only when you press Preview or Import: nothing is linked or kept in sync.",
14547
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUrl.description"
14548
+ },
14549
+ {
14550
+ type: "password",
14551
+ key: "plexToken",
14552
+ label: "Plex token",
14553
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexToken.label",
14554
+ description: "The server owner's X-Plex-Token. Stored in the keychain.",
14555
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexToken.description"
14556
+ },
14557
+ {
14558
+ type: "text",
14559
+ key: "plexPathFrom",
14560
+ label: "Path in Plex",
14561
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathFrom.label",
14562
+ description: "The library folder as Plex sees it, for example /data/movies. Used to match files by path when the ids do not match.",
14563
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathFrom.description"
14564
+ },
14565
+ {
14566
+ type: "text",
14567
+ key: "plexPathTo",
14568
+ label: "Path on this hub",
14569
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathTo.label",
14570
+ description: "Where the same folder is mounted on this hub.",
14571
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathTo.description"
14572
+ },
14573
+ {
14574
+ type: "textarea",
14575
+ key: "plexUserMap",
14576
+ label: "Plex user to Dominevo user",
14577
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUserMap.label",
14578
+ description: "One \"plexName = dominevoUsername\" per line. Without a line a Plex user is matched by username, title or email.",
14579
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUserMap.description"
14580
+ },
14581
+ {
14582
+ type: "addon-action-button",
14583
+ addonId: "media-library",
14584
+ key: "__plex-import-preview",
14585
+ label: "Preview the Plex import",
14586
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-preview.label",
14587
+ description: "Reads Plex and works out what would be imported per user. Writes nothing. Save the settings first.",
14588
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-preview.description",
14589
+ buttonLabel: "Preview",
14590
+ action: "plexImportPreview",
14591
+ successMessage: "{message}"
14592
+ },
14593
+ {
14594
+ type: "addon-action-button",
14595
+ addonId: "media-library",
14596
+ key: "__plex-import-run",
14597
+ label: "Import from Plex",
14598
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-run.label",
14599
+ description: "Imports watched state, resume positions and Plex's TMDB/TVDB/IMDb ids. Safe to run again: a newer Dominevo position is never overwritten.",
14600
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-run.description",
14601
+ buttonLabel: "Import",
14602
+ action: "plexImportRun",
14603
+ variant: "primary",
14604
+ confirmMessage: "Import watch history and ids from Plex now?",
14605
+ successMessage: "{message}"
14505
14606
  }
14506
- if (found.kind === "frame") rememberFailure(key);
14507
- deps.logger.warn(found.kind === "frame" ? "frame grab failed" : "image fetch failed", {
14508
- tags,
14509
- meta: {
14510
- reason: found.kind === "frame" ? "grab-failed" : "fetch-failed",
14511
- error: error instanceof Error ? error.message : String(error)
14512
- }
14513
- });
14514
- return null;
14515
- }
14516
- };
14517
- return async (req, res) => {
14518
- if (req.method !== "GET" && req.method !== "HEAD") return end(res, 405);
14519
- const parts = ((req.url ?? "/").split("?")[0] ?? "/").replace(/^\//, "").split("/");
14520
- const [rawId, which] = parts;
14521
- let itemId = "";
14522
- try {
14523
- itemId = decodeURIComponent(rawId ?? "");
14524
- } catch {
14525
- return end(res, 404);
14526
- }
14527
- if (parts.length !== 2 || !isItemId(itemId) || !isImageKind(which)) {
14528
- deps.logger.warn("image request refused", { meta: { reason: "bad-request" } });
14529
- return end(res, 404);
14530
- }
14531
- const flightKey = `${itemId}:${which}`;
14532
- const pending = inFlight.get(flightKey) ?? load(itemId, which);
14533
- inFlight.set(flightKey, pending);
14534
- let bytes;
14535
- try {
14536
- bytes = await pending;
14537
- } finally {
14538
- inFlight.delete(flightKey);
14539
- }
14540
- const contentType = bytes === null ? null : typeOf(bytes);
14541
- if (bytes === null || contentType === null) return end(res, 404);
14542
- res.writeHead(200, {
14543
- "Content-Type": contentType,
14544
- "Content-Length": bytes.length,
14545
- "Cache-Control": "private, max-age=86400"
14546
- });
14547
- res.end(req.method === "HEAD" ? void 0 : bytes);
14548
- };
14549
- }
14550
- //#endregion
14551
- //#region src/probe.ts
14552
- var CONTAINER_NAMES = new Map([
14553
- ["matroska", "mkv"],
14554
- ["mov", "mp4"],
14555
- ["avi", "avi"],
14556
- ["mpegts", "ts"]
14557
- ]);
14558
- function containerOf(formats) {
14559
- const first = formats.split(",")[0]?.trim() ?? formats;
14560
- return CONTAINER_NAMES.get(first) ?? first;
14561
- }
14562
- function languageOf(tag) {
14563
- if (tag === void 0 || tag === "" || tag === "und") return null;
14564
- return tag;
14565
- }
14566
- function bitDepthOf(pixFmt) {
14567
- if (pixFmt === null) return null;
14568
- const match = /(?:p|le|be)(9|10|12|14|16)(?:le|be)?$/.exec(pixFmt);
14569
- if (match?.[1] !== void 0) return Number(match[1]);
14570
- return /^(yuv|nv|gray|rgb|bgr)/.test(pixFmt) ? 8 : null;
14571
- }
14572
- function hdrOf(line, doviSeen) {
14573
- if (doviSeen) return "dolby-vision";
14574
- if (line.includes("smpte2084")) return "hdr10";
14575
- if (line.includes("arib-std-b67")) return "hlg";
14576
- return null;
14577
- }
14578
- function channelsOf(line) {
14579
- if (/\bmono\b/.test(line)) return 1;
14580
- if (/\bstereo\b/.test(line)) return 2;
14581
- const layout = /\b(\d)\.(\d)(?:\([a-z]+\))?/.exec(line);
14582
- if (layout?.[1] !== void 0 && layout[2] !== void 0) return Number(layout[1]) + Number(layout[2]);
14583
- const count = /\b(\d+) channels\b/.exec(line);
14584
- return count?.[1] !== void 0 ? Number(count[1]) : null;
14585
- }
14586
- var STREAM_LINE = /^\s*Stream #\d+:(\d+)(?:\[[^\]]*\])?(?:\(([^)]*)\))?[^:]*: (Video|Audio|Subtitle): (.*)$/;
14587
- var CHAPTER_LINE = /^\s*Chapter #\d+:\d+: start ([\d.]+), end ([\d.]+)/;
14588
- var CHAPTER_TITLE = /^\s+title\s*:\s*(.*)$/;
14589
- /** Parse the report `ffmpeg -i <file>` prints on stderr. A report that is not one yields no streams and no duration. */
14590
- function parseFfmpegReport(report) {
14591
- const lines = report.split("\n");
14592
- let container = null;
14593
- let durationMs = null;
14594
- const streams = [];
14595
- const chapters = [];
14596
- let doviSeenFor = null;
14597
- let inChapters = false;
14598
- for (const line of lines) {
14599
- const input = /^Input #\d+, ([^,]+(?:,[^,]+)*), from /.exec(line);
14600
- if (input?.[1] !== void 0 && container === null) container = containerOf(input[1]);
14601
- const duration = /^\s*Duration: (\d+):(\d{2}):(\d{2})\.(\d{2})/.exec(line);
14602
- if (duration && durationMs === null) durationMs = (Number(duration[1]) * 3600 + Number(duration[2]) * 60 + Number(duration[3])) * 1e3 + Number(duration[4]) * 10;
14603
- const chapter = CHAPTER_LINE.exec(line);
14604
- if (chapter?.[1] !== void 0 && chapter[2] !== void 0) {
14605
- const startSec = Number(chapter[1]);
14606
- const endSec = Number(chapter[2]);
14607
- if (Number.isFinite(startSec) && Number.isFinite(endSec) && endSec > startSec) chapters.push({
14608
- startSec,
14609
- endSec,
14610
- title: null
14611
- });
14612
- continue;
14613
- }
14614
- const titled = CHAPTER_TITLE.exec(line);
14615
- const last = chapters[chapters.length - 1];
14616
- if (titled?.[1] !== void 0 && last !== void 0 && last.title === null && inChapters) {
14617
- if (titled[1].trim() !== "") chapters[chapters.length - 1] = {
14618
- ...last,
14619
- title: titled[1].trim()
14620
- };
14621
- continue;
14622
- }
14623
- if (/^\s*Chapters:/.test(line)) inChapters = true;
14624
- if (STREAM_LINE.test(line)) inChapters = false;
14625
- if (/DOVI configuration record/.test(line) && streams.length > 0) {
14626
- doviSeenFor = streams.length - 1;
14627
- continue;
14628
- }
14629
- const match = STREAM_LINE.exec(line);
14630
- if (!match) continue;
14631
- const [, indexText, lang, kindText, rest] = match;
14632
- if (indexText === void 0 || kindText === void 0 || rest === void 0) continue;
14633
- const kind = kindText === "Video" ? "video" : kindText === "Audio" ? "audio" : "subtitle";
14634
- const codecMatch = /^([A-Za-z0-9_]+)(?: \(([^)]*)\))?/.exec(rest);
14635
- const codec = codecMatch?.[1] ?? "unknown";
14636
- const rawProfile = codecMatch?.[2];
14637
- const profile = kind !== "subtitle" && rawProfile !== void 0 && !/ 0x|^(default|forced)$/.test(rawProfile) ? rawProfile : null;
14638
- const pixFmt = kind === "video" ? /\b(yuv[a-z0-9]*|nv\d+[a-z0-9]*|gray[a-z0-9]*|rgb[a-z0-9]*|bgr[a-z0-9]*)\b/.exec(rest)?.[1] ?? null : null;
14639
- const size = kind === "video" ? /\b(\d{2,5})x(\d{2,5})\b/.exec(rest) : null;
14640
- streams.push({
14641
- index: Number(indexText),
14642
- kind,
14643
- codec,
14644
- profile,
14645
- language: languageOf(lang),
14646
- channels: kind === "audio" ? channelsOf(rest) : null,
14647
- bitDepth: kind === "video" ? bitDepthOf(pixFmt) : null,
14648
- hdr: kind === "video" ? hdrOf(rest, false) : null,
14649
- width: size?.[1] !== void 0 ? Number(size[1]) : null,
14650
- height: size?.[2] !== void 0 ? Number(size[2]) : null,
14651
- isDefault: /\(default\)/.test(rest),
14652
- isForced: /\(forced\)/.test(rest)
14653
- });
14654
- }
14655
- if (doviSeenFor !== null) {
14656
- const target = streams[doviSeenFor];
14657
- if (target?.kind === "video") streams[doviSeenFor] = {
14658
- ...target,
14659
- hdr: "dolby-vision"
14660
- };
14607
+ ]
14661
14608
  }
14662
- return {
14663
- container,
14664
- durationMs,
14665
- streams,
14666
- chapters
14667
- };
14668
- }
14669
- var PROBE_TIMEOUT_MS = 3e4;
14670
- var REPORT_MAX_BYTES = 1024 * 1024;
14671
- /**
14672
- * ONE ffmpeg per file, reading the input report. ffmpeg exits non-zero with no output file
14673
- * (the report is on stderr), so a non-zero exit is expected and only a missing report is a failure.
14674
- */
14675
- function createFfmpegProber(binaryPath) {
14676
- return (path) => new Promise((resolve, reject) => {
14677
- execFile(binaryPath, [
14678
- "-hide_banner",
14679
- "-nostdin",
14680
- "-i",
14681
- path
14682
- ], {
14683
- timeout: PROBE_TIMEOUT_MS,
14684
- maxBuffer: REPORT_MAX_BYTES,
14685
- encoding: "utf8"
14686
- }, (error, _stdout, stderr) => {
14687
- if (error !== null && (error.killed === true || stderr === "")) {
14688
- reject(new Error(error.killed === true ? "probe timed out" : error.message));
14689
- return;
14690
- }
14691
- const result = parseFfmpegReport(stderr);
14692
- if (result.streams.length === 0) reject(/* @__PURE__ */ new Error("no streams in the report"));
14693
- else resolve(result);
14694
- });
14695
- });
14696
- }
14697
- //#endregion
14698
- //#region src/provider.ts
14699
- /** The `media-library` capability over the store. A caller reads and writes only their own progress. */
14700
- function createMediaLibraryProvider(store, scans) {
14701
- return {
14702
- listSeries: ({ limit, offset, language, caller }) => store.listSeries(caller.userId, limit, offset, language),
14703
- listMovies: ({ limit, offset, language, caller }) => store.listMovies(caller.userId, limit, offset, language),
14704
- listSeasons: ({ seriesId, caller }) => store.listSeasons(caller.userId, seriesId),
14705
- listEpisodes: ({ seriesId, seasonNumber, language, caller }) => store.listEpisodes(caller.userId, seriesId, seasonNumber, language),
14706
- getItem: ({ itemId, language, caller }) => store.getItem(caller.userId, itemId, language),
14707
- search: ({ query, limit, language, caller }) => store.search(caller.userId, query, limit, language),
14708
- listRecentlyAdded: ({ limit, language, caller }) => store.listRecentlyAdded(caller.userId, limit, language),
14709
- listWatchlist: ({ limit, offset, language, caller }) => store.listWatchlist(caller.userId, limit, offset, language),
14710
- setWatchlisted: ({ itemId, on, caller }) => store.setWatchlisted(caller.userId, itemId, on),
14711
- getItemDetails: ({ itemId, language }) => store.getItemDetails(itemId, language),
14712
- getProgress: ({ itemId, caller }) => store.getProgress(caller.userId, itemId),
14713
- setProgress: ({ caller, ...input }) => store.setProgress(caller.userId, input),
14714
- markWatched: ({ caller, ...input }) => store.markWatched(caller.userId, input),
14715
- listContinue: ({ limit, language, caller }) => store.listContinue(caller.userId, limit, language),
14716
- rescan: async () => ({ started: scans.start("manual") }),
14717
- getScanStatus: async () => scans.status()
14718
- };
14719
- }
14609
+ ] };
14720
14610
  //#endregion
14721
14611
  //#region src/enrich.ts
14722
14612
  /** The default order when settings name none (D1125): files next to the media, the arr app, then online. */
@@ -14892,9 +14782,7 @@ var Enricher = class {
14892
14782
  const known = this.deps.cache.getMatch(key);
14893
14783
  if (known === null) return null;
14894
14784
  if (!known.found) return known;
14895
- const predatesTranslations = provider.translates === true && known.match.translations === void 0;
14896
- const predatesDetails = provider.providesDetails === true && known.match.details === void 0;
14897
- return predatesTranslations || predatesDetails ? null : known;
14785
+ return provider.translates === true && known.match.translations === void 0 || provider.providesDetails === true && known.match.details === void 0 ? null : known;
14898
14786
  }
14899
14787
  /** A pinned id is asked for directly: an answer of "nothing" is final, never turned into a title guess. */
14900
14788
  async lookup(provider, ask, item, kind, pin) {
@@ -15182,12 +15070,11 @@ async function classify(root, path, reader) {
15182
15070
  if (folderSeason !== null) seriesDir = dirname(parent);
15183
15071
  else if (parent !== root) seriesDir = parent;
15184
15072
  }
15185
- const prefix = guess.kind === "episode" ? guess.title : "";
15186
15073
  return {
15187
15074
  path,
15188
15075
  kind: "episode",
15189
15076
  seriesDir,
15190
- namedTitle: prefix,
15077
+ namedTitle: guess.kind === "episode" ? guess.title : "",
15191
15078
  season,
15192
15079
  episode,
15193
15080
  year: null
@@ -15694,53 +15581,7 @@ var MediaLibraryAddon = class extends BaseAddon {
15694
15581
  this.scans?.schedule(settings.rescanMinutes);
15695
15582
  this.scans?.start("settings");
15696
15583
  }
15697
- /**
15698
- * One-time, idempotent: the metadata settings of earlier versions (an order string, switches and
15699
- * four keys) become the `metadataProviders` list. The rows are written first, so each key leaves
15700
- * through the normal secret write into a keychain ref addressed by its row id (D787). An old key
15701
- * is released only once its row holds a stored key (a marker counts), and nothing at all is
15702
- * touched while an old secret cannot be read (the keychain is locked): the next boot retries.
15703
- */
15704
- async migrateLegacyProviderSettings() {
15705
- const stored = await this.resolveGlobalStore(void 0, SETTINGS_CAP);
15706
- if (!hasLegacyProviderKeys(stored)) return;
15707
- const unreadable = LEGACY_SECRET_KEYS.filter((key) => isSecretMarker(stored[key]));
15708
- if (unreadable.length > 0) {
15709
- this.ctx.logger.warn("media-library provider migration postponed: a stored key is unreadable", { meta: { keys: unreadable } });
15710
- return;
15711
- }
15712
- const parsed = array(MetadataProviderRowSchema).safeParse(stored["metadataProviders"] ?? []);
15713
- if (!parsed.success) {
15714
- this.ctx.logger.warn("media-library provider migration postponed: the stored list is invalid");
15715
- return;
15716
- }
15717
- const rows = parsed.data.length === 0 ? providerRowsFromLegacy(stored) : fillMissingKeys(parsed.data, stored);
15718
- if (JSON.stringify(rows) !== JSON.stringify(parsed.data)) await this.clusterSettings(SETTINGS_CAP, MediaLibrarySettingsSchema).patch({ metadataProviders: rows });
15719
- const after = await this.resolveGlobalStore(void 0, SETTINGS_CAP);
15720
- const held = array(MetadataProviderRowSchema).safeParse(after["metadataProviders"]);
15721
- const present = LEGACY_PROVIDER_KEYS.filter((key) => stored[key] !== void 0);
15722
- const releasable = present.filter((key) => !LEGACY_SECRET_KEYS.some((secret) => secret === key) || typeof stored[key] === "string" && stored[key] === "" || held.success && rowHoldsKey(held.data, key));
15723
- const secrets = releasable.filter((key) => LEGACY_SECRET_KEYS.some((s) => s === key));
15724
- await this.clearSecrets(secrets);
15725
- const outcome = await this.unsetStoredSettingsKeys(releasable);
15726
- this.ctx.logger.info("media-library provider settings migrated to the provider list", { meta: {
15727
- removed: outcome.removed.length,
15728
- kept: present.length - releasable.length
15729
- } });
15730
- }
15731
- /** A failed migration never stops the boot: the old keys stay and the next boot retries. */
15732
- async migrateProviderSettingsOrKeepOld() {
15733
- try {
15734
- await this.migrateLegacyProviderSettings();
15735
- } catch (error) {
15736
- this.ctx.logger.warn("media-library provider migration failed; the old settings are kept", { meta: {
15737
- step: "migrateLegacyProviderSettings",
15738
- error: String(error)
15739
- } });
15740
- }
15741
- }
15742
15584
  async onInitialize() {
15743
- await this.migrateProviderSettingsOrKeepOld();
15744
15585
  const { ctx } = this;
15745
15586
  const logger = ctx.logger;
15746
15587
  const db = settingsStoreDb(ctx.api.settingsStore);