@dominevo/addon-media-library 0.1.12 → 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([
@@ -13730,6 +13212,20 @@ var TranslationsSchema = object({ translations: array(object({
13730
13212
  overview: string().nullish()
13731
13213
  }).nullish()
13732
13214
  })) });
13215
+ /**
13216
+ * A list parsed per entry: an entry that does not parse is dropped and the rest kept, so one
13217
+ * malformed person never fails the whole response. (No logger reaches this module, so the drop is silent.)
13218
+ */
13219
+ function lenientArray(schema) {
13220
+ return array(unknown()).transform((items) => {
13221
+ const kept = [];
13222
+ for (const item of items) {
13223
+ const parsed = schema.safeParse(item);
13224
+ if (parsed.success) kept.push(parsed.data);
13225
+ }
13226
+ return kept;
13227
+ });
13228
+ }
13733
13229
  var PersonSchema = object({
13734
13230
  id: number().int(),
13735
13231
  name: string().nullish(),
@@ -13747,8 +13243,8 @@ var CrewEntrySchema = PersonSchema.extend({
13747
13243
  jobs: array(object({ job: string().nullish() })).nullish()
13748
13244
  });
13749
13245
  var CreditsSchema = object({
13750
- cast: array(CastEntrySchema).nullish(),
13751
- crew: array(CrewEntrySchema).nullish()
13246
+ cast: lenientArray(CastEntrySchema).nullish(),
13247
+ crew: lenientArray(CrewEntrySchema).nullish()
13752
13248
  });
13753
13249
  /** `release_dates` (movie): per country, a list of releases that may carry a certification. */
13754
13250
  var ReleaseDatesSchema = object({ results: array(object({
@@ -13796,8 +13292,8 @@ var SeasonSchema = object({ episodes: array(object({
13796
13292
  overview: string().nullish(),
13797
13293
  still_path: string().nullish(),
13798
13294
  runtime: number().nullish(),
13799
- guest_stars: array(CastEntrySchema).nullish(),
13800
- crew: array(CrewEntrySchema).nullish()
13295
+ guest_stars: lenientArray(CastEntrySchema).nullish(),
13296
+ crew: lenientArray(CrewEntrySchema).nullish()
13801
13297
  })) });
13802
13298
  /** Waited when TMDB says 429 and names no time. */
13803
13299
  var TMDB_DEFAULT_RETRY_WAIT_MS = 2e3;
@@ -14007,702 +13503,1110 @@ function createTmdbProvider(deps) {
14007
13503
  return hit === void 0 ? null : detailsOf(kind, hit.id);
14008
13504
  },
14009
13505
  async lookup(kind, ids) {
14010
- if (ids.tmdbId !== null) return detailsOf(kind, ids.tmdbId);
14011
- const external = ids.imdbId !== null ? {
14012
- source: "imdb_id",
14013
- value: ids.imdbId
14014
- } : ids.tvdbId !== null ? {
14015
- source: "tvdb_id",
14016
- value: String(ids.tvdbId)
14017
- } : 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));
14018
13695
  if (external === null) return null;
14019
- const found = FindSchema.parse(await call(`/find/${encodeURIComponent(external.value)}`, { external_source: external.source }));
14020
- const id = (kind === "movie" ? found.movie_results : found.tv_results)[0]?.id;
14021
- 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);
14022
13705
  },
14023
13706
  async episodes(match) {
14024
- const base = `/tv/${encodeURIComponent(match.remoteId)}`;
14025
- const show = DetailsSchema.parse(await call(base));
14026
13707
  const out = [];
14027
- for (const season of show.seasons ?? []) {
14028
- const list = SeasonSchema.parse(await call(`${base}/season/${season.season_number}`));
14029
- for (const entry of list.episodes) out.push({
14030
- season: entry.season_number,
14031
- episode: entry.episode_number,
14032
- title: text(entry.name),
14033
- overview: text(entry.overview),
14034
- still: image("w300", entry.still_path),
14035
- details: {
14036
- genres: {},
14037
- runtimeMinutes: positive(entry.runtime),
14038
- certification: null,
14039
- creators: [],
14040
- directors: personsOf(entry.crew, DIRECTOR_JOBS),
14041
- writers: personsOf(entry.crew, WRITER_JOBS),
14042
- cast: [],
14043
- guestStars: castOf(entry.guest_stars)
14044
- }
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)
14045
13717
  });
13718
+ page = list.links?.next ?? null;
14046
13719
  }
14047
13720
  return out;
14048
13721
  }
14049
13722
  };
14050
13723
  }
14051
13724
  //#endregion
14052
- //#region src/tvdb.ts
14053
- var TVDB_ID = "tvdb";
14054
- var API$1 = "https://api4.thetvdb.com/v4";
14055
- /** Said once per scan, never with the key. */
14056
- var TVDB_REJECTED = "TheTVDB key rejected: check the API key in the settings";
14057
- /** Artwork type ids: series poster / background, movie poster / background. */
14058
- var ARTWORK = {
14059
- series: {
14060
- poster: 2,
14061
- fanart: 3
14062
- },
14063
- movie: {
14064
- poster: 14,
14065
- fanart: 15
14066
- }
14067
- };
14068
- var MAX_EPISODE_PAGES = 50;
14069
- /** The login answer; the bearer is read by name below, it is a response, not a setting. */
14070
- var LoginSchema = object({ data: record(string(), string()) });
14071
- var SearchSchema$1 = object({ data: array(object({
14072
- tvdb_id: union([string(), number()]),
14073
- name: string().nullish(),
14074
- year: union([string(), number()]).nullish()
14075
- })).nullish() });
14076
- var RemoteIdSchema = object({
14077
- id: union([string(), number()]),
14078
- sourceName: string()
14079
- });
14080
- 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({
14081
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({
14082
13748
  name: string().nullish(),
14083
- year: union([string(), number()]).nullish(),
14084
- firstAired: string().nullish(),
14085
- overview: string().nullish(),
14086
- image: string().nullish(),
14087
- remoteIds: array(RemoteIdSchema).nullish(),
14088
- artworks: array(object({
14089
- image: string(),
14090
- type: number().int(),
14091
- score: number().nullish()
14092
- })).nullish()
14093
- }) });
14094
- var RemoteSearchSchema = object({ data: array(object({
14095
- series: object({ id: number().int() }).nullish(),
14096
- movie: object({ id: number().int() }).nullish()
14097
- })).nullish() });
14098
- var EpisodesSchema = object({
14099
- data: object({ episodes: array(object({
14100
- seasonNumber: number().int(),
14101
- number: number().int(),
14102
- name: string().nullish(),
14103
- overview: string().nullish(),
14104
- image: string().nullish()
14105
- })) }),
14106
- links: object({ next: number().int().nullish() }).nullish()
13749
+ season: number().int(),
13750
+ number: number().int().nullish(),
13751
+ summary: string().nullish(),
13752
+ image: ImageSchema
14107
13753
  });
14108
- function bestArtwork(extended, type) {
14109
- 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;
14110
13882
  }
14111
- function remoteId(extended, source) {
14112
- 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();
14113
13886
  }
14114
- /** TheTVDB v4: series and movies; a bearer token from the key is held for the provider's lifetime. */
14115
- function createTvdbProvider(deps) {
14116
- let token = null;
14117
- const login = async () => {
14118
- try {
14119
- const bytes = await deps.fetch(`${API$1}/login`, {
14120
- headers: {
14121
- "Content-Type": "application/json",
14122
- Accept: "application/json"
14123
- },
14124
- 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" }
14125
13916
  });
14126
- const bearer = LoginSchema.parse(JSON.parse(bytes.toString("utf8"))).data["token"];
14127
- if (bearer === void 0) throw new Error("TheTVDB login answered without a bearer");
14128
- token = bearer;
14129
- return bearer;
14130
- } catch (error) {
14131
- if (isHttp(error, 401)) throw new ProviderAuthError(TVDB_REJECTED);
14132
- throw error;
13917
+ return null;
14133
13918
  }
13919
+ if ((await stat(real)).size > 10485760) throw new Error("image too large");
13920
+ return readFile(real);
14134
13921
  };
14135
- const call = async (path, query = {}) => {
14136
- const params = new URLSearchParams(query).toString();
14137
- const url = `${API$1}${path}${params === "" ? "" : `?${params}`}`;
14138
- const send = async (bearer) => JSON.parse((await deps.fetch(url, { headers: {
14139
- Authorization: `Bearer ${bearer}`,
14140
- Accept: "application/json"
14141
- } })).toString("utf8"));
14142
- try {
14143
- 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;
14144
13949
  } catch (error) {
14145
- 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;
14146
13958
  }
13959
+ const key = hashKey(`${itemId}:${which}:${origin}`);
13960
+ if (hasFailed(key)) return null;
13961
+ const cached = join(deps.cacheDir, key);
14147
13962
  try {
14148
- 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;
14149
13979
  } catch (error) {
14150
- if (isHttp(error, 401)) throw new ProviderAuthError(TVDB_REJECTED);
14151
- 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;
14152
13996
  }
14153
13997
  };
14154
- const extendedPath = (kind, id) => `/${kind === "movie" ? "movies" : "series"}/${id}/extended`;
14155
- 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 = "";
14156
14003
  try {
14157
- const { data } = ExtendedSchema.parse(await call(extendedPath(kind, id)));
14158
- const imdb = remoteId(data, /imdb/i);
14159
- const tmdb = remoteId(data, /themoviedb|tmdb/i);
14160
- return {
14161
- providerId: TVDB_ID,
14162
- remoteId: String(data.id),
14163
- title: data.name ?? "",
14164
- year: yearOf$2(data.year) ?? yearOf$2(data.firstAired),
14165
- overview: text$1(data.overview),
14166
- tvdbId: data.id,
14167
- tmdbId: tmdb === null || !/^\d+$/.test(tmdb) ? null : Number(tmdb),
14168
- imdbId: imdb,
14169
- poster: bestArtwork(data, ARTWORK[kind].poster) ?? text$1(data.image),
14170
- fanart: bestArtwork(data, ARTWORK[kind].fanart)
14171
- };
14172
- } catch (error) {
14173
- if (isHttp(error, 404)) return null;
14174
- throw error;
14004
+ itemId = decodeURIComponent(rawId ?? "");
14005
+ } catch {
14006
+ return end(res, 404);
14175
14007
  }
14176
- };
14177
- return {
14178
- id: TVDB_ID,
14179
- kinds: ["movie", "series"],
14180
- lookupBy: [
14181
- "tvdbId",
14182
- "imdbId",
14183
- "tmdbId"
14184
- ],
14185
- async identify(kind, title, year) {
14186
- const exact = (SearchSchema$1.parse(await call("/search", {
14187
- query: title,
14188
- type: kind,
14189
- ...year === null ? {} : { year: String(year) }
14190
- })).data ?? []).filter((entry) => foldTitle(entry.name ?? "") === foldTitle(title));
14191
- const sameYear = year === null ? [] : exact.filter((entry) => yearOf$2(entry.year) === year);
14192
- const pool = sameYear.length > 0 ? sameYear : exact;
14193
- const ids = new Set(pool.map((entry) => Number(entry.tvdb_id)));
14194
- const [id] = [...ids];
14195
- return ids.size === 1 && id !== void 0 && Number.isInteger(id) ? detailsOf(kind, id) : null;
14196
- },
14197
- async lookup(kind, ids) {
14198
- if (ids.tvdbId !== null) return detailsOf(kind, ids.tvdbId);
14199
- const external = ids.imdbId ?? (ids.tmdbId === null ? null : String(ids.tmdbId));
14200
- if (external === null) return null;
14201
- let found;
14202
- try {
14203
- found = RemoteSearchSchema.parse(await call(`/search/remoteid/${encodeURIComponent(external)}`));
14204
- } catch (error) {
14205
- if (isHttp(error, 404)) return null;
14206
- throw error;
14207
- }
14208
- const hit = (found.data ?? []).map((entry) => kind === "movie" ? entry.movie : entry.series).find((entry) => entry !== null && entry !== void 0);
14209
- return hit === void 0 || hit === null ? null : detailsOf(kind, hit.id);
14210
- },
14211
- async episodes(match) {
14212
- const out = [];
14213
- let page = 0;
14214
- for (let guard = 0; page !== null && guard < MAX_EPISODE_PAGES; guard += 1) {
14215
- const list = EpisodesSchema.parse(await call(`/series/${encodeURIComponent(match.remoteId)}/episodes/default`, { page: String(page) }));
14216
- for (const entry of list.data.episodes) out.push({
14217
- season: entry.seasonNumber,
14218
- episode: entry.number,
14219
- title: text$1(entry.name),
14220
- overview: text$1(entry.overview),
14221
- still: text$1(entry.image)
14222
- });
14223
- page = list.links?.next ?? null;
14224
- }
14225
- 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);
14226
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);
14227
14029
  };
