@dominevo/addon-media-library 0.1.13 → 0.1.15

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
@@ -8608,57 +8601,6 @@ var NOT_A_DEVICE = {
8608
8601
  INTERNAL: "internal plumbing between addons — never operator-facing"
8609
8602
  };
8610
8603
  //#endregion
8611
- //#region ../types/dist/esm/capabilities/address-role-source.cap.mjs
8612
- /**
8613
- * `address-role-source` — the connection kinds an addon needs of the hub's address
8614
- * palette (D1124). A collection cap, shaped like `retention-source` (D1084): each addon
8615
- * that wants its OWN kind of connection (media playback, a notification link, …)
8616
- * registers a provider and lists its declarations; the hub's collection fan-out
8617
- * concatenates the answers, so no central list has to be edited and `local-network`
8618
- * (which owns the palette and the operator's flags) hardcodes none.
8619
- *
8620
- * A declaration stores nothing. The operator's choice lives in `local-network`
8621
- * (`setDeclaredAddressRole`), validated against the same palette every fixed role uses
8622
- * (`HUB_ADDRESS_ROLES` stays the framework's own four). `default` says what the role
8623
- * resolves to while nothing is flagged: `follow: 'connection'` means "whatever the client
8624
- * is connected to" (the behaviour before the role existed), the others name a fixed role.
8625
- */
8626
- var AddressRoleCardinalitySchema = /* @__PURE__ */ _enum(["many", "single"]);
8627
- /** What an unflagged declared role resolves to. */
8628
- var AddressRoleFollowSchema = /* @__PURE__ */ _enum([
8629
- "connection",
8630
- "appConnections",
8631
- "publicEndpoint",
8632
- "internal"
8633
- ]);
8634
- var addressRoleSourceCapability = {
8635
- name: "address-role-source",
8636
- scope: "system",
8637
- mode: "collection",
8638
- internal: true,
8639
- methods: {
8640
- /** List the address roles this addon declares. */
8641
- listAddressRoles: /* @__PURE__ */ method(/* @__PURE__ */ _void(), /* @__PURE__ */ array(/* @__PURE__ */ object({
8642
- /** Stable id: `<addonId>:<kind>`. */
8643
- id: /* @__PURE__ */ string().min(1),
8644
- /** The addon that declares and consumes the role. */
8645
- owner: /* @__PURE__ */ string().min(1),
8646
- /** i18n key of the label (`addressRole.<owner>.<kind>`). */
8647
- labelKey: /* @__PURE__ */ string().min(1),
8648
- /** English fallback when the key has no translation. */
8649
- label: /* @__PURE__ */ string().min(1),
8650
- /** i18n key of the description. */
8651
- descriptionKey: /* @__PURE__ */ string().min(1).optional(),
8652
- /** English fallback of the description. */
8653
- description: /* @__PURE__ */ string().min(1).optional(),
8654
- /** `many`: a set of addresses the client races; `single`: at most one address carries it. */
8655
- cardinality: AddressRoleCardinalitySchema,
8656
- /** What the role resolves to while the operator has flagged nothing. */
8657
- default: /* @__PURE__ */ object({ follow: AddressRoleFollowSchema })
8658
- })).readonly(), { auth: "admin" }) },
8659
- vocabulary: { notOperatorFacing: NOT_A_DEVICE.INTERNAL }
8660
- };
8661
- //#endregion
8662
8604
  //#region ../types/dist/esm/capabilities/app-source.cap.mjs
8663
8605
  /**
8664
8606
  * `app-source` — collection cap: every addon that offers an app in the viewer
@@ -8713,22 +8655,21 @@ var AppReachSchema = /* @__PURE__ */ discriminatedUnion("kind", [
8713
8655
  ]);
8714
8656
  /** The role an app is offered to. */
8715
8657
  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
8658
  var AppNavSectionSchema = /* @__PURE__ */ object({
8729
8659
  id: /* @__PURE__ */ string(),
8730
8660
  label: /* @__PURE__ */ AppLabelSchema.nullable(),
8731
- items: /* @__PURE__ */ array(AppNavItemSchema)
8661
+ items: /* @__PURE__ */ array(/* @__PURE__ */ object({
8662
+ id: /* @__PURE__ */ string(),
8663
+ label: AppLabelSchema,
8664
+ /** A lucide icon name. */
8665
+ icon: /* @__PURE__ */ string(),
8666
+ path: /* @__PURE__ */ string(),
8667
+ adminOnly: /* @__PURE__ */ boolean().optional(),
8668
+ keywords: /* @__PURE__ */ array(/* @__PURE__ */ string()).optional(),
8669
+ badgeKey: /* @__PURE__ */ string().optional(),
8670
+ /** Interpreted by the shell (phase 4): the item is hidden while the capability is absent. */
8671
+ requiresCapability: /* @__PURE__ */ string().optional()
8672
+ }))
8732
8673
  });
8733
8674
  var appSourceCapability = {
8734
8675
  name: "app-source",
@@ -8762,6 +8703,57 @@ var appSourceCapability = {
8762
8703
  })).readonly(), { auth: "admin" }) },
8763
8704
  vocabulary: { notOperatorFacing: NOT_A_DEVICE.UI_PLUMBING }
8764
8705
  };
