@dominevo/addon-media-library 0.1.3 → 0.1.5

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.
@@ -1,8 +1,10 @@
1
- import { mkdir, readFile, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
2
- import { basename, dirname, extname, isAbsolute, join, sep } from "node:path";
1
+ import { mkdir, open, readFile, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
2
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  import { createReadStream } from "node:fs";
4
4
  import { createHash } from "node:crypto";
5
5
  import { execFile } from "node:child_process";
6
+ import { lookup } from "node:dns/promises";
7
+ import { isIP } from "node:net";
6
8
  //#region ../../node_modules/zod/v4/core/core.js
7
9
  var _a$1;
8
10
  /** A special constant with type `never` */
@@ -206,7 +208,7 @@ var NUMBER_FORMAT_RANGES = {
206
208
  float32: [-34028234663852886e22, 34028234663852886e22],
207
209
  float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
208
210
  };
209
- function pick(schema, mask) {
211
+ function pick$2(schema, mask) {
210
212
  const currDef = schema._zod.def;
211
213
  const checks = currDef.checks;
212
214
  if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements");
@@ -269,7 +271,7 @@ function safeExtend(schema, shape) {
269
271
  return _shape;
270
272
  } }));
271
273
  }
272
- function merge(a, b) {
274
+ function merge$1(a, b) {
273
275
  if (a._zod.def.checks?.length) throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
274
276
  return clone(a, mergeDefs(a._zod.def, {
275
277
  get shape() {
@@ -3485,7 +3487,7 @@ var parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
3485
3487
  var safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
3486
3488
  var safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
3487
3489
  var encode = /* @__PURE__ */ _encode(ZodRealError);
3488
- var decode = /* @__PURE__ */ _decode(ZodRealError);
3490
+ var decode$1 = /* @__PURE__ */ _decode(ZodRealError);
3489
3491
  var encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
3490
3492
  var decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
3491
3493
  var safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
@@ -3546,7 +3548,7 @@ var ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
3546
3548
  inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
3547
3549
  inst.spa = inst.safeParseAsync;
3548
3550
  inst.encode = (data, params) => encode(inst, data, params);
3549
- inst.decode = (data, params) => decode(inst, data, params);
3551
+ inst.decode = (data, params) => decode$1(inst, data, params);
3550
3552
  inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
3551
3553
  inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
3552
3554
  inst.safeEncode = (data, params) => safeEncode(inst, data, params);
@@ -4005,10 +4007,10 @@ var ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
4005
4007
  return safeExtend(this, incoming);
4006
4008
  },
4007
4009
  merge(other) {
4008
- return merge(this, other);
4010
+ return merge$1(this, other);
4009
4011
  },
4010
4012
  pick(mask) {
4011
- return pick(this, mask);
4013
+ return pick$2(this, mask);
4012
4014
  },
4013
4015
  omit(mask) {
4014
4016
  return omit(this, mask);
@@ -8807,6 +8809,8 @@ var MediaItemSummarySchema = /* @__PURE__ */ object({
8807
8809
  /** The caller's progress; `null` when they have none. Absent on a catalogue-only row (series). */
8808
8810
  progress: /* @__PURE__ */ MediaProgressSchema.nullable()
8809
8811
  });
8812
+ /** An episode of a season list: the summary plus its plot, read in the same query. */
8813
+ var MediaEpisodeSummarySchema = /* @__PURE__ */ MediaItemSummarySchema.extend({ overview: /* @__PURE__ */ string().nullable() });
8810
8814
  var MediaItemPageSchema = /* @__PURE__ */ object({
8811
8815
  items: /* @__PURE__ */ array(MediaItemSummarySchema).readonly(),
8812
8816
  /** How many the whole list holds, for paging. */
@@ -8875,7 +8879,7 @@ var mediaLibraryCapability = {
8875
8879
  listEpisodes: /* @__PURE__ */ method(/* @__PURE__ */ object({
8876
8880
  seriesId: /* @__PURE__ */ string().min(1),
8877
8881
  seasonNumber: /* @__PURE__ */ number().int()
8878
- }), /* @__PURE__ */ array(MediaItemSummarySchema).readonly(), { caller: "required" }),
8882
+ }), /* @__PURE__ */ array(MediaEpisodeSummarySchema).readonly(), { caller: "required" }),
8879
8883
  /** One item with its streams and direct-play path; `null` when the id is unknown. */
8880
8884
  getItem: /* @__PURE__ */ method(/* @__PURE__ */ object({ itemId: /* @__PURE__ */ string().min(1) }), /* @__PURE__ */ MediaItemDetailSchema.nullable(), { caller: "required" }),
8881
8885
  /** Series and movies whose title contains the query, case and accents ignored. */
@@ -8927,6 +8931,30 @@ var mediaLibraryCapability = {
8927
8931
  vocabulary: { notOperatorFacing: "the media library is a viewer app surface, not a device action" }
8928
8932
  };
8929
8933
  //#endregion
8934
+ //#region ../types/dist/esm/capabilities/custom-actions.mjs
8935
+ /**
8936
+ * Identity — preserves literal types for downstream inference.
8937
+ *
8938
+ * The constraint is `Record<string, unknown>` (not `CustomActionsSpec`) so
8939
+ * TypeScript does not widen each entry's literal `kind`/`auth` fields to
8940
+ * the broader unions declared on `CustomActionSpec`'s default generics.
8941
+ * Shape validity is enforced separately by the `customAction(...)` helper
8942
+ * whose return type is already a `CustomActionSpec<...>`.
8943
+ */
8944
+ function defineCustomActions(spec) {
8945
+ return spec;
8946
+ }
8947
+ function customAction(input, output, options) {
8948
+ return {
8949
+ input,
8950
+ output,
8951
+ kind: options?.kind ?? "query",
8952
+ auth: options?.auth ?? "protected",
8953
+ scope: options?.scope ?? { kind: "system" },
8954
+ ...options?.caller ? { caller: "required" } : {}
8955
+ };
8956
+ }
8957
+ //#endregion
8930
8958
  //#region src/address-roles.ts
8931
8959
  var MEDIA_ADDRESS_ROLE_ID = "media-library:media";
8932
8960
  function buildAddressRoles() {
@@ -8968,7 +8996,7 @@ function buildApp() {
8968
8996
  }
8969
8997
  //#endregion
8970
8998
  //#region src/arr-client.ts
8971
- var ImageSchema = object({
8999
+ var ImageSchema$1 = object({
8972
9000
  coverType: string(),
8973
9001
  url: string().nullish()
8974
9002
  });
@@ -8980,16 +9008,17 @@ var CommonSchema = object({
8980
9008
  tmdbId: number().int().nullish(),
8981
9009
  imdbId: string().nullish(),
8982
9010
  added: string().nullish(),
8983
- images: array(ImageSchema).default([])
9011
+ images: array(ImageSchema$1).default([])
8984
9012
  });
8985
9013
  var SeriesSchema = CommonSchema.extend({ tvdbId: number().int().nullish() });
8986
9014
  var MovieSchema = CommonSchema.extend({ movieFile: object({ path: string() }).nullish() });
8987
- var EpisodeSchema = object({
9015
+ var EpisodeSchema$1 = object({
8988
9016
  id: number().int(),
8989
9017
  title: string().nullish(),
8990
9018
  seasonNumber: number().int(),
8991
9019
  episodeNumber: number().int(),
8992
- episodeFile: object({ path: string() }).nullish()
9020
+ episodeFile: object({ path: string() }).nullish(),
9021
+ images: array(ImageSchema$1).default([])
8993
9022
  });
8994
9023
  function coverOf(images, type) {
8995
9024
  const url = images.find((image) => image.coverType === type)?.url;
@@ -9022,7 +9051,7 @@ async function fetchArrSeries(source, get) {
9022
9051
  const list = array(SeriesSchema).parse(await get(api(source, "series"), source.apiKey));
9023
9052
  const out = [];
9024
9053
  for (const raw of list) {
9025
- const episodes = array(EpisodeSchema).parse(await get(api(source, `episode?seriesId=${raw.id}&includeEpisodeFile=true`), source.apiKey));
9054
+ const episodes = array(EpisodeSchema$1).parse(await get(api(source, `episode?seriesId=${raw.id}&includeEpisodeFile=true&includeImages=true`), source.apiKey));
9026
9055
  out.push({
9027
9056
  ...entryOf(raw),
9028
9057
  episodes: episodes.map((episode) => ({
@@ -9030,7 +9059,8 @@ async function fetchArrSeries(source, get) {
9030
9059
  title: episode.title ?? "",
9031
9060
  seasonNumber: episode.seasonNumber,
9032
9061
  episodeNumber: episode.episodeNumber,
9033
- path: episode.episodeFile?.path ?? null
9062
+ path: episode.episodeFile?.path ?? null,
9063
+ still: coverOf(episode.images, "screenshot")
9034
9064
  }))
9035
9065
  });
9036
9066
  }
@@ -9130,6 +9160,503 @@ function withOptionalId(record) {
9130
9160
  };
9131
9161
  }
9132
9162
  //#endregion
9163
+ //#region src/settings.ts
9164
+ /** The capability that owns the cluster-scoped settings (D986). */
9165
+ var SETTINGS_CAP = "media-library";
9166
+ /** An http(s) base URL without credentials, query or trailing slash; `''` is "not configured"; `null` is invalid. */
9167
+ function normalizeBaseUrl(raw) {
9168
+ const text = raw.trim();
9169
+ if (text === "") return "";
9170
+ let url;
9171
+ try {
9172
+ url = new URL(text);
9173
+ } catch {
9174
+ return null;
9175
+ }
9176
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
9177
+ if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") return null;
9178
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
9179
+ }
9180
+ var BaseUrlSchema = string().transform((value, ctx) => {
9181
+ const normalized = normalizeBaseUrl(value);
9182
+ if (normalized === null) {
9183
+ ctx.addIssue({
9184
+ code: "custom",
9185
+ message: "expected an http(s) URL"
9186
+ });
9187
+ return NEVER;
9188
+ }
9189
+ return normalized;
9190
+ });
9191
+ /** The metadata steps, in the order they answer by default: files, the arr app, then online (each needs its key or switch), pictures last. */
9192
+ var METADATA_STEPS = [
9193
+ "local",
9194
+ "arr",
9195
+ "tmdb",
9196
+ "tvmaze",
9197
+ "tvdb",
9198
+ "omdb",
9199
+ "anilist",
9200
+ "fanart"
9201
+ ];
9202
+ var DEFAULT_METADATA_ORDER = METADATA_STEPS;
9203
+ /** The steps that cannot answer without the installation's own key. */
9204
+ var KEYED_STEPS = [
9205
+ "tmdb",
9206
+ "tvdb",
9207
+ "omdb",
9208
+ "fanart"
9209
+ ];
9210
+ function isStep(value) {
9211
+ return METADATA_STEPS.some((step) => step === value);
9212
+ }
9213
+ function isKeyedStep(step) {
9214
+ return KEYED_STEPS.some((keyed) => keyed === step);
9215
+ }
9216
+ /** What the settings list shows for each step. */
9217
+ var STEP_NAMES = {
9218
+ local: "Local files",
9219
+ arr: "Sonarr and Radarr",
9220
+ tmdb: "TMDB",
9221
+ tvmaze: "TVmaze",
9222
+ tvdb: "TheTVDB",
9223
+ omdb: "OMDb",
9224
+ anilist: "AniList",
9225
+ fanart: "Fanart.tv"
9226
+ };
9227
+ /** One row of the metadata chain: the row order is the order the steps answer in (D1125). */
9228
+ var MetadataProviderRowSchema = object({
9229
+ /** The step this row is; stable, it addresses the row's secret. */
9230
+ id: string(),
9231
+ /** The step's display name, stamped by the addon for the row title. */
9232
+ name: string().default(""),
9233
+ enabled: boolean().default(true),
9234
+ /** The installation's own key or token, for a keyed step; unused by the others. */
9235
+ apiKey: string().meta({ secret: true }).default("")
9236
+ });
9237
+ /** A row for `step`; AniList needs no account but sends titles out, so it starts off. */
9238
+ function providerRow(step, patch = {}) {
9239
+ return {
9240
+ id: step,
9241
+ name: STEP_NAMES[step],
9242
+ enabled: step !== "anilist",
9243
+ apiKey: "",
9244
+ ...patch
9245
+ };
9246
+ }
9247
+ /** The list a fresh installation starts from: every step, in the default order. */
9248
+ function defaultProviderRows() {
9249
+ return DEFAULT_METADATA_ORDER.map((step) => providerRow(step));
9250
+ }
9251
+ /** A keyed row answers only with a key; the other steps need none. */
9252
+ function rowAnswers(row, step) {
9253
+ return row.enabled && (!isKeyedStep(step) || row.apiKey.trim() !== "");
9254
+ }
9255
+ /** 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. */
9256
+ function resolveMetadataSteps(settings) {
9257
+ const out = [];
9258
+ for (const row of settings.metadataProviders) {
9259
+ const step = row.id.toLowerCase();
9260
+ if (isStep(step) && rowAnswers(row, step) && !out.includes(step)) out.push(step);
9261
+ }
9262
+ return out;
9263
+ }
9264
+ /** The key of a keyed step, or `''` when the step is not answering. */
9265
+ function keyOf(settings, step) {
9266
+ if (!resolveMetadataSteps(settings).includes(step)) return "";
9267
+ return settings.metadataProviders.find((candidate) => candidate.id.toLowerCase() === step)?.apiKey.trim() ?? "";
9268
+ }
9269
+ 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.";
9270
+ var MediaLibrarySettingsSchema = object({
9271
+ seriesArrUrl: BaseUrlSchema.default(""),
9272
+ seriesArrKey: string().default(""),
9273
+ /** Where the series app sees the library, and where this node mounts it. */
9274
+ seriesPathFrom: string().default(""),
9275
+ seriesPathTo: string().default(""),
9276
+ moviesArrUrl: BaseUrlSchema.default(""),
9277
+ moviesArrKey: string().default(""),
9278
+ moviesPathFrom: string().default(""),
9279
+ moviesPathTo: string().default(""),
9280
+ /** Plain folders walked for files the arr apps do not know, one absolute path per line. */
9281
+ folderRoots: string().default(""),
9282
+ rescanMinutes: number().int().min(0).default(60),
9283
+ /** The metadata chain, one row per step in the order they answer; the first answer to a field wins (D1125). */
9284
+ metadataProviders: array(MetadataProviderRowSchema).default(defaultProviderRows),
9285
+ /** The Plex import (a one-shot, re-runnable action): the server, a token, and how paths and users line up. */
9286
+ plexUrl: BaseUrlSchema.default(""),
9287
+ plexToken: string().meta({ secret: true }).default(""),
9288
+ plexPathFrom: string().default(""),
9289
+ plexPathTo: string().default(""),
9290
+ plexUserMap: string().default("")
9291
+ });
9292
+ /** A source is on only when both its URL and key are set; a half-filled one is off, not guessed. */
9293
+ function resolveSources(settings) {
9294
+ const pick = (baseUrl, apiKey, pathFrom, pathTo) => baseUrl === "" || apiKey === "" ? null : {
9295
+ baseUrl,
9296
+ apiKey,
9297
+ pathFrom: pathFrom.trim(),
9298
+ pathTo: pathTo.trim()
9299
+ };
9300
+ return {
9301
+ series: pick(settings.seriesArrUrl, settings.seriesArrKey, settings.seriesPathFrom, settings.seriesPathTo),
9302
+ movies: pick(settings.moviesArrUrl, settings.moviesArrKey, settings.moviesPathFrom, settings.moviesPathTo),
9303
+ folderRoots: settings.folderRoots.split("\n").map((line) => line.trim()).filter((line) => line !== ""),
9304
+ metadataSteps: resolveMetadataSteps(settings),
9305
+ tmdbToken: keyOf(settings, "tmdb"),
9306
+ tvdbApiKey: keyOf(settings, "tvdb"),
9307
+ fanartApiKey: keyOf(settings, "fanart"),
9308
+ omdbApiKey: keyOf(settings, "omdb")
9309
+ };
9310
+ }
9311
+ /** The import is configured only when both the server URL and the token are set. */
9312
+ function resolvePlex(settings) {
9313
+ if (settings.plexUrl === "" || settings.plexToken === "") return null;
9314
+ return {
9315
+ baseUrl: settings.plexUrl,
9316
+ token: settings.plexToken,
9317
+ pathFrom: settings.plexPathFrom.trim(),
9318
+ pathTo: settings.plexPathTo.trim(),
9319
+ userMap: settings.plexUserMap
9320
+ };
9321
+ }
9322
+ var MEDIA_LIBRARY_CLUSTER_SCHEMA = { sections: [
9323
+ {
9324
+ id: "series",
9325
+ title: "Series source",
9326
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.title",
9327
+ fields: [
9328
+ {
9329
+ type: "text",
9330
+ key: "seriesArrUrl",
9331
+ label: "Sonarr URL",
9332
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrUrl.label",
9333
+ description: "Address of the series app, for example http://192.168.1.20:8989. Empty turns the source off.",
9334
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrUrl.description"
9335
+ },
9336
+ {
9337
+ type: "password",
9338
+ key: "seriesArrKey",
9339
+ label: "Sonarr API key",
9340
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrKey.label"
9341
+ },
9342
+ {
9343
+ type: "text",
9344
+ key: "seriesPathFrom",
9345
+ label: "Path in Sonarr",
9346
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathFrom.label",
9347
+ description: "The library folder as the series app sees it, for example /tv.",
9348
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathFrom.description"
9349
+ },
9350
+ {
9351
+ type: "text",
9352
+ key: "seriesPathTo",
9353
+ label: "Path on this hub",
9354
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathTo.label",
9355
+ description: "Where the same folder is mounted on this hub.",
9356
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathTo.description"
9357
+ }
9358
+ ]
9359
+ },
9360
+ {
9361
+ id: "movies",
9362
+ title: "Movies source",
9363
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.title",
9364
+ fields: [
9365
+ {
9366
+ type: "text",
9367
+ key: "moviesArrUrl",
9368
+ label: "Radarr URL",
9369
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrUrl.label",
9370
+ description: "Address of the movies app, for example http://192.168.1.20:7878. Empty turns the source off.",
9371
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrUrl.description"
9372
+ },
9373
+ {
9374
+ type: "password",
9375
+ key: "moviesArrKey",
9376
+ label: "Radarr API key",
9377
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrKey.label"
9378
+ },
9379
+ {
9380
+ type: "text",
9381
+ key: "moviesPathFrom",
9382
+ label: "Path in Radarr",
9383
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathFrom.label",
9384
+ description: "The library folder as the movies app sees it, for example /movies.",
9385
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathFrom.description"
9386
+ },
9387
+ {
9388
+ type: "text",
9389
+ key: "moviesPathTo",
9390
+ label: "Path on this hub",
9391
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathTo.label",
9392
+ description: "Where the same folder is mounted on this hub.",
9393
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathTo.description"
9394
+ }
9395
+ ]
9396
+ },
9397
+ {
9398
+ id: "folders",
9399
+ title: "Folders",
9400
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.title",
9401
+ fields: [{
9402
+ type: "textarea",
9403
+ key: "folderRoots",
9404
+ label: "Folders to walk",
9405
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.label",
9406
+ description: "One absolute path per line. Files the arr apps do not know are added from here.",
9407
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.description"
9408
+ }, {
9409
+ type: "number",
9410
+ key: "rescanMinutes",
9411
+ label: "Rescan every (minutes)",
9412
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.label",
9413
+ description: "0 scans only when asked.",
9414
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
9415
+ min: 0
9416
+ }]
9417
+ },
9418
+ {
9419
+ id: "metadata",
9420
+ title: "Metadata",
9421
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.title",
9422
+ fields: [{
9423
+ type: "info",
9424
+ key: "providersGuide",
9425
+ label: "How to get the keys",
9426
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.providersGuide.label",
9427
+ format: "html",
9428
+ content: PROVIDERS_GUIDE_EN,
9429
+ contentKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.providersGuide.content"
9430
+ }, {
9431
+ type: "editable-array",
9432
+ key: "metadataProviders",
9433
+ label: "Metadata providers",
9434
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.label",
9435
+ 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.",
9436
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.description",
9437
+ default: defaultProviderRows(),
9438
+ reorderable: true,
9439
+ fixedRows: true,
9440
+ itemIdKey: "id",
9441
+ rowTitleTemplate: "{name}",
9442
+ itemFields: [
9443
+ {
9444
+ type: "text",
9445
+ key: "id",
9446
+ label: "Provider",
9447
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.id.label",
9448
+ showWhen: {
9449
+ field: "id",
9450
+ equals: ""
9451
+ }
9452
+ },
9453
+ {
9454
+ type: "text",
9455
+ key: "name",
9456
+ label: "Name",
9457
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.name.label",
9458
+ showWhen: {
9459
+ field: "id",
9460
+ equals: ""
9461
+ }
9462
+ },
9463
+ {
9464
+ type: "boolean",
9465
+ key: "enabled",
9466
+ label: "Use this provider",
9467
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.enabled.label"
9468
+ },
9469
+ {
9470
+ type: "password",
9471
+ key: "apiKey",
9472
+ label: "API key or token",
9473
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.apiKey.label",
9474
+ description: "The key of your own account, stored in the keychain. Without it this provider is skipped.",
9475
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataProviders.apiKey.description",
9476
+ showWhen: {
9477
+ field: "id",
9478
+ in: [...KEYED_STEPS]
9479
+ }
9480
+ }
9481
+ ]
9482
+ }]
9483
+ },
9484
+ {
9485
+ id: "plex",
9486
+ title: "Import from Plex",
9487
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.title",
9488
+ fields: [
9489
+ {
9490
+ type: "text",
9491
+ key: "plexUrl",
9492
+ label: "Plex server URL",
9493
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUrl.label",
9494
+ 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.",
9495
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUrl.description"
9496
+ },
9497
+ {
9498
+ type: "password",
9499
+ key: "plexToken",
9500
+ label: "Plex token",
9501
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexToken.label",
9502
+ description: "The server owner's X-Plex-Token. Stored in the keychain.",
9503
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexToken.description"
9504
+ },
9505
+ {
9506
+ type: "text",
9507
+ key: "plexPathFrom",
9508
+ label: "Path in Plex",
9509
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathFrom.label",
9510
+ description: "The library folder as Plex sees it, for example /data/movies. Used to match files by path when the ids do not match.",
9511
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathFrom.description"
9512
+ },
9513
+ {
9514
+ type: "text",
9515
+ key: "plexPathTo",
9516
+ label: "Path on this hub",
9517
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathTo.label",
9518
+ description: "Where the same folder is mounted on this hub.",
9519
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexPathTo.description"
9520
+ },
9521
+ {
9522
+ type: "textarea",
9523
+ key: "plexUserMap",
9524
+ label: "Plex user to Dominevo user",
9525
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUserMap.label",
9526
+ description: "One \"plexName = dominevoUsername\" per line. Without a line a Plex user is matched by username, title or email.",
9527
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.plexUserMap.description"
9528
+ },
9529
+ {
9530
+ type: "addon-action-button",
9531
+ addonId: "media-library",
9532
+ key: "__plex-import-preview",
9533
+ label: "Preview the Plex import",
9534
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-preview.label",
9535
+ description: "Reads Plex and works out what would be imported per user. Writes nothing. Save the settings first.",
9536
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-preview.description",
9537
+ buttonLabel: "Preview",
9538
+ action: "plexImportPreview",
9539
+ successMessage: "{message}"
9540
+ },
9541
+ {
9542
+ type: "addon-action-button",
9543
+ addonId: "media-library",
9544
+ key: "__plex-import-run",
9545
+ label: "Import from Plex",
9546
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-run.label",
9547
+ description: "Imports watched state, resume positions and Plex's TMDB/TVDB/IMDb ids. Safe to run again: a newer Dominevo position is never overwritten.",
9548
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_plex.__plex-import-run.description",
9549
+ buttonLabel: "Import",
9550
+ action: "plexImportRun",
9551
+ variant: "primary",
9552
+ confirmMessage: "Import watch history and ids from Plex now?",
9553
+ successMessage: "{message}"
9554
+ }
9555
+ ]
9556
+ }
9557
+ ] };
9558
+ //#endregion
9559
+ //#region src/settings-migration.ts
9560
+ /** The settings the provider list replaced; stored by installations that saved before it. */
9561
+ var LEGACY_PROVIDER_KEYS = [
9562
+ "metadataOrder",
9563
+ "metadataLocalEnabled",
9564
+ "metadataArrEnabled",
9565
+ "metadataTvmazeEnabled",
9566
+ "metadataAnilistEnabled",
9567
+ "tmdbToken",
9568
+ "tvdbApiKey",
9569
+ "omdbApiKey",
9570
+ "fanartApiKey"
9571
+ ];
9572
+ /** The old keys that held a credential. */
9573
+ var LEGACY_SECRET_KEYS = [
9574
+ "tmdbToken",
9575
+ "tvdbApiKey",
9576
+ "omdbApiKey",
9577
+ "fanartApiKey"
9578
+ ];
9579
+ var LEGACY_KEY_OF_STEP = {
9580
+ tmdb: "tmdbToken",
9581
+ tvdb: "tvdbApiKey",
9582
+ omdb: "omdbApiKey",
9583
+ fanart: "fanartApiKey"
9584
+ };
9585
+ /** Orders saved by the defaults of earlier versions (TVmaze first, with or without TMDB): they mean "the default". */
9586
+ var LEGACY_DEFAULT_ORDER = /^local[\s,]+arr[\s,]+tvmaze(?:[\s,]+tmdb)?$/i;
9587
+ function text$4(value) {
9588
+ return typeof value === "string" ? value : "";
9589
+ }
9590
+ function flag(value, fallback) {
9591
+ return typeof value === "boolean" ? value : fallback;
9592
+ }
9593
+ /** The old order, then every step it left out (those were off). */
9594
+ function legacyOrder(raw) {
9595
+ const trimmed = raw.trim();
9596
+ if (trimmed === "" || LEGACY_DEFAULT_ORDER.test(trimmed)) return {
9597
+ order: [...DEFAULT_METADATA_ORDER],
9598
+ named: new Set(DEFAULT_METADATA_ORDER)
9599
+ };
9600
+ const named = /* @__PURE__ */ new Set();
9601
+ const order = [];
9602
+ for (const name of trimmed.split(/[\s,]+/)) {
9603
+ const step = name.toLowerCase();
9604
+ if (isStep(step) && !named.has(step)) {
9605
+ named.add(step);
9606
+ order.push(step);
9607
+ }
9608
+ }
9609
+ for (const step of DEFAULT_METADATA_ORDER) if (!named.has(step)) order.push(step);
9610
+ return {
9611
+ order,
9612
+ named
9613
+ };
9614
+ }
9615
+ function hasLegacyProviderKeys(stored) {
9616
+ return LEGACY_PROVIDER_KEYS.some((key) => stored[key] !== void 0);
9617
+ }
9618
+ /**
9619
+ * The provider list the old settings meant. `stored` holds RESOLVED values (the keys are plain
9620
+ * strings here, moved on into the keychain by the write that stores the rows). A step the old
9621
+ * order did not name is off, as it was; a keyed step is on when its key was set.
9622
+ */
9623
+ function providerRowsFromLegacy(stored) {
9624
+ const { order, named } = legacyOrder(text$4(stored["metadataOrder"]));
9625
+ const flags = {
9626
+ local: flag(stored["metadataLocalEnabled"], true),
9627
+ arr: flag(stored["metadataArrEnabled"], true),
9628
+ tvmaze: flag(stored["metadataTvmazeEnabled"], true),
9629
+ anilist: flag(stored["metadataAnilistEnabled"], false)
9630
+ };
9631
+ return order.map((step) => {
9632
+ if (step === "local" || step === "arr" || step === "tvmaze" || step === "anilist") return providerRow(step, { enabled: named.has(step) && flags[step] });
9633
+ const apiKey = text$4(stored[LEGACY_KEY_OF_STEP[step]]);
9634
+ return providerRow(step, {
9635
+ enabled: named.has(step) && apiKey !== "",
9636
+ apiKey
9637
+ });
9638
+ });
9639
+ }
9640
+ /** The old secret key a step's row replaced. */
9641
+ function legacyKeyOfStep(step) {
9642
+ return isStep(step) && isKeyedStep(step) ? LEGACY_KEY_OF_STEP[step] : void 0;
9643
+ }
9644
+ /** Whether the stored row of the step `legacyKey` belonged to holds a key (a marker counts). */
9645
+ function rowHoldsKey(rows, legacyKey) {
9646
+ return rows.some((row) => legacyKeyOfStep(row.id) === legacyKey && row.apiKey.trim() !== "");
9647
+ }
9648
+ /** A stored list whose keyed row is empty takes the old key of that step; nothing else changes. */
9649
+ function fillMissingKeys(rows, stored) {
9650
+ return rows.map((row) => {
9651
+ const legacy = legacyKeyOfStep(row.id);
9652
+ const key = legacy === void 0 ? "" : text$4(stored[legacy]);
9653
+ return row.apiKey.trim() === "" && key !== "" ? {
9654
+ ...row,
9655
+ apiKey: key
9656
+ } : row;
9657
+ });
9658
+ }
9659
+ //#endregion
9133
9660
  //#region src/naming.ts
9134
9661
  /** Case- and accent-insensitive form of a title, for search and ordering. */
9135
9662
  function foldTitle(title) {
@@ -9466,120 +9993,30 @@ var walkFolder = async (root) => {
9466
9993
  };
9467
9994
  };
9468
9995
  //#endregion
9469
- //#region src/img-plane.ts
9470
- var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
9471
- var IMAGE_TIMEOUT_MS = 2e4;
9472
- /** The real fetch: the key travels in a header, a redirect is never followed, the body is size-capped. */
9473
- var httpImageFetch = async (url, apiKey) => {
9474
- const response = await fetch(url, {
9475
- headers: { "X-Api-Key": apiKey },
9476
- redirect: "manual",
9477
- signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
9478
- });
9479
- if (response.status >= 300 && response.status < 400) throw new Error(`redirect refused (HTTP ${response.status}): the key is never sent to another URL`);
9480
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
9481
- if (Number(response.headers.get("content-length") ?? "0") > MAX_IMAGE_BYTES) throw new Error("image too large");
9482
- const body = Buffer.from(await response.arrayBuffer());
9483
- if (body.length > MAX_IMAGE_BYTES) throw new Error("image too large");
9484
- return body;
9485
- };
9486
- function typeOf(bytes) {
9487
- if (bytes.length > 3 && bytes[0] === 255 && bytes[1] === 216) return "image/jpeg";
9488
- if (bytes.length > 8 && bytes.subarray(1, 4).toString("latin1") === "PNG") return "image/png";
9489
- if (bytes.length > 12 && bytes.subarray(8, 12).toString("latin1") === "WEBP") return "image/webp";
9490
- return null;
9491
- }
9492
- /** The remote URL of an arr cover: only a path on the arr's own origin, never another host. */
9493
- function coverUrl(source, path) {
9494
- if (!path.startsWith("/") || path.startsWith("//")) return null;
9495
- const base = new URL(source.baseUrl);
9496
- const url = new URL(`${source.baseUrl}${path}`);
9497
- return url.origin === base.origin ? url.toString() : null;
9498
- }
9499
- function end(res, status) {
9500
- res.writeHead(status, { "Content-Length": 0 });
9501
- res.end();
9502
- }
9503
- /** The `img` plane: `GET /<itemId>/poster|fanart`, fetched from the arr once and cached on disk. */
9504
- function createImagePlaneHandler(deps) {
9505
- const inFlight = /* @__PURE__ */ new Map();
9506
- const load = async (itemId, which) => {
9507
- const tags = { itemId };
9508
- const found = await deps.source(itemId, which);
9509
- if (found === null) return null;
9510
- const key = hashKey(`${itemId}:${which}:${found.source}`);
9511
- const cached = join(deps.cacheDir, key);
9512
- try {
9513
- const onDisk = await readFile(cached);
9514
- if (typeOf(onDisk) !== null) return onDisk;
9515
- deps.logger.warn("cached image is not an image: dropped and fetched again", {
9516
- tags,
9517
- meta: { reason: "cache-corrupt" }
9518
- });
9519
- await unlink(cached);
9520
- } catch {}
9521
- const arr = await deps.arrSource(found.sourceId);
9522
- const url = arr === null ? null : coverUrl(arr, found.source);
9523
- if (arr === null || url === null) {
9524
- deps.logger.warn("image skipped: no usable source", {
9525
- tags,
9526
- meta: { reason: arr === null ? "source-off" : "foreign-origin" }
9527
- });
9528
- return null;
9529
- }
9530
- try {
9531
- const bytes = await deps.fetchImage(url, arr.apiKey);
9532
- if (typeOf(bytes) === null) throw new Error("not an image");
9533
- await mkdir(deps.cacheDir, { recursive: true });
9534
- await writeFile(`${cached}.tmp`, bytes);
9535
- await rename(`${cached}.tmp`, cached);
9536
- return bytes;
9537
- } catch (error) {
9538
- deps.logger.warn("image fetch failed", {
9539
- tags,
9540
- meta: {
9541
- reason: "fetch-failed",
9542
- error: error instanceof Error ? error.message : String(error)
9543
- }
9544
- });
9545
- return null;
9546
- }
9547
- };
9548
- return async (req, res) => {
9549
- if (req.method !== "GET" && req.method !== "HEAD") return end(res, 405);
9550
- const parts = ((req.url ?? "/").split("?")[0] ?? "/").replace(/^\//, "").split("/");
9551
- const [rawId, which] = parts;
9552
- let itemId = "";
9553
- try {
9554
- itemId = decodeURIComponent(rawId ?? "");
9555
- } catch {
9556
- return end(res, 404);
9557
- }
9558
- if (parts.length !== 2 || !isItemId(itemId) || which !== "poster" && which !== "fanart") {
9559
- deps.logger.warn("image request refused", { meta: { reason: "bad-request" } });
9560
- return end(res, 404);
9561
- }
9562
- const flightKey = `${itemId}:${which}`;
9563
- const pending = inFlight.get(flightKey) ?? load(itemId, which);
9564
- inFlight.set(flightKey, pending);
9565
- let bytes;
9566
- try {
9567
- bytes = await pending;
9568
- } finally {
9569
- inFlight.delete(flightKey);
9570
- }
9571
- const contentType = bytes === null ? null : typeOf(bytes);
9572
- if (bytes === null || contentType === null) return end(res, 404);
9573
- res.writeHead(200, {
9574
- "Content-Type": contentType,
9575
- "Content-Length": bytes.length,
9576
- "Cache-Control": "private, max-age=86400"
9996
+ //#region src/db.ts
9997
+ /** Rows per page of a whole-collection read; under the store's 2 000-row default cap. */
9998
+ var READ_ALL_PAGE = 1e3;
9999
+ /**
10000
+ * Every row of `collection` matching `filter`, paged in `orderField` order. A query with no `limit`
10001
+ * is capped by the store (2 000 rows), so a whole-collection read that does not page silently sees
10002
+ * a fraction of a large library.
10003
+ */
10004
+ async function queryAll(db, collection, orderField, filter = {}) {
10005
+ const out = [];
10006
+ for (let offset = 0;; offset += READ_ALL_PAGE) {
10007
+ const page = await db.query(collection, {
10008
+ ...filter,
10009
+ orderBy: {
10010
+ field: orderField,
10011
+ direction: "asc"
10012
+ },
10013
+ limit: READ_ALL_PAGE,
10014
+ offset
9577
10015
  });
9578
- res.end(req.method === "HEAD" ? void 0 : bytes);
9579
- };
10016
+ out.push(...page);
10017
+ if (page.length < 1e3) return out;
10018
+ }
9580
10019
  }
9581
- //#endregion
9582
- //#region src/db.ts
9583
10020
  /** Parse every row with `schema`; a row that does not parse is dropped and reported to `onInvalid`. */
9584
10021
  function parseRows(schema, rows, onInvalid) {
9585
10022
  const out = [];
@@ -9591,11 +10028,147 @@ function parseRows(schema, rows, onInvalid) {
9591
10028
  return out;
9592
10029
  }
9593
10030
  //#endregion
10031
+ //#region src/metadata.ts
10032
+ var ProviderMatchSchema = object({
10033
+ providerId: string(),
10034
+ /** The provider's own id of the match, used to ask for its episodes. */
10035
+ remoteId: string(),
10036
+ title: string(),
10037
+ year: number().int().nullable(),
10038
+ overview: string().nullable(),
10039
+ tvdbId: number().int().nullable(),
10040
+ tmdbId: number().int().nullable(),
10041
+ imdbId: string().nullable(),
10042
+ poster: string().nullable(),
10043
+ fanart: string().nullable()
10044
+ });
10045
+ var ProviderEpisodeSchema = object({
10046
+ season: number().int(),
10047
+ episode: number().int(),
10048
+ title: string().nullable(),
10049
+ overview: string().nullable(),
10050
+ still: string().nullable()
10051
+ });
10052
+ /** The provider refused its credential: asking again cannot work until the operator fixes it. */
10053
+ var ProviderAuthError = class extends Error {
10054
+ constructor(message) {
10055
+ super(message);
10056
+ this.name = "ProviderAuthError";
10057
+ }
10058
+ };
10059
+ //#endregion
10060
+ //#region src/match-cache.ts
10061
+ var MATCHES = "media-library:matches";
10062
+ var MATCHES_DECLARATION = {
10063
+ collection: MATCHES,
10064
+ primaryKey: ["key"],
10065
+ columns: [
10066
+ {
10067
+ name: "key",
10068
+ type: "TEXT",
10069
+ notNull: true
10070
+ },
10071
+ {
10072
+ name: "value",
10073
+ type: "JSON",
10074
+ notNull: true
10075
+ },
10076
+ {
10077
+ name: "fetchedAt",
10078
+ type: "INTEGER",
10079
+ notNull: true
10080
+ }
10081
+ ]
10082
+ };
10083
+ /** A match that was found stays this long; an answered "nothing" and an episode list expire sooner. */
10084
+ var FOUND_TTL_MS = 720 * 60 * 60 * 1e3;
10085
+ var ABSENT_TTL_MS = 4320 * 60 * 1e3;
10086
+ var EntrySchema = discriminatedUnion("found", [object({
10087
+ found: literal(true),
10088
+ match: ProviderMatchSchema
10089
+ }), object({ found: literal(false) })]);
10090
+ var EpisodesSchema$1 = object({ episodes: array(ProviderEpisodeSchema) });
10091
+ var RowSchema = object({
10092
+ key: string(),
10093
+ value: unknown(),
10094
+ fetchedAt: number()
10095
+ });
10096
+ /**
10097
+ * Answers the providers gave, kept so a rescan does not ask again about an unchanged item.
10098
+ * Read once at the start of a scan, written once at its end; a failed provider call is never stored.
10099
+ */
10100
+ var MatchCache = class MatchCache {
10101
+ now;
10102
+ rows = /* @__PURE__ */ new Map();
10103
+ dirty = /* @__PURE__ */ new Set();
10104
+ constructor(now) {
10105
+ this.now = now;
10106
+ }
10107
+ static async load(db, now) {
10108
+ const cache = new MatchCache(now);
10109
+ for (const raw of await queryAll(db, MATCHES, "key")) {
10110
+ const parsed = RowSchema.safeParse(raw);
10111
+ if (parsed.success) cache.rows.set(parsed.data.key, {
10112
+ value: parsed.data.value,
10113
+ fetchedAt: parsed.data.fetchedAt
10114
+ });
10115
+ }
10116
+ return cache;
10117
+ }
10118
+ fresh(key, ttlMs) {
10119
+ const row = this.rows.get(key);
10120
+ return row !== void 0 && this.now() - row.fetchedAt < ttlMs ? { value: row.value } : null;
10121
+ }
10122
+ put(key, value) {
10123
+ this.rows.set(key, {
10124
+ value,
10125
+ fetchedAt: this.now()
10126
+ });
10127
+ this.dirty.add(key);
10128
+ }
10129
+ getMatch(key) {
10130
+ const known = this.fresh(key, FOUND_TTL_MS);
10131
+ if (known === null) return null;
10132
+ const parsed = EntrySchema.safeParse(known.value);
10133
+ if (!parsed.success) return null;
10134
+ return parsed.data.found || this.fresh(key, 2592e5) !== null ? parsed.data : null;
10135
+ }
10136
+ putMatch(key, entry) {
10137
+ this.put(key, entry);
10138
+ }
10139
+ getEpisodes(key) {
10140
+ const known = this.fresh(key, ABSENT_TTL_MS);
10141
+ if (known === null) return null;
10142
+ const parsed = EpisodesSchema$1.safeParse(known.value);
10143
+ return parsed.success ? parsed.data : null;
10144
+ }
10145
+ putEpisodes(key, entry) {
10146
+ this.put(key, entry);
10147
+ }
10148
+ /** How many answers are waiting to be written. */
10149
+ get pending() {
10150
+ return this.dirty.size;
10151
+ }
10152
+ async flush(db) {
10153
+ const writes = [...this.dirty].flatMap((key) => {
10154
+ const row = this.rows.get(key);
10155
+ return row === void 0 ? [] : [{
10156
+ key,
10157
+ value: row.value,
10158
+ fetchedAt: row.fetchedAt
10159
+ }];
10160
+ });
10161
+ this.dirty.clear();
10162
+ if (writes.length > 0) await db.upsertMany(MATCHES, ["key"], writes);
10163
+ }
10164
+ };
10165
+ //#endregion
9594
10166
  //#region src/rows.ts
9595
10167
  /** The collections live in the shared settings database; the closed `database` enum has no media file. */
9596
10168
  var ITEMS = "media-library:items";
9597
10169
  var FILES = "media-library:files";
9598
10170
  var PROGRESS = "media-library:progress";
10171
+ var PINS = "media-library:pins";
9599
10172
  /** Item row: one series, movie or episode of the catalogue. */
9600
10173
  var ItemRowSchema = object({
9601
10174
  id: string(),
@@ -9635,6 +10208,16 @@ var FileRowSchema = object({
9635
10208
  streams: array(LibraryStreamSchema),
9636
10209
  probeError: string().nullable()
9637
10210
  });
10211
+ var PinSourceSchema = _enum(["plex", "manual"]);
10212
+ var PinRowSchema = object({
10213
+ itemId: string(),
10214
+ source: PinSourceSchema,
10215
+ kind: MediaItemKindSchema,
10216
+ tvdbId: number().int().nullable(),
10217
+ tmdbId: number().int().nullable(),
10218
+ imdbId: string().nullable(),
10219
+ pinnedAt: number().int()
10220
+ });
9638
10221
  var ProgressRowSchema = object({
9639
10222
  userId: string(),
9640
10223
  itemId: string(),
@@ -9643,7 +10226,7 @@ var ProgressRowSchema = object({
9643
10226
  updatedAt: number().int(),
9644
10227
  watched: boolean()
9645
10228
  });
9646
- var text = (name, notNull = false) => ({
10229
+ var text$3 = (name, notNull = false) => ({
9647
10230
  name,
9648
10231
  type: "TEXT",
9649
10232
  notNull
@@ -9658,23 +10241,23 @@ var COLLECTIONS = [
9658
10241
  collection: ITEMS,
9659
10242
  primaryKey: ["id"],
9660
10243
  columns: [
9661
- text("id", true),
9662
- text("kind", true),
9663
- text("parentId"),
9664
- text("title", true),
9665
- text("sortTitle", true),
9666
- text("titleFold", true),
10244
+ text$3("id", true),
10245
+ text$3("kind", true),
10246
+ text$3("parentId"),
10247
+ text$3("title", true),
10248
+ text$3("sortTitle", true),
10249
+ text$3("titleFold", true),
9667
10250
  int("year"),
9668
10251
  int("seasonNumber"),
9669
10252
  int("episodeNumber"),
9670
- text("overview"),
10253
+ text$3("overview"),
9671
10254
  int("tvdbId"),
9672
10255
  int("tmdbId"),
9673
- text("imdbId"),
9674
- text("posterSource"),
9675
- text("fanartSource"),
9676
- text("sourceId", true),
9677
- text("filePath"),
10256
+ text$3("imdbId"),
10257
+ text$3("posterSource"),
10258
+ text$3("fanartSource"),
10259
+ text$3("sourceId", true),
10260
+ text$3("filePath"),
9678
10261
  {
9679
10262
  name: "topLevel",
9680
10263
  type: "BOOLEAN",
@@ -9710,7 +10293,7 @@ var COLLECTIONS = [
9710
10293
  collection: FILES,
9711
10294
  primaryKey: ["path"],
9712
10295
  columns: [
9713
- text("path", true),
10296
+ text$3("path", true),
9714
10297
  int("sizeBytes", true),
9715
10298
  int("mtimeMs", true),
9716
10299
  int("probedAt", true),
@@ -9719,14 +10302,28 @@ var COLLECTIONS = [
9719
10302
  type: "BOOLEAN",
9720
10303
  notNull: true
9721
10304
  },
9722
- text("container"),
10305
+ text$3("container"),
9723
10306
  int("durationMs"),
9724
10307
  {
9725
10308
  name: "streams",
9726
10309
  type: "JSON",
9727
10310
  notNull: true
9728
10311
  },
9729
- text("probeError")
10312
+ text$3("probeError")
10313
+ ]
10314
+ },
10315
+ MATCHES_DECLARATION,
10316
+ {
10317
+ collection: PINS,
10318
+ primaryKey: ["itemId", "source"],
10319
+ columns: [
10320
+ text$3("itemId", true),
10321
+ text$3("source", true),
10322
+ text$3("kind", true),
10323
+ int("tvdbId"),
10324
+ int("tmdbId"),
10325
+ text$3("imdbId"),
10326
+ int("pinnedAt", true)
9730
10327
  ]
9731
10328
  },
9732
10329
  {
@@ -9734,8 +10331,8 @@ var COLLECTIONS = [
9734
10331
  primaryKey: ["userId", "itemId"],
9735
10332
  withoutRowid: true,
9736
10333
  columns: [
9737
- text("userId", true),
9738
- text("itemId", true),
10334
+ text$3("userId", true),
10335
+ text$3("itemId", true),
9739
10336
  int("positionMs", true),
9740
10337
  int("durationMs", true),
9741
10338
  int("updatedAt", true),
@@ -9755,6 +10352,365 @@ var COLLECTIONS = [
9755
10352
  }]
9756
10353
  }
9757
10354
  ];
10355
+ //#endregion
10356
+ //#region src/image-source.ts
10357
+ /** An absolute `https` URL, which is fetched with no credential; anything else is not one. */
10358
+ function isRemoteUrl(value) {
10359
+ if (!value.startsWith("https://")) return false;
10360
+ try {
10361
+ return new URL(value).protocol === "https:";
10362
+ } catch {
10363
+ return false;
10364
+ }
10365
+ }
10366
+ var FRAME_AT_FRACTION = .15;
10367
+ var FRAME_FALLBACK_SECONDS = 10;
10368
+ var FRAME_WIDTH_PX = 480;
10369
+ var GRAB_TIMEOUT_MS = 3e4;
10370
+ var FRAME_MAX_BYTES = 4 * 1024 * 1024;
10371
+ /** The ffmpeg arguments for one still: seek before the input (fast), one frame, scaled, JPEG on stdout. */
10372
+ function frameGrabArgs(filePath, durationMs) {
10373
+ const seconds = durationMs === null || durationMs <= 0 ? FRAME_FALLBACK_SECONDS : Math.floor(durationMs * FRAME_AT_FRACTION / 1e3);
10374
+ return [
10375
+ "-hide_banner",
10376
+ "-nostdin",
10377
+ "-loglevel",
10378
+ "error",
10379
+ "-ss",
10380
+ String(seconds),
10381
+ "-i",
10382
+ `file:${resolve(filePath)}`,
10383
+ "-frames:v",
10384
+ "1",
10385
+ "-an",
10386
+ "-sn",
10387
+ "-vf",
10388
+ `scale=${FRAME_WIDTH_PX}:-2`,
10389
+ "-f",
10390
+ "image2pipe",
10391
+ "-c:v",
10392
+ "mjpeg",
10393
+ "-q:v",
10394
+ "4",
10395
+ "pipe:1"
10396
+ ];
10397
+ }
10398
+ function grabFailureReason(error) {
10399
+ if (error.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return "frame too large";
10400
+ return error.killed === true ? "frame grab timed out" : error.message;
10401
+ }
10402
+ /** The ffmpeg the probe uses, asked for one frame. A run with no picture is a failure. */
10403
+ function createFfmpegFrameGrabber(binaryPath) {
10404
+ return (filePath, durationMs) => new Promise((done, reject) => {
10405
+ execFile(binaryPath, frameGrabArgs(filePath, durationMs), {
10406
+ timeout: GRAB_TIMEOUT_MS,
10407
+ maxBuffer: FRAME_MAX_BYTES,
10408
+ encoding: "buffer"
10409
+ }, (error, stdout, stderr) => {
10410
+ if (error !== null) reject(new Error(grabFailureReason(error)));
10411
+ else if (stdout.length === 0) reject(/* @__PURE__ */ new Error(`no frame: ${stderr.toString("utf8").slice(0, 200)}`));
10412
+ else done(stdout);
10413
+ });
10414
+ });
10415
+ }
10416
+ /** The queue behind a limiter is full: the work is refused, not delayed. */
10417
+ var LimiterFullError = class extends Error {
10418
+ constructor() {
10419
+ super("queue full");
10420
+ }
10421
+ };
10422
+ /** At most `limit` runs of `task` at once, at most `maxWaiting` queued behind them; the rest are refused. */
10423
+ function createLimiter(limit, maxWaiting) {
10424
+ let running = 0;
10425
+ const waiting = [];
10426
+ return async (task) => {
10427
+ if (running >= limit) {
10428
+ if (waiting.length >= maxWaiting) throw new LimiterFullError();
10429
+ await new Promise((go) => waiting.push(go));
10430
+ }
10431
+ running += 1;
10432
+ try {
10433
+ return await task();
10434
+ } finally {
10435
+ running -= 1;
10436
+ waiting.shift()?.();
10437
+ }
10438
+ };
10439
+ }
10440
+ //#endregion
10441
+ //#region src/nfo.ts
10442
+ /**
10443
+ * A tolerant reader for the media-center `.nfo` files (`tvshow`, `movie`, `episodedetails`).
10444
+ * It is not an XML parser: it reads the handful of top-level fields the library wants, never
10445
+ * resolves an entity beyond the five predefined ones and numeric references, never follows a
10446
+ * DOCTYPE or an external reference, and refuses a file past {@link NFO_MAX_BYTES}.
10447
+ */
10448
+ var NFO_MAX_BYTES = 256 * 1024;
10449
+ var NAMED = {
10450
+ amp: "&",
10451
+ lt: "<",
10452
+ gt: ">",
10453
+ quot: "\"",
10454
+ apos: "'"
10455
+ };
10456
+ function decode(text) {
10457
+ const cdata = /^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/.exec(text);
10458
+ if (cdata?.[1] !== void 0) return cdata[1].trim();
10459
+ return text.replace(/&(?:#(\d{1,6})|#x([0-9a-fA-F]{1,6})|([A-Za-z][A-Za-z0-9]{0,31}));/g, (_whole, dec, hex, name) => {
10460
+ if (typeof name === "string") return NAMED[name] ?? "";
10461
+ const code = typeof dec === "string" ? Number(dec) : Number.parseInt(String(hex), 16);
10462
+ return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : "";
10463
+ }).trim();
10464
+ }
10465
+ /** Every `<name …>body</name>` in document order, found by `indexOf` scans only: linear whatever the input. */
10466
+ function tagsOf(xml, name) {
10467
+ const out = [];
10468
+ const lower = xml.toLowerCase();
10469
+ const open = `<${name}`;
10470
+ const close = `</${name}>`;
10471
+ let from = 0;
10472
+ for (;;) {
10473
+ const start = lower.indexOf(open, from);
10474
+ if (start === -1) break;
10475
+ const after = lower.charAt(start + open.length);
10476
+ const gt = lower.indexOf(">", start);
10477
+ if (gt === -1) break;
10478
+ if (!(after === ">" || /\s/.test(after)) || lower.charAt(gt - 1) === "/") {
10479
+ from = start + open.length;
10480
+ continue;
10481
+ }
10482
+ const end = lower.indexOf(close, gt + 1);
10483
+ if (end === -1) break;
10484
+ out.push({
10485
+ attrs: xml.slice(start + open.length, gt),
10486
+ body: xml.slice(gt + 1, end)
10487
+ });
10488
+ from = end + close.length;
10489
+ }
10490
+ return out;
10491
+ }
10492
+ function textOf(xml, name) {
10493
+ const [first] = tagsOf(xml, name);
10494
+ if (first === void 0) return null;
10495
+ const value = decode(first.body);
10496
+ return value === "" ? null : value;
10497
+ }
10498
+ function intOf(value) {
10499
+ if (value === null || !/^\d{1,9}$/.test(value)) return null;
10500
+ return Number(value);
10501
+ }
10502
+ function attrOf(attrs, name) {
10503
+ const match = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, "i").exec(attrs);
10504
+ return match === null ? null : match[1] ?? match[2] ?? null;
10505
+ }
10506
+ /** The ids the file names, by `uniqueid type=`, with the older `<tvdbid>` / `<imdbid>` tags as a fallback. */
10507
+ function idsOf(xml) {
10508
+ let tvdbId = null;
10509
+ let tmdbId = null;
10510
+ let imdbId = null;
10511
+ for (const tag of tagsOf(xml, "uniqueid")) {
10512
+ const type = attrOf(tag.attrs, "type")?.toLowerCase();
10513
+ const value = decode(tag.body);
10514
+ if (type === "tvdb") tvdbId ??= intOf(value);
10515
+ else if (type === "tmdb") tmdbId ??= intOf(value);
10516
+ else if (type === "imdb" && /^tt\d{1,12}$/.test(value)) imdbId ??= value;
10517
+ }
10518
+ tvdbId ??= intOf(textOf(xml, "tvdbid"));
10519
+ tmdbId ??= intOf(textOf(xml, "tmdbid"));
10520
+ const legacyImdb = textOf(xml, "imdbid") ?? textOf(xml, "imdb_id");
10521
+ if (imdbId === null && legacyImdb !== null && /^tt\d{1,12}$/.test(legacyImdb)) imdbId = legacyImdb;
10522
+ return {
10523
+ tvdbId,
10524
+ tmdbId,
10525
+ imdbId
10526
+ };
10527
+ }
10528
+ /** Remove every `open…close` block (an unterminated one to the end), by `indexOf` scans: linear. */
10529
+ function stripBlocks(text, open, close) {
10530
+ const lower = text.toLowerCase();
10531
+ let out = "";
10532
+ let from = 0;
10533
+ for (;;) {
10534
+ const start = lower.indexOf(open, from);
10535
+ if (start === -1) return out + text.slice(from);
10536
+ out += text.slice(from, start);
10537
+ const end = lower.indexOf(close, start + open.length);
10538
+ if (end === -1) return out;
10539
+ from = end + close.length;
10540
+ }
10541
+ }
10542
+ /** `null` when the text is not one of the three documents, or is over the cap. */
10543
+ function parseNfo(source) {
10544
+ if (source.length > 262144) return null;
10545
+ const xml = stripBlocks(stripBlocks(source, "<!--", "-->"), "<!doctype", ">");
10546
+ const root = /<(tvshow|movie|episodedetails)[\s>]/i.exec(xml)?.[1]?.toLowerCase();
10547
+ if (root !== "tvshow" && root !== "movie" && root !== "episodedetails") return null;
10548
+ const premiered = textOf(xml, "premiered") ?? textOf(xml, "aired");
10549
+ const year = intOf(textOf(xml, "year")) ?? (premiered === null ? null : intOf(/^(\d{4})/.exec(premiered)?.[1] ?? null));
10550
+ return {
10551
+ root,
10552
+ title: textOf(xml, "title"),
10553
+ year,
10554
+ plot: textOf(xml, "plot"),
10555
+ ...idsOf(xml),
10556
+ season: intOf(textOf(xml, "season")),
10557
+ episode: intOf(textOf(xml, "episode"))
10558
+ };
10559
+ }
10560
+ //#endregion
10561
+ //#region src/sidecars.ts
10562
+ /** The local image kind is stored in an item's cover column as `local:<absolute path>`. */
10563
+ var LOCAL_PREFIX = "local:";
10564
+ function localCover(path) {
10565
+ return `${LOCAL_PREFIX}${path}`;
10566
+ }
10567
+ /** The absolute path of a `local:` cover, or `null` when the value is not one. */
10568
+ function localCoverPath(value) {
10569
+ return value.startsWith("local:") ? value.slice(6) : null;
10570
+ }
10571
+ var IMAGE_EXTENSIONS = [
10572
+ ".jpg",
10573
+ ".jpeg",
10574
+ ".png"
10575
+ ];
10576
+ function createLocalReader() {
10577
+ const listings = /* @__PURE__ */ new Map();
10578
+ return {
10579
+ list(dir) {
10580
+ const cached = listings.get(dir);
10581
+ if (cached !== void 0) return cached;
10582
+ const read = readdir(dir).then((names) => new Map(names.map((name) => [name.toLowerCase(), name])), () => /* @__PURE__ */ new Map());
10583
+ listings.set(dir, read);
10584
+ return read;
10585
+ },
10586
+ async nfo(path) {
10587
+ try {
10588
+ const handle = await open(path, "r");
10589
+ try {
10590
+ const buffer = Buffer.alloc(NFO_MAX_BYTES + 1);
10591
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
10592
+ if (bytesRead > 262144) return null;
10593
+ return parseNfo(buffer.subarray(0, bytesRead).toString("utf8"));
10594
+ } finally {
10595
+ await handle.close();
10596
+ }
10597
+ } catch {
10598
+ return null;
10599
+ }
10600
+ }
10601
+ };
10602
+ }
10603
+ /** A season folder: `Season 02`, `Season2`, `S02`, `S 02`, `Specials` (season 0). */
10604
+ function seasonOfFolder(name) {
10605
+ const trimmed = name.trim();
10606
+ if (/^specials?$/i.test(trimmed)) return 0;
10607
+ const match = /^(?:season|stagione|s)[\s._-]*(\d{1,3})$/i.exec(trimmed);
10608
+ return match?.[1] === void 0 ? null : Number(match[1]);
10609
+ }
10610
+ /** The folder that holds a show: the file's folder, or its parent when that is a season folder. */
10611
+ function seriesDirOf(filePath) {
10612
+ const parent = dirname(filePath);
10613
+ return seasonOfFolder(basename(parent)) === null ? parent : dirname(parent);
10614
+ }
10615
+ var NO_LOCAL = {
10616
+ title: null,
10617
+ year: null,
10618
+ overview: null,
10619
+ tvdbId: null,
10620
+ tmdbId: null,
10621
+ imdbId: null,
10622
+ poster: null,
10623
+ fanart: null,
10624
+ season: null,
10625
+ episode: null
10626
+ };
10627
+ function fromNfo(nfo) {
10628
+ if (nfo === null) return NO_LOCAL;
10629
+ return {
10630
+ ...NO_LOCAL,
10631
+ title: nfo.title,
10632
+ year: nfo.year,
10633
+ overview: nfo.plot,
10634
+ tvdbId: nfo.tvdbId,
10635
+ tmdbId: nfo.tmdbId,
10636
+ imdbId: nfo.imdbId,
10637
+ season: nfo.season,
10638
+ episode: nfo.episode
10639
+ };
10640
+ }
10641
+ /** First candidate base name (without extension) that exists in `listing` with an image extension. */
10642
+ function firstImage(dir, listing, bases) {
10643
+ for (const base of bases) for (const extension of IMAGE_EXTENSIONS) {
10644
+ const real = listing.get(`${base.toLowerCase()}${extension}`);
10645
+ if (real !== void 0) return localCover(join(dir, real));
10646
+ }
10647
+ return null;
10648
+ }
10649
+ function pick$1(...values) {
10650
+ for (const value of values) if (value !== null) return value;
10651
+ return null;
10652
+ }
10653
+ function merge(first, second) {
10654
+ return {
10655
+ title: pick$1(first.title, second.title),
10656
+ year: pick$1(first.year, second.year),
10657
+ overview: pick$1(first.overview, second.overview),
10658
+ tvdbId: pick$1(first.tvdbId, second.tvdbId),
10659
+ tmdbId: pick$1(first.tmdbId, second.tmdbId),
10660
+ imdbId: pick$1(first.imdbId, second.imdbId),
10661
+ poster: pick$1(first.poster, second.poster),
10662
+ fanart: pick$1(first.fanart, second.fanart),
10663
+ season: pick$1(first.season, second.season),
10664
+ episode: pick$1(first.episode, second.episode)
10665
+ };
10666
+ }
10667
+ function videoCount(listing) {
10668
+ let count = 0;
10669
+ for (const name of listing.keys()) if (VIDEO_EXTENSIONS.has(extname(name))) count += 1;
10670
+ return count;
10671
+ }
10672
+ /** `tvshow.nfo`, `poster.*`, `folder.*`, `fanart.*` of a series folder. */
10673
+ async function localSeries(reader, seriesDir) {
10674
+ const listing = await reader.list(seriesDir);
10675
+ const nfoName = listing.get("tvshow.nfo");
10676
+ const nfo = nfoName === void 0 ? null : await reader.nfo(join(seriesDir, nfoName));
10677
+ return {
10678
+ ...fromNfo(nfo?.root === "tvshow" ? nfo : null),
10679
+ poster: firstImage(seriesDir, listing, ["poster", "folder"]),
10680
+ fanart: firstImage(seriesDir, listing, ["fanart"])
10681
+ };
10682
+ }
10683
+ /** `<episode>.nfo` and `<episode>-thumb.*` next to the file. */
10684
+ async function localEpisode(reader, filePath) {
10685
+ const dir = dirname(filePath);
10686
+ const base = basename(filePath, extname(filePath));
10687
+ const listing = await reader.list(dir);
10688
+ const nfoName = listing.get(`${base.toLowerCase()}.nfo`);
10689
+ const nfo = nfoName === void 0 ? null : await reader.nfo(join(dir, nfoName));
10690
+ return {
10691
+ ...fromNfo(nfo?.root === "episodedetails" ? nfo : null),
10692
+ poster: firstImage(dir, listing, [`${base}-thumb`])
10693
+ };
10694
+ }
10695
+ /**
10696
+ * `<movie>.nfo` / `movie.nfo` and the matching posters. A name that applies to the whole
10697
+ * folder (`poster.jpg`, `movie.nfo`) is taken only when the folder holds this one video.
10698
+ */
10699
+ async function localMovie(reader, filePath) {
10700
+ const dir = dirname(filePath);
10701
+ const base = basename(filePath, extname(filePath));
10702
+ const listing = await reader.list(dir);
10703
+ const solo = videoCount(listing) <= 1;
10704
+ const named = listing.get(`${base.toLowerCase()}.nfo`);
10705
+ const shared = solo ? listing.get("movie.nfo") : void 0;
10706
+ const own = named === void 0 ? null : await reader.nfo(join(dir, named));
10707
+ const folderWide = shared === void 0 ? null : await reader.nfo(join(dir, shared));
10708
+ return {
10709
+ ...merge(fromNfo(own?.root === "movie" ? own : null), fromNfo(folderWide?.root === "movie" ? folderWide : null)),
10710
+ poster: firstImage(dir, listing, [`${base}-poster`, ...solo ? ["poster", "folder"] : []]),
10711
+ fanart: firstImage(dir, listing, [`${base}-fanart`, ...solo ? ["fanart"] : []])
10712
+ };
10713
+ }
9758
10714
  var FILE_PLANE_PREFIX = "file";
9759
10715
  var HUB_PLANE_BASE = "/addon/media-library";
9760
10716
  var SEARCH_DEFAULT_LIMIT = 50;
@@ -9792,6 +10748,10 @@ var LibraryStore = class {
9792
10748
  async queryItems(filter) {
9793
10749
  return this.items(ITEMS, await this.db.query(ITEMS, filter));
9794
10750
  }
10751
+ /** Every item row matching `filter`, past the store's default row cap. */
10752
+ async queryAllItems(filter = {}) {
10753
+ return this.items(ITEMS, await queryAll(this.db, ITEMS, "id", filter));
10754
+ }
9795
10755
  async queryFiles(filter) {
9796
10756
  return parseRows(FileRowSchema, await this.db.query(FILES, filter), this.invalid(FILES));
9797
10757
  }
@@ -9911,7 +10871,10 @@ var LibraryStore = class {
9911
10871
  direction: "asc"
9912
10872
  }
9913
10873
  });
9914
- return this.summaries(rows, userId);
10874
+ return (await this.summaries(rows, userId)).map((summary, index) => ({
10875
+ ...summary,
10876
+ overview: rows[index]?.overview ?? null
10877
+ }));
9915
10878
  }
9916
10879
  async getItem(userId, itemId) {
9917
10880
  const [row] = await this.queryItems({
@@ -9954,17 +10917,47 @@ var LibraryStore = class {
9954
10917
  row: file
9955
10918
  };
9956
10919
  }
10920
+ /** Where an image may come from, best first. A cover that fails falls back to a frame of the file. */
9957
10921
  async imageSource(itemId, which) {
9958
10922
  const [item] = await this.queryItems({
9959
10923
  where: { id: itemId },
9960
10924
  limit: 1
9961
10925
  });
9962
- if (item === void 0) return null;
9963
- const source = which === "poster" ? item.posterSource : item.fanartSource;
9964
- return source === null ? null : {
9965
- source,
9966
- sourceId: item.sourceId
9967
- };
10926
+ if (item === void 0) return [];
10927
+ const out = [];
10928
+ const cover = which === "poster" ? item.posterSource : item.fanartSource;
10929
+ if (cover !== null) {
10930
+ const local = localCoverPath(cover);
10931
+ if (local !== null) out.push({
10932
+ kind: "local",
10933
+ path: local
10934
+ });
10935
+ else if (isRemoteUrl(cover)) out.push({
10936
+ kind: "remote",
10937
+ url: cover
10938
+ });
10939
+ else if (cover.startsWith("/")) out.push({
10940
+ kind: "arr",
10941
+ path: cover,
10942
+ sourceId: item.sourceId
10943
+ });
10944
+ else this.logger.warn("image skipped: no usable source", {
10945
+ tags: { itemId },
10946
+ meta: { reason: "foreign-origin" }
10947
+ });
10948
+ }
10949
+ if (which === "poster" && item.kind !== "series" && item.filePath !== null) {
10950
+ const [file] = await this.queryFiles({
10951
+ where: { path: item.filePath },
10952
+ limit: 1
10953
+ });
10954
+ if (file !== void 0) out.push({
10955
+ kind: "frame",
10956
+ filePath: item.filePath,
10957
+ durationMs: file.durationMs
10958
+ });
10959
+ }
10960
+ return out;
9968
10961
  }
9969
10962
  /** Serialise the read-compare-write of one (user, item) so two writes of one person cannot interleave. */
9970
10963
  async locked(key, run) {
@@ -9987,7 +10980,10 @@ var LibraryStore = class {
9987
10980
  return row === void 0 ? null : toProgress(row);
9988
10981
  }
9989
10982
  /** Write `next` unless the stored row is NEWER; answer the row that holds. Last write wins on the client clock. */
9990
- writeIfNewer(userId, next) {
10983
+ async writeIfNewer(userId, next) {
10984
+ return (await this.writeIfNewerOutcome(userId, next)).progress;
10985
+ }
10986
+ writeIfNewerOutcome(userId, next) {
9991
10987
  return this.locked(`${userId}\u0000${next.itemId}`, async () => {
9992
10988
  const [stored] = await this.queryProgress({
9993
10989
  where: {
@@ -10004,11 +11000,37 @@ var LibraryStore = class {
10004
11000
  incoming: next.updatedAt
10005
11001
  }
10006
11002
  });
10007
- return toProgress(stored);
11003
+ return {
11004
+ progress: toProgress(stored),
11005
+ written: false
11006
+ };
10008
11007
  }
10009
11008
  await this.db.upsertMany(PROGRESS, ["userId", "itemId"], [{ ...next }]);
10010
- return toProgress(next);
11009
+ return {
11010
+ progress: toProgress(next),
11011
+ written: true
11012
+ };
11013
+ });
11014
+ }
11015
+ /**
11016
+ * Bring in a place another system held, on THAT system's clock: written only when nothing equal or
11017
+ * newer is stored, so a re-run changes nothing and a newer Dominevo position survives.
11018
+ * With `dryRun` nothing is written; the answer says what would have been.
11019
+ */
11020
+ async importProgress(userId, next, dryRun) {
11021
+ const row = {
11022
+ userId,
11023
+ ...next
11024
+ };
11025
+ if (!dryRun) return (await this.writeIfNewerOutcome(userId, row)).written;
11026
+ const [stored] = await this.queryProgress({
11027
+ where: {
11028
+ userId,
11029
+ itemId: next.itemId
11030
+ },
11031
+ limit: 1
10011
11032
  });
11033
+ return stored === void 0 || stored.updatedAt < next.updatedAt;
10012
11034
  }
10013
11035
  async requirePlayable(itemId) {
10014
11036
  const [item] = await this.queryItems({
@@ -10113,7 +11135,7 @@ function toSummary(row, file, progress) {
10113
11135
  seriesId: row.kind === "episode" ? row.parentId : null,
10114
11136
  seasonNumber: row.seasonNumber,
10115
11137
  episodeNumber: row.episodeNumber,
10116
- posterPath: row.posterSource === null ? null : imagePathOf(row.id, "poster"),
11138
+ posterPath: row.posterSource === null && !(row.kind !== "series" && file !== void 0) ? null : imagePathOf(row.id, "poster"),
10117
11139
  addedAt: row.addedAt,
10118
11140
  durationMs: file?.durationMs ?? null,
10119
11141
  playable: row.kind !== "series" && file !== void 0,
@@ -10121,32 +11143,1970 @@ function toSummary(row, file, progress) {
10121
11143
  };
10122
11144
  }
10123
11145
  //#endregion
10124
- //#region src/probe.ts
10125
- var CONTAINER_NAMES = new Map([
10126
- ["matroska", "mkv"],
10127
- ["mov", "mp4"],
10128
- ["avi", "avi"],
10129
- ["mpegts", "ts"]
10130
- ]);
10131
- function containerOf(formats) {
10132
- const first = formats.split(",")[0]?.trim() ?? formats;
10133
- return CONTAINER_NAMES.get(first) ?? first;
10134
- }
10135
- function languageOf(tag) {
10136
- if (tag === void 0 || tag === "" || tag === "und") return null;
10137
- return tag;
11146
+ //#region src/pins.ts
11147
+ var NO_IDS$1 = {
11148
+ tvdbId: null,
11149
+ tmdbId: null,
11150
+ imdbId: null
11151
+ };
11152
+ /** A pin source outranks the ones after it: an admin's identify beats an import. */
11153
+ var PRECEDENCE = ["manual", "plex"];
11154
+ /** Fold the pins of one item per field, the highest-ranked source first. */
11155
+ function resolvePins(rows) {
11156
+ const out = /* @__PURE__ */ new Map();
11157
+ const ranked = rows.toSorted((a, b) => PRECEDENCE.indexOf(a.source) - PRECEDENCE.indexOf(b.source));
11158
+ for (const row of ranked) {
11159
+ const held = out.get(row.itemId) ?? NO_IDS$1;
11160
+ out.set(row.itemId, {
11161
+ tvdbId: held.tvdbId ?? row.tvdbId,
11162
+ tmdbId: held.tmdbId ?? row.tmdbId,
11163
+ imdbId: held.imdbId ?? row.imdbId
11164
+ });
11165
+ }
11166
+ return out;
10138
11167
  }
10139
- function bitDepthOf(pixFmt) {
10140
- if (pixFmt === null) return null;
10141
- const match = /(?:p|le|be)(9|10|12|14|16)(?:le|be)?$/.exec(pixFmt);
10142
- if (match?.[1] !== void 0) return Number(match[1]);
10143
- return /^(yuv|nv|gray|rgb|bgr)/.test(pixFmt) ? 8 : null;
11168
+ function hasAnyId(ids) {
11169
+ return ids.tvdbId !== null || ids.tmdbId !== null || ids.imdbId !== null;
10144
11170
  }
10145
- function hdrOf(line, doviSeen) {
10146
- if (doviSeen) return "dolby-vision";
10147
- if (line.includes("smpte2084")) return "hdr10";
10148
- if (line.includes("arib-std-b67")) return "hlg";
10149
- return null;
11171
+ /** Every pin, resolved. A row that does not parse is dropped and reported. */
11172
+ async function loadPins(db, onInvalid) {
11173
+ return resolvePins(parseRows(PinRowSchema, await queryAll(db, PINS, "itemId"), onInvalid));
11174
+ }
11175
+ /** Write pins of one `source`; a rescan never touches this collection. */
11176
+ async function writePins(db, source, writes, now) {
11177
+ const rows = writes.filter((write) => hasAnyId(write.ids)).map((write) => ({
11178
+ itemId: write.itemId,
11179
+ source,
11180
+ kind: write.kind,
11181
+ tvdbId: write.ids.tvdbId,
11182
+ tmdbId: write.ids.tmdbId,
11183
+ imdbId: write.ids.imdbId,
11184
+ pinnedAt: now
11185
+ }));
11186
+ if (rows.length > 0) await db.upsertMany(PINS, ["itemId", "source"], rows);
11187
+ }
11188
+ /** The pins one source holds, per item (an import compares its new answer with what it pinned before). */
11189
+ async function loadSourcePins(db, source, onInvalid) {
11190
+ return resolvePins(parseRows(PinRowSchema, await queryAll(db, PINS, "itemId"), onInvalid).filter((row) => row.source === source));
11191
+ }
11192
+ /** Remove the pins of one `source` for these items. Another source's pin is never touched. */
11193
+ async function deletePins(db, source, itemIds) {
11194
+ if (itemIds.length === 0) return 0;
11195
+ return db.deleteWhere(PINS, {
11196
+ where: { source },
11197
+ whereIn: { itemId: [...itemIds] }
11198
+ });
11199
+ }
11200
+ var ID_ORDER = [
11201
+ {
11202
+ key: "tmdbId",
11203
+ via: "tmdb"
11204
+ },
11205
+ {
11206
+ key: "imdbId",
11207
+ via: "imdb"
11208
+ },
11209
+ {
11210
+ key: "tvdbId",
11211
+ via: "tvdb"
11212
+ }
11213
+ ];
11214
+ /** An index that answers only when exactly one item holds the key: two holders is not a match, it is a guess. */
11215
+ var UniqueIndex = class {
11216
+ rows = /* @__PURE__ */ new Map();
11217
+ add(key, row) {
11218
+ if (key === null) return;
11219
+ const held = this.rows.get(key);
11220
+ if (held === void 0) this.rows.set(key, [row]);
11221
+ else held.push(row);
11222
+ }
11223
+ get(key) {
11224
+ if (key === null) return null;
11225
+ const held = this.rows.get(key);
11226
+ return held !== void 0 && held.length === 1 ? held[0] ?? null : null;
11227
+ }
11228
+ };
11229
+ /**
11230
+ * A pin is only for an id the item lacks. A field the row already holds does not count as held when it
11231
+ * is the very value an earlier Plex pin supplied: that pin is still doing its job.
11232
+ */
11233
+ function pinFor(row, ids, earlier) {
11234
+ const open = (plex, ours, pinned) => plex !== null && (ours === null || ours === pinned) ? plex : null;
11235
+ const next = {
11236
+ tmdbId: open(ids.tmdbId, row.tmdbId, earlier?.tmdbId),
11237
+ imdbId: open(ids.imdbId, row.imdbId, earlier?.imdbId),
11238
+ tvdbId: open(ids.tvdbId, row.tvdbId, earlier?.tvdbId)
11239
+ };
11240
+ return next.tmdbId === null && next.imdbId === null && next.tvdbId === null ? null : {
11241
+ itemId: row.id,
11242
+ kind: row.kind,
11243
+ ids: next
11244
+ };
11245
+ }
11246
+ function idIndexes(rows) {
11247
+ const indexes = {
11248
+ tmdbId: new UniqueIndex(),
11249
+ imdbId: new UniqueIndex(),
11250
+ tvdbId: new UniqueIndex()
11251
+ };
11252
+ for (const row of rows) {
11253
+ indexes.tmdbId.add(row.tmdbId, row);
11254
+ indexes.imdbId.add(row.imdbId, row);
11255
+ indexes.tvdbId.add(row.tvdbId, row);
11256
+ }
11257
+ return indexes;
11258
+ }
11259
+ function byIds(indexes, ids) {
11260
+ for (const { key, via } of ID_ORDER) {
11261
+ const row = indexes[key].get(ids[key]);
11262
+ if (row !== null) return {
11263
+ row,
11264
+ via
11265
+ };
11266
+ }
11267
+ return null;
11268
+ }
11269
+ var two = (n) => String(n).padStart(2, "0");
11270
+ /**
11271
+ * Match Plex's catalogue to ours without guessing: a movie by tmdb, then imdb, then tvdb; an episode by
11272
+ * its series (ids, then an exact title and year) and its season and episode number; and, for what is
11273
+ * left, the file path (mapped from Plex's view of the disk to this hub's) equal to our item's file.
11274
+ */
11275
+ function matchCatalog(catalog, ours, paths, earlier = /* @__PURE__ */ new Map()) {
11276
+ const movies = ours.filter((row) => row.kind === "movie");
11277
+ const series = ours.filter((row) => row.kind === "series");
11278
+ const episodes = ours.filter((row) => row.kind === "episode");
11279
+ const movieIds = idIndexes(movies);
11280
+ const seriesIds = idIndexes(series);
11281
+ const byPath = /* @__PURE__ */ new Map();
11282
+ for (const row of [...movies, ...episodes]) if (row.filePath !== null) byPath.set(row.filePath, row);
11283
+ const byTitle = /* @__PURE__ */ new Map();
11284
+ for (const row of series) {
11285
+ const key = foldTitle(row.title);
11286
+ byTitle.set(key, [...byTitle.get(key) ?? [], row]);
11287
+ }
11288
+ const episodeAt = /* @__PURE__ */ new Map();
11289
+ const duplicated = /* @__PURE__ */ new Set();
11290
+ for (const row of episodes) {
11291
+ if (row.parentId === null || row.seasonNumber === null || row.episodeNumber === null) continue;
11292
+ const key = `${row.parentId}\u0000${row.seasonNumber}\u0000${row.episodeNumber}`;
11293
+ if (episodeAt.has(key)) duplicated.add(key);
11294
+ episodeAt.set(key, row);
11295
+ }
11296
+ const itemByRatingKey = /* @__PURE__ */ new Map();
11297
+ const pins = /* @__PURE__ */ new Map();
11298
+ const judged = /* @__PURE__ */ new Set();
11299
+ const judge = (row, ids) => {
11300
+ judged.add(row.id);
11301
+ const pin = pinFor(row, ids, earlier.get(row.id));
11302
+ if (pin !== null) pins.set(row.id, pin);
11303
+ };
11304
+ const unmatchedTitles = [];
11305
+ const via = {
11306
+ tmdb: 0,
11307
+ imdb: 0,
11308
+ tvdb: 0,
11309
+ series: 0,
11310
+ path: 0
11311
+ };
11312
+ let matched = 0;
11313
+ let unmatched = 0;
11314
+ const hit = (ratingKey, row, how, ids) => {
11315
+ itemByRatingKey.set(ratingKey, row.id);
11316
+ via[how] += 1;
11317
+ matched += 1;
11318
+ if (ids !== null) judge(row, ids);
11319
+ };
11320
+ const miss = (title) => {
11321
+ unmatched += 1;
11322
+ if (unmatchedTitles.length < 20) unmatchedTitles.push(title);
11323
+ };
11324
+ const pathMatch = (files) => {
11325
+ for (const file of files) {
11326
+ const row = byPath.get(mapPath(file, paths.from, paths.to));
11327
+ if (row !== void 0) return row;
11328
+ }
11329
+ return null;
11330
+ };
11331
+ for (const movie of catalog.movies) {
11332
+ const found = byIds(movieIds, movie.ids);
11333
+ if (found !== null) {
11334
+ hit(movie.ratingKey, found.row, found.via, movie.ids);
11335
+ continue;
11336
+ }
11337
+ const viaPath = pathMatch(movie.files);
11338
+ if (viaPath !== null && viaPath.kind === "movie") hit(movie.ratingKey, viaPath, "path", movie.ids);
11339
+ else miss(movie.year === null ? movie.title : `${movie.title} (${movie.year})`);
11340
+ }
11341
+ const seriesOf = /* @__PURE__ */ new Map();
11342
+ for (const show of catalog.shows) {
11343
+ const found = byIds(seriesIds, show.ids);
11344
+ if (found !== null) {
11345
+ seriesOf.set(show.ratingKey, found.row);
11346
+ judge(found.row, show.ids);
11347
+ continue;
11348
+ }
11349
+ const sameYear = (byTitle.get(foldTitle(show.title)) ?? []).filter((row) => row.year === null || show.year === null || row.year === show.year);
11350
+ const only = sameYear.length === 1 ? sameYear[0] : void 0;
11351
+ if (only !== void 0) {
11352
+ seriesOf.set(show.ratingKey, only);
11353
+ judge(only, show.ids);
11354
+ }
11355
+ }
11356
+ for (const episode of catalog.episodes) {
11357
+ const label = `${episode.showTitle} S${two(episode.season ?? 0)}E${two(episode.episode ?? 0)}`;
11358
+ const show = seriesOf.get(episode.showRatingKey);
11359
+ if (show !== void 0 && episode.season !== null && episode.episode !== null) {
11360
+ const key = `${show.id}\u0000${episode.season}\u0000${episode.episode}`;
11361
+ const row = duplicated.has(key) ? void 0 : episodeAt.get(key);
11362
+ if (row !== void 0) {
11363
+ hit(episode.ratingKey, row, "series", null);
11364
+ continue;
11365
+ }
11366
+ }
11367
+ const viaPath = pathMatch(episode.files);
11368
+ if (viaPath !== null && viaPath.kind === "episode") hit(episode.ratingKey, viaPath, "path", null);
11369
+ else miss(label);
11370
+ }
11371
+ return {
11372
+ itemByRatingKey,
11373
+ pins: [...pins.values()],
11374
+ stalePins: [...judged].filter((id) => earlier.has(id) && !pins.has(id)),
11375
+ matched,
11376
+ unmatched,
11377
+ unmatchedTitles,
11378
+ via
11379
+ };
11380
+ }
11381
+ //#endregion
11382
+ //#region src/plex-users.ts
11383
+ var fold = (text) => text.trim().toLowerCase();
11384
+ /** `plexName = dominevoUsername` lines; blank lines and `#` comments ignored. */
11385
+ function parseUserMap(raw) {
11386
+ const map = /* @__PURE__ */ new Map();
11387
+ for (const line of raw.split("\n")) {
11388
+ const trimmed = line.trim();
11389
+ if (trimmed === "" || trimmed.startsWith("#")) continue;
11390
+ const at = trimmed.indexOf("=");
11391
+ if (at < 1) continue;
11392
+ const from = fold(trimmed.slice(0, at));
11393
+ const to = fold(trimmed.slice(at + 1));
11394
+ if (from !== "" && to !== "") map.set(from, to);
11395
+ }
11396
+ return map;
11397
+ }
11398
+ /**
11399
+ * Match each Plex user to one Dominevo user: the operator's map first, then the Plex username, title or
11400
+ * email equal (case-insensitive) to the Dominevo username. A name two Dominevo users share matches
11401
+ * neither; a Plex user with no token is skipped with the reason the client gave.
11402
+ */
11403
+ function matchUsers(plexUsers, dominevoUsers, overrides) {
11404
+ const named = /* @__PURE__ */ new Map();
11405
+ for (const user of dominevoUsers) {
11406
+ const key = fold(user.username);
11407
+ named.set(key, [...named.get(key) ?? [], user]);
11408
+ }
11409
+ const only = (name) => {
11410
+ const found = named.get(fold(name)) ?? [];
11411
+ return found.length === 1 ? found[0] ?? null : found.length > 1 ? "ambiguous" : null;
11412
+ };
11413
+ return plexUsers.map((plex) => {
11414
+ if (plex.token === null) return {
11415
+ plex,
11416
+ user: null,
11417
+ reason: plex.skipReason ?? "no token for this user"
11418
+ };
11419
+ const names = [
11420
+ plex.username,
11421
+ plex.title,
11422
+ plex.email
11423
+ ].filter((name) => name !== "");
11424
+ const mapped = names.map((name) => overrides.get(fold(name))).find((to) => to !== void 0);
11425
+ const candidates = mapped !== void 0 ? [mapped] : names;
11426
+ for (const name of candidates) {
11427
+ const found = only(name);
11428
+ if (found === "ambiguous") return {
11429
+ plex,
11430
+ user: null,
11431
+ reason: `more than one Dominevo user is named "${name}"`
11432
+ };
11433
+ if (found !== null) return {
11434
+ plex,
11435
+ user: found,
11436
+ reason: null
11437
+ };
11438
+ }
11439
+ return {
11440
+ plex,
11441
+ user: null,
11442
+ reason: mapped !== void 0 ? `the user map names "${mapped}", which is not a Dominevo user` : "no Dominevo user with this username, title or email"
11443
+ };
11444
+ });
11445
+ }
11446
+ //#endregion
11447
+ //#region src/plex-import.ts
11448
+ var PlexUserReportSchema = object({
11449
+ plexUser: string(),
11450
+ dominevoUser: string().nullable(),
11451
+ /** Why the user was left out; `null` when imported. */
11452
+ skipped: string().nullable(),
11453
+ watched: number().int(),
11454
+ inProgress: number().int(),
11455
+ /** Positions written (a run) or that would be (a preview). */
11456
+ applied: number().int(),
11457
+ /** Positions left alone because Dominevo already holds an equal or newer one. */
11458
+ keptNewer: number().int(),
11459
+ /** Plex items this user watched that match nothing in the library. */
11460
+ unmatched: number().int()
11461
+ });
11462
+ var PlexImportReportSchema = object({
11463
+ mode: _enum(["preview", "run"]),
11464
+ startedAt: number().int(),
11465
+ finishedAt: number().int(),
11466
+ catalog: object({
11467
+ movies: number().int(),
11468
+ shows: number().int(),
11469
+ episodes: number().int(),
11470
+ matched: number().int(),
11471
+ unmatched: number().int(),
11472
+ unmatchedTitles: array(string()),
11473
+ via: record(string(), number().int())
11474
+ }),
11475
+ /** Ids pinned onto items (written by a run, planned by a preview). */
11476
+ pins: number().int(),
11477
+ users: array(PlexUserReportSchema)
11478
+ });
11479
+ var labelOf = (user) => user.username || user.title || user.id;
11480
+ /** What one Plex state becomes here: in progress when Plex holds an offset, otherwise watched. */
11481
+ function progressOf(state) {
11482
+ const updatedAt = state.lastViewedAtMs ?? 0;
11483
+ if (state.viewOffsetMs > 0) return {
11484
+ positionMs: state.viewOffsetMs,
11485
+ durationMs: state.durationMs,
11486
+ watched: isWatched(state.viewOffsetMs, state.durationMs),
11487
+ updatedAt
11488
+ };
11489
+ return {
11490
+ positionMs: state.durationMs,
11491
+ durationMs: state.durationMs,
11492
+ watched: true,
11493
+ updatedAt
11494
+ };
11495
+ }
11496
+ /**
11497
+ * One import pass. `preview` reads everything and writes NOTHING; `run` pins ids and brings progress in
11498
+ * through the store's newer-wins path, so running it again changes nothing and never overwrites a newer
11499
+ * Dominevo position. No connection is kept: this is the whole of it.
11500
+ */
11501
+ async function runPlexImport(deps, mode) {
11502
+ const { logger, store } = deps;
11503
+ const startedAt = deps.now();
11504
+ const dry = mode === "preview";
11505
+ const catalog = await deps.plex.catalog();
11506
+ const match = matchCatalog(catalog, await store.queryAllItems(), {
11507
+ from: deps.pathFrom,
11508
+ to: deps.pathTo
11509
+ }, await loadSourcePins(deps.db, "plex", (message) => logger.warn(message)));
11510
+ if (!dry) {
11511
+ await writePins(deps.db, "plex", match.pins, deps.now());
11512
+ await deletePins(deps.db, "plex", match.stalePins);
11513
+ }
11514
+ const matches = matchUsers(await deps.plex.users(), await deps.listUsers(), parseUserMap(deps.userMap));
11515
+ const users = [];
11516
+ for (const entry of matches) {
11517
+ const report = await importUser(deps, entry, match.itemByRatingKey, dry);
11518
+ users.push(report);
11519
+ logger.info("plex import user", { meta: {
11520
+ mode,
11521
+ plexUser: report.plexUser,
11522
+ dominevoUser: report.dominevoUser,
11523
+ skipped: report.skipped,
11524
+ watched: report.watched,
11525
+ inProgress: report.inProgress,
11526
+ applied: report.applied,
11527
+ keptNewer: report.keptNewer,
11528
+ unmatched: report.unmatched
11529
+ } });
11530
+ }
11531
+ const finishedAt = deps.now();
11532
+ logger.info("plex import finished", { meta: {
11533
+ mode,
11534
+ matched: match.matched,
11535
+ unmatched: match.unmatched,
11536
+ pins: match.pins.length,
11537
+ users: users.length,
11538
+ skippedUsers: users.filter((user) => user.skipped !== null).length
11539
+ } });
11540
+ return {
11541
+ mode,
11542
+ startedAt,
11543
+ finishedAt,
11544
+ catalog: {
11545
+ movies: catalog.movies.length,
11546
+ shows: catalog.shows.length,
11547
+ episodes: catalog.episodes.length,
11548
+ matched: match.matched,
11549
+ unmatched: match.unmatched,
11550
+ unmatchedTitles: match.unmatchedTitles.slice(0, 20),
11551
+ via: { ...match.via }
11552
+ },
11553
+ pins: match.pins.length,
11554
+ users
11555
+ };
11556
+ }
11557
+ async function importUser(deps, entry, itemByRatingKey, dry) {
11558
+ const empty = {
11559
+ plexUser: labelOf(entry.plex),
11560
+ dominevoUser: entry.user?.username ?? null,
11561
+ watched: 0,
11562
+ inProgress: 0,
11563
+ applied: 0,
11564
+ keptNewer: 0,
11565
+ unmatched: 0
11566
+ };
11567
+ if (entry.user === null || entry.plex.token === null) return {
11568
+ ...empty,
11569
+ skipped: entry.reason ?? "no matching user"
11570
+ };
11571
+ let states;
11572
+ try {
11573
+ states = await deps.plex.viewStates(entry.plex.token);
11574
+ } catch (error) {
11575
+ return {
11576
+ ...empty,
11577
+ skipped: `Plex refused this user's library: ${error instanceof Error ? error.message : String(error)}`
11578
+ };
11579
+ }
11580
+ const out = {
11581
+ ...empty,
11582
+ skipped: null
11583
+ };
11584
+ for (const state of states) {
11585
+ const itemId = itemByRatingKey.get(state.ratingKey);
11586
+ if (itemId === void 0) {
11587
+ out.unmatched += 1;
11588
+ continue;
11589
+ }
11590
+ const next = progressOf(state);
11591
+ if (next.watched) out.watched += 1;
11592
+ else out.inProgress += 1;
11593
+ if (await deps.store.importProgress(entry.user.id, {
11594
+ itemId,
11595
+ ...next
11596
+ }, dry)) out.applied += 1;
11597
+ else out.keptNewer += 1;
11598
+ }
11599
+ return out;
11600
+ }
11601
+ /** Runs one import at a time in the background; the report is read back with `status()`. */
11602
+ var PlexImportController = class {
11603
+ logger;
11604
+ now;
11605
+ running = null;
11606
+ last = {
11607
+ mode: null,
11608
+ startedAt: null,
11609
+ error: null,
11610
+ report: null
11611
+ };
11612
+ constructor(logger, now) {
11613
+ this.logger = logger;
11614
+ this.now = now;
11615
+ }
11616
+ status() {
11617
+ return {
11618
+ ...this.last,
11619
+ running: this.running !== null
11620
+ };
11621
+ }
11622
+ /** `false` when one is already running. `build` is called now and may throw (not configured). */
11623
+ start(mode, build, secrets, after) {
11624
+ if (this.running !== null) return false;
11625
+ const deps = build();
11626
+ this.running = mode;
11627
+ this.last = {
11628
+ mode,
11629
+ startedAt: this.now(),
11630
+ error: null,
11631
+ report: null
11632
+ };
11633
+ (async () => {
11634
+ try {
11635
+ const report = await runPlexImport(deps, mode);
11636
+ this.last = {
11637
+ ...this.last,
11638
+ report
11639
+ };
11640
+ after?.(report);
11641
+ } catch (error) {
11642
+ let message = error instanceof Error ? error.message : String(error);
11643
+ for (const secret of secrets) if (secret !== "") message = message.split(secret).join("***");
11644
+ this.logger.error("plex import failed", { meta: {
11645
+ mode,
11646
+ error: message
11647
+ } });
11648
+ this.last = {
11649
+ ...this.last,
11650
+ error: message
11651
+ };
11652
+ } finally {
11653
+ this.running = null;
11654
+ }
11655
+ })();
11656
+ return true;
11657
+ }
11658
+ };
11659
+ //#endregion
11660
+ //#region src/custom-actions.ts
11661
+ /** A settings button sends its resolved params object (`{}` here); a void input refused it. */
11662
+ var NoInput = object({});
11663
+ var Started = object({
11664
+ started: boolean(),
11665
+ message: string()
11666
+ });
11667
+ /**
11668
+ * The Plex import. Admin only: it reads every Plex user's history and writes other users' progress.
11669
+ * Both start the work in the background (a library of thousands of items outlives a request) and
11670
+ * `plexImportStatus` answers where it is and, when done, the report.
11671
+ */
11672
+ var mediaLibraryActions = defineCustomActions({
11673
+ plexImportPreview: customAction(NoInput, Started, {
11674
+ kind: "mutation",
11675
+ auth: "admin"
11676
+ }),
11677
+ plexImportRun: customAction(NoInput, Started, {
11678
+ kind: "mutation",
11679
+ auth: "admin"
11680
+ }),
11681
+ plexImportStatus: customAction(NoInput, object({
11682
+ running: boolean(),
11683
+ mode: _enum(["preview", "run"]).nullable(),
11684
+ startedAt: number().int().nullable(),
11685
+ error: string().nullable(),
11686
+ report: PlexImportReportSchema.nullable()
11687
+ }), {
11688
+ kind: "query",
11689
+ auth: "admin"
11690
+ })
11691
+ });
11692
+ //#endregion
11693
+ //#region src/plex-client.ts
11694
+ /**
11695
+ * A read-only client for a Plex Media Server and plex.tv. Every request is bounded by a timeout and
11696
+ * carries the token in the `X-Plex-Token` header only — never in a URL, a log line or an error.
11697
+ *
11698
+ * Endpoints (checked against the open-source python-plexapi client, `plexapi/myplex.py`):
11699
+ * - PMS GET /identity machineIdentifier
11700
+ * - PMS GET /library/sections the libraries (JSON)
11701
+ * - PMS GET /library/sections/{key}/all?type=1|2|4 movies / shows / episodes, `includeGuids=1`, paged
11702
+ * - plex.tv GET /api/v2/user the token owner (JSON)
11703
+ * - plex.tv GET /api/home/users Plex Home members (XML)
11704
+ * - plex.tv GET /api/servers/{machineId}/shared_servers per-user `accessToken` for this server (XML)
11705
+ * - plex.tv POST /api/home/users/{id}/switch a Home member's own token, `authenticationToken` (XML)
11706
+ */
11707
+ var PLEX_TIMEOUT_MS = 2e4;
11708
+ var MAX_PAGES = 400;
11709
+ var PLEX_TV = "https://plex.tv";
11710
+ /** The largest page a Plex server may send: more is refused rather than held in memory. */
11711
+ var PLEX_MAX_BODY_BYTES = 32 * 1024 * 1024;
11712
+ async function readCapped$1(response, limit = PLEX_MAX_BODY_BYTES) {
11713
+ const tooBig = /* @__PURE__ */ new Error(`Plex response larger than ${limit} bytes`);
11714
+ const declared = Number(response.headers.get("content-length"));
11715
+ if (Number.isFinite(declared) && declared > limit) throw tooBig;
11716
+ if (response.body === null) return "";
11717
+ const reader = response.body.getReader();
11718
+ const chunks = [];
11719
+ let size = 0;
11720
+ for (;;) {
11721
+ const part = await reader.read();
11722
+ if (part.done) break;
11723
+ size += part.value.byteLength;
11724
+ if (size > limit) {
11725
+ await reader.cancel();
11726
+ throw tooBig;
11727
+ }
11728
+ chunks.push(part.value);
11729
+ }
11730
+ return Buffer.concat(chunks).toString("utf8");
11731
+ }
11732
+ var httpPlex = async (request) => {
11733
+ const response = await fetch(request.url, {
11734
+ method: request.method,
11735
+ headers: { ...request.headers },
11736
+ redirect: "error",
11737
+ signal: AbortSignal.timeout(request.timeoutMs)
11738
+ });
11739
+ return {
11740
+ status: response.status,
11741
+ body: await readCapped$1(response)
11742
+ };
11743
+ };
11744
+ var NO_IDS = {
11745
+ tvdbId: null,
11746
+ tmdbId: null,
11747
+ imdbId: null
11748
+ };
11749
+ /** `tmdb://12`, `imdb://tt1`, `tvdb://5` and the legacy agent forms; anything else is ignored. */
11750
+ function parsePlexGuids(guids) {
11751
+ let ids = NO_IDS;
11752
+ for (const guid of guids) {
11753
+ const match = /^(?:com\.plexapp\.agents\.)?(tmdb|themoviedb|imdb|tvdb|thetvdb):\/\/([A-Za-z0-9]+)/.exec(guid);
11754
+ const kind = match?.[1];
11755
+ const value = match?.[2];
11756
+ if (kind === void 0 || value === void 0) continue;
11757
+ if (kind === "imdb") {
11758
+ if (/^tt\d{1,12}$/.test(value) && ids.imdbId === null) ids = {
11759
+ ...ids,
11760
+ imdbId: value
11761
+ };
11762
+ } else if (/^\d{1,10}$/.test(value)) {
11763
+ const id = Number(value);
11764
+ if ((kind === "tmdb" || kind === "themoviedb") && ids.tmdbId === null) ids = {
11765
+ ...ids,
11766
+ tmdbId: id
11767
+ };
11768
+ else if ((kind === "tvdb" || kind === "thetvdb") && ids.tvdbId === null) ids = {
11769
+ ...ids,
11770
+ tvdbId: id
11771
+ };
11772
+ }
11773
+ }
11774
+ return ids;
11775
+ }
11776
+ var text$2 = union([string(), number()]).transform(String);
11777
+ var MetadataSchema = object({
11778
+ ratingKey: text$2,
11779
+ title: string().optional(),
11780
+ year: number().optional(),
11781
+ viewCount: number().optional(),
11782
+ viewOffset: number().optional(),
11783
+ lastViewedAt: number().optional(),
11784
+ duration: number().optional(),
11785
+ index: number().optional(),
11786
+ parentIndex: number().optional(),
11787
+ grandparentRatingKey: text$2.optional(),
11788
+ grandparentTitle: string().optional(),
11789
+ Guid: array(object({ id: string() })).optional(),
11790
+ Media: array(object({ Part: array(object({ file: string().optional() })).optional() })).optional()
11791
+ });
11792
+ var PageSchema = object({ MediaContainer: object({
11793
+ size: number().optional(),
11794
+ totalSize: number().optional(),
11795
+ Metadata: array(MetadataSchema).optional()
11796
+ }) });
11797
+ var SectionsSchema = object({ MediaContainer: object({ Directory: array(object({
11798
+ key: text$2,
11799
+ type: string()
11800
+ })).optional() }) });
11801
+ var IdentitySchema = object({ MediaContainer: object({ machineIdentifier: string() }) });
11802
+ var OwnerSchema = object({
11803
+ id: text$2,
11804
+ username: string().nullish(),
11805
+ title: string().nullish(),
11806
+ email: string().nullish()
11807
+ });
11808
+ var ENTITIES = {
11809
+ "&amp;": "&",
11810
+ "&quot;": "\"",
11811
+ "&apos;": "'",
11812
+ "&#39;": "'",
11813
+ "&lt;": "<",
11814
+ "&gt;": ">"
11815
+ };
11816
+ /** The attributes of every `<tag ...>` in `xml`. plex.tv answers its v1 endpoints in XML. */
11817
+ function xmlTags(xml, tag) {
11818
+ const out = [];
11819
+ const open = new RegExp(`<${tag}\\s([^>]*?)/?>`, "g");
11820
+ for (const found of xml.matchAll(open)) {
11821
+ const attributes = {};
11822
+ for (const pair of (found[1] ?? "").matchAll(/([\w:-]+)="([^"]*)"/g)) {
11823
+ const name = pair[1];
11824
+ if (name !== void 0) attributes[name] = (pair[2] ?? "").replace(/&(?:amp|quot|apos|#39|lt|gt);/g, (e) => ENTITIES[e] ?? e);
11825
+ }
11826
+ out.push(attributes);
11827
+ }
11828
+ return out;
11829
+ }
11830
+ var PlexError = class extends Error {
11831
+ constructor(message) {
11832
+ super(message);
11833
+ this.name = "PlexError";
11834
+ }
11835
+ };
11836
+ var PlexClient = class {
11837
+ settings;
11838
+ http;
11839
+ plexTv;
11840
+ pageSize;
11841
+ /** Every token this client has seen: scrubbed out of any message it raises. */
11842
+ secrets = /* @__PURE__ */ new Set();
11843
+ constructor(settings, http = httpPlex, plexTv = PLEX_TV, pageSize = 500) {
11844
+ this.settings = settings;
11845
+ this.http = http;
11846
+ this.plexTv = plexTv;
11847
+ this.pageSize = pageSize;
11848
+ this.secrets.add(settings.token);
11849
+ }
11850
+ scrub(message) {
11851
+ let out = message;
11852
+ for (const secret of this.secrets) if (secret !== "") out = out.split(secret).join("***");
11853
+ return out;
11854
+ }
11855
+ async call(what, url, token, options) {
11856
+ this.secrets.add(token);
11857
+ let response;
11858
+ try {
11859
+ response = await this.http({
11860
+ url,
11861
+ method: options.method ?? "GET",
11862
+ headers: {
11863
+ Accept: options.json ? "application/json" : "application/xml",
11864
+ "X-Plex-Token": token,
11865
+ "X-Plex-Client-Identifier": "dominevo-media-library",
11866
+ "X-Plex-Product": "Dominevo"
11867
+ },
11868
+ timeoutMs: PLEX_TIMEOUT_MS
11869
+ });
11870
+ } catch (error) {
11871
+ throw new PlexError(this.scrub(`${what}: ${error instanceof Error ? error.message : String(error)}`));
11872
+ }
11873
+ if (response.status < 200 || response.status >= 300) throw new PlexError(`${what}: HTTP ${response.status}`);
11874
+ return response.body;
11875
+ }
11876
+ async json(what, url, token, schema) {
11877
+ const body = await this.call(what, url, token, { json: true });
11878
+ try {
11879
+ return schema.parse(JSON.parse(body));
11880
+ } catch {
11881
+ throw new PlexError(`${what}: unexpected answer`);
11882
+ }
11883
+ }
11884
+ async machineIdentifier() {
11885
+ const { baseUrl, token } = this.settings;
11886
+ return (await this.json("identity", `${baseUrl}/identity`, token, IdentitySchema)).MediaContainer.machineIdentifier;
11887
+ }
11888
+ async pages(what, path, token, withGuids) {
11889
+ const out = [];
11890
+ for (let page = 0; page < MAX_PAGES; page += 1) {
11891
+ const url = `${this.settings.baseUrl}${path}${path.includes("?") ? "&" : "?"}includeGuids=${withGuids ? 1 : 0}&X-Plex-Container-Start=${page * this.pageSize}&X-Plex-Container-Size=${this.pageSize}`;
11892
+ const answer = await this.json(what, url, token, PageSchema);
11893
+ const rows = answer.MediaContainer.Metadata ?? [];
11894
+ out.push(...rows);
11895
+ const total = answer.MediaContainer.totalSize;
11896
+ if (rows.length === 0 || total !== void 0 && out.length >= total) break;
11897
+ }
11898
+ return out;
11899
+ }
11900
+ async sections(token) {
11901
+ const dirs = (await this.json("library sections", `${this.settings.baseUrl}/library/sections`, token, SectionsSchema)).MediaContainer.Directory ?? [];
11902
+ return {
11903
+ movie: dirs.filter((d) => d.type === "movie").map((d) => d.key),
11904
+ show: dirs.filter((d) => d.type === "show").map((d) => d.key)
11905
+ };
11906
+ }
11907
+ /** The whole library with the ids Plex holds, read with the server owner's token. */
11908
+ async catalog() {
11909
+ const { token } = this.settings;
11910
+ const sections = await this.sections(token);
11911
+ const filesOf = (row) => (row.Media ?? []).flatMap((media) => (media.Part ?? []).flatMap((part) => part.file === void 0 ? [] : [part.file]));
11912
+ const guidsOf = (row) => parsePlexGuids((row.Guid ?? []).map((g) => g.id));
11913
+ const movies = [];
11914
+ const shows = [];
11915
+ const episodes = [];
11916
+ for (const key of sections.movie) for (const row of await this.pages("movies", `/library/sections/${key}/all?type=1`, token, true)) movies.push({
11917
+ ratingKey: row.ratingKey,
11918
+ title: row.title ?? "",
11919
+ year: row.year ?? null,
11920
+ ids: guidsOf(row),
11921
+ files: filesOf(row)
11922
+ });
11923
+ for (const key of sections.show) {
11924
+ for (const row of await this.pages("shows", `/library/sections/${key}/all?type=2`, token, true)) shows.push({
11925
+ ratingKey: row.ratingKey,
11926
+ title: row.title ?? "",
11927
+ year: row.year ?? null,
11928
+ ids: guidsOf(row)
11929
+ });
11930
+ for (const row of await this.pages("episodes", `/library/sections/${key}/all?type=4`, token, false)) episodes.push({
11931
+ ratingKey: row.ratingKey,
11932
+ showRatingKey: row.grandparentRatingKey ?? "",
11933
+ showTitle: row.grandparentTitle ?? "",
11934
+ season: row.parentIndex ?? null,
11935
+ episode: row.index ?? null,
11936
+ files: filesOf(row)
11937
+ });
11938
+ }
11939
+ return {
11940
+ movies,
11941
+ shows,
11942
+ episodes
11943
+ };
11944
+ }
11945
+ /** What one user has watched or started, by rating key (rating keys are the server's, shared by all users). */
11946
+ async viewStates(userToken) {
11947
+ const sections = await this.sections(userToken);
11948
+ const out = [];
11949
+ const take = (rows) => {
11950
+ for (const row of rows) {
11951
+ const viewCount = row.viewCount ?? 0;
11952
+ const viewOffsetMs = row.viewOffset ?? 0;
11953
+ if (viewCount <= 0 && viewOffsetMs <= 0) continue;
11954
+ out.push({
11955
+ ratingKey: row.ratingKey,
11956
+ viewCount,
11957
+ viewOffsetMs,
11958
+ lastViewedAtMs: row.lastViewedAt === void 0 ? null : row.lastViewedAt * 1e3,
11959
+ durationMs: row.duration ?? 0
11960
+ });
11961
+ }
11962
+ };
11963
+ for (const key of sections.movie) take(await this.pages("movie states", `/library/sections/${key}/all?type=1`, userToken, false));
11964
+ for (const key of sections.show) take(await this.pages("episode states", `/library/sections/${key}/all?type=4`, userToken, false));
11965
+ return out;
11966
+ }
11967
+ /** Everyone with access to this server, each with the token that reads their state, or the reason there is none. */
11968
+ async users() {
11969
+ const { token } = this.settings;
11970
+ const machineId = await this.machineIdentifier();
11971
+ const owner = OwnerSchema.parse(JSON.parse(await this.call("plex.tv account", `${this.plexTv}/api/v2/user`, token, { json: true })));
11972
+ const byId = /* @__PURE__ */ new Map();
11973
+ const entry = (id) => byId.get(id) ?? {
11974
+ username: "",
11975
+ title: "",
11976
+ email: "",
11977
+ inHome: false,
11978
+ protectedByPin: false,
11979
+ shared: null
11980
+ };
11981
+ byId.set(owner.id, {
11982
+ ...entry(owner.id),
11983
+ username: owner.username ?? "",
11984
+ title: owner.title ?? owner.username ?? "",
11985
+ email: owner.email ?? ""
11986
+ });
11987
+ const home = await this.call("plex home users", `${this.plexTv}/api/home/users`, token, { json: false });
11988
+ for (const user of xmlTags(home, "User")) {
11989
+ const id = user["id"];
11990
+ if (id === void 0) continue;
11991
+ const known = entry(id);
11992
+ byId.set(id, {
11993
+ ...known,
11994
+ username: user["username"] || known.username,
11995
+ title: user["title"] || known.title,
11996
+ email: user["email"] || known.email,
11997
+ inHome: true,
11998
+ protectedByPin: user["protected"] === "1"
11999
+ });
12000
+ }
12001
+ const shared = await this.call("plex shared servers", `${this.plexTv}/api/servers/${encodeURIComponent(machineId)}/shared_servers`, token, { json: false });
12002
+ for (const share of xmlTags(shared, "SharedServer")) {
12003
+ const id = share["userID"];
12004
+ const accessToken = share["accessToken"];
12005
+ if (id === void 0) continue;
12006
+ if (accessToken !== void 0) this.secrets.add(accessToken);
12007
+ const known = entry(id);
12008
+ byId.set(id, {
12009
+ ...known,
12010
+ username: share["username"] || known.username,
12011
+ title: known.title || share["username"] || "",
12012
+ email: share["email"] || known.email,
12013
+ shared: accessToken ?? null
12014
+ });
12015
+ }
12016
+ const users = [];
12017
+ for (const [id, user] of byId) {
12018
+ const base = {
12019
+ id,
12020
+ username: user.username,
12021
+ title: user.title,
12022
+ email: user.email
12023
+ };
12024
+ if (id === owner.id) users.push({
12025
+ ...base,
12026
+ token,
12027
+ skipReason: null
12028
+ });
12029
+ else if (user.shared !== null) users.push({
12030
+ ...base,
12031
+ token: user.shared,
12032
+ skipReason: null
12033
+ });
12034
+ else if (user.protectedByPin) users.push({
12035
+ ...base,
12036
+ token: null,
12037
+ skipReason: "Plex Home user protected by a PIN: no token can be obtained"
12038
+ });
12039
+ else if (user.inHome) users.push(await this.switched(base, token));
12040
+ else users.push({
12041
+ ...base,
12042
+ token: null,
12043
+ skipReason: "no access token for this server (not shared with it)"
12044
+ });
12045
+ }
12046
+ return users;
12047
+ }
12048
+ async switched(base, token) {
12049
+ try {
12050
+ const body = await this.call("plex home switch", `${this.plexTv}/api/home/users/${encodeURIComponent(base.id)}/switch`, token, {
12051
+ method: "POST",
12052
+ json: false
12053
+ });
12054
+ const switched = xmlTags(body, "user")[0]?.["authenticationToken"] ?? xmlTags(body, "User")[0]?.["authenticationToken"];
12055
+ if (switched === void 0 || switched === "") return {
12056
+ ...base,
12057
+ token: null,
12058
+ skipReason: "Plex did not return a token for this Home user"
12059
+ };
12060
+ this.secrets.add(switched);
12061
+ return {
12062
+ ...base,
12063
+ token: switched,
12064
+ skipReason: null
12065
+ };
12066
+ } catch (error) {
12067
+ return {
12068
+ ...base,
12069
+ token: null,
12070
+ skipReason: this.scrub(`Home user switch failed: ${error instanceof Error ? error.message : String(error)}`)
12071
+ };
12072
+ }
12073
+ }
12074
+ };
12075
+ //#endregion
12076
+ //#region src/provider-text.ts
12077
+ /** Text helpers shared by the online providers. */
12078
+ function text$1(value) {
12079
+ const trimmed = value?.trim() ?? "";
12080
+ return trimmed === "" ? null : trimmed;
12081
+ }
12082
+ /** The leading four-digit year of a date or range ("2011-04-17", "2011–2019"), or null. */
12083
+ function yearOf$2(value) {
12084
+ const match = /^(\d{4})/.exec(String(value ?? ""));
12085
+ return match?.[1] === void 0 ? null : Number(match[1]);
12086
+ }
12087
+ /** HTML to plain text: tags dropped, line breaks kept, the common entities decoded. */
12088
+ function stripHtml(html) {
12089
+ if (html === null || html === void 0) return null;
12090
+ const out = html.replace(/<br\s*\/?>/gi, "\n").replace(/<[^>]*>/g, "").replace(/&#(\d{1,6});/g, (_whole, dec) => {
12091
+ const code = Number(dec);
12092
+ return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : "";
12093
+ }).replace(/&quot;/g, "\"").replace(/&apos;|&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").trim();
12094
+ return out === "" ? null : out;
12095
+ }
12096
+ /** True when an HTTP failure from the remote fetch ("HTTP 401") carries this status. */
12097
+ function isHttp(error, status) {
12098
+ return error instanceof Error && new RegExp(`\\bHTTP ${status}\\b`).test(error.message);
12099
+ }
12100
+ //#endregion
12101
+ //#region src/anilist.ts
12102
+ var ANILIST_ID = "anilist";
12103
+ var API$5 = "https://graphql.anilist.co";
12104
+ /** Formats that make an anime a series, and a movie. */
12105
+ var FORMATS = {
12106
+ series: [
12107
+ "TV",
12108
+ "TV_SHORT",
12109
+ "ONA"
12110
+ ],
12111
+ movie: ["MOVIE"]
12112
+ };
12113
+ var QUERY = `query ($search: String, $year: Int, $formats: [MediaFormat]) {
12114
+ Page(perPage: 15) {
12115
+ media(search: $search, seasonYear: $year, type: ANIME, format_in: $formats) {
12116
+ id
12117
+ seasonYear
12118
+ startDate { year }
12119
+ title { romaji english native }
12120
+ synonyms
12121
+ description(asHtml: false)
12122
+ coverImage { extraLarge }
12123
+ bannerImage
12124
+ }
12125
+ }
12126
+ }`;
12127
+ var AnswerSchema$2 = object({ data: object({ Page: object({ media: array(object({
12128
+ id: number().int(),
12129
+ seasonYear: number().int().nullish(),
12130
+ startDate: object({ year: number().int().nullish() }).nullish(),
12131
+ title: object({
12132
+ romaji: string().nullish(),
12133
+ english: string().nullish(),
12134
+ native: string().nullish()
12135
+ }),
12136
+ synonyms: array(string()).nullish(),
12137
+ description: string().nullish(),
12138
+ coverImage: object({ extraLarge: string().nullish() }).nullish(),
12139
+ bannerImage: string().nullish()
12140
+ })) }) }) });
12141
+ var namesOf = (media) => [
12142
+ media.title.romaji,
12143
+ media.title.english,
12144
+ media.title.native,
12145
+ ...media.synonyms ?? []
12146
+ ].filter((name) => typeof name === "string" && name !== "");
12147
+ /**
12148
+ * AniList: anime only, keyless GraphQL. A title is trusted only when exactly one entry carries it
12149
+ * (romaji, english, native or a synonym). No ids of other databases and no per-episode titles.
12150
+ * Its rate limit answers 429, which is a failure the scan counts; there is no retry here.
12151
+ */
12152
+ function createAnilistProvider(deps) {
12153
+ return {
12154
+ id: ANILIST_ID,
12155
+ kinds: ["movie", "series"],
12156
+ lookupBy: [],
12157
+ async identify(kind, title, year) {
12158
+ const bytes = await deps.fetch(API$5, {
12159
+ headers: {
12160
+ "Content-Type": "application/json",
12161
+ Accept: "application/json"
12162
+ },
12163
+ body: JSON.stringify({
12164
+ query: QUERY,
12165
+ variables: {
12166
+ search: title,
12167
+ formats: FORMATS[kind],
12168
+ ...year === null ? {} : { year }
12169
+ }
12170
+ })
12171
+ });
12172
+ const media = AnswerSchema$2.parse(JSON.parse(bytes.toString("utf8"))).data.Page.media;
12173
+ const wanted = foldTitle(title);
12174
+ const exact = media.filter((entry) => namesOf(entry).some((name) => foldTitle(name) === wanted));
12175
+ const [only] = exact;
12176
+ if (exact.length !== 1 || only === void 0) return null;
12177
+ return {
12178
+ providerId: ANILIST_ID,
12179
+ remoteId: String(only.id),
12180
+ title: text$1(only.title.english) ?? text$1(only.title.romaji) ?? text$1(only.title.native) ?? title,
12181
+ year: only.seasonYear ?? only.startDate?.year ?? null,
12182
+ overview: stripHtml(only.description),
12183
+ tvdbId: null,
12184
+ tmdbId: null,
12185
+ imdbId: null,
12186
+ poster: text$1(only.coverImage?.extraLarge),
12187
+ fanart: text$1(only.bannerImage)
12188
+ };
12189
+ },
12190
+ async episodes() {
12191
+ return [];
12192
+ }
12193
+ };
12194
+ }
12195
+ //#endregion
12196
+ //#region src/fanart.ts
12197
+ var FANART_ID = "fanart";
12198
+ var API$4 = "https://webservice.fanart.tv/v3";
12199
+ var DEFAULT_LANGUAGE$1 = "en";
12200
+ /** Said once per scan, never with the key. */
12201
+ var FANART_REJECTED = "Fanart.tv key rejected: check the API key in the settings";
12202
+ var ArtSchema = array(object({
12203
+ url: string(),
12204
+ lang: string().nullish(),
12205
+ likes: union([string(), number()]).nullish()
12206
+ }));
12207
+ var AnswerSchema$1 = object({
12208
+ movieposter: ArtSchema.nullish(),
12209
+ moviebackground: ArtSchema.nullish(),
12210
+ tvposter: ArtSchema.nullish(),
12211
+ showbackground: ArtSchema.nullish()
12212
+ });
12213
+ /** The item's language first, then English, then whatever is there; the most liked within each. */
12214
+ function pick(art, language) {
12215
+ const liked = (entry) => Number(entry.likes ?? 0);
12216
+ const sorted = [...art ?? []].sort((a, b) => liked(b) - liked(a));
12217
+ const of = (lang) => sorted.find((entry) => entry.lang === lang);
12218
+ return (of(language) ?? of(DEFAULT_LANGUAGE$1) ?? sorted[0])?.url ?? null;
12219
+ }
12220
+ /** Fanart.tv: pictures only, for ids another step settled (movie by tmdb or imdb, series by tvdb). */
12221
+ function createFanartProvider(deps) {
12222
+ const language = deps.language ?? DEFAULT_LANGUAGE$1;
12223
+ const headers = {
12224
+ "api-key": deps.apiKey,
12225
+ Accept: "application/json"
12226
+ };
12227
+ const path = (kind, ids) => {
12228
+ if (kind === "movie") {
12229
+ const id = ids.tmdbId ?? ids.imdbId;
12230
+ return id === null ? null : `/movies/${encodeURIComponent(String(id))}`;
12231
+ }
12232
+ return ids.tvdbId === null ? null : `/tv/${ids.tvdbId}`;
12233
+ };
12234
+ return {
12235
+ id: FANART_ID,
12236
+ kinds: ["movie", "series"],
12237
+ lookupBy: [
12238
+ "tmdbId",
12239
+ "imdbId",
12240
+ "tvdbId"
12241
+ ],
12242
+ async images(kind, ids) {
12243
+ const where = path(kind, ids);
12244
+ if (where === null) return null;
12245
+ try {
12246
+ const bytes = await deps.fetch(`${API$4}${where}`, { headers });
12247
+ const answer = AnswerSchema$1.parse(JSON.parse(bytes.toString("utf8")));
12248
+ const poster = pick(kind === "movie" ? answer.movieposter : answer.tvposter, language);
12249
+ const fanart = pick(kind === "movie" ? answer.moviebackground : answer.showbackground, language);
12250
+ return poster === null && fanart === null ? null : {
12251
+ poster,
12252
+ fanart
12253
+ };
12254
+ } catch (error) {
12255
+ if (isHttp(error, 401) || isHttp(error, 403)) throw new ProviderAuthError(FANART_REJECTED);
12256
+ if (isHttp(error, 404)) return null;
12257
+ throw error;
12258
+ }
12259
+ }
12260
+ };
12261
+ }
12262
+ //#endregion
12263
+ //#region src/omdb.ts
12264
+ var OMDB_ID = "omdb";
12265
+ var API$3 = "https://www.omdbapi.com/";
12266
+ /** Said once per scan, never with the key. */
12267
+ var OMDB_REJECTED = "OMDb key rejected: check the API key in the settings";
12268
+ var NOT_FOUND = /not found|incorrect imdb id|too many results/i;
12269
+ var MAX_SEASONS = 60;
12270
+ var AnswerSchema = object({
12271
+ Response: string(),
12272
+ Error: string().nullish()
12273
+ }).passthrough();
12274
+ var SearchSchema$3 = object({ Search: array(object({
12275
+ Title: string(),
12276
+ Year: string().nullish(),
12277
+ imdbID: string()
12278
+ })).nullish() });
12279
+ var TitleSchema = object({
12280
+ Title: string(),
12281
+ Year: string().nullish(),
12282
+ Plot: string().nullish(),
12283
+ Poster: string().nullish(),
12284
+ imdbID: string(),
12285
+ totalSeasons: string().nullish()
12286
+ });
12287
+ var SeasonSchema$1 = object({ Episodes: array(object({
12288
+ Title: string().nullish(),
12289
+ Episode: string()
12290
+ })) });
12291
+ /** "N/A" is OMDb's word for nothing. */
12292
+ var field = (value) => {
12293
+ const trimmed = text$1(value);
12294
+ return trimmed === null || trimmed === "N/A" ? null : trimmed;
12295
+ };
12296
+ /** OMDb: movies and series by IMDb id or exact title. */
12297
+ function createOmdbProvider(deps) {
12298
+ /** The parsed answer, or null for "not found"; any failure message is scrubbed of the key and the URL. */
12299
+ const call = async (query) => {
12300
+ const params = new URLSearchParams({
12301
+ ...query,
12302
+ apikey: deps.apiKey
12303
+ });
12304
+ let body;
12305
+ try {
12306
+ body = JSON.parse((await deps.fetch(`${API$3}?${params.toString()}`)).toString("utf8"));
12307
+ } catch (error) {
12308
+ if (isHttp(error, 401)) throw new ProviderAuthError(OMDB_REJECTED);
12309
+ const reason = error instanceof Error ? error.message : String(error);
12310
+ throw new Error(`OMDb request failed: ${reason.split(deps.apiKey).join("***")}`);
12311
+ }
12312
+ const answer = AnswerSchema.parse(body);
12313
+ if (answer.Response !== "False") return body;
12314
+ const message = answer.Error ?? "";
12315
+ if (/invalid api key|no api key/i.test(message)) throw new ProviderAuthError(OMDB_REJECTED);
12316
+ if (NOT_FOUND.test(message)) return null;
12317
+ throw new Error(`OMDb answered: ${message.split(deps.apiKey).join("***") || "an error"}`);
12318
+ };
12319
+ const byImdb = async (id) => {
12320
+ const body = await call({ i: id });
12321
+ if (body === null) return null;
12322
+ const title = TitleSchema.parse(body);
12323
+ return {
12324
+ providerId: OMDB_ID,
12325
+ remoteId: title.imdbID,
12326
+ title: title.Title,
12327
+ year: yearOf$2(title.Year),
12328
+ overview: field(title.Plot),
12329
+ tvdbId: null,
12330
+ tmdbId: null,
12331
+ imdbId: title.imdbID,
12332
+ poster: field(title.Poster),
12333
+ fanart: null
12334
+ };
12335
+ };
12336
+ return {
12337
+ id: OMDB_ID,
12338
+ kinds: ["movie", "series"],
12339
+ lookupBy: ["imdbId"],
12340
+ async identify(kind, title, year) {
12341
+ const body = await call({
12342
+ s: title,
12343
+ type: kind,
12344
+ ...year === null ? {} : { y: String(year) }
12345
+ });
12346
+ if (body === null) return null;
12347
+ const exact = (SearchSchema$3.parse(body).Search ?? []).filter((entry) => foldTitle(entry.Title) === foldTitle(title));
12348
+ const sameYear = year === null ? [] : exact.filter((entry) => yearOf$2(entry.Year) === year);
12349
+ const pool = sameYear.length > 0 ? sameYear : exact;
12350
+ const [only] = pool;
12351
+ return pool.length === 1 && only !== void 0 ? byImdb(only.imdbID) : null;
12352
+ },
12353
+ async lookup(_kind, ids) {
12354
+ return ids.imdbId === null ? null : byImdb(ids.imdbId);
12355
+ },
12356
+ async episodes(match) {
12357
+ const head = await call({ i: match.remoteId });
12358
+ if (head === null) return [];
12359
+ const total = Number(field(TitleSchema.parse(head).totalSeasons) ?? 0);
12360
+ const out = [];
12361
+ for (let season = 1; season <= Math.min(total, MAX_SEASONS); season += 1) {
12362
+ const body = await call({
12363
+ i: match.remoteId,
12364
+ Season: String(season)
12365
+ });
12366
+ if (body === null) continue;
12367
+ for (const entry of SeasonSchema$1.parse(body).Episodes) {
12368
+ const episode = Number(entry.Episode);
12369
+ if (!Number.isInteger(episode)) continue;
12370
+ out.push({
12371
+ season,
12372
+ episode,
12373
+ title: field(entry.Title),
12374
+ overview: null,
12375
+ still: null
12376
+ });
12377
+ }
12378
+ }
12379
+ return out;
12380
+ }
12381
+ };
12382
+ }
12383
+ //#endregion
12384
+ //#region src/tmdb.ts
12385
+ var TMDB_ID = "tmdb";
12386
+ var API$2 = "https://api.themoviedb.org/3";
12387
+ var IMAGES = "https://image.tmdb.org/t/p";
12388
+ var DEFAULT_LANGUAGE = "en-US";
12389
+ /** Said once per scan, never with the token. */
12390
+ var TMDB_REJECTED = "TMDB token rejected: check the API Read Access Token in the settings";
12391
+ var SearchSchema$2 = object({ results: array(object({
12392
+ id: number().int(),
12393
+ title: string().nullish(),
12394
+ name: string().nullish(),
12395
+ release_date: string().nullish(),
12396
+ first_air_date: string().nullish()
12397
+ })) });
12398
+ var DetailsSchema = object({
12399
+ id: number().int(),
12400
+ title: string().nullish(),
12401
+ name: string().nullish(),
12402
+ release_date: string().nullish(),
12403
+ first_air_date: string().nullish(),
12404
+ overview: string().nullish(),
12405
+ poster_path: string().nullish(),
12406
+ backdrop_path: string().nullish(),
12407
+ imdb_id: string().nullish(),
12408
+ external_ids: object({
12409
+ imdb_id: string().nullish(),
12410
+ tvdb_id: number().int().nullish()
12411
+ }).nullish(),
12412
+ seasons: array(object({ season_number: number().int() })).nullish()
12413
+ });
12414
+ var FindSchema = object({
12415
+ movie_results: array(object({ id: number().int() })).default([]),
12416
+ tv_results: array(object({ id: number().int() })).default([])
12417
+ });
12418
+ var SeasonSchema = object({ episodes: array(object({
12419
+ season_number: number().int(),
12420
+ episode_number: number().int(),
12421
+ name: string().nullish(),
12422
+ overview: string().nullish(),
12423
+ still_path: string().nullish()
12424
+ })) });
12425
+ function yearOf$1(date) {
12426
+ const match = /^(\d{4})/.exec(date ?? "");
12427
+ return match?.[1] === void 0 ? null : Number(match[1]);
12428
+ }
12429
+ function text(value) {
12430
+ const trimmed = value?.trim() ?? "";
12431
+ return trimmed === "" ? null : trimmed;
12432
+ }
12433
+ function image(size, path) {
12434
+ return path === null || path === void 0 || !path.startsWith("/") ? null : `${IMAGES}/${size}${path}`;
12435
+ }
12436
+ var nameOf = (entry) => entry.title ?? entry.name ?? "";
12437
+ var yearIn = (entry) => yearOf$1(entry.release_date ?? entry.first_air_date);
12438
+ /** TMDB: movies and series, with the installation's own read token. All calls go through the shared remote fetch. */
12439
+ function createTmdbProvider(deps) {
12440
+ const language = deps.language ?? DEFAULT_LANGUAGE;
12441
+ const headers = {
12442
+ Authorization: `Bearer ${deps.token}`,
12443
+ Accept: "application/json"
12444
+ };
12445
+ const segment = (kind) => kind === "movie" ? "movie" : "tv";
12446
+ const call = async (path, query = {}) => {
12447
+ const params = new URLSearchParams({
12448
+ ...query,
12449
+ language
12450
+ });
12451
+ try {
12452
+ const bytes = await deps.fetch(`${API$2}${path}?${params.toString()}`, { headers });
12453
+ return JSON.parse(bytes.toString("utf8"));
12454
+ } catch (error) {
12455
+ if (error instanceof Error && /\b401\b/.test(error.message)) throw new ProviderAuthError(TMDB_REJECTED);
12456
+ throw error;
12457
+ }
12458
+ };
12459
+ const matchOf = (details) => ({
12460
+ providerId: TMDB_ID,
12461
+ remoteId: String(details.id),
12462
+ title: details.title ?? details.name ?? "",
12463
+ year: yearOf$1(details.release_date ?? details.first_air_date),
12464
+ overview: text(details.overview),
12465
+ tvdbId: details.external_ids?.tvdb_id ?? null,
12466
+ tmdbId: details.id,
12467
+ imdbId: text(details.external_ids?.imdb_id) ?? text(details.imdb_id),
12468
+ poster: image("w500", details.poster_path),
12469
+ fanart: image("w1280", details.backdrop_path)
12470
+ });
12471
+ const detailsOf = async (kind, id) => {
12472
+ try {
12473
+ return matchOf(DetailsSchema.parse(await call(`/${segment(kind)}/${id}`, { append_to_response: "external_ids" })));
12474
+ } catch (error) {
12475
+ if (error instanceof Error && /\b404\b/.test(error.message)) return null;
12476
+ throw error;
12477
+ }
12478
+ };
12479
+ return {
12480
+ id: TMDB_ID,
12481
+ kinds: ["movie", "series"],
12482
+ lookupBy: [
12483
+ "tmdbId",
12484
+ "imdbId",
12485
+ "tvdbId"
12486
+ ],
12487
+ async identify(kind, title, year) {
12488
+ const exact = SearchSchema$2.parse(await call(`/search/${segment(kind)}`, {
12489
+ query: title,
12490
+ include_adult: "false",
12491
+ ...year === null ? {} : kind === "movie" ? { year: String(year) } : { first_air_date_year: String(year) }
12492
+ })).results.filter((entry) => foldTitle(nameOf(entry)) === foldTitle(title));
12493
+ const hit = (year === null ? void 0 : exact.find((entry) => yearIn(entry) === year)) ?? exact[0];
12494
+ return hit === void 0 ? null : detailsOf(kind, hit.id);
12495
+ },
12496
+ async lookup(kind, ids) {
12497
+ if (ids.tmdbId !== null) return detailsOf(kind, ids.tmdbId);
12498
+ const external = ids.imdbId !== null ? {
12499
+ source: "imdb_id",
12500
+ value: ids.imdbId
12501
+ } : ids.tvdbId !== null ? {
12502
+ source: "tvdb_id",
12503
+ value: String(ids.tvdbId)
12504
+ } : null;
12505
+ if (external === null) return null;
12506
+ const found = FindSchema.parse(await call(`/find/${encodeURIComponent(external.value)}`, { external_source: external.source }));
12507
+ const id = (kind === "movie" ? found.movie_results : found.tv_results)[0]?.id;
12508
+ return id === void 0 ? null : detailsOf(kind, id);
12509
+ },
12510
+ async episodes(match) {
12511
+ const base = `/tv/${encodeURIComponent(match.remoteId)}`;
12512
+ const show = DetailsSchema.parse(await call(base));
12513
+ const out = [];
12514
+ for (const season of show.seasons ?? []) {
12515
+ const list = SeasonSchema.parse(await call(`${base}/season/${season.season_number}`));
12516
+ for (const entry of list.episodes) out.push({
12517
+ season: entry.season_number,
12518
+ episode: entry.episode_number,
12519
+ title: text(entry.name),
12520
+ overview: text(entry.overview),
12521
+ still: image("w300", entry.still_path)
12522
+ });
12523
+ }
12524
+ return out;
12525
+ }
12526
+ };
12527
+ }
12528
+ //#endregion
12529
+ //#region src/tvdb.ts
12530
+ var TVDB_ID = "tvdb";
12531
+ var API$1 = "https://api4.thetvdb.com/v4";
12532
+ /** Said once per scan, never with the key. */
12533
+ var TVDB_REJECTED = "TheTVDB key rejected: check the API key in the settings";
12534
+ /** Artwork type ids: series poster / background, movie poster / background. */
12535
+ var ARTWORK = {
12536
+ series: {
12537
+ poster: 2,
12538
+ fanart: 3
12539
+ },
12540
+ movie: {
12541
+ poster: 14,
12542
+ fanart: 15
12543
+ }
12544
+ };
12545
+ var MAX_EPISODE_PAGES = 50;
12546
+ /** The login answer; the bearer is read by name below, it is a response, not a setting. */
12547
+ var LoginSchema = object({ data: record(string(), string()) });
12548
+ var SearchSchema$1 = object({ data: array(object({
12549
+ tvdb_id: union([string(), number()]),
12550
+ name: string().nullish(),
12551
+ year: union([string(), number()]).nullish()
12552
+ })).nullish() });
12553
+ var RemoteIdSchema = object({
12554
+ id: union([string(), number()]),
12555
+ sourceName: string()
12556
+ });
12557
+ var ExtendedSchema = object({ data: object({
12558
+ id: number().int(),
12559
+ name: string().nullish(),
12560
+ year: union([string(), number()]).nullish(),
12561
+ firstAired: string().nullish(),
12562
+ overview: string().nullish(),
12563
+ image: string().nullish(),
12564
+ remoteIds: array(RemoteIdSchema).nullish(),
12565
+ artworks: array(object({
12566
+ image: string(),
12567
+ type: number().int(),
12568
+ score: number().nullish()
12569
+ })).nullish()
12570
+ }) });
12571
+ var RemoteSearchSchema = object({ data: array(object({
12572
+ series: object({ id: number().int() }).nullish(),
12573
+ movie: object({ id: number().int() }).nullish()
12574
+ })).nullish() });
12575
+ var EpisodesSchema = object({
12576
+ data: object({ episodes: array(object({
12577
+ seasonNumber: number().int(),
12578
+ number: number().int(),
12579
+ name: string().nullish(),
12580
+ overview: string().nullish(),
12581
+ image: string().nullish()
12582
+ })) }),
12583
+ links: object({ next: number().int().nullish() }).nullish()
12584
+ });
12585
+ function bestArtwork(extended, type) {
12586
+ return (extended.artworks ?? []).filter((art) => art.type === type).sort((a, b) => (b.score ?? 0) - (a.score ?? 0))[0]?.image ?? null;
12587
+ }
12588
+ function remoteId(extended, source) {
12589
+ return extended.remoteIds?.find((entry) => source.test(entry.sourceName))?.id.toString() ?? null;
12590
+ }
12591
+ /** TheTVDB v4: series and movies; a bearer token from the key is held for the provider's lifetime. */
12592
+ function createTvdbProvider(deps) {
12593
+ let token = null;
12594
+ const login = async () => {
12595
+ try {
12596
+ const bytes = await deps.fetch(`${API$1}/login`, {
12597
+ headers: {
12598
+ "Content-Type": "application/json",
12599
+ Accept: "application/json"
12600
+ },
12601
+ body: JSON.stringify({ apikey: deps.apiKey })
12602
+ });
12603
+ const bearer = LoginSchema.parse(JSON.parse(bytes.toString("utf8"))).data["token"];
12604
+ if (bearer === void 0) throw new Error("TheTVDB login answered without a bearer");
12605
+ token = bearer;
12606
+ return bearer;
12607
+ } catch (error) {
12608
+ if (isHttp(error, 401)) throw new ProviderAuthError(TVDB_REJECTED);
12609
+ throw error;
12610
+ }
12611
+ };
12612
+ const call = async (path, query = {}) => {
12613
+ const params = new URLSearchParams(query).toString();
12614
+ const url = `${API$1}${path}${params === "" ? "" : `?${params}`}`;
12615
+ const send = async (bearer) => JSON.parse((await deps.fetch(url, { headers: {
12616
+ Authorization: `Bearer ${bearer}`,
12617
+ Accept: "application/json"
12618
+ } })).toString("utf8"));
12619
+ try {
12620
+ return await send(token ?? await login());
12621
+ } catch (error) {
12622
+ if (!isHttp(error, 401)) throw error;
12623
+ }
12624
+ try {
12625
+ return await send(await login());
12626
+ } catch (error) {
12627
+ if (isHttp(error, 401)) throw new ProviderAuthError(TVDB_REJECTED);
12628
+ throw error;
12629
+ }
12630
+ };
12631
+ const extendedPath = (kind, id) => `/${kind === "movie" ? "movies" : "series"}/${id}/extended`;
12632
+ const detailsOf = async (kind, id) => {
12633
+ try {
12634
+ const { data } = ExtendedSchema.parse(await call(extendedPath(kind, id)));
12635
+ const imdb = remoteId(data, /imdb/i);
12636
+ const tmdb = remoteId(data, /themoviedb|tmdb/i);
12637
+ return {
12638
+ providerId: TVDB_ID,
12639
+ remoteId: String(data.id),
12640
+ title: data.name ?? "",
12641
+ year: yearOf$2(data.year) ?? yearOf$2(data.firstAired),
12642
+ overview: text$1(data.overview),
12643
+ tvdbId: data.id,
12644
+ tmdbId: tmdb === null || !/^\d+$/.test(tmdb) ? null : Number(tmdb),
12645
+ imdbId: imdb,
12646
+ poster: bestArtwork(data, ARTWORK[kind].poster) ?? text$1(data.image),
12647
+ fanart: bestArtwork(data, ARTWORK[kind].fanart)
12648
+ };
12649
+ } catch (error) {
12650
+ if (isHttp(error, 404)) return null;
12651
+ throw error;
12652
+ }
12653
+ };
12654
+ return {
12655
+ id: TVDB_ID,
12656
+ kinds: ["movie", "series"],
12657
+ lookupBy: [
12658
+ "tvdbId",
12659
+ "imdbId",
12660
+ "tmdbId"
12661
+ ],
12662
+ async identify(kind, title, year) {
12663
+ const exact = (SearchSchema$1.parse(await call("/search", {
12664
+ query: title,
12665
+ type: kind,
12666
+ ...year === null ? {} : { year: String(year) }
12667
+ })).data ?? []).filter((entry) => foldTitle(entry.name ?? "") === foldTitle(title));
12668
+ const sameYear = year === null ? [] : exact.filter((entry) => yearOf$2(entry.year) === year);
12669
+ const pool = sameYear.length > 0 ? sameYear : exact;
12670
+ const ids = new Set(pool.map((entry) => Number(entry.tvdb_id)));
12671
+ const [id] = [...ids];
12672
+ return ids.size === 1 && id !== void 0 && Number.isInteger(id) ? detailsOf(kind, id) : null;
12673
+ },
12674
+ async lookup(kind, ids) {
12675
+ if (ids.tvdbId !== null) return detailsOf(kind, ids.tvdbId);
12676
+ const external = ids.imdbId ?? (ids.tmdbId === null ? null : String(ids.tmdbId));
12677
+ if (external === null) return null;
12678
+ let found;
12679
+ try {
12680
+ found = RemoteSearchSchema.parse(await call(`/search/remoteid/${encodeURIComponent(external)}`));
12681
+ } catch (error) {
12682
+ if (isHttp(error, 404)) return null;
12683
+ throw error;
12684
+ }
12685
+ const hit = (found.data ?? []).map((entry) => kind === "movie" ? entry.movie : entry.series).find((entry) => entry !== null && entry !== void 0);
12686
+ return hit === void 0 || hit === null ? null : detailsOf(kind, hit.id);
12687
+ },
12688
+ async episodes(match) {
12689
+ const out = [];
12690
+ let page = 0;
12691
+ for (let guard = 0; page !== null && guard < MAX_EPISODE_PAGES; guard += 1) {
12692
+ const list = EpisodesSchema.parse(await call(`/series/${encodeURIComponent(match.remoteId)}/episodes/default`, { page: String(page) }));
12693
+ for (const entry of list.data.episodes) out.push({
12694
+ season: entry.seasonNumber,
12695
+ episode: entry.number,
12696
+ title: text$1(entry.name),
12697
+ overview: text$1(entry.overview),
12698
+ still: text$1(entry.image)
12699
+ });
12700
+ page = list.links?.next ?? null;
12701
+ }
12702
+ return out;
12703
+ }
12704
+ };
12705
+ }
12706
+ //#endregion
12707
+ //#region src/tvmaze.ts
12708
+ var TVMAZE_ID = "tvmaze";
12709
+ var API = "https://api.tvmaze.com";
12710
+ var ImageSchema = object({
12711
+ medium: string().nullish(),
12712
+ original: string().nullish()
12713
+ }).nullish();
12714
+ var ShowSchema = object({
12715
+ id: number().int(),
12716
+ name: string(),
12717
+ premiered: string().nullish(),
12718
+ summary: string().nullish(),
12719
+ image: ImageSchema,
12720
+ externals: object({
12721
+ thetvdb: number().int().nullish(),
12722
+ imdb: string().nullish()
12723
+ }).nullish()
12724
+ });
12725
+ var SearchSchema = array(object({
12726
+ score: number(),
12727
+ show: ShowSchema
12728
+ }));
12729
+ var EpisodeSchema = object({
12730
+ name: string().nullish(),
12731
+ season: number().int(),
12732
+ number: number().int().nullish(),
12733
+ summary: string().nullish(),
12734
+ image: ImageSchema
12735
+ });
12736
+ /** The summary field is HTML; keep the text. */
12737
+ function plain(html) {
12738
+ if (html === null || html === void 0) return null;
12739
+ const text = html.replace(/<[^>]*>/g, " ").replace(/&#(\d{1,6});|&#x([0-9a-f]{1,6});/gi, (_whole, dec, hex) => {
12740
+ const code = typeof dec === "string" ? Number(dec) : Number.parseInt(String(hex), 16);
12741
+ return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : "";
12742
+ }).replace(/&apos;/g, "'").replace(/&quot;/g, "\"").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/\s+/g, " ").trim();
12743
+ return text === "" ? null : text;
12744
+ }
12745
+ function imageOf(image) {
12746
+ const url = image?.original ?? image?.medium ?? null;
12747
+ return url !== null && url.startsWith("https://") ? url : null;
12748
+ }
12749
+ function yearOf(premiered) {
12750
+ const match = /^(\d{4})/.exec(premiered ?? "");
12751
+ return match?.[1] === void 0 ? null : Number(match[1]);
12752
+ }
12753
+ /** TVmaze: keyless, series only. Every call goes through the shared remote fetch and one spaced queue. */
12754
+ function createTvmazeProvider(deps) {
12755
+ const sleep = deps.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
12756
+ const now = deps.now ?? Date.now;
12757
+ const gap = deps.minGapMs ?? 600;
12758
+ let tail = Promise.resolve();
12759
+ let lastCallAt = Number.NEGATIVE_INFINITY;
12760
+ const call = (path) => {
12761
+ const run = async () => {
12762
+ const wait = lastCallAt + gap - now();
12763
+ if (wait > 0) await sleep(wait);
12764
+ lastCallAt = now();
12765
+ const bytes = await deps.fetch(`${API}${path}`);
12766
+ return JSON.parse(bytes.toString("utf8"));
12767
+ };
12768
+ const result = tail.then(run, run);
12769
+ tail = result.catch(() => void 0);
12770
+ return result;
12771
+ };
12772
+ const matchOf = (show) => ({
12773
+ providerId: TVMAZE_ID,
12774
+ remoteId: String(show.id),
12775
+ title: show.name,
12776
+ year: yearOf(show.premiered),
12777
+ overview: plain(show.summary),
12778
+ tvdbId: show.externals?.thetvdb ?? null,
12779
+ tmdbId: null,
12780
+ imdbId: show.externals?.imdb ?? null,
12781
+ poster: imageOf(show.image),
12782
+ fanart: null
12783
+ });
12784
+ return {
12785
+ id: TVMAZE_ID,
12786
+ kinds: ["series"],
12787
+ async lookup(_kind, ids) {
12788
+ const query = ids.tvdbId !== null ? `thetvdb=${ids.tvdbId}` : ids.imdbId !== null ? `imdb=${encodeURIComponent(ids.imdbId)}` : null;
12789
+ if (query === null) return null;
12790
+ try {
12791
+ return matchOf(ShowSchema.parse(await call(`/lookup/shows?${query}`)));
12792
+ } catch (error) {
12793
+ if (error instanceof Error && /\b404\b/.test(error.message)) return null;
12794
+ throw error;
12795
+ }
12796
+ },
12797
+ async identify(_kind, title, year) {
12798
+ const found = SearchSchema.parse(await call(`/search/shows?q=${encodeURIComponent(title)}`));
12799
+ const sameYear = year === null ? void 0 : found.find((entry) => yearOf(entry.show.premiered) === year);
12800
+ const top = found[0];
12801
+ const hit = sameYear ?? (year === null || top !== void 0 && foldTitle(top.show.name) === foldTitle(title) ? top : void 0);
12802
+ if (hit === void 0) return null;
12803
+ const show = hit.show;
12804
+ return {
12805
+ providerId: TVMAZE_ID,
12806
+ remoteId: String(show.id),
12807
+ title: show.name,
12808
+ year: yearOf(show.premiered),
12809
+ overview: plain(show.summary),
12810
+ tvdbId: show.externals?.thetvdb ?? null,
12811
+ tmdbId: null,
12812
+ imdbId: show.externals?.imdb ?? null,
12813
+ poster: imageOf(show.image),
12814
+ fanart: null
12815
+ };
12816
+ },
12817
+ async episodes(match) {
12818
+ return array(EpisodeSchema).parse(await call(`/shows/${encodeURIComponent(match.remoteId)}/episodes?specials=1`)).flatMap((entry) => entry.number === null || entry.number === void 0 ? [] : [{
12819
+ season: entry.season,
12820
+ episode: entry.number,
12821
+ title: entry.name ?? null,
12822
+ overview: plain(entry.summary),
12823
+ still: imageOf(entry.image)
12824
+ }]);
12825
+ }
12826
+ };
12827
+ }
12828
+ //#endregion
12829
+ //#region src/remote-fetch.ts
12830
+ var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
12831
+ var IMAGE_TIMEOUT_MS = 2e4;
12832
+ var MAX_REDIRECTS = 3;
12833
+ /** Read a response body, aborting as soon as it passes `cap`: the rest is never buffered. */
12834
+ async function readCapped(response, cap) {
12835
+ if (Number(response.headers.get("content-length") ?? "0") > cap) throw new Error("image too large");
12836
+ if (response.body === null) return Buffer.alloc(0);
12837
+ const reader = response.body.getReader();
12838
+ const chunks = [];
12839
+ let total = 0;
12840
+ for (;;) {
12841
+ const { done, value } = await reader.read();
12842
+ if (done) break;
12843
+ total += value.byteLength;
12844
+ if (total > cap) {
12845
+ await reader.cancel();
12846
+ throw new Error("image too large");
12847
+ }
12848
+ chunks.push(Buffer.from(value));
12849
+ }
12850
+ return Buffer.concat(chunks, total);
12851
+ }
12852
+ function v4Private(address) {
12853
+ const [a = 0, b = 0] = address.split(".").map(Number);
12854
+ return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a >= 224;
12855
+ }
12856
+ /** Loopback, private, link-local, ULA, CGNAT, multicast and unspecified addresses, v4 and v6. */
12857
+ function isPrivateAddress(address) {
12858
+ const kind = isIP(address);
12859
+ if (kind === 4) return v4Private(address);
12860
+ if (kind !== 6) return true;
12861
+ const lower = address.toLowerCase();
12862
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
12863
+ if (mapped?.[1] !== void 0) return v4Private(mapped[1]);
12864
+ if (lower === "::" || lower === "::1") return true;
12865
+ return /^(fe[89ab]|f[cd]|ff)/.test(lower);
12866
+ }
12867
+ var resolveAll = async (host) => (await lookup(host, { all: true })).map((entry) => entry.address);
12868
+ /**
12869
+ * https only, at most 3 redirects each re-validated, every address the host resolves to must be
12870
+ * public, no credential, a bounded time and a streamed size cap.
12871
+ * A resolver answer can differ from the one `fetch` gets (rebinding): the host check narrows, not closes, that window.
12872
+ */
12873
+ function createRemoteFetch(deps = {}) {
12874
+ const doFetch = deps.fetchImpl ?? fetch;
12875
+ const resolve = deps.resolve ?? resolveAll;
12876
+ return async (start, init) => {
12877
+ let url = start;
12878
+ const startOrigin = isRemoteUrl(start) ? new URL(start).origin : "";
12879
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
12880
+ if (!isRemoteUrl(url)) throw new Error("only an https URL is fetched");
12881
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
12882
+ const addresses = isIP(host) === 0 ? await resolve(host) : [host];
12883
+ if (addresses.length === 0 || addresses.some(isPrivateAddress)) throw new Error("host refused: not a public address");
12884
+ const sameOrigin = new URL(url).origin === startOrigin;
12885
+ const response = await doFetch(url, {
12886
+ redirect: "manual",
12887
+ ...sameOrigin && init?.headers !== void 0 ? { headers: { ...init.headers } } : {},
12888
+ ...hop === 0 && init?.body !== void 0 ? {
12889
+ method: "POST",
12890
+ body: init.body
12891
+ } : {},
12892
+ signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
12893
+ });
12894
+ if (response.status >= 300 && response.status < 400) {
12895
+ const location = response.headers.get("location");
12896
+ if (location === null) throw new Error("redirect without a location");
12897
+ url = new URL(location, url).toString();
12898
+ continue;
12899
+ }
12900
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
12901
+ return readCapped(response, MAX_IMAGE_BYTES);
12902
+ }
12903
+ throw new Error("too many redirects");
12904
+ };
12905
+ }
12906
+ var httpRemoteFetch = createRemoteFetch();
12907
+ //#endregion
12908
+ //#region src/img-plane.ts
12909
+ var FAILED_GRAB_TTL_MS = 30 * 6e4;
12910
+ var FAILED_GRAB_MAX = 500;
12911
+ /** The real fetch: the key travels in a header, a redirect is never followed, the body is size-capped as it streams. */
12912
+ var httpImageFetch = async (url, apiKey) => {
12913
+ const response = await fetch(url, {
12914
+ headers: { "X-Api-Key": apiKey },
12915
+ redirect: "manual",
12916
+ signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
12917
+ });
12918
+ if (response.status >= 300 && response.status < 400) throw new Error(`redirect refused (HTTP ${response.status}): the key is never sent to another URL`);
12919
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
12920
+ return readCapped(response, MAX_IMAGE_BYTES);
12921
+ };
12922
+ function typeOf(bytes) {
12923
+ if (bytes.length > 3 && bytes[0] === 255 && bytes[1] === 216) return "image/jpeg";
12924
+ if (bytes.length > 8 && bytes.subarray(1, 4).toString("latin1") === "PNG") return "image/png";
12925
+ if (bytes.length > 12 && bytes.subarray(8, 12).toString("latin1") === "WEBP") return "image/webp";
12926
+ return null;
12927
+ }
12928
+ /** The remote URL of an arr cover: only a path on the arr's own origin, never another host. */
12929
+ function coverUrl(source, path) {
12930
+ if (!path.startsWith("/") || path.startsWith("//")) return null;
12931
+ const base = new URL(source.baseUrl);
12932
+ const url = new URL(`${source.baseUrl}${path}`);
12933
+ return url.origin === base.origin ? url.toString() : null;
12934
+ }
12935
+ function end(res, status) {
12936
+ res.writeHead(status, { "Content-Length": 0 });
12937
+ res.end();
12938
+ }
12939
+ /** The `img` plane: `GET /<itemId>/poster|fanart`, fetched from the arr once and cached on disk. */
12940
+ function createImagePlaneHandler(deps) {
12941
+ const inFlight = /* @__PURE__ */ new Map();
12942
+ const now = deps.now ?? Date.now;
12943
+ /** key → when the failure is forgotten: a transient failure retries, and the set is bounded. */
12944
+ const failedGrabs = /* @__PURE__ */ new Map();
12945
+ const hasFailed = (key) => {
12946
+ const until = failedGrabs.get(key);
12947
+ if (until === void 0) return false;
12948
+ if (until > now()) return true;
12949
+ failedGrabs.delete(key);
12950
+ return false;
12951
+ };
12952
+ const rememberFailure = (key) => {
12953
+ failedGrabs.delete(key);
12954
+ failedGrabs.set(key, now() + FAILED_GRAB_TTL_MS);
12955
+ for (const oldest of failedGrabs.keys()) {
12956
+ if (failedGrabs.size <= FAILED_GRAB_MAX) break;
12957
+ failedGrabs.delete(oldest);
12958
+ }
12959
+ };
12960
+ const limitGrabs = createLimiter(deps.grabConcurrency ?? 2, deps.grabQueueLimit ?? 32);
12961
+ /** A sidecar image is read only from inside a configured root, symlinks resolved, and only up to the size cap. */
12962
+ const readLocal = async (path, tags) => {
12963
+ const real = await resolveServable(path, await deps.roots?.() ?? []);
12964
+ if (real === null) {
12965
+ deps.logger.warn("image refused: outside the configured folders", {
12966
+ tags,
12967
+ meta: { reason: "outside-roots" }
12968
+ });
12969
+ return null;
12970
+ }
12971
+ if ((await stat(real)).size > 10485760) throw new Error("image too large");
12972
+ return readFile(real);
12973
+ };
12974
+ const produce = async (found, tags) => {
12975
+ if (found.kind === "frame") return limitGrabs(() => deps.grabFrame(found.filePath, found.durationMs));
12976
+ if (found.kind === "remote") return deps.fetchRemote(found.url);
12977
+ const arr = await deps.arrSource(found.sourceId);
12978
+ const url = arr === null ? null : coverUrl(arr, found.path);
12979
+ if (arr === null || url === null) {
12980
+ deps.logger.warn("image skipped: no usable source", {
12981
+ tags,
12982
+ meta: { reason: arr === null ? "source-off" : "foreign-origin" }
12983
+ });
12984
+ return null;
12985
+ }
12986
+ return deps.fetchImage(url, arr.apiKey);
12987
+ };
12988
+ const load = async (itemId, which) => {
12989
+ for (const found of await deps.source(itemId, which)) {
12990
+ const bytes = await loadOne(itemId, which, found);
12991
+ if (bytes !== null) return bytes;
12992
+ }
12993
+ return null;
12994
+ };
12995
+ const loadOne = async (itemId, which, found) => {
12996
+ const tags = { itemId };
12997
+ const origin = found.kind === "arr" ? found.path : found.kind === "remote" ? found.url : found.kind === "local" ? found.path : `frame:${found.filePath}`;
12998
+ if (found.kind === "local") try {
12999
+ const bytes = await readLocal(found.path, tags);
13000
+ return bytes !== null && typeOf(bytes) !== null ? bytes : null;
13001
+ } catch (error) {
13002
+ deps.logger.warn("image fetch failed", {
13003
+ tags,
13004
+ meta: {
13005
+ reason: "read-failed",
13006
+ error: error instanceof Error ? error.message : String(error)
13007
+ }
13008
+ });
13009
+ return null;
13010
+ }
13011
+ const key = hashKey(`${itemId}:${which}:${origin}`);
13012
+ if (hasFailed(key)) return null;
13013
+ const cached = join(deps.cacheDir, key);
13014
+ try {
13015
+ const onDisk = await readFile(cached);
13016
+ if (typeOf(onDisk) !== null) return onDisk;
13017
+ deps.logger.warn("cached image is not an image: dropped and fetched again", {
13018
+ tags,
13019
+ meta: { reason: "cache-corrupt" }
13020
+ });
13021
+ await unlink(cached);
13022
+ } catch {}
13023
+ try {
13024
+ const bytes = await produce(found, tags);
13025
+ if (bytes === null) return null;
13026
+ if (typeOf(bytes) === null) throw new Error("not an image");
13027
+ await mkdir(deps.cacheDir, { recursive: true });
13028
+ await writeFile(`${cached}.tmp`, bytes);
13029
+ await rename(`${cached}.tmp`, cached);
13030
+ return bytes;
13031
+ } catch (error) {
13032
+ if (error instanceof LimiterFullError) {
13033
+ deps.logger.warn("frame grab refused", {
13034
+ tags,
13035
+ meta: { reason: "queue-full" }
13036
+ });
13037
+ return null;
13038
+ }
13039
+ if (found.kind === "frame") rememberFailure(key);
13040
+ deps.logger.warn(found.kind === "frame" ? "frame grab failed" : "image fetch failed", {
13041
+ tags,
13042
+ meta: {
13043
+ reason: found.kind === "frame" ? "grab-failed" : "fetch-failed",
13044
+ error: error instanceof Error ? error.message : String(error)
13045
+ }
13046
+ });
13047
+ return null;
13048
+ }
13049
+ };
13050
+ return async (req, res) => {
13051
+ if (req.method !== "GET" && req.method !== "HEAD") return end(res, 405);
13052
+ const parts = ((req.url ?? "/").split("?")[0] ?? "/").replace(/^\//, "").split("/");
13053
+ const [rawId, which] = parts;
13054
+ let itemId = "";
13055
+ try {
13056
+ itemId = decodeURIComponent(rawId ?? "");
13057
+ } catch {
13058
+ return end(res, 404);
13059
+ }
13060
+ if (parts.length !== 2 || !isItemId(itemId) || which !== "poster" && which !== "fanart") {
13061
+ deps.logger.warn("image request refused", { meta: { reason: "bad-request" } });
13062
+ return end(res, 404);
13063
+ }
13064
+ const flightKey = `${itemId}:${which}`;
13065
+ const pending = inFlight.get(flightKey) ?? load(itemId, which);
13066
+ inFlight.set(flightKey, pending);
13067
+ let bytes;
13068
+ try {
13069
+ bytes = await pending;
13070
+ } finally {
13071
+ inFlight.delete(flightKey);
13072
+ }
13073
+ const contentType = bytes === null ? null : typeOf(bytes);
13074
+ if (bytes === null || contentType === null) return end(res, 404);
13075
+ res.writeHead(200, {
13076
+ "Content-Type": contentType,
13077
+ "Content-Length": bytes.length,
13078
+ "Cache-Control": "private, max-age=86400"
13079
+ });
13080
+ res.end(req.method === "HEAD" ? void 0 : bytes);
13081
+ };
13082
+ }
13083
+ //#endregion
13084
+ //#region src/probe.ts
13085
+ var CONTAINER_NAMES = new Map([
13086
+ ["matroska", "mkv"],
13087
+ ["mov", "mp4"],
13088
+ ["avi", "avi"],
13089
+ ["mpegts", "ts"]
13090
+ ]);
13091
+ function containerOf(formats) {
13092
+ const first = formats.split(",")[0]?.trim() ?? formats;
13093
+ return CONTAINER_NAMES.get(first) ?? first;
13094
+ }
13095
+ function languageOf(tag) {
13096
+ if (tag === void 0 || tag === "" || tag === "und") return null;
13097
+ return tag;
13098
+ }
13099
+ function bitDepthOf(pixFmt) {
13100
+ if (pixFmt === null) return null;
13101
+ const match = /(?:p|le|be)(9|10|12|14|16)(?:le|be)?$/.exec(pixFmt);
13102
+ if (match?.[1] !== void 0) return Number(match[1]);
13103
+ return /^(yuv|nv|gray|rgb|bgr)/.test(pixFmt) ? 8 : null;
13104
+ }
13105
+ function hdrOf(line, doviSeen) {
13106
+ if (doviSeen) return "dolby-vision";
13107
+ if (line.includes("smpte2084")) return "hdr10";
13108
+ if (line.includes("arib-std-b67")) return "hlg";
13109
+ return null;
10150
13110
  }
10151
13111
  function channelsOf(line) {
10152
13112
  if (/\bmono\b/.test(line)) return 1;
@@ -10260,10 +13220,371 @@ function createMediaLibraryProvider(store, scans) {
10260
13220
  getScanStatus: async () => scans.status()
10261
13221
  };
10262
13222
  }
10263
- var ARR_SERIES = "arr-series";
10264
- var ARR_MOVIES = "arr-movies";
10265
- var FOLDER = "folder";
10266
- function row(base) {
13223
+ //#endregion
13224
+ //#region src/enrich.ts
13225
+ /** The default order when settings name none (D1125): files next to the media, the arr app, then online. */
13226
+ var DEFAULT_STEPS = DEFAULT_METADATA_ORDER;
13227
+ /** After this many failed calls in one scan a provider is left alone until the next scan. */
13228
+ var PROVIDER_FAILURE_LIMIT = 3;
13229
+ function fill(into, from) {
13230
+ return {
13231
+ title: into.title ?? from.title,
13232
+ year: into.year ?? from.year,
13233
+ overview: into.overview ?? from.overview,
13234
+ tvdbId: into.tvdbId ?? from.tvdbId,
13235
+ tmdbId: into.tmdbId ?? from.tmdbId,
13236
+ imdbId: into.imdbId ?? from.imdbId,
13237
+ poster: into.poster ?? from.poster,
13238
+ fanart: into.fanart ?? from.fanart,
13239
+ season: into.season ?? from.season,
13240
+ episode: into.episode ?? from.episode
13241
+ };
13242
+ }
13243
+ function isArr(item) {
13244
+ return item.sourceId.startsWith("arr-");
13245
+ }
13246
+ /** What the arr app said about the item; a made-up title is no answer. */
13247
+ function arrLayer(item) {
13248
+ if (!isArr(item)) return NO_LOCAL;
13249
+ return {
13250
+ ...NO_LOCAL,
13251
+ title: item.titlePlaceholder ? null : item.title,
13252
+ year: item.year,
13253
+ overview: item.overview,
13254
+ tvdbId: item.tvdbId,
13255
+ tmdbId: item.tmdbId,
13256
+ imdbId: item.imdbId,
13257
+ poster: item.posterSource,
13258
+ fanart: item.fanartSource
13259
+ };
13260
+ }
13261
+ /** What an import or an admin pinned: ids only. Asked after local files and the arr app, before any online guess. */
13262
+ function pinLayer(pins, item) {
13263
+ const pin = pins?.get(item.id);
13264
+ return pin === void 0 ? NO_LOCAL : {
13265
+ ...NO_LOCAL,
13266
+ tvdbId: pin.tvdbId,
13267
+ tmdbId: pin.tmdbId,
13268
+ imdbId: pin.imdbId
13269
+ };
13270
+ }
13271
+ /** What the file name and folder said: the last step, always on. */
13272
+ function fileLayer(item) {
13273
+ return {
13274
+ ...NO_LOCAL,
13275
+ title: item.title,
13276
+ year: isArr(item) ? null : item.year
13277
+ };
13278
+ }
13279
+ var DEFAULT_LOOKUP_BY = ["tvdbId", "imdbId"];
13280
+ /** Only the ids a provider understands are handed to it. */
13281
+ function usable(provider, ids) {
13282
+ const keys = provider.lookupBy ?? DEFAULT_LOOKUP_BY;
13283
+ return {
13284
+ tvdbId: keys.includes("tvdbId") ? ids.tvdbId : null,
13285
+ imdbId: keys.includes("imdbId") ? ids.imdbId : null,
13286
+ tmdbId: keys.includes("tmdbId") ? ids.tmdbId : null
13287
+ };
13288
+ }
13289
+ function hasId(ids) {
13290
+ return ids.tvdbId !== null || ids.imdbId !== null || ids.tmdbId !== null;
13291
+ }
13292
+ var Enricher = class {
13293
+ steps;
13294
+ deps;
13295
+ failures = /* @__PURE__ */ new Map();
13296
+ seriesMatch = /* @__PURE__ */ new Map();
13297
+ matches = /* @__PURE__ */ new Map();
13298
+ constructor(steps, deps) {
13299
+ this.steps = steps;
13300
+ this.deps = deps;
13301
+ }
13302
+ provider(id) {
13303
+ if ((this.failures.get(id) ?? 0) >= PROVIDER_FAILURE_LIMIT) return null;
13304
+ return this.deps.providers.find((entry) => entry.id === id) ?? null;
13305
+ }
13306
+ imageProvider(id) {
13307
+ if ((this.failures.get(id) ?? 0) >= PROVIDER_FAILURE_LIMIT) return null;
13308
+ return this.deps.images?.find((entry) => entry.id === id) ?? null;
13309
+ }
13310
+ /**
13311
+ * The pictures an image-only provider holds for the ids settled so far. Only poster and fanart are
13312
+ * taken, and `fill` keeps whatever an earlier step already gave. Cached like a match (an answer of
13313
+ * "nothing" too), so a rescan does not ask again.
13314
+ */
13315
+ async imageLayer(provider, item, acc) {
13316
+ const kind = item.kind === "movie" ? "movie" : "series";
13317
+ const keys = provider.lookupBy;
13318
+ const ids = {
13319
+ tvdbId: keys.includes("tvdbId") ? acc.tvdbId : null,
13320
+ imdbId: keys.includes("imdbId") ? acc.imdbId : null,
13321
+ tmdbId: keys.includes("tmdbId") ? acc.tmdbId : null
13322
+ };
13323
+ if (!hasId(ids)) return NO_LOCAL;
13324
+ const key = `${provider.id}:images:${kind}:${ids.tvdbId ?? ""}:${ids.imdbId ?? ""}:${ids.tmdbId ?? ""}`;
13325
+ const known = this.deps.cache.getMatch(key);
13326
+ if (known !== null) return known.found ? {
13327
+ ...NO_LOCAL,
13328
+ poster: known.match.poster,
13329
+ fanart: known.match.fanart
13330
+ } : NO_LOCAL;
13331
+ try {
13332
+ const found = await provider.images(kind, ids);
13333
+ this.deps.cache.putMatch(key, found === null ? { found: false } : {
13334
+ found: true,
13335
+ match: {
13336
+ providerId: provider.id,
13337
+ remoteId: key,
13338
+ title: "",
13339
+ year: null,
13340
+ overview: null,
13341
+ tvdbId: null,
13342
+ tmdbId: null,
13343
+ imdbId: null,
13344
+ poster: found.poster,
13345
+ fanart: found.fanart
13346
+ }
13347
+ });
13348
+ return found === null ? NO_LOCAL : {
13349
+ ...NO_LOCAL,
13350
+ poster: found.poster,
13351
+ fanart: found.fanart
13352
+ };
13353
+ } catch (error) {
13354
+ this.failed(provider.id, item.id, error);
13355
+ return NO_LOCAL;
13356
+ }
13357
+ }
13358
+ failed(id, itemId, error) {
13359
+ if (error instanceof ProviderAuthError) {
13360
+ if ((this.failures.get(id) ?? 0) < PROVIDER_FAILURE_LIMIT) {
13361
+ this.failures.set(id, PROVIDER_FAILURE_LIMIT);
13362
+ this.deps.logger.warn(error.message, { meta: {
13363
+ provider: id,
13364
+ pausedForThisScan: true
13365
+ } });
13366
+ }
13367
+ return;
13368
+ }
13369
+ const count = (this.failures.get(id) ?? 0) + 1;
13370
+ this.failures.set(id, count);
13371
+ this.deps.logger.warn("metadata provider failed: the field is left to the next step", {
13372
+ tags: { itemId },
13373
+ meta: {
13374
+ provider: id,
13375
+ error: error instanceof Error ? error.message : String(error),
13376
+ ...count >= PROVIDER_FAILURE_LIMIT ? { pausedForThisScan: true } : {}
13377
+ }
13378
+ });
13379
+ }
13380
+ /** A pinned id is asked for directly: an answer of "nothing" is final, never turned into a title guess. */
13381
+ async lookup(provider, ask, item, kind, pin) {
13382
+ const key = `${provider.id}:lookup:${kind}:${pin.tvdbId ?? ""}:${pin.imdbId ?? ""}:${pin.tmdbId ?? ""}`;
13383
+ const known = this.deps.cache.getMatch(key);
13384
+ if (known !== null) return known.found ? known.match : null;
13385
+ const pending = this.matches.get(key);
13386
+ if (pending !== void 0) return pending;
13387
+ const run = (async () => {
13388
+ try {
13389
+ const match = await ask(kind, pin);
13390
+ this.deps.cache.putMatch(key, match === null ? { found: false } : {
13391
+ found: true,
13392
+ match
13393
+ });
13394
+ return match;
13395
+ } catch (error) {
13396
+ this.failed(provider.id, item.id, error);
13397
+ return null;
13398
+ }
13399
+ })();
13400
+ this.matches.set(key, run);
13401
+ return run;
13402
+ }
13403
+ /**
13404
+ * Which ids a pinned item is looked up by. What the arr app or a sidecar file said (`held`) wins per
13405
+ * id: when it gave one, the pin's ids are not asked at all, so the metadata never comes from another
13406
+ * show than the id the item keeps.
13407
+ */
13408
+ lookupAsk(provider, item, held) {
13409
+ const pin = this.deps.pins?.get(item.id) ?? (provider.lookupBy === void 0 ? void 0 : {
13410
+ tvdbId: null,
13411
+ tmdbId: null,
13412
+ imdbId: null
13413
+ });
13414
+ if (provider.lookup === void 0 || pin === void 0) return null;
13415
+ const fromHeld = usable(provider, held);
13416
+ const fromPin = usable(provider, pin);
13417
+ if (!hasId(fromPin) && !hasId(fromHeld)) return null;
13418
+ if (hasId(fromHeld)) return {
13419
+ ids: fromHeld,
13420
+ fromPin: false
13421
+ };
13422
+ return {
13423
+ ids: fromPin,
13424
+ fromPin: true
13425
+ };
13426
+ }
13427
+ async identify(provider, item, title, year, held) {
13428
+ const kind = item.kind === "movie" ? "movie" : "series";
13429
+ const ask = this.lookupAsk(provider, item, held);
13430
+ if (provider.lookup !== void 0 && ask !== null) {
13431
+ const found = await this.lookup(provider, provider.lookup.bind(provider), item, kind, ask.ids);
13432
+ if (found !== null || ask.fromPin) return found;
13433
+ }
13434
+ const key = `${provider.id}:id:${kind}:${foldTitle(title)}:${year ?? 0}`;
13435
+ const known = this.deps.cache.getMatch(key);
13436
+ if (known !== null) return known.found ? known.match : null;
13437
+ const pending = this.matches.get(key);
13438
+ if (pending !== void 0) return pending;
13439
+ const run = (async () => {
13440
+ try {
13441
+ const match = await provider.identify(kind, title, year);
13442
+ this.deps.cache.putMatch(key, match === null ? { found: false } : {
13443
+ found: true,
13444
+ match
13445
+ });
13446
+ return match;
13447
+ } catch (error) {
13448
+ this.failed(provider.id, item.id, error);
13449
+ return null;
13450
+ }
13451
+ })();
13452
+ this.matches.set(key, run);
13453
+ return run;
13454
+ }
13455
+ async episodesOf(provider, item, match) {
13456
+ const key = `${provider.id}:eps:${match.remoteId}`;
13457
+ const known = this.deps.cache.getEpisodes(key);
13458
+ if (known !== null) return known.episodes;
13459
+ try {
13460
+ const episodes = await provider.episodes(match);
13461
+ this.deps.cache.putEpisodes(key, { episodes: [...episodes] });
13462
+ return episodes;
13463
+ } catch (error) {
13464
+ this.failed(provider.id, item.id, error);
13465
+ return [];
13466
+ }
13467
+ }
13468
+ async onlineLayer(provider, item, acc, resolved, held) {
13469
+ if (item.kind !== "episode") {
13470
+ const match = await this.identify(provider, item, acc.title ?? item.title, acc.year ?? item.year, held);
13471
+ this.seriesMatch.set(`${provider.id}:${item.id}`, match);
13472
+ if (match === null) return NO_LOCAL;
13473
+ return {
13474
+ ...NO_LOCAL,
13475
+ title: match.title,
13476
+ year: match.year,
13477
+ overview: match.overview,
13478
+ tvdbId: match.tvdbId,
13479
+ tmdbId: match.tmdbId,
13480
+ imdbId: match.imdbId,
13481
+ poster: match.poster,
13482
+ fanart: match.fanart
13483
+ };
13484
+ }
13485
+ const parent = item.parentId === null ? void 0 : resolved.get(item.parentId);
13486
+ if (parent === void 0 || item.seasonNumber === null || item.episodeNumber === null) return NO_LOCAL;
13487
+ const known = this.seriesMatch.get(`${provider.id}:${parent.id}`);
13488
+ const match = known !== void 0 ? known : await this.identify(provider, parent, parent.title, parent.year, {
13489
+ tvdbId: parent.tvdbId,
13490
+ imdbId: parent.imdbId,
13491
+ tmdbId: parent.tmdbId
13492
+ });
13493
+ if (match === null) return NO_LOCAL;
13494
+ const found = (await this.episodesOf(provider, item, match)).find((entry) => entry.season === item.seasonNumber && entry.episode === item.episodeNumber);
13495
+ if (found === void 0) return NO_LOCAL;
13496
+ return {
13497
+ ...NO_LOCAL,
13498
+ title: found.title,
13499
+ overview: found.overview,
13500
+ poster: found.still
13501
+ };
13502
+ }
13503
+ canAsk(provider, item) {
13504
+ return provider.kinds.includes(item.kind === "movie" ? "movie" : "series");
13505
+ }
13506
+ needsOnline(item, acc) {
13507
+ if (item.kind === "episode") return acc.overview === null || acc.poster === null || item.titlePlaceholder && acc.title === null;
13508
+ return acc.overview === null || acc.poster === null;
13509
+ }
13510
+ async localLayer(item, firstEpisodeFile) {
13511
+ const { reader } = this.deps;
13512
+ if (item.kind === "series") {
13513
+ const file = firstEpisodeFile.get(item.id);
13514
+ return file === void 0 ? NO_LOCAL : localSeries(reader, seriesDirOf(file));
13515
+ }
13516
+ if (item.filePath === null) return NO_LOCAL;
13517
+ return item.kind === "movie" ? localMovie(reader, item.filePath) : localEpisode(reader, item.filePath);
13518
+ }
13519
+ async resolve(item, resolved, firstEpisodeFile) {
13520
+ let acc = NO_LOCAL;
13521
+ let pinned = false;
13522
+ let held = {
13523
+ tvdbId: null,
13524
+ imdbId: null,
13525
+ tmdbId: null
13526
+ };
13527
+ const applyPin = () => {
13528
+ if (pinned) return;
13529
+ pinned = true;
13530
+ held = {
13531
+ tvdbId: acc.tvdbId,
13532
+ imdbId: acc.imdbId,
13533
+ tmdbId: acc.tmdbId
13534
+ };
13535
+ acc = fill(acc, pinLayer(this.deps.pins, item));
13536
+ };
13537
+ for (const step of this.steps) if (step === "local") acc = fill(acc, await this.localLayer(item, firstEpisodeFile));
13538
+ else if (step === "arr") acc = fill(acc, arrLayer(item));
13539
+ else {
13540
+ applyPin();
13541
+ const images = this.imageProvider(step);
13542
+ const provider = this.provider(step);
13543
+ if (images !== null && item.kind !== "episode" && images.kinds.includes(item.kind === "movie" ? "movie" : "series") && (acc.poster === null || acc.fanart === null)) acc = fill(acc, await this.imageLayer(images, item, acc));
13544
+ else if (provider !== null && this.canAsk(provider, item) && this.needsOnline(item, acc)) acc = fill(acc, await this.onlineLayer(provider, item, acc, resolved, held));
13545
+ }
13546
+ applyPin();
13547
+ acc = fill(acc, fileLayer(item));
13548
+ const title = acc.title ?? item.title;
13549
+ return {
13550
+ ...item,
13551
+ title,
13552
+ sortTitle: sortKey(title),
13553
+ titleFold: foldTitle(title),
13554
+ year: acc.year,
13555
+ overview: acc.overview,
13556
+ tvdbId: acc.tvdbId,
13557
+ tmdbId: acc.tmdbId,
13558
+ imdbId: acc.imdbId,
13559
+ posterSource: acc.poster,
13560
+ fanartSource: acc.fanart,
13561
+ seasonNumber: item.seasonNumber ?? acc.season,
13562
+ episodeNumber: item.episodeNumber ?? acc.episode
13563
+ };
13564
+ }
13565
+ };
13566
+ /**
13567
+ * Resolve every item's metadata per field, first answer wins, in the order of `steps`
13568
+ * (default: sidecar files, the arr app, online providers) and the file name last (D1125).
13569
+ * Series and movies go first so an episode finds its show already identified.
13570
+ */
13571
+ async function enrichItems(items, steps, deps) {
13572
+ const firstEpisodeFile = /* @__PURE__ */ new Map();
13573
+ for (const item of items) if (item.kind === "episode" && item.parentId !== null && item.filePath !== null) {
13574
+ if (!firstEpisodeFile.has(item.parentId)) firstEpisodeFile.set(item.parentId, item.filePath);
13575
+ }
13576
+ const enricher = new Enricher(steps, deps);
13577
+ const resolved = /* @__PURE__ */ new Map();
13578
+ const ordered = [...items.filter((item) => item.kind !== "episode"), ...items.filter((item) => item.kind === "episode")];
13579
+ for (const item of ordered) {
13580
+ resolved.set(item.id, await enricher.resolve(item, resolved, firstEpisodeFile));
13581
+ await deps.checkpoint?.();
13582
+ }
13583
+ return items.map((item) => resolved.get(item.id) ?? item);
13584
+ }
13585
+ //#endregion
13586
+ //#region src/new-item.ts
13587
+ function newItem(base) {
10267
13588
  return {
10268
13589
  parentId: null,
10269
13590
  sortTitle: sortKey(base.title),
@@ -10279,14 +13600,176 @@ function row(base) {
10279
13600
  fanartSource: null,
10280
13601
  filePath: null,
10281
13602
  addedHint: null,
13603
+ titlePlaceholder: false,
10282
13604
  ...base
10283
13605
  };
10284
13606
  }
13607
+ //#endregion
13608
+ //#region src/folder-items.ts
13609
+ var FOLDER = "folder";
13610
+ /** `1x02`, `E02`, `Episode 2`, a bare `02 - Title`: only read inside a season folder. */
13611
+ function loneEpisodeNumber(baseName) {
13612
+ const match = /^(?:s\d{1,2})?[\s._-]*(?:e|ep|episode)[\s._-]*(\d{1,3})\b/i.exec(baseName) ?? /^(\d{1,3})(?:[\s._-]|$)/.exec(baseName);
13613
+ return match?.[1] === void 0 ? null : Number(match[1]);
13614
+ }
13615
+ function crossFormat(baseName) {
13616
+ const match = /(?:^|[\s._-])(\d{1,2})x(\d{2,3})(?:[\s._-]|$)/i.exec(baseName);
13617
+ return match?.[1] === void 0 || match[2] === void 0 ? null : {
13618
+ season: Number(match[1]),
13619
+ episode: Number(match[2])
13620
+ };
13621
+ }
13622
+ function within(root, dir) {
13623
+ const rel = relative(root, dir);
13624
+ return rel === "" || !rel.startsWith("..") && !rel.startsWith(sep);
13625
+ }
13626
+ async function tvshowDir(root, start, reader) {
13627
+ for (let dir = start; within(root, dir); dir = dirname(dir)) {
13628
+ if ((await reader.list(dir)).has("tvshow.nfo")) return dir;
13629
+ if (dir === root || dirname(dir) === dir) break;
13630
+ }
13631
+ return null;
13632
+ }
13633
+ async function classify(root, path, reader) {
13634
+ const parent = dirname(path);
13635
+ const file = basename(path);
13636
+ const stem = file.replace(/\.[A-Za-z0-9]+$/, "");
13637
+ const guess = guessFromFilename(file, "");
13638
+ const folderSeason = seasonOfFolder(basename(parent));
13639
+ const cross = crossFormat(stem);
13640
+ const nfoDir = await tvshowDir(root, parent, reader);
13641
+ const season = guess.seasonNumber ?? cross?.season ?? folderSeason;
13642
+ let episode = guess.episodeNumber ?? cross?.episode ?? null;
13643
+ if (!(guess.kind === "episode" || cross !== null) && !(folderSeason !== null || nfoDir !== null)) return {
13644
+ path,
13645
+ kind: "movie",
13646
+ seriesDir: null,
13647
+ namedTitle: guess.title,
13648
+ season: null,
13649
+ episode: null,
13650
+ year: guess.year
13651
+ };
13652
+ if (episode === null) episode = loneEpisodeNumber(stem);
13653
+ let seriesDir = nfoDir;
13654
+ if (seriesDir === null) {
13655
+ if (folderSeason !== null) seriesDir = dirname(parent);
13656
+ else if (parent !== root) seriesDir = parent;
13657
+ }
13658
+ const prefix = guess.kind === "episode" ? guess.title : "";
13659
+ return {
13660
+ path,
13661
+ kind: "episode",
13662
+ seriesDir,
13663
+ namedTitle: prefix,
13664
+ season,
13665
+ episode,
13666
+ year: null
13667
+ };
13668
+ }
13669
+ /** The most frequent non-empty title, ties by name: the same set of files names a show the same way every scan. */
13670
+ function commonTitle(titles) {
13671
+ const counts = /* @__PURE__ */ new Map();
13672
+ for (const title of titles) if (title !== "") counts.set(title, (counts.get(title) ?? 0) + 1);
13673
+ return [...counts].toSorted((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]?.[0] ?? null;
13674
+ }
13675
+ /** A year-bearing folder (`Gamma (2019)`) names a movie better than a bare file name does. */
13676
+ function movieNamed(root, entry) {
13677
+ const folder = dirname(entry.path);
13678
+ if (folder !== root && within(root, folder)) {
13679
+ const named = guessFromFilename(basename(folder), "");
13680
+ if (named.year !== null && named.title !== "" && (entry.year === null || entry.namedTitle === "")) return {
13681
+ title: named.title,
13682
+ year: named.year
13683
+ };
13684
+ }
13685
+ return {
13686
+ title: entry.namedTitle,
13687
+ year: entry.year
13688
+ };
13689
+ }
13690
+ /**
13691
+ * Group the video files of one folder root into series (by their show folder), seasons and
13692
+ * movies (one per file). Ids keep the scheme of the first folder source: a movie is
13693
+ * `folder:m:<hash of path>`, a show `folder:s:<hash of its folded title>`, an episode
13694
+ * `folder:e:<hash of path>`.
13695
+ */
13696
+ async function folderItems(root, paths, reader) {
13697
+ const classified = await Promise.all(paths.map((path) => classify(root, path, reader)));
13698
+ const out = [];
13699
+ const groups = /* @__PURE__ */ new Map();
13700
+ for (const entry of classified) {
13701
+ if (entry.kind === "movie") {
13702
+ const named = movieNamed(root, entry);
13703
+ const title = named.title === "" ? basename(entry.path).replace(/\.[^.]+$/, "") : named.title;
13704
+ out.push(newItem({
13705
+ id: itemId(FOLDER, "m", hashKey(entry.path)),
13706
+ kind: "movie",
13707
+ title,
13708
+ sourceId: FOLDER,
13709
+ topLevel: true,
13710
+ year: named.year,
13711
+ filePath: entry.path
13712
+ }));
13713
+ continue;
13714
+ }
13715
+ const key = entry.seriesDir ?? `name:${foldTitle(entry.namedTitle)}`;
13716
+ const group = groups.get(key);
13717
+ if (group === void 0) groups.set(key, [entry]);
13718
+ else group.push(entry);
13719
+ }
13720
+ for (const [key, members] of groups) {
13721
+ const seriesDir = key.startsWith("name:") ? null : key;
13722
+ const folderName = seriesDir === null || seriesDir === root ? null : basename(seriesDir);
13723
+ const folderGuess = folderName === null ? null : guessFromFilename(folderName, "");
13724
+ const title = commonTitle(members.map((entry) => entry.namedTitle)) ?? (folderGuess !== null && folderGuess.title !== "" ? folderGuess.title : null) ?? (basename(root) === "" ? "Unknown" : basename(root));
13725
+ const seriesId = itemId(FOLDER, "s", hashKey(foldTitle(title)));
13726
+ out.push(newItem({
13727
+ id: seriesId,
13728
+ kind: "series",
13729
+ title,
13730
+ sourceId: FOLDER,
13731
+ topLevel: true,
13732
+ year: folderGuess?.year ?? null
13733
+ }));
13734
+ for (const entry of members.toSorted((a, b) => a.path.localeCompare(b.path))) out.push(newItem({
13735
+ id: itemId(FOLDER, "e", hashKey(entry.path)),
13736
+ kind: "episode",
13737
+ title: `${title} S${entry.season ?? 0}E${entry.episode ?? 0}`,
13738
+ titlePlaceholder: true,
13739
+ sourceId: FOLDER,
13740
+ topLevel: false,
13741
+ parentId: seriesId,
13742
+ seasonNumber: entry.season,
13743
+ episodeNumber: entry.episode,
13744
+ filePath: entry.path
13745
+ }));
13746
+ }
13747
+ return out;
13748
+ }
13749
+ //#endregion
13750
+ //#region src/scanner.ts
13751
+ /** The online providers this scan may ask: the fixed ones, plus each keyed one whose key is set. */
13752
+ function onlineProviders(deps, sources) {
13753
+ const keyed = (make, key) => make !== void 0 && (key ?? "") !== "" ? [make(key ?? "")] : [];
13754
+ const fanartKey = sources.fanartApiKey ?? "";
13755
+ return {
13756
+ providers: [
13757
+ ...deps.providers ?? [],
13758
+ ...keyed(deps.createTmdb, sources.tmdbToken),
13759
+ ...keyed(deps.createTvdb, sources.tvdbApiKey),
13760
+ ...keyed(deps.createOmdb, sources.omdbApiKey),
13761
+ ...deps.createAnilist !== void 0 && (sources.metadataSteps ?? []).includes("anilist") ? [deps.createAnilist()] : []
13762
+ ],
13763
+ images: deps.createFanart !== void 0 && fanartKey !== "" ? [deps.createFanart(fanartKey)] : []
13764
+ };
13765
+ }
13766
+ var ARR_SERIES = "arr-series";
13767
+ var ARR_MOVIES = "arr-movies";
10285
13768
  function seriesItems(series, source) {
10286
13769
  const out = [];
10287
13770
  for (const show of series) {
10288
13771
  const seriesKey = itemId(ARR_SERIES, "s", show.id);
10289
- out.push(row({
13772
+ out.push(newItem({
10290
13773
  id: seriesKey,
10291
13774
  kind: "series",
10292
13775
  title: show.title,
@@ -10301,13 +13784,15 @@ function seriesItems(series, source) {
10301
13784
  fanartSource: show.fanart,
10302
13785
  addedHint: show.addedAt
10303
13786
  }));
10304
- for (const episode of show.episodes) out.push(row({
13787
+ for (const episode of show.episodes) out.push(newItem({
10305
13788
  id: itemId(ARR_SERIES, "e", episode.id),
10306
13789
  kind: "episode",
10307
13790
  title: episode.title === "" ? `Episode ${episode.episodeNumber}` : episode.title,
13791
+ titlePlaceholder: episode.title === "",
10308
13792
  sourceId: ARR_SERIES,
10309
13793
  topLevel: false,
10310
13794
  parentId: seriesKey,
13795
+ posterSource: episode.still,
10311
13796
  seasonNumber: episode.seasonNumber,
10312
13797
  episodeNumber: episode.episodeNumber,
10313
13798
  filePath: episode.path === null ? null : mapPath(episode.path, source.pathFrom, source.pathTo),
@@ -10317,7 +13802,7 @@ function seriesItems(series, source) {
10317
13802
  return out;
10318
13803
  }
10319
13804
  function movieItems(movies, source) {
10320
- return movies.map((movie) => row({
13805
+ return movies.map((movie) => newItem({
10321
13806
  id: itemId(ARR_MOVIES, "m", movie.id),
10322
13807
  kind: "movie",
10323
13808
  title: movie.title,
@@ -10346,11 +13831,12 @@ async function scanLibrary(deps, sources) {
10346
13831
  };
10347
13832
  const errors = [];
10348
13833
  const existingItems = /* @__PURE__ */ new Map();
10349
- for (const raw of await db.query(ITEMS)) {
13834
+ for (const raw of await queryAll(db, ITEMS, "id")) {
10350
13835
  const parsed = ItemRowSchema.safeParse(raw);
10351
13836
  if (parsed.success) existingItems.set(parsed.data.id, parsed.data);
10352
13837
  }
10353
13838
  const harvests = [];
13839
+ const reader = deps.reader ?? createLocalReader();
10354
13840
  const countOf = (sourceId) => [...existingItems.values()].filter((item) => item.sourceId === sourceId).length;
10355
13841
  const harvest = async (sourceId, read) => {
10356
13842
  try {
@@ -10402,14 +13888,47 @@ async function scanLibrary(deps, sources) {
10402
13888
  reason: dir.reason
10403
13889
  } });
10404
13890
  }
10405
- for (const file of walked.files) {
10406
- if (claimed.has(file.path)) continue;
10407
- found.push(...folderItems(file.path));
10408
- }
13891
+ found.push(...await folderItems(root, walked.files.map((file) => file.path).filter((path) => !claimed.has(path)), reader));
10409
13892
  }
10410
13893
  if (!allComplete) throw new Error("a folder root could not be read");
10411
13894
  return dedupe(found);
10412
13895
  });
13896
+ const cache = await MatchCache.load(db, deps.now);
13897
+ const pins = await loadPins(db, (message) => logger.warn(`dropped an unreadable pin: ${message}`));
13898
+ const saveMatches = async (atLeast) => {
13899
+ if (cache.pending === 0 || cache.pending < atLeast) return;
13900
+ try {
13901
+ await cache.flush(db);
13902
+ } catch (error) {
13903
+ logger.warn("metadata matches could not be saved: they are asked for again next scan", { meta: { error: error instanceof Error ? error.message : String(error) } });
13904
+ }
13905
+ };
13906
+ for (const [index, entry] of harvests.entries()) {
13907
+ try {
13908
+ const online = onlineProviders(deps, sources);
13909
+ const items = await enrichItems(entry.items, sources.metadataSteps ?? DEFAULT_STEPS, {
13910
+ reader,
13911
+ providers: online.providers,
13912
+ images: online.images,
13913
+ cache,
13914
+ logger,
13915
+ pins,
13916
+ checkpoint: () => saveMatches(20)
13917
+ });
13918
+ harvests[index] = {
13919
+ ...entry,
13920
+ items
13921
+ };
13922
+ } catch (error) {
13923
+ const message = error instanceof Error ? error.message : String(error);
13924
+ errors.push(`${entry.sourceId} metadata: ${message}`);
13925
+ logger.error("metadata step failed: the items keep what their source said", { meta: {
13926
+ sourceId: entry.sourceId,
13927
+ error: message
13928
+ } });
13929
+ }
13930
+ await saveMatches(1);
13931
+ }
10413
13932
  const writes = [];
10414
13933
  const seenIds = /* @__PURE__ */ new Set();
10415
13934
  for (const entry of harvests) for (const item of entry.items) {
@@ -10420,7 +13939,7 @@ async function scanLibrary(deps, sources) {
10420
13939
  }
10421
13940
  seenIds.add(item.id);
10422
13941
  const previous = existingItems.get(item.id);
10423
- const { addedHint, ...fields } = item;
13942
+ const { addedHint, titlePlaceholder: _placeholder, ...fields } = item;
10424
13943
  writes.push({
10425
13944
  ...fields,
10426
13945
  addedAt: previous?.addedAt ?? addedHint ?? startedAt,
@@ -10429,7 +13948,7 @@ async function scanLibrary(deps, sources) {
10429
13948
  }
10430
13949
  if (writes.length > 0) await db.upsertMany(ITEMS, ["id"], writes);
10431
13950
  const knownFiles = /* @__PURE__ */ new Map();
10432
- for (const raw of await db.query(FILES)) {
13951
+ for (const raw of await queryAll(db, FILES, "path")) {
10433
13952
  const parsed = FileRowSchema.safeParse(raw);
10434
13953
  if (parsed.success) knownFiles.set(parsed.data.path, parsed.data);
10435
13954
  }
@@ -10521,38 +14040,6 @@ function dedupe(items) {
10521
14040
  for (const item of items) if (!seen.has(item.id)) seen.set(item.id, item);
10522
14041
  return [...seen.values()];
10523
14042
  }
10524
- /** What a file nobody catalogued becomes: a movie, or an episode under a show named from the file. */
10525
- function folderItems(path) {
10526
- const guess = guessFromFilename(basename(path), basename(dirname(path)));
10527
- const fileKey = hashKey(path);
10528
- if (guess.kind === "movie") return [row({
10529
- id: itemId(FOLDER, "m", fileKey),
10530
- kind: "movie",
10531
- title: guess.title,
10532
- sourceId: FOLDER,
10533
- topLevel: true,
10534
- year: guess.year,
10535
- filePath: path
10536
- })];
10537
- const seriesKey = itemId(FOLDER, "s", hashKey(foldTitle(guess.title)));
10538
- return [row({
10539
- id: seriesKey,
10540
- kind: "series",
10541
- title: guess.title,
10542
- sourceId: FOLDER,
10543
- topLevel: true
10544
- }), row({
10545
- id: itemId(FOLDER, "e", fileKey),
10546
- kind: "episode",
10547
- title: `${guess.title} S${guess.seasonNumber ?? 0}E${guess.episodeNumber ?? 0}`,
10548
- sourceId: FOLDER,
10549
- topLevel: false,
10550
- parentId: seriesKey,
10551
- seasonNumber: guess.seasonNumber,
10552
- episodeNumber: guess.episodeNumber,
10553
- filePath: path
10554
- })];
10555
- }
10556
14043
  //#endregion
10557
14044
  //#region src/scan-controller.ts
10558
14045
  /** Runs scans one at a time: a second request while one runs is answered "already running", never queued. */
@@ -10619,160 +14106,6 @@ var ScanController = class {
10619
14106
  }
10620
14107
  };
10621
14108
  //#endregion
10622
- //#region src/settings.ts
10623
- /** The capability that owns the cluster-scoped settings (D986). */
10624
- var SETTINGS_CAP = "media-library";
10625
- /** An http(s) base URL without credentials, query or trailing slash; `''` is "not configured"; `null` is invalid. */
10626
- function normalizeBaseUrl(raw) {
10627
- const text = raw.trim();
10628
- if (text === "") return "";
10629
- let url;
10630
- try {
10631
- url = new URL(text);
10632
- } catch {
10633
- return null;
10634
- }
10635
- if (url.protocol !== "http:" && url.protocol !== "https:") return null;
10636
- if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") return null;
10637
- return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
10638
- }
10639
- var BaseUrlSchema = string().transform((value, ctx) => {
10640
- const normalized = normalizeBaseUrl(value);
10641
- if (normalized === null) {
10642
- ctx.addIssue({
10643
- code: "custom",
10644
- message: "expected an http(s) URL"
10645
- });
10646
- return NEVER;
10647
- }
10648
- return normalized;
10649
- });
10650
- var MediaLibrarySettingsSchema = object({
10651
- seriesArrUrl: BaseUrlSchema.default(""),
10652
- seriesArrKey: string().default(""),
10653
- /** Where the series app sees the library, and where this node mounts it. */
10654
- seriesPathFrom: string().default(""),
10655
- seriesPathTo: string().default(""),
10656
- moviesArrUrl: BaseUrlSchema.default(""),
10657
- moviesArrKey: string().default(""),
10658
- moviesPathFrom: string().default(""),
10659
- moviesPathTo: string().default(""),
10660
- /** Plain folders walked for files the arr apps do not know, one absolute path per line. */
10661
- folderRoots: string().default(""),
10662
- rescanMinutes: number().int().min(0).default(60)
10663
- });
10664
- /** A source is on only when both its URL and key are set; a half-filled one is off, not guessed. */
10665
- function resolveSources(settings) {
10666
- const pick = (baseUrl, apiKey, pathFrom, pathTo) => baseUrl === "" || apiKey === "" ? null : {
10667
- baseUrl,
10668
- apiKey,
10669
- pathFrom: pathFrom.trim(),
10670
- pathTo: pathTo.trim()
10671
- };
10672
- return {
10673
- series: pick(settings.seriesArrUrl, settings.seriesArrKey, settings.seriesPathFrom, settings.seriesPathTo),
10674
- movies: pick(settings.moviesArrUrl, settings.moviesArrKey, settings.moviesPathFrom, settings.moviesPathTo),
10675
- folderRoots: settings.folderRoots.split("\n").map((line) => line.trim()).filter((line) => line !== "")
10676
- };
10677
- }
10678
- var MEDIA_LIBRARY_CLUSTER_SCHEMA = { sections: [
10679
- {
10680
- id: "series",
10681
- title: "Series source",
10682
- titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.title",
10683
- fields: [
10684
- {
10685
- type: "text",
10686
- key: "seriesArrUrl",
10687
- label: "Sonarr URL",
10688
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrUrl.label",
10689
- description: "Address of the series app, for example http://192.168.1.20:8989. Empty turns the source off.",
10690
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrUrl.description"
10691
- },
10692
- {
10693
- type: "password",
10694
- key: "seriesArrKey",
10695
- label: "Sonarr API key",
10696
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesArrKey.label"
10697
- },
10698
- {
10699
- type: "text",
10700
- key: "seriesPathFrom",
10701
- label: "Path in Sonarr",
10702
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathFrom.label",
10703
- description: "The library folder as the series app sees it, for example /tv.",
10704
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathFrom.description"
10705
- },
10706
- {
10707
- type: "text",
10708
- key: "seriesPathTo",
10709
- label: "Path on this hub",
10710
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathTo.label",
10711
- description: "Where the same folder is mounted on this hub.",
10712
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_series.seriesPathTo.description"
10713
- }
10714
- ]
10715
- },
10716
- {
10717
- id: "movies",
10718
- title: "Movies source",
10719
- titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.title",
10720
- fields: [
10721
- {
10722
- type: "text",
10723
- key: "moviesArrUrl",
10724
- label: "Radarr URL",
10725
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrUrl.label",
10726
- description: "Address of the movies app, for example http://192.168.1.20:7878. Empty turns the source off.",
10727
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrUrl.description"
10728
- },
10729
- {
10730
- type: "password",
10731
- key: "moviesArrKey",
10732
- label: "Radarr API key",
10733
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesArrKey.label"
10734
- },
10735
- {
10736
- type: "text",
10737
- key: "moviesPathFrom",
10738
- label: "Path in Radarr",
10739
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathFrom.label",
10740
- description: "The library folder as the movies app sees it, for example /movies.",
10741
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathFrom.description"
10742
- },
10743
- {
10744
- type: "text",
10745
- key: "moviesPathTo",
10746
- label: "Path on this hub",
10747
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathTo.label",
10748
- description: "Where the same folder is mounted on this hub.",
10749
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_movies.moviesPathTo.description"
10750
- }
10751
- ]
10752
- },
10753
- {
10754
- id: "folders",
10755
- title: "Folders",
10756
- titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.title",
10757
- fields: [{
10758
- type: "textarea",
10759
- key: "folderRoots",
10760
- label: "Folders to walk",
10761
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.label",
10762
- description: "One absolute path per line. Files the arr apps do not know are added from here.",
10763
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.description"
10764
- }, {
10765
- type: "number",
10766
- key: "rescanMinutes",
10767
- label: "Rescan every (minutes)",
10768
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.label",
10769
- description: "0 scans only when asked.",
10770
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
10771
- min: 0
10772
- }]
10773
- }
10774
- ] };
10775
- //#endregion
10776
14109
  //#region src/media-library.addon.ts
10777
14110
  /**
10778
14111
  * media-library — the catalogue of the self-hosted media stack (D1120): arr apps give structure,
@@ -10799,12 +14132,59 @@ var MediaLibraryAddon = class extends BaseAddon {
10799
14132
  this.scans?.schedule(settings.rescanMinutes);
10800
14133
  this.scans?.start("settings");
10801
14134
  }
14135
+ /**
14136
+ * One-time, idempotent: the metadata settings of earlier versions (an order string, switches and
14137
+ * four keys) become the `metadataProviders` list. The rows are written first, so each key leaves
14138
+ * through the normal secret write into a keychain ref addressed by its row id (D787). An old key
14139
+ * is released only once its row holds a stored key (a marker counts), and nothing at all is
14140
+ * touched while an old secret cannot be read (the keychain is locked): the next boot retries.
14141
+ */
14142
+ async migrateLegacyProviderSettings() {
14143
+ const stored = await this.resolveGlobalStore(void 0, SETTINGS_CAP);
14144
+ if (!hasLegacyProviderKeys(stored)) return;
14145
+ const unreadable = LEGACY_SECRET_KEYS.filter((key) => isSecretMarker(stored[key]));
14146
+ if (unreadable.length > 0) {
14147
+ this.ctx.logger.warn("media-library provider migration postponed: a stored key is unreadable", { meta: { keys: unreadable } });
14148
+ return;
14149
+ }
14150
+ const parsed = array(MetadataProviderRowSchema).safeParse(stored["metadataProviders"] ?? []);
14151
+ if (!parsed.success) {
14152
+ this.ctx.logger.warn("media-library provider migration postponed: the stored list is invalid");
14153
+ return;
14154
+ }
14155
+ const rows = parsed.data.length === 0 ? providerRowsFromLegacy(stored) : fillMissingKeys(parsed.data, stored);
14156
+ if (JSON.stringify(rows) !== JSON.stringify(parsed.data)) await this.clusterSettings(SETTINGS_CAP, MediaLibrarySettingsSchema).patch({ metadataProviders: rows });
14157
+ const after = await this.resolveGlobalStore(void 0, SETTINGS_CAP);
14158
+ const held = array(MetadataProviderRowSchema).safeParse(after["metadataProviders"]);
14159
+ const present = LEGACY_PROVIDER_KEYS.filter((key) => stored[key] !== void 0);
14160
+ const releasable = present.filter((key) => !LEGACY_SECRET_KEYS.some((secret) => secret === key) || typeof stored[key] === "string" && stored[key] === "" || held.success && rowHoldsKey(held.data, key));
14161
+ const secrets = releasable.filter((key) => LEGACY_SECRET_KEYS.some((s) => s === key));
14162
+ await this.clearSecrets(secrets);
14163
+ const outcome = await this.unsetStoredSettingsKeys(releasable);
14164
+ this.ctx.logger.info("media-library provider settings migrated to the provider list", { meta: {
14165
+ removed: outcome.removed.length,
14166
+ kept: present.length - releasable.length
14167
+ } });
14168
+ }
14169
+ /** A failed migration never stops the boot: the old keys stay and the next boot retries. */
14170
+ async migrateProviderSettingsOrKeepOld() {
14171
+ try {
14172
+ await this.migrateLegacyProviderSettings();
14173
+ } catch (error) {
14174
+ this.ctx.logger.warn("media-library provider migration failed; the old settings are kept", { meta: {
14175
+ step: "migrateLegacyProviderSettings",
14176
+ error: String(error)
14177
+ } });
14178
+ }
14179
+ }
10802
14180
  async onInitialize() {
14181
+ await this.migrateProviderSettingsOrKeepOld();
10803
14182
  const { ctx } = this;
10804
14183
  const logger = ctx.logger;
10805
14184
  const db = settingsStoreDb(ctx.api.settingsStore);
10806
14185
  const store = new LibraryStore(db, logger);
10807
14186
  await store.init();
14187
+ const ffmpeg = await ctx.deps.ensureFfmpeg();
10808
14188
  const scans = new ScanController({
10809
14189
  db,
10810
14190
  logger,
@@ -10821,10 +14201,54 @@ var MediaLibraryAddon = class extends BaseAddon {
10821
14201
  return null;
10822
14202
  }
10823
14203
  },
10824
- probe: createFfmpegProber(await ctx.deps.ensureFfmpeg()),
14204
+ probe: createFfmpegProber(ffmpeg),
14205
+ providers: [createTvmazeProvider({ fetch: httpRemoteFetch })],
14206
+ createTmdb: (token) => createTmdbProvider({
14207
+ fetch: httpRemoteFetch,
14208
+ token
14209
+ }),
14210
+ createTvdb: (apiKey) => createTvdbProvider({
14211
+ fetch: httpRemoteFetch,
14212
+ apiKey
14213
+ }),
14214
+ createOmdb: (apiKey) => createOmdbProvider({
14215
+ fetch: httpRemoteFetch,
14216
+ apiKey
14217
+ }),
14218
+ createFanart: (apiKey) => createFanartProvider({
14219
+ fetch: httpRemoteFetch,
14220
+ apiKey
14221
+ }),
14222
+ createAnilist: () => createAnilistProvider({ fetch: httpRemoteFetch }),
10825
14223
  now: () => Date.now()
10826
14224
  }, async () => resolveSources(await this.readSettings()), logger);
10827
14225
  this.scans = scans;
14226
+ const plexImports = new PlexImportController(logger, () => Date.now());
14227
+ const startPlex = async (mode) => {
14228
+ const plex = resolvePlex(await this.readSettings());
14229
+ if (plex === null) throw new Error("Plex is not configured: set the server URL and the token first");
14230
+ const build = () => ({
14231
+ plex: new PlexClient({
14232
+ baseUrl: plex.baseUrl,
14233
+ token: plex.token
14234
+ }),
14235
+ store,
14236
+ db,
14237
+ listUsers: async () => ctx.api.userManagement.listUsers.query(),
14238
+ pathFrom: plex.pathFrom,
14239
+ pathTo: plex.pathTo,
14240
+ userMap: plex.userMap,
14241
+ logger,
14242
+ now: () => Date.now()
14243
+ });
14244
+ const started = plexImports.start(mode, build, [plex.token], (report) => {
14245
+ if (mode === "run" && report.pins > 0) scans.start("manual");
14246
+ });
14247
+ return {
14248
+ started,
14249
+ message: started ? `Plex ${mode === "run" ? "import" : "preview"} started: read the report with plexImportStatus` : "A Plex import is already running"
14250
+ };
14251
+ };
10828
14252
  const roots = async () => {
10829
14253
  const settings = await this.readSettings();
10830
14254
  return [
@@ -10835,7 +14259,7 @@ var MediaLibraryAddon = class extends BaseAddon {
10835
14259
  };
10836
14260
  await ctx.dataPlane?.serve({
10837
14261
  prefix: FILE_PLANE_PREFIX,
10838
- access: "authenticated",
14262
+ access: "viewer",
10839
14263
  handler: createFilePlaneHandler({
10840
14264
  lookup: async (itemId) => (await store.playableFile(itemId))?.path ?? null,
10841
14265
  roots,
@@ -10844,7 +14268,7 @@ var MediaLibraryAddon = class extends BaseAddon {
10844
14268
  });
10845
14269
  await ctx.dataPlane?.serve({
10846
14270
  prefix: "img",
10847
- access: "authenticated",
14271
+ access: "viewer",
10848
14272
  handler: createImagePlaneHandler({
10849
14273
  source: (itemId, which) => store.imageSource(itemId, which),
10850
14274
  arrSource: async (sourceId) => {
@@ -10853,6 +14277,9 @@ var MediaLibraryAddon = class extends BaseAddon {
10853
14277
  },
10854
14278
  cacheDir: join(ctx.dataDir, IMG_CACHE_DIR),
10855
14279
  fetchImage: httpImageFetch,
14280
+ fetchRemote: httpRemoteFetch,
14281
+ roots,
14282
+ grabFrame: createFfmpegFrameGrabber(ffmpeg),
10856
14283
  logger
10857
14284
  })
10858
14285
  });
@@ -10862,20 +14289,28 @@ var MediaLibraryAddon = class extends BaseAddon {
10862
14289
  const apps = { listApps: async () => [buildApp()] };
10863
14290
  const addressRoles = { listAddressRoles: async () => buildAddressRoles() };
10864
14291
  logger.info("media-library initialized");
10865
- return [
10866
- {
10867
- capability: mediaLibraryCapability,
10868
- provider: createMediaLibraryProvider(store, scans)
10869
- },
10870
- {
10871
- capability: appSourceCapability,
10872
- provider: apps
10873
- },
10874
- {
10875
- capability: addressRoleSourceCapability,
10876
- provider: addressRoles
14292
+ return {
14293
+ providers: [
14294
+ {
14295
+ capability: mediaLibraryCapability,
14296
+ provider: createMediaLibraryProvider(store, scans)
14297
+ },
14298
+ {
14299
+ capability: appSourceCapability,
14300
+ provider: apps
14301
+ },
14302
+ {
14303
+ capability: addressRoleSourceCapability,
14304
+ provider: addressRoles
14305
+ }
14306
+ ],
14307
+ customActions: mediaLibraryActions,
14308
+ actionHandlers: {
14309
+ plexImportPreview: async () => startPlex("preview"),
14310
+ plexImportRun: async () => startPlex("run"),
14311
+ plexImportStatus: async () => plexImports.status()
10877
14312
  }
10878
- ];
14313
+ };
10879
14314
  }
10880
14315
  async onShutdown() {
10881
14316
  this.scans?.stop();
@@ -10883,4 +14318,4 @@ var MediaLibraryAddon = class extends BaseAddon {
10883
14318
  }
10884
14319
  };
10885
14320
  //#endregion
10886
- export { MediaLibraryAddon, MediaLibraryAddon as default };
14321
+ export { MediaLibraryAddon, MediaLibraryAddon as default, mediaLibraryActions as customActions };