14228
14030
  }
14229
- //#endregion
14230
- //#region src/tvmaze.ts
14231
- var TVMAZE_ID = "tvmaze";
14232
- var API = "https://api.tvmaze.com";
14233
- var ImageSchema = object({
14234
- medium: string().nullish(),
14235
- original: string().nullish()
14236
- }).nullish();
14237
- var ShowSchema = object({
14238
- id: number().int(),
14239
- name: string(),
14240
- premiered: string().nullish(),
14241
- summary: string().nullish(),
14242
- image: ImageSchema,
14243
- externals: object({
14244
- thetvdb: number().int().nullish(),
14245
- imdb: string().nullish()
14246
- }).nullish()
14247
- });
14248
- var SearchSchema = array(object({
14249
- score: number(),
14250
- show: ShowSchema
14251
- }));
14252
- var EpisodeSchema = object({
14253
- name: string().nullish(),
14254
- season: number().int(),
14255
- number: number().int().nullish(),
14256
- summary: string().nullish(),
14257
- image: ImageSchema
14258
- });
14259
- /** The summary field is HTML; keep the text. */
14260
- function plain(html) {
14261
- if (html === null || html === void 0) return null;
14262
- const text = html.replace(/<[^>]*>/g, " ").replace(/&#(\d{1,6});|&#x([0-9a-f]{1,6});/gi, (_whole, dec, hex) => {
14263
- const code = typeof dec === "string" ? Number(dec) : Number.parseInt(String(hex), 16);
14264
- return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : "";
14265
- }).replace(/&apos;/g, "'").replace(/&quot;/g, "\"").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/\s+/g, " ").trim();
14266
- 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;
14267
14046
  }