8706
+ //#endregion
8707
+ //#region ../types/dist/esm/capabilities/address-role-source.cap.mjs
8708
+ /**
8709
+ * `address-role-source` — the connection kinds an addon needs of the hub's address
8710
+ * palette (D1124). A collection cap, shaped like `retention-source` (D1084): each addon
8711
+ * that wants its OWN kind of connection (media playback, a notification link, …)
8712
+ * registers a provider and lists its declarations; the hub's collection fan-out
8713
+ * concatenates the answers, so no central list has to be edited and `local-network`
8714
+ * (which owns the palette and the operator's flags) hardcodes none.
8715
+ *
8716
+ * A declaration stores nothing. The operator's choice lives in `local-network`
8717
+ * (`setDeclaredAddressRole`), validated against the same palette every fixed role uses
8718
+ * (`HUB_ADDRESS_ROLES` stays the framework's own four). `default` says what the role
8719
+ * resolves to while nothing is flagged: `follow: 'connection'` means "whatever the client
8720
+ * is connected to" (the behaviour before the role existed), the others name a fixed role.
8721
+ */
8722
+ var AddressRoleCardinalitySchema = /* @__PURE__ */ _enum(["many", "single"]);
8723
+ /** What an unflagged declared role resolves to. */
8724
+ var AddressRoleFollowSchema = /* @__PURE__ */ _enum([
8725
+ "connection",
8726
+ "appConnections",
8727
+ "publicEndpoint",
8728
+ "internal"
8729
+ ]);
8730
+ var addressRoleSourceCapability = {
8731
+ name: "address-role-source",
8732
+ scope: "system",
8733
+ mode: "collection",
8734
+ internal: true,
8735
+ methods: {
8736
+ /** List the address roles this addon declares. */
8737
+ listAddressRoles: /* @__PURE__ */ method(/* @__PURE__ */ _void(), /* @__PURE__ */ array(/* @__PURE__ */ object({
8738
+ /** Stable id: `<addonId>:<kind>`. */
8739
+ id: /* @__PURE__ */ string().min(1),
8740
+ /** The addon that declares and consumes the role. */
8741
+ owner: /* @__PURE__ */ string().min(1),
8742
+ /** i18n key of the label (`addressRole.<owner>.<kind>`). */
8743
+ labelKey: /* @__PURE__ */ string().min(1),
8744
+ /** English fallback when the key has no translation. */
8745
+ label: /* @__PURE__ */ string().min(1),
8746
+ /** i18n key of the description. */
8747
+ descriptionKey: /* @__PURE__ */ string().min(1).optional(),
8748
+ /** English fallback of the description. */
8749
+ description: /* @__PURE__ */ string().min(1).optional(),
8750
+ /** `many`: a set of addresses the client races; `single`: at most one address carries it. */
8751
+ cardinality: AddressRoleCardinalitySchema,
8752
+ /** What the role resolves to while the operator has flagged nothing. */
8753
+ default: /* @__PURE__ */ object({ follow: AddressRoleFollowSchema })
8754
+ })).readonly(), { auth: "admin" }) },
8755
+ vocabulary: { notOperatorFacing: NOT_A_DEVICE.INTERNAL }
8756
+ };
8765
8757
  var MediaItemKindSchema = /* @__PURE__ */ _enum([
8766
8758
  "series",
8767
8759
  "movie",
@@ -8971,7 +8963,20 @@ var mediaLibraryCapability = {
8971
8963
  name: "media-library",
8972
8964
  scope: "system",
8973
8965
  mode: "singleton",
8974
- role: { feature: "media" },
8966
+ role: { feature: "media.library" },
8967
+ features: [{
8968
+ id: "media.library",
8969
+ app: "media",
8970
+ label: {
8971
+ key: "feature.media.library",
8972
+ fallback: "Media library"
8973
+ },
8974
+ description: {
8975
+ key: "feature.media.library.description",
8976
+ fallback: "Browse the media library."
8977
+ },
8978
+ defaultRoles: ["admin", "viewer"]
8979
+ }],
8975
8980
  methods: {
8976
8981
  /** Series, sorted by title. */
8977
8982
  listSeries: /* @__PURE__ */ method(PageInputSchema, MediaItemPageSchema, { caller: "required" }),
@@ -9084,7 +9089,8 @@ function customAction(input, output, options) {
9084
9089
  kind: options?.kind ?? "query",
9085
9090
  auth: options?.auth ?? "protected",
9086
9091
  scope: options?.scope ?? { kind: "system" },
9087
- ...options?.caller ? { caller: "required" } : {}
9092
+ ...options?.caller ? { caller: "required" } : {},
9093
+ ...options?.feature !== void 0 ? { feature: options.feature } : {}
9088
9094
  };
9089
9095
  }
9090
9096
  //#endregion
@@ -9170,7 +9176,7 @@ function buildPluginApp(version) {
9170
9176
  version
9171
9177
  },
9172
9178
  reach: { kind: "hub" },
9173
- adminOnly: true,
9179
+ adminOnly: false,
9174
9180
  nav: [],
9175
9181
  takesSharedSearch: false,
9176
9182
  settings: null
@@ -9342,629 +9348,119 @@ function withOptionalId(record) {
9342
9348
  };
9343
9349
  }
9344
9350
  //#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;
9351
+ //#region src/servable.ts
9352
+ /**
9353
+ * A file is servable only when its REAL path (symlinks resolved) is inside a configured root.
9354
+ * The path itself comes from the catalogue by item id; this is the second lock on the same door,
9355
+ * so a catalogue row that names `/etc/passwd`, or a symlink that points out of the library, serves nothing.
9356
+ */
9357
+ async function resolveServable(path, roots) {
9358
+ if (!isAbsolute(path) || path.includes("\0")) return null;
9359
+ let real;
9353
9360
  try {
9354
- url = new URL(text);
9361
+ real = await realpath(path);
9355
9362
  } catch {
9356
9363
  return null;
9357
9364
  }
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;
9365
+ for (const root of roots) {
9366
+ if (root === "") continue;
9367
+ let realRoot;
9368
+ try {
9369
+ realRoot = await realpath(root);
9370
+ } catch {
9371
+ continue;
9372
+ }
9373
+ const prefix = realRoot.endsWith(sep) ? realRoot : `${realRoot}${sep}`;
9374
+ if (real.startsWith(prefix)) return real;
9370
9375
  }
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);
9376
+ return null;
9394
9377
  }
9395
- function isKeyedStep(step) {
9396
- return KEYED_STEPS.some((keyed) => keyed === step);
9378
+ //#endregion
9379
+ //#region src/naming.ts
9380
+ /** Case- and accent-insensitive form of a title, for search and ordering. */
9381
+ function foldTitle(title) {
9382
+ return title.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().trim();
9397
9383
  }
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
- };
9384
+ /** The ordering key: the folded title without a leading article. */
9385
+ function sortKey(title) {
9386
+ return foldTitle(title).replace(/^(the|a|an|il|lo|la|le|i|gli|un|una)\s+/, "");
9428
9387
  }
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));
9388
+ /** A stable short id for a thing that has no id of its own (a folder-found file or show). */
9389
+ function hashKey(text) {
9390
+ return createHash("sha1").update(text).digest("hex").slice(0, 16);
9432
9391
  }
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() !== "");
9392
+ function itemId(sourceId, letter, key) {
9393
+ return `${sourceId}:${letter}:${key}`;
9436
9394
  }
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;
9395
+ var ID_PATTERN = /^[a-z-]+:[sme]:[A-Za-z0-9]+$/;
9396
+ /** An item id as a client may send it: the shape this module mints, nothing else. */
9397
+ function isItemId(candidate) {
9398
+ return ID_PATTERN.test(candidate);
9445
9399
  }
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() ?? "";
9400
+ /** Apply a path-prefix mapping (arr path → local path). A path outside the prefix is returned unchanged. */
9401
+ function mapPath(path, from, to) {
9402
+ if (from === "" || to === "") return path;
9403
+ const prefix = from.replace(/\/+$/, "");
9404
+ if (path === prefix) return to.replace(/\/+$/, "");
9405
+ if (path.startsWith(`${prefix}/`)) return `${to.replace(/\/+$/, "")}${path.slice(prefix.length)}`;
9406
+ return path;
9450
9407
  }
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
- };
9408
+ function cleanName(raw) {
9409
+ return raw.replace(/[._]+/g, " ").replace(/\s+/g, " ").replace(/[\s-]+$/, "").trim();
9410
+ }
9411
+ /** Guess what a file nobody catalogued is, from its name: `Show.S01E02…` is an episode, anything else a movie. */
9412
+ function guessFromFilename(fileName, parentDir) {
9413
+ const base = fileName.replace(/\.[A-Za-z0-9]+$/, "");
9414
+ const episode = /^(.*?)[\s._-]*S(\d{1,2})E(\d{1,3})/i.exec(base);
9415
+ if (episode?.[2] !== void 0 && episode[3] !== void 0) {
9416
+ const named = cleanName(episode[1] ?? "");
9417
+ return {
9418
+ kind: "episode",
9419
+ title: named === "" ? cleanName(parentDir) : named,
9420
+ year: null,
9421
+ seasonNumber: Number(episode[2]),
9422
+ episodeNumber: Number(episode[3])
9423
+ };
9424
+ }
9425
+ const year = /[([.\s_-]((?:19|20)\d{2})[)\].\s_-]/.exec(`${base} `);
9426
+ const title = cleanName(year ? base.slice(0, year.index) : base);
9484
9427
  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")
9428
+ kind: "movie",
9429
+ title: title === "" ? cleanName(base) : title,
9430
+ year: year?.[1] !== void 0 ? Number(year[1]) : null,
9431
+ seasonNumber: null,
9432
+ episodeNumber: null
9493
9433
  };
