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