14268
- function imageOf(image) {
14269
- const url = image?.original ?? image?.medium ?? null;
14270
- 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;
14271
14052
  }
14272
- function yearOf(premiered) {
14273
- const match = /^(\d{4})/.exec(premiered ?? "");
14274
- 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;
14275
14058
  }
14276
- /** TVmaze: keyless, series only. Every call goes through the shared remote fetch and one spaced queue. */
14277
- function createTvmazeProvider(deps) {
14278
- const sleep = deps.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
14279
- const now = deps.now ?? Date.now;
14280
- const gap = deps.minGapMs ?? 600;
14281
- let tail = Promise.resolve();
14282
- let lastCallAt = Number.NEGATIVE_INFINITY;
14283
- const call = (path) => {
14284
- const run = async () => {
14285
- const wait = lastCallAt + gap - now();
14286
- if (wait > 0) await sleep(wait);
14287
- lastCallAt = now();
14288
- const bytes = await deps.fetch(`${API}${path}`);
14289
- 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"
14290
14141
  };
14291
- const result = tail.then(run, run);
14292
- tail = result.catch(() => void 0);
14293
- return result;
14142
+ }
14143
+ return {
14144
+ container,
14145
+ durationMs,
14146
+ streams,
14147
+ chapters
14294
14148
  };
14295
- const matchOf = (show) => ({
14296
- providerId: TVMAZE_ID,
14297
- remoteId: String(show.id),
14298
- title: show.name,
14299
- year: yearOf(show.premiered),
14300
- overview: plain(show.summary),
14301
- tvdbId: show.externals?.thetvdb ?? null,
14302
- tmdbId: null,
14303
- imdbId: show.externals?.imdb ?? null,
14304
- poster: imageOf(show.image),
14305
- 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
+ });
14306
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) {
14307
14182
  return {
14308
- id: TVMAZE_ID,
14309
- kinds: ["series"],
14310
- async lookup(_kind, ids) {
14311
- const query = ids.tvdbId !== null ? `thetvdb=${ids.tvdbId}` : ids.imdbId !== null ? `imdb=${encodeURIComponent(ids.imdbId)}` : null;
14312
- if (query === null) return null;
14313
- try {
14314
- return matchOf(ShowSchema.parse(await call(`/lookup/shows?${query}`)));
14315
- } catch (error) {
14316
- if (error instanceof Error && /\b404\b/.test(error.message)) return null;
14317
- throw error;
14318
- }
14319
- },
14320
- async identify(_kind, title, year) {
14321
- const found = SearchSchema.parse(await call(`/search/shows?q=${encodeURIComponent(title)}`));
14322
- const sameYear = year === null ? void 0 : found.find((entry) => yearOf(entry.show.premiered) === year);
14323
- const top = found[0];
14324
- const hit = sameYear ?? (year === null || top !== void 0 && foldTitle(top.show.name) === foldTitle(title) ? top : void 0);
14325
- if (hit === void 0) return null;
14326
- const show = hit.show;
14327
- return {
14328
- providerId: TVMAZE_ID,
14329
- remoteId: String(show.id),
14330
- title: show.name,
14331
- year: yearOf(show.premiered),
14332
- overview: plain(show.summary),
14333
- tvdbId: show.externals?.thetvdb ?? null,
14334
- tmdbId: null,
14335
- imdbId: show.externals?.imdb ?? null,
14336
- poster: imageOf(show.image),
14337
- fanart: null
14338
- };
14339
- },
14340
- async episodes(match) {
14341
- return array(EpisodeSchema).parse(await call(`/shows/${encodeURIComponent(match.remoteId)}/episodes?specials=1`)).flatMap((entry) => entry.number === null || entry.number === void 0 ? [] : [{
14342
- season: entry.season,
14343
- episode: entry.number,
14344
- title: entry.name ?? null,
14345
- overview: plain(entry.summary),
14346
- still: imageOf(entry.image)
14347
- }]);
14348
- }
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()
14349
14199
  };
14350
14200
  }