9494
9434
  }
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;
9435
+ //#endregion
9436
+ //#region src/file-plane.ts
9437
+ /**
9438
+ * Parse one `Range: bytes=…` header against a file of `size` bytes. A header this server does not
9439
+ * understand, and a multi-range one, is served as the whole file (200), which RFC 9110 allows.
9440
+ */
9441
+ function parseRange(header, size) {
9442
+ if (header === void 0) return { kind: "full" };
9443
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
9444
+ if (match === null) return { kind: "full" };
9445
+ const [, first = "", last = ""] = match;
9446
+ if (first === "" && last === "") return { kind: "full" };
9447
+ if (first === "") {
9448
+ const suffix = Number(last);
9449
+ if (suffix === 0 || size === 0) return { kind: "unsatisfiable" };
9450
+ return {
9451
+ kind: "range",
9452
+ start: Math.max(0, size - suffix),
9453
+ end: size - 1
9454
+ };
9455
+ }
9456
+ const start = Number(first);
9457
+ if (start >= size) return { kind: "unsatisfiable" };
9458
+ const end = last === "" ? size - 1 : Math.min(Number(last), size - 1);
9459
+ if (end < start) return { kind: "full" };
9498
9460
  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
9461
+ kind: "range",
9462
+ start,
9463
+ end
9968
9464
  };
9969
9465
  }
9970
9466
  var CONTENT_TYPES = new Map([
@@ -14203,8 +13699,7 @@ function createTvdbProvider(deps) {
14203
13699
  ...year === null ? {} : { year: String(year) }
14204
13700
  })).data ?? []).filter((entry) => foldTitle(entry.name ?? "") === foldTitle(title));
14205
13701
  const sameYear = year === null ? [] : exact.filter((entry) => yearOf$2(entry.year) === year);
14206
- const pool = sameYear.length > 0 ? sameYear : exact;
14207
- const ids = new Set(pool.map((entry) => Number(entry.tvdb_id)));
13702
+ const ids = new Set((sameYear.length > 0 ? sameYear : exact).map((entry) => Number(entry.tvdb_id)));
14208
13703
  const [id] = [...ids];
14209
13704
  return ids.size === 1 && id !== void 0 && Number.isInteger(id) ? detailsOf(kind, id) : null;
14210
13705
  },
@@ -14503,220 +13998,629 @@ function createImagePlaneHandler(deps) {
14503
13998
  });
14504
13999
  return null;
14505
14000
  }
14506
- if (found.kind === "frame") rememberFailure(key);
14507
- deps.logger.warn(found.kind === "frame" ? "frame grab failed" : "image fetch failed", {
14508
- tags,
14509
- meta: {
14510
- reason: found.kind === "frame" ? "grab-failed" : "fetch-failed",
14511
- error: error instanceof Error ? error.message : String(error)
14512
- }
14513
- });
14514
- return null;
14515
- }
14516
- };
14517
- return async (req, res) => {
14518
- if (req.method !== "GET" && req.method !== "HEAD") return end(res, 405);
14519
- const parts = ((req.url ?? "/").split("?")[0] ?? "/").replace(/^\//, "").split("/");
14520
- const [rawId, which] = parts;
14521
- let itemId = "";
14522
- try {
14523
- itemId = decodeURIComponent(rawId ?? "");
14524
- } catch {
14525
- return end(res, 404);
14526
- }
14527
- if (parts.length !== 2 || !isItemId(itemId) || !isImageKind(which)) {
14528
- deps.logger.warn("image request refused", { meta: { reason: "bad-request" } });
14529
- return end(res, 404);
14530
- }
14531
- const flightKey = `${itemId}:${which}`;
14532
- const pending = inFlight.get(flightKey) ?? load(itemId, which);
14533
- inFlight.set(flightKey, pending);
14534
- let bytes;
14535
- try {
14536
- bytes = await pending;
14537
- } finally {
14538
- inFlight.delete(flightKey);
14539
- }
14540
- const contentType = bytes === null ? null : typeOf(bytes);
14541
- if (bytes === null || contentType === null) return end(res, 404);
14542
- res.writeHead(200, {
14543
- "Content-Type": contentType,
14544
- "Content-Length": bytes.length,
14545
- "Cache-Control": "private, max-age=86400"
14546
- });
14547
- res.end(req.method === "HEAD" ? void 0 : bytes);
14548
- };
14549
- }
14550
- //#endregion
14551
- //#region src/probe.ts
14552
- var CONTAINER_NAMES = new Map([
14553
- ["matroska", "mkv"],
14554
- ["mov", "mp4"],
14555
- ["avi", "avi"],
14556
- ["mpegts", "ts"]
14557
- ]);
14558
- function containerOf(formats) {
14559
- const first = formats.split(",")[0]?.trim() ?? formats;
14560
- return CONTAINER_NAMES.get(first) ?? first;
14561
- }
14562
- function languageOf(tag) {
14563
- if (tag === void 0 || tag === "" || tag === "und") return null;
14564
- return tag;
14565
- }
14566
- function bitDepthOf(pixFmt) {
14567
- if (pixFmt === null) return null;
14568
- const match = /(?:p|le|be)(9|10|12|14|16)(?:le|be)?$/.exec(pixFmt);
14569
- if (match?.[1] !== void 0) return Number(match[1]);
14570
- return /^(yuv|nv|gray|rgb|bgr)/.test(pixFmt) ? 8 : null;
14571
- }
14572
- function hdrOf(line, doviSeen) {
14573
- if (doviSeen) return "dolby-vision";
14574
- if (line.includes("smpte2084")) return "hdr10";
14575
- if (line.includes("arib-std-b67")) return "hlg";
14576
- return null;
14577
- }
14578
- function channelsOf(line) {
14579
- if (/\bmono\b/.test(line)) return 1;
14580
- if (/\bstereo\b/.test(line)) return 2;
14581
- const layout = /\b(\d)\.(\d)(?:\([a-z]+\))?/.exec(line);
14582
- if (layout?.[1] !== void 0 && layout[2] !== void 0) return Number(layout[1]) + Number(layout[2]);
14583
- const count = /\b(\d+) channels\b/.exec(line);
14584
- return count?.[1] !== void 0 ? Number(count[1]) : null;
14585
- }
14586
- var STREAM_LINE = /^\s*Stream #\d+:(\d+)(?:\[[^\]]*\])?(?:\(([^)]*)\))?[^:]*: (Video|Audio|Subtitle): (.*)$/;
14587
- var CHAPTER_LINE = /^\s*Chapter #\d+:\d+: start ([\d.]+), end ([\d.]+)/;
14588
- var CHAPTER_TITLE = /^\s+title\s*:\s*(.*)$/;
14589
- /** Parse the report `ffmpeg -i <file>` prints on stderr. A report that is not one yields no streams and no duration. */
14590
- function parseFfmpegReport(report) {
14591
- const lines = report.split("\n");
14592
- let container = null;
14593
- let durationMs = null;
14594
- const streams = [];
14595
- const chapters = [];
14596
- let doviSeenFor = null;
14597
- let inChapters = false;
14598
- for (const line of lines) {
14599
- const input = /^Input #\d+, ([^,]+(?:,[^,]+)*), from /.exec(line);
14600
- if (input?.[1] !== void 0 && container === null) container = containerOf(input[1]);
14601
- const duration = /^\s*Duration: (\d+):(\d{2}):(\d{2})\.(\d{2})/.exec(line);
14602
- if (duration && durationMs === null) durationMs = (Number(duration[1]) * 3600 + Number(duration[2]) * 60 + Number(duration[3])) * 1e3 + Number(duration[4]) * 10;
14603
- const chapter = CHAPTER_LINE.exec(line);
14604
- if (chapter?.[1] !== void 0 && chapter[2] !== void 0) {
14605
- const startSec = Number(chapter[1]);
14606
- const endSec = Number(chapter[2]);
14607
- if (Number.isFinite(startSec) && Number.isFinite(endSec) && endSec > startSec) chapters.push({
14608
- startSec,
14609
- endSec,
14610
- title: null
14611
- });
14612
- continue;
14613
- }
14614
- const titled = CHAPTER_TITLE.exec(line);
14615
- const last = chapters[chapters.length - 1];
14616
- if (titled?.[1] !== void 0 && last !== void 0 && last.title === null && inChapters) {
14617
- if (titled[1].trim() !== "") chapters[chapters.length - 1] = {
14618
- ...last,
14619
- title: titled[1].trim()
14620
- };
14621
- continue;
14622
- }
14623
- if (/^\s*Chapters:/.test(line)) inChapters = true;
14624
- if (STREAM_LINE.test(line)) inChapters = false;
14625
- if (/DOVI configuration record/.test(line) && streams.length > 0) {
14626
- doviSeenFor = streams.length - 1;
14627
- continue;
14628
- }
14629
- const match = STREAM_LINE.exec(line);
14630
- if (!match) continue;
14631
- const [, indexText, lang, kindText, rest] = match;
14632
- if (indexText === void 0 || kindText === void 0 || rest === void 0) continue;
14633
- const kind = kindText === "Video" ? "video" : kindText === "Audio" ? "audio" : "subtitle";
14634
- const codecMatch = /^([A-Za-z0-9_]+)(?: \(([^)]*)\))?/.exec(rest);
14635
- const codec = codecMatch?.[1] ?? "unknown";
14636
- const rawProfile = codecMatch?.[2];
14637
- const profile = kind !== "subtitle" && rawProfile !== void 0 && !/ 0x|^(default|forced)$/.test(rawProfile) ? rawProfile : null;
14638
- const pixFmt = kind === "video" ? /\b(yuv[a-z0-9]*|nv\d+[a-z0-9]*|gray[a-z0-9]*|rgb[a-z0-9]*|bgr[a-z0-9]*)\b/.exec(rest)?.[1] ?? null : null;
14639
- const size = kind === "video" ? /\b(\d{2,5})x(\d{2,5})\b/.exec(rest) : null;
14640
- streams.push({
14641
- index: Number(indexText),
14642
- kind,
14643
- codec,
14644
- profile,
14645
- language: languageOf(lang),
14646
- channels: kind === "audio" ? channelsOf(rest) : null,
14647
- bitDepth: kind === "video" ? bitDepthOf(pixFmt) : null,
14648
- hdr: kind === "video" ? hdrOf(rest, false) : null,
14649
- width: size?.[1] !== void 0 ? Number(size[1]) : null,
14650
- height: size?.[2] !== void 0 ? Number(size[2]) : null,
14651
- isDefault: /\(default\)/.test(rest),
14652
- isForced: /\(forced\)/.test(rest)
14653
- });
14654
- }
14655
- if (doviSeenFor !== null) {
14656
- const target = streams[doviSeenFor];
14657
- if (target?.kind === "video") streams[doviSeenFor] = {
14658
- ...target,
14659
- hdr: "dolby-vision"
14660
- };
14001
+ if (found.kind === "frame") rememberFailure(key);
14002
+ deps.logger.warn(found.kind === "frame" ? "frame grab failed" : "image fetch failed", {
14003
+ tags,
14004
+ meta: {
14005
+ reason: found.kind === "frame" ? "grab-failed" : "fetch-failed",
14006
+ error: error instanceof Error ? error.message : String(error)
14007
+ }
14008
+ });
14009
+ return null;
14010
+ }
14011
+ };
14012
+ return async (req, res) => {
14013
+ if (req.method !== "GET" && req.method !== "HEAD") return end(res, 405);
14014
+ const parts = ((req.url ?? "/").split("?")[0] ?? "/").replace(/^\//, "").split("/");
14015
+ const [rawId, which] = parts;
14016
+ let itemId = "";
14017
+ try {
14018
+ itemId = decodeURIComponent(rawId ?? "");
14019
+ } catch {
14020
+ return end(res, 404);
14021
+ }
14022
+ if (parts.length !== 2 || !isItemId(itemId) || !isImageKind(which)) {
14023
+ deps.logger.warn("image request refused", { meta: { reason: "bad-request" } });
14024
+ return end(res, 404);
14025
+ }
14026
+ const flightKey = `${itemId}:${which}`;
14027
+ const pending = inFlight.get(flightKey) ?? load(itemId, which);
14028
+ inFlight.set(flightKey, pending);
14029
+ let bytes;
14030
+ try {
14031
+ bytes = await pending;
14032
+ } finally {
14033
+ inFlight.delete(flightKey);
14034
+ }
14035
+ const contentType = bytes === null ? null : typeOf(bytes);
14036
+ if (bytes === null || contentType === null) return end(res, 404);
14037
+ res.writeHead(200, {
14038
+ "Content-Type": contentType,
14039
+ "Content-Length": bytes.length,
14040
+ "Cache-Control": "private, max-age=86400"
14041
+ });
14042
+ res.end(req.method === "HEAD" ? void 0 : bytes);
14043
+ };
14044
+ }
14045
+ //#endregion
14046
+ //#region src/probe.ts
14047
+ var CONTAINER_NAMES = new Map([
14048
+ ["matroska", "mkv"],
14049
+ ["mov", "mp4"],
14050
+ ["avi", "avi"],
14051
+ ["mpegts", "ts"]
14052
+ ]);
14053
+ function containerOf(formats) {
14054
+ const first = formats.split(",")[0]?.trim() ?? formats;
14055
+ return CONTAINER_NAMES.get(first) ?? first;
14056
+ }
14057
+ function languageOf(tag) {
14058
+ if (tag === void 0 || tag === "" || tag === "und") return null;
14059
+ return tag;
14060
+ }
14061
+ function bitDepthOf(pixFmt) {
14062
+ if (pixFmt === null) return null;
14063
+ const match = /(?:p|le|be)(9|10|12|14|16)(?:le|be)?$/.exec(pixFmt);
14064
+ if (match?.[1] !== void 0) return Number(match[1]);
14065
+ return /^(yuv|nv|gray|rgb|bgr)/.test(pixFmt) ? 8 : null;
14066
+ }
14067
+ function hdrOf(line, doviSeen) {
14068
+ if (doviSeen) return "dolby-vision";
14069
+ if (line.includes("smpte2084")) return "hdr10";
14070
+ if (line.includes("arib-std-b67")) return "hlg";
14071
+ return null;
14072
+ }
14073
+ function channelsOf(line) {
14074
+ if (/\bmono\b/.test(line)) return 1;
14075
+ if (/\bstereo\b/.test(line)) return 2;
14076
+ const layout = /\b(\d)\.(\d)(?:\([a-z]+\))?/.exec(line);
14077
+ if (layout?.[1] !== void 0 && layout[2] !== void 0) return Number(layout[1]) + Number(layout[2]);
14078
+ const count = /\b(\d+) channels\b/.exec(line);
14079
+ return count?.[1] !== void 0 ? Number(count[1]) : null;
14080
+ }
14081
+ var STREAM_LINE = /^\s*Stream #\d+:(\d+)(?:\[[^\]]*\])?(?:\(([^)]*)\))?[^:]*: (Video|Audio|Subtitle): (.*)$/;
14082
+ var CHAPTER_LINE = /^\s*Chapter #\d+:\d+: start ([\d.]+), end ([\d.]+)/;
14083
+ var CHAPTER_TITLE = /^\s+title\s*:\s*(.*)$/;
14084
+ /** Parse the report `ffmpeg -i <file>` prints on stderr. A report that is not one yields no streams and no duration. */
14085
+ function parseFfmpegReport(report) {
14086
+ const lines = report.split("\n");
14087
+ let container = null;
14088
+ let durationMs = null;
14089
+ const streams = [];
14090
+ const chapters = [];
14091
+ let doviSeenFor = null;
14092
+ let inChapters = false;
14093
+ for (const line of lines) {
14094
+ const input = /^Input #\d+, ([^,]+(?:,[^,]+)*), from /.exec(line);
14095
+ if (input?.[1] !== void 0 && container === null) container = containerOf(input[1]);
14096
+ const duration = /^\s*Duration: (\d+):(\d{2}):(\d{2})\.(\d{2})/.exec(line);
14097
+ if (duration && durationMs === null) durationMs = (Number(duration[1]) * 3600 + Number(duration[2]) * 60 + Number(duration[3])) * 1e3 + Number(duration[4]) * 10;
14098
+ const chapter = CHAPTER_LINE.exec(line);
14099
+ if (chapter?.[1] !== void 0 && chapter[2] !== void 0) {
14100
+ const startSec = Number(chapter[1]);
14101
+ const endSec = Number(chapter[2]);
14102
+ if (Number.isFinite(startSec) && Number.isFinite(endSec) && endSec > startSec) chapters.push({
14103
+ startSec,
14104
+ endSec,
14105
+ title: null
14106
+ });
14107
+ continue;
14108
+ }
14109
+ const titled = CHAPTER_TITLE.exec(line);
14110
+ const last = chapters[chapters.length - 1];
14111
+ if (titled?.[1] !== void 0 && last !== void 0 && last.title === null && inChapters) {
14112
+ if (titled[1].trim() !== "") chapters[chapters.length - 1] = {
14113
+ ...last,
14114
+ title: titled[1].trim()
14115
+ };
14116
+ continue;
14117
+ }
14118
+ if (/^\s*Chapters:/.test(line)) inChapters = true;
14119
+ if (STREAM_LINE.test(line)) inChapters = false;
14120
+ if (/DOVI configuration record/.test(line) && streams.length > 0) {
14121
+ doviSeenFor = streams.length - 1;
14122
+ continue;
14123
+ }
14124
+ const match = STREAM_LINE.exec(line);
14125
+ if (!match) continue;
14126
+ const [, indexText, lang, kindText, rest] = match;
14127
+ if (indexText === void 0 || kindText === void 0 || rest === void 0) continue;
14128
+ const kind = kindText === "Video" ? "video" : kindText === "Audio" ? "audio" : "subtitle";
14129
+ const codecMatch = /^([A-Za-z0-9_]+)(?: \(([^)]*)\))?/.exec(rest);
14130
+ const codec = codecMatch?.[1] ?? "unknown";
14131
+ const rawProfile = codecMatch?.[2];
14132
+ const profile = kind !== "subtitle" && rawProfile !== void 0 && !/ 0x|^(default|forced)$/.test(rawProfile) ? rawProfile : null;
14133
+ 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;
14134
+ const size = kind === "video" ? /\b(\d{2,5})x(\d{2,5})\b/.exec(rest) : null;
14135
+ streams.push({
14136
+ index: Number(indexText),
14137
+ kind,
14138
+ codec,
14139
+ profile,
14140
+ language: languageOf(lang),
14141
+ channels: kind === "audio" ? channelsOf(rest) : null,
14142
+ bitDepth: kind === "video" ? bitDepthOf(pixFmt) : null,
14143
+ hdr: kind === "video" ? hdrOf(rest, false) : null,
14144
+ width: size?.[1] !== void 0 ? Number(size[1]) : null,
14145
+ height: size?.[2] !== void 0 ? Number(size[2]) : null,
14146
+ isDefault: /\(default\)/.test(rest),
14147
+ isForced: /\(forced\)/.test(rest)
14148
+ });
14149
+ }
14150
+ if (doviSeenFor !== null) {
14151
+ const target = streams[doviSeenFor];
14152
+ if (target?.kind === "video") streams[doviSeenFor] = {
14153
+ ...target,
14154
+ hdr: "dolby-vision"
14155
+ };
14156
+ }
14157
+ return {
14158
+ container,
14159
+ durationMs,
14160
+ streams,
14161
+ chapters
14162
+ };
14163
+ }
14164
+ var PROBE_TIMEOUT_MS = 3e4;
14165
+ var REPORT_MAX_BYTES = 1024 * 1024;
14166
+ /**
14167
+ * ONE ffmpeg per file, reading the input report. ffmpeg exits non-zero with no output file
14168
+ * (the report is on stderr), so a non-zero exit is expected and only a missing report is a failure.
14169
+ */
14170
+ function createFfmpegProber(binaryPath) {
14171
+ return (path) => new Promise((resolve, reject) => {
14172
+ execFile(binaryPath, [
14173
+ "-hide_banner",
14174
+ "-nostdin",
14175
+ "-i",
14176
+ path
14177
+ ], {
14178
+ timeout: PROBE_TIMEOUT_MS,
14179
+ maxBuffer: REPORT_MAX_BYTES,
14180
+ encoding: "utf8"
14181
+ }, (error, _stdout, stderr) => {
14182
+ if (error !== null && (error.killed === true || stderr === "")) {
14183
+ reject(new Error(error.killed === true ? "probe timed out" : error.message));
14184
+ return;
14185
+ }
14186
+ const result = parseFfmpegReport(stderr);
14187
+ if (result.streams.length === 0) reject(/* @__PURE__ */ new Error("no streams in the report"));
14188
+ else resolve(result);
14189
+ });
14190
+ });
14191
+ }
14192
+ //#endregion
14193
+ //#region src/provider.ts
14194
+ /** The `media-library` capability over the store. A caller reads and writes only their own progress. */
14195
+ function createMediaLibraryProvider(store, scans) {
14196
+ return {
14197
+ listSeries: ({ limit, offset, language, caller }) => store.listSeries(caller.userId, limit, offset, language),
14198
+ listMovies: ({ limit, offset, language, caller }) => store.listMovies(caller.userId, limit, offset, language),
14199
+ listSeasons: ({ seriesId, caller }) => store.listSeasons(caller.userId, seriesId),
14200
+ listEpisodes: ({ seriesId, seasonNumber, language, caller }) => store.listEpisodes(caller.userId, seriesId, seasonNumber, language),
14201
+ getItem: ({ itemId, language, caller }) => store.getItem(caller.userId, itemId, language),
14202
+ search: ({ query, limit, language, caller }) => store.search(caller.userId, query, limit, language),
14203
+ listRecentlyAdded: ({ limit, language, caller }) => store.listRecentlyAdded(caller.userId, limit, language),
14204
+ listWatchlist: ({ limit, offset, language, caller }) => store.listWatchlist(caller.userId, limit, offset, language),
14205
+ setWatchlisted: ({ itemId, on, caller }) => store.setWatchlisted(caller.userId, itemId, on),
14206
+ getItemDetails: ({ itemId, language }) => store.getItemDetails(itemId, language),
14207
+ getProgress: ({ itemId, caller }) => store.getProgress(caller.userId, itemId),
14208
+ setProgress: ({ caller, ...input }) => store.setProgress(caller.userId, input),
14209
+ markWatched: ({ caller, ...input }) => store.markWatched(caller.userId, input),
14210
+ listContinue: ({ limit, language, caller }) => store.listContinue(caller.userId, limit, language),
14211
+ rescan: async () => ({ started: scans.start("manual") }),
14212
+ getScanStatus: async () => scans.status()
14213
+ };
14214
+ }
14215
+ //#endregion
14216
+ //#region src/settings.ts
14217
+ /** The capability that owns the cluster-scoped settings (D986). */
14218
+ var SETTINGS_CAP = "media-library";
14219
+ /** An http(s) base URL without credentials, query or trailing slash; `''` is "not configured"; `null` is invalid. */
14220
+ function normalizeBaseUrl(raw) {
14221
+ const text = raw.trim();
14222
+ if (text === "") return "";
14223
+ let url;
14224
+ try {
14225
+ url = new URL(text);
14226
+ } catch {
14227
+ return null;
14228
+ }
14229
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
14230
+ if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") return null;
14231
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
14232
+ }
14233
+ var BaseUrlSchema = string().transform((value, ctx) => {
14234
+ const normalized = normalizeBaseUrl(value);
14235
+ if (normalized === null) {
14236
+ ctx.addIssue({
14237
+ code: "custom",
14238
+ message: "expected an http(s) URL"
14239
+ });
14240
+ return NEVER;
14241
+ }
14242
+ return normalized;
14243
+ });
14244
+ /** The metadata steps, in the order they answer by default: files, the arr app, then online (each needs its key or switch), pictures last. */
14245
+ var METADATA_STEPS = [
14246
+ "local",
14247
+ "arr",
14248
+ "tmdb",
14249
+ "tvmaze",
14250
+ "tvdb",
14251
+ "omdb",
14252
+ "anilist",
14253
+ "fanart"
14254
+ ];
14255
+ var DEFAULT_METADATA_ORDER = METADATA_STEPS;
14256
+ /** The steps that cannot answer without the installation's own key. */
14257
+ var KEYED_STEPS = [
14258
+ "tmdb",
14259
+ "tvdb",
14260
+ "omdb",
14261
+ "fanart"
14262
+ ];
14263
+ function isStep(value) {
14264
+ return METADATA_STEPS.some((step) => step === value);
14265
+ }
14266
+ function isKeyedStep(step) {
14267
+ return KEYED_STEPS.some((keyed) => keyed === step);
14268
+ }
14269
+ /** What the settings list shows for each step. */
14270
+ var STEP_NAMES = {
14271
+ local: "Local files",
14272
+ arr: "Sonarr and Radarr",
14273
+ tmdb: "TMDB",
14274
+ tvmaze: "TVmaze",
14275
+ tvdb: "TheTVDB",
14276
+ omdb: "OMDb",
14277
+ anilist: "AniList",
14278
+ fanart: "Fanart.tv"
14279
+ };
14280
+ /** One row of the metadata chain: the row order is the order the steps answer in (D1125). */
14281
+ var MetadataProviderRowSchema = object({
14282
+ /** The step this row is; stable, it addresses the row's secret. */
14283
+ id: string(),
14284
+ /** The step's display name, stamped by the addon for the row title. */
14285
+ name: string().default(""),
14286
+ enabled: boolean().default(true),
14287
+ /** The installation's own key or token, for a keyed step; unused by the others. */
14288
+ apiKey: string().meta({ secret: true }).default("")
14289
+ });
14290
+ /** A row for `step`; AniList needs no account but sends titles out, so it starts off. */
14291
+ function providerRow(step, patch = {}) {
14292
+ return {
14293
+ id: step,
14294
+ name: STEP_NAMES[step],
14295
+ enabled: step !== "anilist",
14296
+ apiKey: "",
14297
+ ...patch
14298
+ };
14299
+ }
14300
+ /** The list a fresh installation starts from: every step, in the default order. */
14301
+ function defaultProviderRows() {
14302
+ return DEFAULT_METADATA_ORDER.map((step) => providerRow(step));
14303
+ }
14304
+ /** A keyed row answers only with a key; the other steps need none. */
14305
+ function rowAnswers(row, step) {
14306
+ return row.enabled && (!isKeyedStep(step) || row.apiKey.trim() !== "");
14307
+ }
14308
+ /** 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. */
14309
+ function resolveMetadataSteps(settings) {
14310
+ const out = [];
14311
+ for (const row of settings.metadataProviders) {
14312
+ const step = row.id.toLowerCase();
14313
+ if (isStep(step) && rowAnswers(row, step) && !out.includes(step)) out.push(step);
14314
+ }
14315
+ return out;
14316
+ }
14317
+ /** The key of a keyed step, or `''` when the step is not answering. */
14318
+ function keyOf(settings, step) {
14319
+ if (!resolveMetadataSteps(settings).includes(step)) return "";
14320
+ return settings.metadataProviders.find((candidate) => candidate.id.toLowerCase() === step)?.apiKey.trim() ?? "";
14321
+ }
14322
+ 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.";
14323
+ var MediaLibrarySettingsSchema = object({
14324
+ seriesArrUrl: BaseUrlSchema.default(""),
14325
+ seriesArrKey: string().default(""),
14326
+ /** Where the series app sees the library, and where this node mounts it. */
14327
+ seriesPathFrom: string().default(""),
14328
+ seriesPathTo: string().default(""),
14329
+ moviesArrUrl: BaseUrlSchema.default(""),
14330
+ moviesArrKey: string().default(""),
14331
+ moviesPathFrom: string().default(""),
14332
+ moviesPathTo: string().default(""),
14333
+ /** Plain folders walked for files the arr apps do not know, one absolute path per line. */
14334
+ folderRoots: string().default(""),
14335
+ rescanMinutes: number().int().min(0).default(60),
14336
+ /** Scrub thumbnails, generated in the background with ffmpeg and cached under the addon's data dir. */
14337
+ trickplay: boolean().default(true),
14338
+ /** The metadata chain, one row per step in the order they answer; the first answer to a field wins (D1125). */
14339
+ metadataProviders: array(MetadataProviderRowSchema).default(defaultProviderRows),
14340
+ /** The Plex import (a one-shot, re-runnable action): the server, a token, and how paths and users line up. */
14341
+ plexUrl: BaseUrlSchema.default(""),
14342
+ plexToken: string().meta({ secret: true }).default(""),
14343
+ plexPathFrom: string().default(""),
14344
+ plexPathTo: string().default(""),
14345
+ plexUserMap: string().default("")
14346
+ });
14347
+ /** A source is on only when both its URL and key are set; a half-filled one is off, not guessed. */
14348
+ function resolveSources(settings) {
14349
+ const pick = (baseUrl, apiKey, pathFrom, pathTo) => baseUrl === "" || apiKey === "" ? null : {
14350
+ baseUrl,
14351
+ apiKey,
14352
+ pathFrom: pathFrom.trim(),
14353
+ pathTo: pathTo.trim()
14354
+ };
14355
+ return {
14356
+ series: pick(settings.seriesArrUrl, settings.seriesArrKey, settings.seriesPathFrom, settings.seriesPathTo),
14357
+ movies: pick(settings.moviesArrUrl, settings.moviesArrKey, settings.moviesPathFrom, settings.moviesPathTo),
14358
+ folderRoots: settings.folderRoots.split("\n").map((line) => line.trim()).filter((line) => line !== ""),
14359
+ metadataSteps: resolveMetadataSteps(settings),
14360
+ tmdbToken: keyOf(settings, "tmdb"),
14361
+ tvdbApiKey: keyOf(settings, "tvdb"),
14362
+ fanartApiKey: keyOf(settings, "fanart"),
14363
+ omdbApiKey: keyOf(settings, "omdb")
14364
+ };
14365
+ }
14366
+ /** The import is configured only when both the server URL and the token are set. */
14367
+ function resolvePlex(settings) {
14368
+ if (settings.plexUrl === "" || settings.plexToken === "") return null;
14369
+ return {
14370
+ baseUrl: settings.plexUrl,
14371
+ token: settings.plexToken,
14372
+ pathFrom: settings.plexPathFrom.trim(),
14373
+ pathTo: settings.plexPathTo.trim(),
14374
+ userMap: settings.plexUserMap
14375
+ };
14376
+ }
14377
+ var MEDIA_LIBRARY_CLUSTER_SCHEMA = { sections: [
14378
+ {
14379
+ id: "series",
14380
+ title: "Series source",
14381
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.title",
14382
+ fields: [
14383
+ {
14384
+ type: "text",
14385
+ key: "seriesArrUrl",
14386
+ label: "Sonarr URL",
14387
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrUrl.label",
14388
+ description: "Address of the series app, for example http://192.168.1.20:8989. Empty turns the source off.",
14389
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrUrl.description"
14390
+ },
14391
+ {
14392
+ type: "password",
14393
+ key: "seriesArrKey",
14394
+ label: "Sonarr API key",
14395
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrKey.label"
14396
+ },
14397
+ {
14398
+ type: "text",
14399
+ key: "seriesPathFrom",
14400
+ label: "Path in Sonarr",
14401
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathFrom.label",
14402
+ description: "The library folder as the series app sees it, for example /tv.",
14403
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathFrom.description"
14404
+ },
14405
+ {
14406
+ type: "text",
14407
+ key: "seriesPathTo",
14408
+ label: "Path on this hub",
14409
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathTo.label",
14410
+ description: "Where the same folder is mounted on this hub.",
14411
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathTo.description"
14412
+ }
14413
+ ]
14414
+ },
14415
+ {
14416
+ id: "movies",
14417
+ title: "Movies source",
14418
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.title",
14419
+ fields: [
14420
+ {
14421
+ type: "text",
14422
+ key: "moviesArrUrl",
14423
+ label: "Radarr URL",
14424
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrUrl.label",
14425
+ description: "Address of the movies app, for example http://192.168.1.20:7878. Empty turns the source off.",
14426
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrUrl.description"
14427
+ },
14428
+ {
14429
+ type: "password",
14430
+ key: "moviesArrKey",
14431
+ label: "Radarr API key",
14432
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrKey.label"
14433
+ },
14434
+ {
14435
+ type: "text",
14436
+ key: "moviesPathFrom",
14437
+ label: "Path in Radarr",
14438
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathFrom.label",
14439
+ description: "The library folder as the movies app sees it, for example /movies.",
14440
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathFrom.description"
14441
+ },
14442
+ {
14443
+ type: "text",
14444
+ key: "moviesPathTo",
14445
+ label: "Path on this hub",
14446
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathTo.label",
14447
+ description: "Where the same folder is mounted on this hub.",
14448
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathTo.description"
14449
+ }
14450
+ ]
14451
+ },
14452
+ {
14453
+ id: "folders",
14454
+ title: "Folders",
14455
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.title",
14456
+ fields: [
14457
+ {
14458
+ type: "textarea",
14459
+ key: "folderRoots",
14460
+ label: "Folders to walk",
14461
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.label",
14462
+ description: "One absolute path per line. Files the arr apps do not know are added from here.",
14463
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.description"
14464
+ },
14465
+ {
14466
+ type: "number",
14467
+ key: "rescanMinutes",
14468
+ label: "Rescan every (minutes)",
14469
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.label",
14470
+ description: "0 scans only when asked.",
14471
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
14472
+ min: 0
14473
+ },
14474
+ {
14475
+ type: "boolean",
14476
+ key: "trickplay",
14477
+ label: "Scrub thumbnails",
14478
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.label",
14479
+ description: "Generate preview pictures for the seek bar in the background, one ffmpeg at a time at low priority.",
14480
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.description"
14481
+ }
14482
+ ]
14483
+ },
14484
+ {
14485
+ id: "metadata",
14486
+ title: "Metadata",
14487
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.title",
14488
+ fields: [{
14489
+ type: "info",
14490
+ key: "providersGuide",
14491
+ label: "How to get the keys",
14492
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.providersGuide.label",
14493
+ format: "html",
14494
+ content: PROVIDERS_GUIDE_EN,
14495
+ contentKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.providersGuide.content"
14496
+ }, {
14497
+ type: "editable-array",
14498
+ key: "metadataProviders",
14499
+ label: "Metadata providers",
14500
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.label",
14501
+ 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.",
14502
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.description",
14503
+ default: defaultProviderRows(),
14504
+ reorderable: true,
14505
+ fixedRows: true,
14506
+ itemIdKey: "id",
14507
+ rowTitleTemplate: "{name}",
14508
+ itemFields: [
14509
+ {
14510
+ type: "text",
14511
+ key: "id",
14512
+ label: "Provider",
14513
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.id.label",
14514
+ showWhen: {
14515
+ field: "id",
14516
+ equals: ""
14517
+ }
14518
+ },
14519
+ {
14520
+ type: "text",
14521
+ key: "name",
14522
+ label: "Name",
14523
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.name.label",
14524
+ showWhen: {
14525
+ field: "id",
14526
+ equals: ""
14527
+ }
14528
+ },
14529
+ {
14530
+ type: "boolean",
14531
+ key: "enabled",
14532
+ label: "Use this provider",
14533
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.enabled.label"
14534
+ },
14535
+ {
14536
+ type: "password",
14537
+ key: "apiKey",
14538
+ label: "API key or token",
14539
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.apiKey.label",
14540
+ description: "The key of your own account, stored in the keychain. Without it this provider is skipped.",
14541
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.apiKey.description",
14542
+ showWhen: {
14543
+ field: "id",
14544
+ in: [...KEYED_STEPS]
14545
+ }
14546
+ }
14547
+ ]
14548
+ }]
14549
+ },
14550
+ {
14551
+ id: "plex",
14552
+ title: "Import from Plex",
14553
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.title",
14554
+ fields: [
14555
+ {
14556
+ type: "text",
14557
+ key: "plexUrl",
14558
+ label: "Plex server URL",
14559
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUrl.label",
14560
+ 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.",
14561
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUrl.description"
14562
+ },
14563
+ {
14564
+ type: "password",
14565
+ key: "plexToken",
14566
+ label: "Plex token",
14567
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexToken.label",
14568
+ description: "The server owner's X-Plex-Token. Stored in the keychain.",
14569
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexToken.description"
14570
+ },
14571
+ {
14572
+ type: "text",
14573
+ key: "plexPathFrom",
14574
+ label: "Path in Plex",
14575
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathFrom.label",
14576
+ description: "The library folder as Plex sees it, for example /data/movies. Used to match files by path when the ids do not match.",
14577
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathFrom.description"
14578
+ },
14579
+ {
14580
+ type: "text",
14581
+ key: "plexPathTo",
14582
+ label: "Path on this hub",
14583
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathTo.label",
14584
+ description: "Where the same folder is mounted on this hub.",
14585
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathTo.description"
14586
+ },
14587
+ {
14588
+ type: "textarea",
14589
+ key: "plexUserMap",
14590
+ label: "Plex user to Dominevo user",
14591
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUserMap.label",
14592
+ description: "One \"plexName = dominevoUsername\" per line. Without a line a Plex user is matched by username, title or email.",
14593
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUserMap.description"
14594
+ },
14595
+ {
14596
+ type: "addon-action-button",
14597
+ addonId: "media-library",
14598
+ key: "__plex-import-preview",
14599
+ label: "Preview the Plex import",
14600
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-preview.label",
14601
+ description: "Reads Plex and works out what would be imported per user. Writes nothing. Save the settings first.",
14602
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-preview.description",
14603
+ buttonLabel: "Preview",
14604
+ action: "plexImportPreview",
14605
+ successMessage: "{message}"
14606
+ },
14607
+ {
14608
+ type: "addon-action-button",
14609
+ addonId: "media-library",
14610
+ key: "__plex-import-run",
14611
+ label: "Import from Plex",
14612
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-run.label",
14613
+ description: "Imports watched state, resume positions and Plex's TMDB/TVDB/IMDb ids. Safe to run again: a newer Dominevo position is never overwritten.",
14614
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-run.description",
14615
+ buttonLabel: "Import",
14616
+ action: "plexImportRun",
14617
+ variant: "primary",
14618
+ confirmMessage: "Import watch history and ids from Plex now?",
14619
+ successMessage: "{message}"
14620
+ }
14621
+ ]
14661
14622
  }
14662
- return {
14663
- container,
14664
- durationMs,
14665
- streams,
14666
- chapters
14667
- };
14668
- }
14669
- var PROBE_TIMEOUT_MS = 3e4;
14670
- var REPORT_MAX_BYTES = 1024 * 1024;
14671
- /**
14672
- * ONE ffmpeg per file, reading the input report. ffmpeg exits non-zero with no output file
14673
- * (the report is on stderr), so a non-zero exit is expected and only a missing report is a failure.
14674
- */
14675
- function createFfmpegProber(binaryPath) {
14676
- return (path) => new Promise((resolve, reject) => {
14677
- execFile(binaryPath, [
14678
- "-hide_banner",
14679
- "-nostdin",
14680
- "-i",
14681
- path
14682
- ], {
14683
- timeout: PROBE_TIMEOUT_MS,
14684
- maxBuffer: REPORT_MAX_BYTES,
14685
- encoding: "utf8"
14686
- }, (error, _stdout, stderr) => {
14687
- if (error !== null && (error.killed === true || stderr === "")) {
14688
- reject(new Error(error.killed === true ? "probe timed out" : error.message));
14689
- return;
14690
- }
14691
- const result = parseFfmpegReport(stderr);
14692
- if (result.streams.length === 0) reject(/* @__PURE__ */ new Error("no streams in the report"));
14693
- else resolve(result);
14694
- });
14695
- });
14696
- }
14697
- //#endregion
14698
- //#region src/provider.ts
14699
- /** The `media-library` capability over the store. A caller reads and writes only their own progress. */
14700
- function createMediaLibraryProvider(store, scans) {
14701
- return {
14702
- listSeries: ({ limit, offset, language, caller }) => store.listSeries(caller.userId, limit, offset, language),
14703
- listMovies: ({ limit, offset, language, caller }) => store.listMovies(caller.userId, limit, offset, language),
14704
- listSeasons: ({ seriesId, caller }) => store.listSeasons(caller.userId, seriesId),
14705
- listEpisodes: ({ seriesId, seasonNumber, language, caller }) => store.listEpisodes(caller.userId, seriesId, seasonNumber, language),
14706
- getItem: ({ itemId, language, caller }) => store.getItem(caller.userId, itemId, language),
14707
- search: ({ query, limit, language, caller }) => store.search(caller.userId, query, limit, language),
14708
- listRecentlyAdded: ({ limit, language, caller }) => store.listRecentlyAdded(caller.userId, limit, language),
14709
- listWatchlist: ({ limit, offset, language, caller }) => store.listWatchlist(caller.userId, limit, offset, language),
14710
- setWatchlisted: ({ itemId, on, caller }) => store.setWatchlisted(caller.userId, itemId, on),
14711
- getItemDetails: ({ itemId, language }) => store.getItemDetails(itemId, language),
14712
- getProgress: ({ itemId, caller }) => store.getProgress(caller.userId, itemId),
14713
- setProgress: ({ caller, ...input }) => store.setProgress(caller.userId, input),
14714
- markWatched: ({ caller, ...input }) => store.markWatched(caller.userId, input),
14715
- listContinue: ({ limit, language, caller }) => store.listContinue(caller.userId, limit, language),
14716
- rescan: async () => ({ started: scans.start("manual") }),
14717
- getScanStatus: async () => scans.status()
14718
- };
14719
- }
14623
+ ] };
14720
14624
  //#endregion