14351
14201
  //#endregion
14352
- //#region src/img-plane.ts
14353
- var FAILED_GRAB_TTL_MS = 30 * 6e4;
14354
- var FAILED_GRAB_MAX = 500;
14355
- /** The real fetch: the key travels in a header, a redirect is never followed, the body is size-capped as it streams. */
14356
- var httpImageFetch = async (url, apiKey) => {
14357
- const response = await fetch(url, {
14358
- headers: { "X-Api-Key": apiKey },
14359
- redirect: "manual",
14360
- signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
14361
- });
14362
- if (response.status >= 300 && response.status < 400) throw new Error(`redirect refused (HTTP ${response.status}): the key is never sent to another URL`);
14363
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
14364
- return readCapped(response, MAX_IMAGE_BYTES);
14365
- };
14366
- function typeOf(bytes) {
14367
- if (bytes.length > 3 && bytes[0] === 255 && bytes[1] === 216) return "image/jpeg";
14368
- if (bytes.length > 8 && bytes.subarray(1, 4).toString("latin1") === "PNG") return "image/png";
14369
- if (bytes.length > 12 && bytes.subarray(8, 12).toString("latin1") === "WEBP") return "image/webp";
14370
- 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(/\/+$/, "")}`;
14371
14218
  }
14372
- /**
14373
- * The remote URL of an arr cover: a path on the arr's own origin, or an absolute URL that already
14374
- * IS on that origin (the arr app answers plain http on a LAN). Never another host, port or scheme,
14375
- * and never a URL that carries credentials.
14376
- */
14377
- function coverUrl(source, path) {
14378
- if (/^https?:\/\//i.test(path)) {
14379
- const absolute = URL.canParse(path) ? new URL(path) : null;
14380
- const own = new URL(source.baseUrl);
14381
- 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;
14382
14227
  }
14383
- if (!path.startsWith("/") || path.startsWith("//")) return null;
14384
- const base = new URL(source.baseUrl);
14385
- const url = new URL(`${source.baseUrl}${path}`);
14386
- 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);
14387
14251
  }
14388
- function end(res, status) {
14389
- res.writeHead(status, { "Content-Length": 0 });
14390
- res.end();
14252
+ function isKeyedStep(step) {
14253
+ return KEYED_STEPS.some((keyed) => keyed === step);
14391
14254
  }
14392
- /** The `img` plane: `GET /<itemId>/poster|fanart`, fetched from the arr once and cached on disk. */
14393
- function createImagePlaneHandler(deps) {
14394
- const inFlight = /* @__PURE__ */ new Map();
14395
- const now = deps.now ?? Date.now;
14396
- /** key → when the failure is forgotten: a transient failure retries, and the set is bounded. */
14397
- const failedGrabs = /* @__PURE__ */ new Map();
14398
- const hasFailed = (key) => {
14399
- const until = failedGrabs.get(key);
14400
- if (until === void 0) return false;
14401
- if (until > now()) return true;
14402
- failedGrabs.delete(key);
14403
- return false;
14404
- };
14405
- const rememberFailure = (key) => {
14406
- failedGrabs.delete(key);
14407
- failedGrabs.set(key, now() + FAILED_GRAB_TTL_MS);
14408
- for (const oldest of failedGrabs.keys()) {
14409
- if (failedGrabs.size <= FAILED_GRAB_MAX) break;
14410
- failedGrabs.delete(oldest);
14411
- }
14412
- };
14413
- const limitGrabs = createLimiter(deps.grabConcurrency ?? 2, deps.grabQueueLimit ?? 32);
14414
- /** A sidecar image is read only from inside a configured root, symlinks resolved, and only up to the size cap. */
14415
- const readLocal = async (path, tags) => {
14416
- const real = await resolveServable(path, await deps.roots?.() ?? []);
14417
- if (real === null) {
14418
- deps.logger.warn("image refused: outside the configured folders", {
14419
- tags,
14420
- meta: { reason: "outside-roots" }
14421
- });
14422
- return null;
14423
- }
14424
- if ((await stat(real)).size > 10485760) throw new Error("image too large");
14425
- 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
14426
14284
  };
14427
- const produce = async (found, tags) => {
14428
- if (found.kind === "frame") return limitGrabs(() => deps.grabFrame(found.filePath, found.durationMs));
14429
- if (found.kind === "remote") return deps.fetchRemote(found.url);
14430
- const arr = await deps.arrSource(found.sourceId);
14431
- const url = arr === null ? null : coverUrl(arr, found.path);
14432
- if (arr === null || url === null) {
14433
- deps.logger.warn("image skipped: no usable source", {
14434
- tags,
14435
- meta: { reason: arr === null ? "source-off" : "foreign-origin" }
14436
- });
14437
- return null;
14438
- }
14439
- 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()
14440
14340
  };
14441
- const load = async (itemId, which) => {
14442
- for (const found of await deps.source(itemId, which)) {
14443
- const bytes = await loadOne(itemId, which, found);
14444
- if (bytes !== null) return bytes;
14445
- }
14446
- 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")
14447
14350
  };
14448
- const loadOne = async (itemId, which, found) => {
14449
- const tags = { itemId };
14450
- const origin = found.kind === "arr" ? found.path : found.kind === "remote" ? found.url : found.kind === "local" ? found.path : `frame:${found.filePath}`;
14451
- if (found.kind === "local") try {
14452
- const bytes = await readLocal(found.path, tags);
14453
- return bytes !== null && typeOf(bytes) !== null ? bytes : null;
14454
- } catch (error) {
14455
- deps.logger.warn("image fetch failed", {
14456
- tags,
14457
- meta: {
14458
- reason: "read-failed",
14459
- 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
+ }
14460
14532
  }
14461
- });
14462
- return null;
14463
- }
14464
- const key = hashKey(`${itemId}:${which}:${origin}`);
14465
- if (hasFailed(key)) return null;
14466
- const cached = join(deps.cacheDir, key);
14467
- try {
14468
- const onDisk = await readFile(cached);
14469
- if (typeOf(onDisk) !== null) return onDisk;
14470
- deps.logger.warn("cached image is not an image: dropped and fetched again", {
14471
- tags,
14472
- meta: { reason: "cache-corrupt" }
14473
- });
14474
- await unlink(cached);
14475
- } catch {}
14476
- try {
14477
- const bytes = await produce(found, tags);
14478
- if (bytes === null) return null;
14479
- if (typeOf(bytes) === null) throw new Error("not an image");
14480
- await mkdir(deps.cacheDir, { recursive: true });
14481
- await writeFile(`${cached}.tmp`, bytes);
14482
- await rename(`${cached}.tmp`, cached);
14483
- return bytes;
14484
- } catch (error) {
14485
- if (error instanceof LimiterFullError) {
14486
- deps.logger.warn("frame grab refused", {
14487
- tags,
14488
- meta: { reason: "queue-full" }
14489
- });
14490
- 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}"
14491
14606
  }
14492
- if (found.kind === "frame") rememberFailure(key);
14493
- deps.logger.warn(found.kind === "frame" ? "frame grab failed" : "image fetch failed", {
14494
- tags,
14495
- meta: {
14496
- reason: found.kind === "frame" ? "grab-failed" : "fetch-failed",
14497
- error: error instanceof Error ? error.message : String(error)
14498
- }
14499
- });
14500
- return null;
14501
- }
14502
- };
14503
- return async (req, res) => {
14504
- if (req.method !== "GET" && req.method !== "HEAD") return end(res, 405);
14505
- const parts = ((req.url ?? "/").split("?")[0] ?? "/").replace(/^\//, "").split("/");
14506
- const [rawId, which] = parts;
14507
- let itemId = "";
14508
- try {
14509
- itemId = decodeURIComponent(rawId ?? "");
14510
- } catch {
14511
- return end(res, 404);
14512
- }
14513
- if (parts.length !== 2 || !isItemId(itemId) || !isImageKind(which)) {
14514
- deps.logger.warn("image request refused", { meta: { reason: "bad-request" } });
14515
- return end(res, 404);
14516
- }
14517
- const flightKey = `${itemId}:${which}`;
14518
- const pending = inFlight.get(flightKey) ?? load(itemId, which);
14519
- inFlight.set(flightKey, pending);
14520
- let bytes;
14521
- try {
14522
- bytes = await pending;
14523
- } finally {
14524
- inFlight.delete(flightKey);
14525
- }
14526
- const contentType = bytes === null ? null : typeOf(bytes);
14527
- if (bytes === null || contentType === null) return end(res, 404);
14528
- res.writeHead(200, {
14529
- "Content-Type": contentType,
14530
- "Content-Length": bytes.length,
14531
- "Cache-Control": "private, max-age=86400"
14532
- });
14533
- res.end(req.method === "HEAD" ? void 0 : bytes);
14534
- };
14535
- }
14536
- //#endregion
14537
- //#region src/probe.ts
14538
- var CONTAINER_NAMES = new Map([
14539
- ["matroska", "mkv"],
14540
- ["mov", "mp4"],
14541
- ["avi", "avi"],
14542
- ["mpegts", "ts"]
14543
- ]);
14544
- function containerOf(formats) {
14545
- const first = formats.split(",")[0]?.trim() ?? formats;
14546
- return CONTAINER_NAMES.get(first) ?? first;
14547
- }
14548
- function languageOf(tag) {
14549
- if (tag === void 0 || tag === "" || tag === "und") return null;
14550
- return tag;
14551
- }
14552
- function bitDepthOf(pixFmt) {
14553
- if (pixFmt === null) return null;
14554
- const match = /(?:p|le|be)(9|10|12|14|16)(?:le|be)?$/.exec(pixFmt);
14555
- if (match?.[1] !== void 0) return Number(match[1]);
14556
- return /^(yuv|nv|gray|rgb|bgr)/.test(pixFmt) ? 8 : null;
14557
- }
14558
- function hdrOf(line, doviSeen) {
14559
- if (doviSeen) return "dolby-vision";
14560
- if (line.includes("smpte2084")) return "hdr10";
14561
- if (line.includes("arib-std-b67")) return "hlg";
14562
- return null;
14563
- }
14564
- function channelsOf(line) {
14565
- if (/\bmono\b/.test(line)) return 1;
14566
- if (/\bstereo\b/.test(line)) return 2;
14567
- const layout = /\b(\d)\.(\d)(?:\([a-z]+\))?/.exec(line);
14568
- if (layout?.[1] !== void 0 && layout[2] !== void 0) return Number(layout[1]) + Number(layout[2]);
14569
- const count = /\b(\d+) channels\b/.exec(line);
14570
- return count?.[1] !== void 0 ? Number(count[1]) : null;
14571
- }
14572
- var STREAM_LINE = /^\s*Stream #\d+:(\d+)(?:\[[^\]]*\])?(?:\(([^)]*)\))?[^:]*: (Video|Audio|Subtitle): (.*)$/;
14573
- var CHAPTER_LINE = /^\s*Chapter #\d+:\d+: start ([\d.]+), end ([\d.]+)/;
14574
- var CHAPTER_TITLE = /^\s+title\s*:\s*(.*)$/;
14575
- /** Parse the report `ffmpeg -i <file>` prints on stderr. A report that is not one yields no streams and no duration. */
14576
- function parseFfmpegReport(report) {
14577
- const lines = report.split("\n");
14578
- let container = null;
14579
- let durationMs = null;
14580
- const streams = [];
14581
- const chapters = [];
14582
- let doviSeenFor = null;
14583
- let inChapters = false;
14584
- for (const line of lines) {
14585
- const input = /^Input #\d+, ([^,]+(?:,[^,]+)*), from /.exec(line);
14586
- if (input?.[1] !== void 0 && container === null) container = containerOf(input[1]);
14587
- const duration = /^\s*Duration: (\d+):(\d{2}):(\d{2})\.(\d{2})/.exec(line);
14588
- if (duration && durationMs === null) durationMs = (Number(duration[1]) * 3600 + Number(duration[2]) * 60 + Number(duration[3])) * 1e3 + Number(duration[4]) * 10;
14589
- const chapter = CHAPTER_LINE.exec(line);
14590
- if (chapter?.[1] !== void 0 && chapter[2] !== void 0) {
14591
- const startSec = Number(chapter[1]);
14592
- const endSec = Number(chapter[2]);
14593
- if (Number.isFinite(startSec) && Number.isFinite(endSec) && endSec > startSec) chapters.push({
14594
- startSec,
14595
- endSec,
14596
- title: null
14597
- });
14598
- continue;
14599
- }
14600
- const titled = CHAPTER_TITLE.exec(line);
14601
- const last = chapters[chapters.length - 1];
14602
- if (titled?.[1] !== void 0 && last !== void 0 && last.title === null && inChapters) {
14603
- if (titled[1].trim() !== "") chapters[chapters.length - 1] = {
14604
- ...last,
14605
- title: titled[1].trim()
14606
- };
14607
- continue;
14608
- }
14609
- if (/^\s*Chapters:/.test(line)) inChapters = true;
14610
- if (STREAM_LINE.test(line)) inChapters = false;
14611
- if (/DOVI configuration record/.test(line) && streams.length > 0) {
14612
- doviSeenFor = streams.length - 1;
14613
- continue;
14614
- }
14615
- const match = STREAM_LINE.exec(line);
14616
- if (!match) continue;
14617
- const [, indexText, lang, kindText, rest] = match;
14618
- if (indexText === void 0 || kindText === void 0 || rest === void 0) continue;
14619
- const kind = kindText === "Video" ? "video" : kindText === "Audio" ? "audio" : "subtitle";
14620
- const codecMatch = /^([A-Za-z0-9_]+)(?: \(([^)]*)\))?/.exec(rest);
14621
- const codec = codecMatch?.[1] ?? "unknown";
14622
- const rawProfile = codecMatch?.[2];
14623
- const profile = kind !== "subtitle" && rawProfile !== void 0 && !/ 0x|^(default|forced)$/.test(rawProfile) ? rawProfile : null;
14624
- 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;
14625
- const size = kind === "video" ? /\b(\d{2,5})x(\d{2,5})\b/.exec(rest) : null;
14626
- streams.push({
14627
- index: Number(indexText),
14628
- kind,
14629
- codec,
14630
- profile,
14631
- language: languageOf(lang),
14632
- channels: kind === "audio" ? channelsOf(rest) : null,
14633
- bitDepth: kind === "video" ? bitDepthOf(pixFmt) : null,
14634
- hdr: kind === "video" ? hdrOf(rest, false) : null,
14635
- width: size?.[1] !== void 0 ? Number(size[1]) : null,
14636
- height: size?.[2] !== void 0 ? Number(size[2]) : null,
14637
- isDefault: /\(default\)/.test(rest),
14638
- isForced: /\(forced\)/.test(rest)
14639
- });
14640
- }
14641
- if (doviSeenFor !== null) {
14642
- const target = streams[doviSeenFor];
14643
- if (target?.kind === "video") streams[doviSeenFor] = {
14644
- ...target,
14645
- hdr: "dolby-vision"
14646
- };
14607
+ ]
14647
14608
  }
14648
- return {
14649
- container,
14650
- durationMs,
14651
- streams,
14652
- chapters
14653
- };
14654
- }
14655
- var PROBE_TIMEOUT_MS = 3e4;
14656
- var REPORT_MAX_BYTES = 1024 * 1024;
14657
- /**
14658
- * ONE ffmpeg per file, reading the input report. ffmpeg exits non-zero with no output file
14659
- * (the report is on stderr), so a non-zero exit is expected and only a missing report is a failure.
14660
- */
14661
- function createFfmpegProber(binaryPath) {
14662
- return (path) => new Promise((resolve, reject) => {
14663
- execFile(binaryPath, [
14664
- "-hide_banner",
14665
- "-nostdin",
14666
- "-i",
14667
- path
14668
- ], {
14669
- timeout: PROBE_TIMEOUT_MS,
14670
- maxBuffer: REPORT_MAX_BYTES,
14671
- encoding: "utf8"
14672
- }, (error, _stdout, stderr) => {
14673
- if (error !== null && (error.killed === true || stderr === "")) {
14674
- reject(new Error(error.killed === true ? "probe timed out" : error.message));
14675
- return;
14676
- }
14677
- const result = parseFfmpegReport(stderr);
14678
- if (result.streams.length === 0) reject(/* @__PURE__ */ new Error("no streams in the report"));
14679
- else resolve(result);
14680
- });
14681
- });
14682
- }
14683
- //#endregion
14684
- //#region src/provider.ts
14685
- /** The `media-library` capability over the store. A caller reads and writes only their own progress. */
14686
- function createMediaLibraryProvider(store, scans) {
14687
- return {
14688
- listSeries: ({ limit, offset, language, caller }) => store.listSeries(caller.userId, limit, offset, language),
14689
- listMovies: ({ limit, offset, language, caller }) => store.listMovies(caller.userId, limit, offset, language),
14690
- listSeasons: ({ seriesId, caller }) => store.listSeasons(caller.userId, seriesId),
14691
- listEpisodes: ({ seriesId, seasonNumber, language, caller }) => store.listEpisodes(caller.userId, seriesId, seasonNumber, language),
14692
- getItem: ({ itemId, language, caller }) => store.getItem(caller.userId, itemId, language),
14693
- search: ({ query, limit, language, caller }) => store.search(caller.userId, query, limit, language),
14694
- listRecentlyAdded: ({ limit, language, caller }) => store.listRecentlyAdded(caller.userId, limit, language),
14695
- listWatchlist: ({ limit, offset, language, caller }) => store.listWatchlist(caller.userId, limit, offset, language),
14696
- setWatchlisted: ({ itemId, on, caller }) => store.setWatchlisted(caller.userId, itemId, on),
14697
- getItemDetails: ({ itemId, language }) => store.getItemDetails(itemId, language),
14698
- getProgress: ({ itemId, caller }) => store.getProgress(caller.userId, itemId),
14699
- setProgress: ({ caller, ...input }) => store.setProgress(caller.userId, input),
14700
- markWatched: ({ caller, ...input }) => store.markWatched(caller.userId, input),
14701
- listContinue: ({ limit, language, caller }) => store.listContinue(caller.userId, limit, language),
14702
- rescan: async () => ({ started: scans.start("manual") }),
14703
- getScanStatus: async () => scans.status()
14704
- };
14705
- }
14609
+ ] };
14706
14610
  //#endregion
14707
14611
  //#region src/enrich.ts
14708
14612
  /** The default order when settings name none (D1125): files next to the media, the arr app, then online. */
@@ -14878,9 +14782,7 @@ var Enricher = class {
14878
14782
  const known = this.deps.cache.getMatch(key);
14879
14783
  if (known === null) return null;
14880
14784
  if (!known.found) return known;
14881
- const predatesTranslations = provider.translates === true && known.match.translations === void 0;
14882
- const predatesDetails = provider.providesDetails === true && known.match.details === void 0;
14883
- 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;
14884
14786
  }
14885
14787
  /** A pinned id is asked for directly: an answer of "nothing" is final, never turned into a title guess. */
14886
14788
  async lookup(provider, ask, item, kind, pin) {
@@ -15168,12 +15070,11 @@ async function classify(root, path, reader) {
15168
15070
  if (folderSeason !== null) seriesDir = dirname(parent);
15169
15071
  else if (parent !== root) seriesDir = parent;
15170
15072
  }
15171
- const prefix = guess.kind === "episode" ? guess.title : "";
15172
15073
  return {
15173
15074
  path,
15174
15075
  kind: "episode",
15175
15076
  seriesDir,
15176
- namedTitle: prefix,
15077
+ namedTitle: guess.kind === "episode" ? guess.title : "",
15177
15078
  season,
15178
15079
  episode,
15179
15080
  year: null
@@ -15680,53 +15581,7 @@ var MediaLibraryAddon = class extends BaseAddon {
15680
15581
  this.scans?.schedule(settings.rescanMinutes);
15681
15582
  this.scans?.start("settings");
15682
15583
  }
15683
- /**
15684
- * One-time, idempotent: the metadata settings of earlier versions (an order string, switches and
15685
- * four keys) become the `metadataProviders` list. The rows are written first, so each key leaves
15686
- * through the normal secret write into a keychain ref addressed by its row id (D787). An old key
15687
- * is released only once its row holds a stored key (a marker counts), and nothing at all is
15688
- * touched while an old secret cannot be read (the keychain is locked): the next boot retries.
15689
- */
15690
- async migrateLegacyProviderSettings() {
15691
- const stored = await this.resolveGlobalStore(void 0, SETTINGS_CAP);
15692
- if (!hasLegacyProviderKeys(stored)) return;
15693
- const unreadable = LEGACY_SECRET_KEYS.filter((key) => isSecretMarker(stored[key]));
15694
- if (unreadable.length > 0) {
15695
- this.ctx.logger.warn("media-library provider migration postponed: a stored key is unreadable", { meta: { keys: unreadable } });
15696
- return;
15697
- }
15698
- const parsed = array(MetadataProviderRowSchema).safeParse(stored["metadataProviders"] ?? []);
15699
- if (!parsed.success) {
15700
- this.ctx.logger.warn("media-library provider migration postponed: the stored list is invalid");
15701
- return;
15702
- }
15703
- const rows = parsed.data.length === 0 ? providerRowsFromLegacy(stored) : fillMissingKeys(parsed.data, stored);
15704
- if (JSON.stringify(rows) !== JSON.stringify(parsed.data)) await this.clusterSettings(SETTINGS_CAP, MediaLibrarySettingsSchema).patch({ metadataProviders: rows });
15705
- const after = await this.resolveGlobalStore(void 0, SETTINGS_CAP);
15706
- const held = array(MetadataProviderRowSchema).safeParse(after["metadataProviders"]);
15707
- const present = LEGACY_PROVIDER_KEYS.filter((key) => stored[key] !== void 0);
15708
- const releasable = present.filter((key) => !LEGACY_SECRET_KEYS.some((secret) => secret === key) || typeof stored[key] === "string" && stored[key] === "" || held.success && rowHoldsKey(held.data, key));
15709
- const secrets = releasable.filter((key) => LEGACY_SECRET_KEYS.some((s) => s === key));
15710
- await this.clearSecrets(secrets);
15711
- const outcome = await this.unsetStoredSettingsKeys(releasable);
15712
- this.ctx.logger.info("media-library provider settings migrated to the provider list", { meta: {
15713
- removed: outcome.removed.length,
15714
- kept: present.length - releasable.length
15715
- } });
15716
- }
15717
- /** A failed migration never stops the boot: the old keys stay and the next boot retries. */
15718
- async migrateProviderSettingsOrKeepOld() {
15719
- try {
15720
- await this.migrateLegacyProviderSettings();
15721
- } catch (error) {
15722
- this.ctx.logger.warn("media-library provider migration failed; the old settings are kept", { meta: {
15723
- step: "migrateLegacyProviderSettings",
15724
- error: String(error)
15725
- } });
15726
- }
15727
- }
15728
15584
  async onInitialize() {
15729
- await this.migrateProviderSettingsOrKeepOld();
15730
15585
  const { ctx } = this;
15731
15586
  const logger = ctx.logger;
15732
15587
  const db = settingsStoreDb(ctx.api.settingsStore);