14721
14625
  //#region src/enrich.ts
14722
14626
  /** The default order when settings name none (D1125): files next to the media, the arr app, then online. */
@@ -14892,9 +14796,7 @@ var Enricher = class {
14892
14796
  const known = this.deps.cache.getMatch(key);
14893
14797
  if (known === null) return null;
14894
14798
  if (!known.found) return known;
14895
- const predatesTranslations = provider.translates === true && known.match.translations === void 0;
14896
- const predatesDetails = provider.providesDetails === true && known.match.details === void 0;
14897
- return predatesTranslations || predatesDetails ? null : known;
14799
+ return provider.translates === true && known.match.translations === void 0 || provider.providesDetails === true && known.match.details === void 0 ? null : known;
14898
14800
  }
14899
14801
  /** A pinned id is asked for directly: an answer of "nothing" is final, never turned into a title guess. */
14900
14802
  async lookup(provider, ask, item, kind, pin) {
@@ -15182,12 +15084,11 @@ async function classify(root, path, reader) {
15182
15084
  if (folderSeason !== null) seriesDir = dirname(parent);
15183
15085
  else if (parent !== root) seriesDir = parent;
15184
15086
  }
15185
- const prefix = guess.kind === "episode" ? guess.title : "";
15186
15087
  return {
15187
15088
  path,
15188
15089
  kind: "episode",
15189
15090
  seriesDir,
15190
- namedTitle: prefix,
15091
+ namedTitle: guess.kind === "episode" ? guess.title : "",
15191
15092
  season,
15192
15093
  episode,
15193
15094
  year: null
@@ -15694,53 +15595,7 @@ var MediaLibraryAddon = class extends BaseAddon {
15694
15595
  this.scans?.schedule(settings.rescanMinutes);
15695
15596
  this.scans?.start("settings");
15696
15597
  }
15697
- /**
15698
- * One-time, idempotent: the metadata settings of earlier versions (an order string, switches and
15699
- * four keys) become the `metadataProviders` list. The rows are written first, so each key leaves
15700
- * through the normal secret write into a keychain ref addressed by its row id (D787). An old key
15701
- * is released only once its row holds a stored key (a marker counts), and nothing at all is
15702
- * touched while an old secret cannot be read (the keychain is locked): the next boot retries.
15703
- */
15704
- async migrateLegacyProviderSettings() {
15705
- const stored = await this.resolveGlobalStore(void 0, SETTINGS_CAP);
15706
- if (!hasLegacyProviderKeys(stored)) return;
15707
- const unreadable = LEGACY_SECRET_KEYS.filter((key) => isSecretMarker(stored[key]));
15708
- if (unreadable.length > 0) {
15709
- this.ctx.logger.warn("media-library provider migration postponed: a stored key is unreadable", { meta: { keys: unreadable } });
15710
- return;
15711
- }
15712
- const parsed = array(MetadataProviderRowSchema).safeParse(stored["metadataProviders"] ?? []);
15713
- if (!parsed.success) {
15714
- this.ctx.logger.warn("media-library provider migration postponed: the stored list is invalid");
15715
- return;
15716
- }
15717
- const rows = parsed.data.length === 0 ? providerRowsFromLegacy(stored) : fillMissingKeys(parsed.data, stored);
15718
- if (JSON.stringify(rows) !== JSON.stringify(parsed.data)) await this.clusterSettings(SETTINGS_CAP, MediaLibrarySettingsSchema).patch({ metadataProviders: rows });
15719
- const after = await this.resolveGlobalStore(void 0, SETTINGS_CAP);
15720
- const held = array(MetadataProviderRowSchema).safeParse(after["metadataProviders"]);
15721
- const present = LEGACY_PROVIDER_KEYS.filter((key) => stored[key] !== void 0);
15722
- const releasable = present.filter((key) => !LEGACY_SECRET_KEYS.some((secret) => secret === key) || typeof stored[key] === "string" && stored[key] === "" || held.success && rowHoldsKey(held.data, key));
15723
- const secrets = releasable.filter((key) => LEGACY_SECRET_KEYS.some((s) => s === key));
15724
- await this.clearSecrets(secrets);
15725
- const outcome = await this.unsetStoredSettingsKeys(releasable);
15726
- this.ctx.logger.info("media-library provider settings migrated to the provider list", { meta: {
15727
- removed: outcome.removed.length,
15728
- kept: present.length - releasable.length
15729
- } });
15730
- }
15731
- /** A failed migration never stops the boot: the old keys stay and the next boot retries. */
15732
- async migrateProviderSettingsOrKeepOld() {
15733
- try {
15734
- await this.migrateLegacyProviderSettings();
15735
- } catch (error) {
15736
- this.ctx.logger.warn("media-library provider migration failed; the old settings are kept", { meta: {
15737
- step: "migrateLegacyProviderSettings",
15738
- error: String(error)
15739
- } });
15740
- }
15741
- }
15742
15598
  async onInitialize() {
15743
- await this.migrateProviderSettingsOrKeepOld();
15744
15599
  const { ctx } = this;
15745
15600
  const logger = ctx.logger;
15746
15601
  const db = settingsStoreDb(ctx.api.settingsStore);