@dominevo/addon-media-library 0.1.3 → 0.1.4

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$1(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$1(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. */
@@ -8972,7 +8976,7 @@ function buildApp() {
8972
8976
  }
8973
8977
  //#endregion
8974
8978
  //#region src/arr-client.ts
8975
- var ImageSchema = object({
8979
+ var ImageSchema$1 = object({
8976
8980
  coverType: string(),
8977
8981
  url: string().nullish()
8978
8982
  });
@@ -8984,16 +8988,17 @@ var CommonSchema = object({
8984
8988
  tmdbId: number().int().nullish(),
8985
8989
  imdbId: string().nullish(),
8986
8990
  added: string().nullish(),
8987
- images: array(ImageSchema).default([])
8991
+ images: array(ImageSchema$1).default([])
8988
8992
  });
8989
8993
  var SeriesSchema = CommonSchema.extend({ tvdbId: number().int().nullish() });
8990
8994
  var MovieSchema = CommonSchema.extend({ movieFile: object({ path: string() }).nullish() });
8991
- var EpisodeSchema = object({
8995
+ var EpisodeSchema$1 = object({
8992
8996
  id: number().int(),
8993
8997
  title: string().nullish(),
8994
8998
  seasonNumber: number().int(),
8995
8999
  episodeNumber: number().int(),
8996
- episodeFile: object({ path: string() }).nullish()
9000
+ episodeFile: object({ path: string() }).nullish(),
9001
+ images: array(ImageSchema$1).default([])
8997
9002
  });
8998
9003
  function coverOf(images, type) {
8999
9004
  const url = images.find((image) => image.coverType === type)?.url;
@@ -9026,7 +9031,7 @@ async function fetchArrSeries(source, get) {
9026
9031
  const list = array(SeriesSchema).parse(await get(api(source, "series"), source.apiKey));
9027
9032
  const out = [];
9028
9033
  for (const raw of list) {
9029
- const episodes = array(EpisodeSchema).parse(await get(api(source, `episode?seriesId=${raw.id}&includeEpisodeFile=true`), source.apiKey));
9034
+ const episodes = array(EpisodeSchema$1).parse(await get(api(source, `episode?seriesId=${raw.id}&includeEpisodeFile=true&includeImages=true`), source.apiKey));
9030
9035
  out.push({
9031
9036
  ...entryOf(raw),
9032
9037
  episodes: episodes.map((episode) => ({
@@ -9034,7 +9039,8 @@ async function fetchArrSeries(source, get) {
9034
9039
  title: episode.title ?? "",
9035
9040
  seasonNumber: episode.seasonNumber,
9036
9041
  episodeNumber: episode.episodeNumber,
9037
- path: episode.episodeFile?.path ?? null
9042
+ path: episode.episodeFile?.path ?? null,
9043
+ still: coverOf(episode.images, "screenshot")
9038
9044
  }))
9039
9045
  });
9040
9046
  }
@@ -9470,10 +9476,267 @@ var walkFolder = async (root) => {
9470
9476
  };
9471
9477
  };
9472
9478
  //#endregion
9473
- //#region src/img-plane.ts
9479
+ //#region src/tvmaze.ts
9480
+ var TVMAZE_ID = "tvmaze";
9481
+ var API = "https://api.tvmaze.com";
9482
+ var ImageSchema = object({
9483
+ medium: string().nullish(),
9484
+ original: string().nullish()
9485
+ }).nullish();
9486
+ var ShowSchema = object({
9487
+ id: number().int(),
9488
+ name: string(),
9489
+ premiered: string().nullish(),
9490
+ summary: string().nullish(),
9491
+ image: ImageSchema,
9492
+ externals: object({
9493
+ thetvdb: number().int().nullish(),
9494
+ imdb: string().nullish()
9495
+ }).nullish()
9496
+ });
9497
+ var SearchSchema = array(object({
9498
+ score: number(),
9499
+ show: ShowSchema
9500
+ }));
9501
+ var EpisodeSchema = object({
9502
+ name: string().nullish(),
9503
+ season: number().int(),
9504
+ number: number().int().nullish(),
9505
+ summary: string().nullish(),
9506
+ image: ImageSchema
9507
+ });
9508
+ /** The summary field is HTML; keep the text. */
9509
+ function plain(html) {
9510
+ if (html === null || html === void 0) return null;
9511
+ const text = html.replace(/<[^>]*>/g, " ").replace(/&#(\d{1,6});|&#x([0-9a-f]{1,6});/gi, (_whole, dec, hex) => {
9512
+ const code = typeof dec === "string" ? Number(dec) : Number.parseInt(String(hex), 16);
9513
+ return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : "";
9514
+ }).replace(/&apos;/g, "'").replace(/&quot;/g, "\"").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/\s+/g, " ").trim();
9515
+ return text === "" ? null : text;
9516
+ }
9517
+ function imageOf(image) {
9518
+ const url = image?.original ?? image?.medium ?? null;
9519
+ return url !== null && url.startsWith("https://") ? url : null;
9520
+ }
9521
+ function yearOf(premiered) {
9522
+ const match = /^(\d{4})/.exec(premiered ?? "");
9523
+ return match?.[1] === void 0 ? null : Number(match[1]);
9524
+ }
9525
+ /** TVmaze: keyless, series only. Every call goes through the shared remote fetch and one spaced queue. */
9526
+ function createTvmazeProvider(deps) {
9527
+ const sleep = deps.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
9528
+ const now = deps.now ?? Date.now;
9529
+ const gap = deps.minGapMs ?? 600;
9530
+ let tail = Promise.resolve();
9531
+ let lastCallAt = Number.NEGATIVE_INFINITY;
9532
+ const call = (path) => {
9533
+ const run = async () => {
9534
+ const wait = lastCallAt + gap - now();
9535
+ if (wait > 0) await sleep(wait);
9536
+ lastCallAt = now();
9537
+ const bytes = await deps.fetch(`${API}${path}`);
9538
+ return JSON.parse(bytes.toString("utf8"));
9539
+ };
9540
+ const result = tail.then(run, run);
9541
+ tail = result.catch(() => void 0);
9542
+ return result;
9543
+ };
9544
+ return {
9545
+ id: TVMAZE_ID,
9546
+ kinds: ["series"],
9547
+ async identify(_kind, title, year) {
9548
+ const found = SearchSchema.parse(await call(`/search/shows?q=${encodeURIComponent(title)}`));
9549
+ const sameYear = year === null ? void 0 : found.find((entry) => yearOf(entry.show.premiered) === year);
9550
+ const top = found[0];
9551
+ const hit = sameYear ?? (year === null || top !== void 0 && foldTitle(top.show.name) === foldTitle(title) ? top : void 0);
9552
+ if (hit === void 0) return null;
9553
+ const show = hit.show;
9554
+ return {
9555
+ providerId: TVMAZE_ID,
9556
+ remoteId: String(show.id),
9557
+ title: show.name,
9558
+ year: yearOf(show.premiered),
9559
+ overview: plain(show.summary),
9560
+ tvdbId: show.externals?.thetvdb ?? null,
9561
+ tmdbId: null,
9562
+ imdbId: show.externals?.imdb ?? null,
9563
+ poster: imageOf(show.image),
9564
+ fanart: null
9565
+ };
9566
+ },
9567
+ async episodes(match) {
9568
+ return array(EpisodeSchema).parse(await call(`/shows/${encodeURIComponent(match.remoteId)}/episodes?specials=1`)).flatMap((entry) => entry.number === null || entry.number === void 0 ? [] : [{
9569
+ season: entry.season,
9570
+ episode: entry.number,
9571
+ title: entry.name ?? null,
9572
+ overview: plain(entry.summary),
9573
+ still: imageOf(entry.image)
9574
+ }]);
9575
+ }
9576
+ };
9577
+ }
9578
+ //#endregion
9579
+ //#region src/image-source.ts
9580
+ /** An absolute `https` URL, which is fetched with no credential; anything else is not one. */
9581
+ function isRemoteUrl(value) {
9582
+ if (!value.startsWith("https://")) return false;
9583
+ try {
9584
+ return new URL(value).protocol === "https:";
9585
+ } catch {
9586
+ return false;
9587
+ }
9588
+ }
9589
+ var FRAME_AT_FRACTION = .15;
9590
+ var FRAME_FALLBACK_SECONDS = 10;
9591
+ var FRAME_WIDTH_PX = 480;
9592
+ var GRAB_TIMEOUT_MS = 3e4;
9593
+ var FRAME_MAX_BYTES = 4 * 1024 * 1024;
9594
+ /** The ffmpeg arguments for one still: seek before the input (fast), one frame, scaled, JPEG on stdout. */
9595
+ function frameGrabArgs(filePath, durationMs) {
9596
+ const seconds = durationMs === null || durationMs <= 0 ? FRAME_FALLBACK_SECONDS : Math.floor(durationMs * FRAME_AT_FRACTION / 1e3);
9597
+ return [
9598
+ "-hide_banner",
9599
+ "-nostdin",
9600
+ "-loglevel",
9601
+ "error",
9602
+ "-ss",
9603
+ String(seconds),
9604
+ "-i",
9605
+ `file:${(0, node_path.resolve)(filePath)}`,
9606
+ "-frames:v",
9607
+ "1",
9608
+ "-an",
9609
+ "-sn",
9610
+ "-vf",
9611
+ `scale=${FRAME_WIDTH_PX}:-2`,
9612
+ "-f",
9613
+ "image2pipe",
9614
+ "-c:v",
9615
+ "mjpeg",
9616
+ "-q:v",
9617
+ "4",
9618
+ "pipe:1"
9619
+ ];
9620
+ }
9621
+ function grabFailureReason(error) {
9622
+ if (error.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return "frame too large";
9623
+ return error.killed === true ? "frame grab timed out" : error.message;
9624
+ }
9625
+ /** The ffmpeg the probe uses, asked for one frame. A run with no picture is a failure. */
9626
+ function createFfmpegFrameGrabber(binaryPath) {
9627
+ return (filePath, durationMs) => new Promise((done, reject) => {
9628
+ (0, node_child_process.execFile)(binaryPath, frameGrabArgs(filePath, durationMs), {
9629
+ timeout: GRAB_TIMEOUT_MS,
9630
+ maxBuffer: FRAME_MAX_BYTES,
9631
+ encoding: "buffer"
9632
+ }, (error, stdout, stderr) => {
9633
+ if (error !== null) reject(new Error(grabFailureReason(error)));
9634
+ else if (stdout.length === 0) reject(/* @__PURE__ */ new Error(`no frame: ${stderr.toString("utf8").slice(0, 200)}`));
9635
+ else done(stdout);
9636
+ });
9637
+ });
9638
+ }
9639
+ /** The queue behind a limiter is full: the work is refused, not delayed. */
9640
+ var LimiterFullError = class extends Error {
9641
+ constructor() {
9642
+ super("queue full");
9643
+ }
9644
+ };
9645
+ /** At most `limit` runs of `task` at once, at most `maxWaiting` queued behind them; the rest are refused. */
9646
+ function createLimiter(limit, maxWaiting) {
9647
+ let running = 0;
9648
+ const waiting = [];
9649
+ return async (task) => {
9650
+ if (running >= limit) {
9651
+ if (waiting.length >= maxWaiting) throw new LimiterFullError();
9652
+ await new Promise((go) => waiting.push(go));
9653
+ }
9654
+ running += 1;
9655
+ try {
9656
+ return await task();
9657
+ } finally {
9658
+ running -= 1;
9659
+ waiting.shift()?.();
9660
+ }
9661
+ };
9662
+ }
9663
+ //#endregion
9664
+ //#region src/remote-fetch.ts
9474
9665
  var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
9475
9666
  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. */
9667
+ var MAX_REDIRECTS = 3;
9668
+ /** Read a response body, aborting as soon as it passes `cap`: the rest is never buffered. */
9669
+ async function readCapped(response, cap) {
9670
+ if (Number(response.headers.get("content-length") ?? "0") > cap) throw new Error("image too large");
9671
+ if (response.body === null) return Buffer.alloc(0);
9672
+ const reader = response.body.getReader();
9673
+ const chunks = [];
9674
+ let total = 0;
9675
+ for (;;) {
9676
+ const { done, value } = await reader.read();
9677
+ if (done) break;
9678
+ total += value.byteLength;
9679
+ if (total > cap) {
9680
+ await reader.cancel();
9681
+ throw new Error("image too large");
9682
+ }
9683
+ chunks.push(Buffer.from(value));
9684
+ }
9685
+ return Buffer.concat(chunks, total);
9686
+ }
9687
+ function v4Private(address) {
9688
+ const [a = 0, b = 0] = address.split(".").map(Number);
9689
+ 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;
9690
+ }
9691
+ /** Loopback, private, link-local, ULA, CGNAT, multicast and unspecified addresses, v4 and v6. */
9692
+ function isPrivateAddress(address) {
9693
+ const kind = (0, node_net.isIP)(address);
9694
+ if (kind === 4) return v4Private(address);
9695
+ if (kind !== 6) return true;
9696
+ const lower = address.toLowerCase();
9697
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
9698
+ if (mapped?.[1] !== void 0) return v4Private(mapped[1]);
9699
+ if (lower === "::" || lower === "::1") return true;
9700
+ return /^(fe[89ab]|f[cd]|ff)/.test(lower);
9701
+ }
9702
+ var resolveAll = async (host) => (await (0, node_dns_promises.lookup)(host, { all: true })).map((entry) => entry.address);
9703
+ /**
9704
+ * https only, at most 3 redirects each re-validated, every address the host resolves to must be
9705
+ * public, no credential, a bounded time and a streamed size cap.
9706
+ * A resolver answer can differ from the one `fetch` gets (rebinding): the host check narrows, not closes, that window.
9707
+ */
9708
+ function createRemoteFetch(deps = {}) {
9709
+ const doFetch = deps.fetchImpl ?? fetch;
9710
+ const resolve = deps.resolve ?? resolveAll;
9711
+ return async (start) => {
9712
+ let url = start;
9713
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
9714
+ if (!isRemoteUrl(url)) throw new Error("only an https URL is fetched");
9715
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
9716
+ const addresses = (0, node_net.isIP)(host) === 0 ? await resolve(host) : [host];
9717
+ if (addresses.length === 0 || addresses.some(isPrivateAddress)) throw new Error("host refused: not a public address");
9718
+ const response = await doFetch(url, {
9719
+ redirect: "manual",
9720
+ signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
9721
+ });
9722
+ if (response.status >= 300 && response.status < 400) {
9723
+ const location = response.headers.get("location");
9724
+ if (location === null) throw new Error("redirect without a location");
9725
+ url = new URL(location, url).toString();
9726
+ continue;
9727
+ }
9728
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
9729
+ return readCapped(response, MAX_IMAGE_BYTES);
9730
+ }
9731
+ throw new Error("too many redirects");
9732
+ };
9733
+ }
9734
+ var httpRemoteFetch = createRemoteFetch();
9735
+ //#endregion
9736
+ //#region src/img-plane.ts
9737
+ var FAILED_GRAB_TTL_MS = 30 * 6e4;
9738
+ var FAILED_GRAB_MAX = 500;
9739
+ /** The real fetch: the key travels in a header, a redirect is never followed, the body is size-capped as it streams. */
9477
9740
  var httpImageFetch = async (url, apiKey) => {
9478
9741
  const response = await fetch(url, {
9479
9742
  headers: { "X-Api-Key": apiKey },
@@ -9482,10 +9745,7 @@ var httpImageFetch = async (url, apiKey) => {
9482
9745
  });
9483
9746
  if (response.status >= 300 && response.status < 400) throw new Error(`redirect refused (HTTP ${response.status}): the key is never sent to another URL`);
9484
9747
  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;
9748
+ return readCapped(response, MAX_IMAGE_BYTES);
9489
9749
  };
9490
9750
  function typeOf(bytes) {
9491
9751
  if (bytes.length > 3 && bytes[0] === 255 && bytes[1] === 216) return "image/jpeg";
@@ -9507,11 +9767,77 @@ function end(res, status) {
9507
9767
  /** The `img` plane: `GET /<itemId>/poster|fanart`, fetched from the arr once and cached on disk. */
9508
9768
  function createImagePlaneHandler(deps) {
9509
9769
  const inFlight = /* @__PURE__ */ new Map();
9770
+ const now = deps.now ?? Date.now;
9771
+ /** key → when the failure is forgotten: a transient failure retries, and the set is bounded. */
9772
+ const failedGrabs = /* @__PURE__ */ new Map();
9773
+ const hasFailed = (key) => {
9774
+ const until = failedGrabs.get(key);
9775
+ if (until === void 0) return false;
9776
+ if (until > now()) return true;
9777
+ failedGrabs.delete(key);
9778
+ return false;
9779
+ };
9780
+ const rememberFailure = (key) => {
9781
+ failedGrabs.delete(key);
9782
+ failedGrabs.set(key, now() + FAILED_GRAB_TTL_MS);
9783
+ for (const oldest of failedGrabs.keys()) {
9784
+ if (failedGrabs.size <= FAILED_GRAB_MAX) break;
9785
+ failedGrabs.delete(oldest);
9786
+ }
9787
+ };
9788
+ const limitGrabs = createLimiter(deps.grabConcurrency ?? 2, deps.grabQueueLimit ?? 32);
9789
+ /** A sidecar image is read only from inside a configured root, symlinks resolved, and only up to the size cap. */
9790
+ const readLocal = async (path, tags) => {
9791
+ const real = await resolveServable(path, await deps.roots?.() ?? []);
9792
+ if (real === null) {
9793
+ deps.logger.warn("image refused: outside the configured folders", {
9794
+ tags,
9795
+ meta: { reason: "outside-roots" }
9796
+ });
9797
+ return null;
9798
+ }
9799
+ if ((await (0, node_fs_promises.stat)(real)).size > 10485760) throw new Error("image too large");
9800
+ return (0, node_fs_promises.readFile)(real);
9801
+ };
9802
+ const produce = async (found, tags) => {
9803
+ if (found.kind === "frame") return limitGrabs(() => deps.grabFrame(found.filePath, found.durationMs));
9804
+ if (found.kind === "remote") return deps.fetchRemote(found.url);
9805
+ const arr = await deps.arrSource(found.sourceId);
9806
+ const url = arr === null ? null : coverUrl(arr, found.path);
9807
+ if (arr === null || url === null) {
9808
+ deps.logger.warn("image skipped: no usable source", {
9809
+ tags,
9810
+ meta: { reason: arr === null ? "source-off" : "foreign-origin" }
9811
+ });
9812
+ return null;
9813
+ }
9814
+ return deps.fetchImage(url, arr.apiKey);
9815
+ };
9510
9816
  const load = async (itemId, which) => {
9817
+ for (const found of await deps.source(itemId, which)) {
9818
+ const bytes = await loadOne(itemId, which, found);
9819
+ if (bytes !== null) return bytes;
9820
+ }
9821
+ return null;
9822
+ };
9823
+ const loadOne = async (itemId, which, found) => {
9511
9824
  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}`);
9825
+ const origin = found.kind === "arr" ? found.path : found.kind === "remote" ? found.url : found.kind === "local" ? found.path : `frame:${found.filePath}`;
9826
+ if (found.kind === "local") try {
9827
+ const bytes = await readLocal(found.path, tags);
9828
+ return bytes !== null && typeOf(bytes) !== null ? bytes : null;
9829
+ } catch (error) {
9830
+ deps.logger.warn("image fetch failed", {
9831
+ tags,
9832
+ meta: {
9833
+ reason: "read-failed",
9834
+ error: error instanceof Error ? error.message : String(error)
9835
+ }
9836
+ });
9837
+ return null;
9838
+ }
9839
+ const key = hashKey(`${itemId}:${which}:${origin}`);
9840
+ if (hasFailed(key)) return null;
9515
9841
  const cached = (0, node_path.join)(deps.cacheDir, key);
9516
9842
  try {
9517
9843
  const onDisk = await (0, node_fs_promises.readFile)(cached);
@@ -9522,27 +9848,27 @@ function createImagePlaneHandler(deps) {
9522
9848
  });
9523
9849
  await (0, node_fs_promises.unlink)(cached);
9524
9850
  } 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
9851
  try {
9535
- const bytes = await deps.fetchImage(url, arr.apiKey);
9852
+ const bytes = await produce(found, tags);
9853
+ if (bytes === null) return null;
9536
9854
  if (typeOf(bytes) === null) throw new Error("not an image");
9537
9855
  await (0, node_fs_promises.mkdir)(deps.cacheDir, { recursive: true });
9538
9856
  await (0, node_fs_promises.writeFile)(`${cached}.tmp`, bytes);
9539
9857
  await (0, node_fs_promises.rename)(`${cached}.tmp`, cached);
9540
9858
  return bytes;
9541
9859
  } catch (error) {
9542
- deps.logger.warn("image fetch failed", {
9860
+ if (error instanceof LimiterFullError) {
9861
+ deps.logger.warn("frame grab refused", {
9862
+ tags,
9863
+ meta: { reason: "queue-full" }
9864
+ });
9865
+ return null;
9866
+ }
9867
+ if (found.kind === "frame") rememberFailure(key);
9868
+ deps.logger.warn(found.kind === "frame" ? "frame grab failed" : "image fetch failed", {
9543
9869
  tags,
9544
9870
  meta: {
9545
- reason: "fetch-failed",
9871
+ reason: found.kind === "frame" ? "grab-failed" : "fetch-failed",
9546
9872
  error: error instanceof Error ? error.message : String(error)
9547
9873
  }
9548
9874
  });
@@ -9595,6 +9921,134 @@ function parseRows(schema, rows, onInvalid) {
9595
9921
  return out;
9596
9922
  }
9597
9923
  //#endregion
9924
+ //#region src/metadata.ts
9925
+ var ProviderMatchSchema = object({
9926
+ providerId: string(),
9927
+ /** The provider's own id of the match, used to ask for its episodes. */
9928
+ remoteId: string(),
9929
+ title: string(),
9930
+ year: number().int().nullable(),
9931
+ overview: string().nullable(),
9932
+ tvdbId: number().int().nullable(),
9933
+ tmdbId: number().int().nullable(),
9934
+ imdbId: string().nullable(),
9935
+ poster: string().nullable(),
9936
+ fanart: string().nullable()
9937
+ });
9938
+ var ProviderEpisodeSchema = object({
9939
+ season: number().int(),
9940
+ episode: number().int(),
9941
+ title: string().nullable(),
9942
+ overview: string().nullable(),
9943
+ still: string().nullable()
9944
+ });
9945
+ //#endregion
9946
+ //#region src/match-cache.ts
9947
+ var MATCHES = "media-library:matches";
9948
+ var MATCHES_DECLARATION = {
9949
+ collection: MATCHES,
9950
+ primaryKey: ["key"],
9951
+ columns: [
9952
+ {
9953
+ name: "key",
9954
+ type: "TEXT",
9955
+ notNull: true
9956
+ },
9957
+ {
9958
+ name: "value",
9959
+ type: "JSON",
9960
+ notNull: true
9961
+ },
9962
+ {
9963
+ name: "fetchedAt",
9964
+ type: "INTEGER",
9965
+ notNull: true
9966
+ }
9967
+ ]
9968
+ };
9969
+ /** A match that was found stays this long; an answered "nothing" and an episode list expire sooner. */
9970
+ var FOUND_TTL_MS = 720 * 60 * 60 * 1e3;
9971
+ var ABSENT_TTL_MS = 4320 * 60 * 1e3;
9972
+ var EntrySchema = discriminatedUnion("found", [object({
9973
+ found: literal(true),
9974
+ match: ProviderMatchSchema
9975
+ }), object({ found: literal(false) })]);
9976
+ var EpisodesSchema = object({ episodes: array(ProviderEpisodeSchema) });
9977
+ var RowSchema = object({
9978
+ key: string(),
9979
+ value: unknown(),
9980
+ fetchedAt: number()
9981
+ });
9982
+ /**
9983
+ * Answers the providers gave, kept so a rescan does not ask again about an unchanged item.
9984
+ * Read once at the start of a scan, written once at its end; a failed provider call is never stored.
9985
+ */
9986
+ var MatchCache = class MatchCache {
9987
+ now;
9988
+ rows = /* @__PURE__ */ new Map();
9989
+ dirty = /* @__PURE__ */ new Set();
9990
+ constructor(now) {
9991
+ this.now = now;
9992
+ }
9993
+ static async load(db, now) {
9994
+ const cache = new MatchCache(now);
9995
+ for (const raw of await db.query(MATCHES)) {
9996
+ const parsed = RowSchema.safeParse(raw);
9997
+ if (parsed.success) cache.rows.set(parsed.data.key, {
9998
+ value: parsed.data.value,
9999
+ fetchedAt: parsed.data.fetchedAt
10000
+ });
10001
+ }
10002
+ return cache;
10003
+ }
10004
+ fresh(key, ttlMs) {
10005
+ const row = this.rows.get(key);
10006
+ return row !== void 0 && this.now() - row.fetchedAt < ttlMs ? { value: row.value } : null;
10007
+ }
10008
+ put(key, value) {
10009
+ this.rows.set(key, {
10010
+ value,
10011
+ fetchedAt: this.now()
10012
+ });
10013
+ this.dirty.add(key);
10014
+ }
10015
+ getMatch(key) {
10016
+ const known = this.fresh(key, FOUND_TTL_MS);
10017
+ if (known === null) return null;
10018
+ const parsed = EntrySchema.safeParse(known.value);
10019
+ if (!parsed.success) return null;
10020
+ return parsed.data.found || this.fresh(key, 2592e5) !== null ? parsed.data : null;
10021
+ }
10022
+ putMatch(key, entry) {
10023
+ this.put(key, entry);
10024
+ }
10025
+ getEpisodes(key) {
10026
+ const known = this.fresh(key, ABSENT_TTL_MS);
10027
+ if (known === null) return null;
10028
+ const parsed = EpisodesSchema.safeParse(known.value);
10029
+ return parsed.success ? parsed.data : null;
10030
+ }
10031
+ putEpisodes(key, entry) {
10032
+ this.put(key, entry);
10033
+ }
10034
+ /** How many answers are waiting to be written. */
10035
+ get pending() {
10036
+ return this.dirty.size;
10037
+ }
10038
+ async flush(db) {
10039
+ const writes = [...this.dirty].flatMap((key) => {
10040
+ const row = this.rows.get(key);
10041
+ return row === void 0 ? [] : [{
10042
+ key,
10043
+ value: row.value,
10044
+ fetchedAt: row.fetchedAt
10045
+ }];
10046
+ });
10047
+ this.dirty.clear();
10048
+ if (writes.length > 0) await db.upsertMany(MATCHES, ["key"], writes);
10049
+ }
10050
+ };
10051
+ //#endregion
9598
10052
  //#region src/rows.ts
9599
10053
  /** The collections live in the shared settings database; the closed `database` enum has no media file. */
9600
10054
  var ITEMS = "media-library:items";
@@ -9733,6 +10187,7 @@ var COLLECTIONS = [
9733
10187
  text("probeError")
9734
10188
  ]
9735
10189
  },
10190
+ MATCHES_DECLARATION,
9736
10191
  {
9737
10192
  collection: PROGRESS,
9738
10193
  primaryKey: ["userId", "itemId"],
@@ -9759,6 +10214,280 @@ var COLLECTIONS = [
9759
10214
  }]
9760
10215
  }
9761
10216
  ];
10217
+ //#endregion
10218
+ //#region src/nfo.ts
10219
+ /**
10220
+ * A tolerant reader for the media-center `.nfo` files (`tvshow`, `movie`, `episodedetails`).
10221
+ * It is not an XML parser: it reads the handful of top-level fields the library wants, never
10222
+ * resolves an entity beyond the five predefined ones and numeric references, never follows a
10223
+ * DOCTYPE or an external reference, and refuses a file past {@link NFO_MAX_BYTES}.
10224
+ */
10225
+ var NFO_MAX_BYTES = 256 * 1024;
10226
+ var NAMED = {
10227
+ amp: "&",
10228
+ lt: "<",
10229
+ gt: ">",
10230
+ quot: "\"",
10231
+ apos: "'"
10232
+ };
10233
+ function decode(text) {
10234
+ const cdata = /^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/.exec(text);
10235
+ if (cdata?.[1] !== void 0) return cdata[1].trim();
10236
+ 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) => {
10237
+ if (typeof name === "string") return NAMED[name] ?? "";
10238
+ const code = typeof dec === "string" ? Number(dec) : Number.parseInt(String(hex), 16);
10239
+ return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : "";
10240
+ }).trim();
10241
+ }
10242
+ /** Every `<name …>body</name>` in document order, found by `indexOf` scans only: linear whatever the input. */
10243
+ function tagsOf(xml, name) {
10244
+ const out = [];
10245
+ const lower = xml.toLowerCase();
10246
+ const open = `<${name}`;
10247
+ const close = `</${name}>`;
10248
+ let from = 0;
10249
+ for (;;) {
10250
+ const start = lower.indexOf(open, from);
10251
+ if (start === -1) break;
10252
+ const after = lower.charAt(start + open.length);
10253
+ const gt = lower.indexOf(">", start);
10254
+ if (gt === -1) break;
10255
+ if (!(after === ">" || /\s/.test(after)) || lower.charAt(gt - 1) === "/") {
10256
+ from = start + open.length;
10257
+ continue;
10258
+ }
10259
+ const end = lower.indexOf(close, gt + 1);
10260
+ if (end === -1) break;
10261
+ out.push({
10262
+ attrs: xml.slice(start + open.length, gt),
10263
+ body: xml.slice(gt + 1, end)
10264
+ });
10265
+ from = end + close.length;
10266
+ }
10267
+ return out;
10268
+ }
10269
+ function textOf(xml, name) {
10270
+ const [first] = tagsOf(xml, name);
10271
+ if (first === void 0) return null;
10272
+ const value = decode(first.body);
10273
+ return value === "" ? null : value;
10274
+ }
10275
+ function intOf(value) {
10276
+ if (value === null || !/^\d{1,9}$/.test(value)) return null;
10277
+ return Number(value);
10278
+ }
10279
+ function attrOf(attrs, name) {
10280
+ const match = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, "i").exec(attrs);
10281
+ return match === null ? null : match[1] ?? match[2] ?? null;
10282
+ }
10283
+ /** The ids the file names, by `uniqueid type=`, with the older `<tvdbid>` / `<imdbid>` tags as a fallback. */
10284
+ function idsOf(xml) {
10285
+ let tvdbId = null;
10286
+ let tmdbId = null;
10287
+ let imdbId = null;
10288
+ for (const tag of tagsOf(xml, "uniqueid")) {
10289
+ const type = attrOf(tag.attrs, "type")?.toLowerCase();
10290
+ const value = decode(tag.body);
10291
+ if (type === "tvdb") tvdbId ??= intOf(value);
10292
+ else if (type === "tmdb") tmdbId ??= intOf(value);
10293
+ else if (type === "imdb" && /^tt\d{1,12}$/.test(value)) imdbId ??= value;
10294
+ }
10295
+ tvdbId ??= intOf(textOf(xml, "tvdbid"));
10296
+ tmdbId ??= intOf(textOf(xml, "tmdbid"));
10297
+ const legacyImdb = textOf(xml, "imdbid") ?? textOf(xml, "imdb_id");
10298
+ if (imdbId === null && legacyImdb !== null && /^tt\d{1,12}$/.test(legacyImdb)) imdbId = legacyImdb;
10299
+ return {
10300
+ tvdbId,
10301
+ tmdbId,
10302
+ imdbId
10303
+ };
10304
+ }
10305
+ /** Remove every `open…close` block (an unterminated one to the end), by `indexOf` scans: linear. */
10306
+ function stripBlocks(text, open, close) {
10307
+ const lower = text.toLowerCase();
10308
+ let out = "";
10309
+ let from = 0;
10310
+ for (;;) {
10311
+ const start = lower.indexOf(open, from);
10312
+ if (start === -1) return out + text.slice(from);
10313
+ out += text.slice(from, start);
10314
+ const end = lower.indexOf(close, start + open.length);
10315
+ if (end === -1) return out;
10316
+ from = end + close.length;
10317
+ }
10318
+ }
10319
+ /** `null` when the text is not one of the three documents, or is over the cap. */
10320
+ function parseNfo(source) {
10321
+ if (source.length > 262144) return null;
10322
+ const xml = stripBlocks(stripBlocks(source, "<!--", "-->"), "<!doctype", ">");
10323
+ const root = /<(tvshow|movie|episodedetails)[\s>]/i.exec(xml)?.[1]?.toLowerCase();
10324
+ if (root !== "tvshow" && root !== "movie" && root !== "episodedetails") return null;
10325
+ const premiered = textOf(xml, "premiered") ?? textOf(xml, "aired");
10326
+ const year = intOf(textOf(xml, "year")) ?? (premiered === null ? null : intOf(/^(\d{4})/.exec(premiered)?.[1] ?? null));
10327
+ return {
10328
+ root,
10329
+ title: textOf(xml, "title"),
10330
+ year,
10331
+ plot: textOf(xml, "plot"),
10332
+ ...idsOf(xml),
10333
+ season: intOf(textOf(xml, "season")),
10334
+ episode: intOf(textOf(xml, "episode"))
10335
+ };
10336
+ }
10337
+ //#endregion
10338
+ //#region src/sidecars.ts
10339
+ /** The local image kind is stored in an item's cover column as `local:<absolute path>`. */
10340
+ var LOCAL_PREFIX = "local:";
10341
+ function localCover(path) {
10342
+ return `${LOCAL_PREFIX}${path}`;
10343
+ }
10344
+ /** The absolute path of a `local:` cover, or `null` when the value is not one. */
10345
+ function localCoverPath(value) {
10346
+ return value.startsWith("local:") ? value.slice(6) : null;
10347
+ }
10348
+ var IMAGE_EXTENSIONS = [
10349
+ ".jpg",
10350
+ ".jpeg",
10351
+ ".png"
10352
+ ];
10353
+ function createLocalReader() {
10354
+ const listings = /* @__PURE__ */ new Map();
10355
+ return {
10356
+ list(dir) {
10357
+ const cached = listings.get(dir);
10358
+ if (cached !== void 0) return cached;
10359
+ const read = (0, node_fs_promises.readdir)(dir).then((names) => new Map(names.map((name) => [name.toLowerCase(), name])), () => /* @__PURE__ */ new Map());
10360
+ listings.set(dir, read);
10361
+ return read;
10362
+ },
10363
+ async nfo(path) {
10364
+ try {
10365
+ const handle = await (0, node_fs_promises.open)(path, "r");
10366
+ try {
10367
+ const buffer = Buffer.alloc(NFO_MAX_BYTES + 1);
10368
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
10369
+ if (bytesRead > 262144) return null;
10370
+ return parseNfo(buffer.subarray(0, bytesRead).toString("utf8"));
10371
+ } finally {
10372
+ await handle.close();
10373
+ }
10374
+ } catch {
10375
+ return null;
10376
+ }
10377
+ }
10378
+ };
10379
+ }
10380
+ /** A season folder: `Season 02`, `Season2`, `S02`, `S 02`, `Specials` (season 0). */
10381
+ function seasonOfFolder(name) {
10382
+ const trimmed = name.trim();
10383
+ if (/^specials?$/i.test(trimmed)) return 0;
10384
+ const match = /^(?:season|stagione|s)[\s._-]*(\d{1,3})$/i.exec(trimmed);
10385
+ return match?.[1] === void 0 ? null : Number(match[1]);
10386
+ }
10387
+ /** The folder that holds a show: the file's folder, or its parent when that is a season folder. */
10388
+ function seriesDirOf(filePath) {
10389
+ const parent = (0, node_path.dirname)(filePath);
10390
+ return seasonOfFolder((0, node_path.basename)(parent)) === null ? parent : (0, node_path.dirname)(parent);
10391
+ }
10392
+ var NO_LOCAL = {
10393
+ title: null,
10394
+ year: null,
10395
+ overview: null,
10396
+ tvdbId: null,
10397
+ tmdbId: null,
10398
+ imdbId: null,
10399
+ poster: null,
10400
+ fanart: null,
10401
+ season: null,
10402
+ episode: null
10403
+ };
10404
+ function fromNfo(nfo) {
10405
+ if (nfo === null) return NO_LOCAL;
10406
+ return {
10407
+ ...NO_LOCAL,
10408
+ title: nfo.title,
10409
+ year: nfo.year,
10410
+ overview: nfo.plot,
10411
+ tvdbId: nfo.tvdbId,
10412
+ tmdbId: nfo.tmdbId,
10413
+ imdbId: nfo.imdbId,
10414
+ season: nfo.season,
10415
+ episode: nfo.episode
10416
+ };
10417
+ }
10418
+ /** First candidate base name (without extension) that exists in `listing` with an image extension. */
10419
+ function firstImage(dir, listing, bases) {
10420
+ for (const base of bases) for (const extension of IMAGE_EXTENSIONS) {
10421
+ const real = listing.get(`${base.toLowerCase()}${extension}`);
10422
+ if (real !== void 0) return localCover((0, node_path.join)(dir, real));
10423
+ }
10424
+ return null;
10425
+ }
10426
+ function pick(...values) {
10427
+ for (const value of values) if (value !== null) return value;
10428
+ return null;
10429
+ }
10430
+ function merge(first, second) {
10431
+ return {
10432
+ title: pick(first.title, second.title),
10433
+ year: pick(first.year, second.year),
10434
+ overview: pick(first.overview, second.overview),
10435
+ tvdbId: pick(first.tvdbId, second.tvdbId),
10436
+ tmdbId: pick(first.tmdbId, second.tmdbId),
10437
+ imdbId: pick(first.imdbId, second.imdbId),
10438
+ poster: pick(first.poster, second.poster),
10439
+ fanart: pick(first.fanart, second.fanart),
10440
+ season: pick(first.season, second.season),
10441
+ episode: pick(first.episode, second.episode)
10442
+ };
10443
+ }
10444
+ function videoCount(listing) {
10445
+ let count = 0;
10446
+ for (const name of listing.keys()) if (VIDEO_EXTENSIONS.has((0, node_path.extname)(name))) count += 1;
10447
+ return count;
10448
+ }
10449
+ /** `tvshow.nfo`, `poster.*`, `folder.*`, `fanart.*` of a series folder. */
10450
+ async function localSeries(reader, seriesDir) {
10451
+ const listing = await reader.list(seriesDir);
10452
+ const nfoName = listing.get("tvshow.nfo");
10453
+ const nfo = nfoName === void 0 ? null : await reader.nfo((0, node_path.join)(seriesDir, nfoName));
10454
+ return {
10455
+ ...fromNfo(nfo?.root === "tvshow" ? nfo : null),
10456
+ poster: firstImage(seriesDir, listing, ["poster", "folder"]),
10457
+ fanart: firstImage(seriesDir, listing, ["fanart"])
10458
+ };
10459
+ }
10460
+ /** `<episode>.nfo` and `<episode>-thumb.*` next to the file. */
10461
+ async function localEpisode(reader, filePath) {
10462
+ const dir = (0, node_path.dirname)(filePath);
10463
+ const base = (0, node_path.basename)(filePath, (0, node_path.extname)(filePath));
10464
+ const listing = await reader.list(dir);
10465
+ const nfoName = listing.get(`${base.toLowerCase()}.nfo`);
10466
+ const nfo = nfoName === void 0 ? null : await reader.nfo((0, node_path.join)(dir, nfoName));
10467
+ return {
10468
+ ...fromNfo(nfo?.root === "episodedetails" ? nfo : null),
10469
+ poster: firstImage(dir, listing, [`${base}-thumb`])
10470
+ };
10471
+ }
10472
+ /**
10473
+ * `<movie>.nfo` / `movie.nfo` and the matching posters. A name that applies to the whole
10474
+ * folder (`poster.jpg`, `movie.nfo`) is taken only when the folder holds this one video.
10475
+ */
10476
+ async function localMovie(reader, filePath) {
10477
+ const dir = (0, node_path.dirname)(filePath);
10478
+ const base = (0, node_path.basename)(filePath, (0, node_path.extname)(filePath));
10479
+ const listing = await reader.list(dir);
10480
+ const solo = videoCount(listing) <= 1;
10481
+ const named = listing.get(`${base.toLowerCase()}.nfo`);
10482
+ const shared = solo ? listing.get("movie.nfo") : void 0;
10483
+ const own = named === void 0 ? null : await reader.nfo((0, node_path.join)(dir, named));
10484
+ const folderWide = shared === void 0 ? null : await reader.nfo((0, node_path.join)(dir, shared));
10485
+ return {
10486
+ ...merge(fromNfo(own?.root === "movie" ? own : null), fromNfo(folderWide?.root === "movie" ? folderWide : null)),
10487
+ poster: firstImage(dir, listing, [`${base}-poster`, ...solo ? ["poster", "folder"] : []]),
10488
+ fanart: firstImage(dir, listing, [`${base}-fanart`, ...solo ? ["fanart"] : []])
10489
+ };
10490
+ }
9762
10491
  var FILE_PLANE_PREFIX = "file";
9763
10492
  var HUB_PLANE_BASE = "/addon/media-library";
9764
10493
  var SEARCH_DEFAULT_LIMIT = 50;
@@ -9915,7 +10644,10 @@ var LibraryStore = class {
9915
10644
  direction: "asc"
9916
10645
  }
9917
10646
  });
9918
- return this.summaries(rows, userId);
10647
+ return (await this.summaries(rows, userId)).map((summary, index) => ({
10648
+ ...summary,
10649
+ overview: rows[index]?.overview ?? null
10650
+ }));
9919
10651
  }
9920
10652
  async getItem(userId, itemId) {
9921
10653
  const [row] = await this.queryItems({
@@ -9958,17 +10690,47 @@ var LibraryStore = class {
9958
10690
  row: file
9959
10691
  };
9960
10692
  }
10693
+ /** Where an image may come from, best first. A cover that fails falls back to a frame of the file. */
9961
10694
  async imageSource(itemId, which) {
9962
10695
  const [item] = await this.queryItems({
9963
10696
  where: { id: itemId },
9964
10697
  limit: 1
9965
10698
  });
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
- };
10699
+ if (item === void 0) return [];
10700
+ const out = [];
10701
+ const cover = which === "poster" ? item.posterSource : item.fanartSource;
10702
+ if (cover !== null) {
10703
+ const local = localCoverPath(cover);
10704
+ if (local !== null) out.push({
10705
+ kind: "local",
10706
+ path: local
10707
+ });
10708
+ else if (isRemoteUrl(cover)) out.push({
10709
+ kind: "remote",
10710
+ url: cover
10711
+ });
10712
+ else if (cover.startsWith("/")) out.push({
10713
+ kind: "arr",
10714
+ path: cover,
10715
+ sourceId: item.sourceId
10716
+ });
10717
+ else this.logger.warn("image skipped: no usable source", {
10718
+ tags: { itemId },
10719
+ meta: { reason: "foreign-origin" }
10720
+ });
10721
+ }
10722
+ if (which === "poster" && item.kind !== "series" && item.filePath !== null) {
10723
+ const [file] = await this.queryFiles({
10724
+ where: { path: item.filePath },
10725
+ limit: 1
10726
+ });
10727
+ if (file !== void 0) out.push({
10728
+ kind: "frame",
10729
+ filePath: item.filePath,
10730
+ durationMs: file.durationMs
10731
+ });
10732
+ }
10733
+ return out;
9972
10734
  }
9973
10735
  /** Serialise the read-compare-write of one (user, item) so two writes of one person cannot interleave. */
9974
10736
  async locked(key, run) {
@@ -10117,7 +10879,7 @@ function toSummary(row, file, progress) {
10117
10879
  seriesId: row.kind === "episode" ? row.parentId : null,
10118
10880
  seasonNumber: row.seasonNumber,
10119
10881
  episodeNumber: row.episodeNumber,
10120
- posterPath: row.posterSource === null ? null : imagePathOf(row.id, "poster"),
10882
+ posterPath: row.posterSource === null && !(row.kind !== "series" && file !== void 0) ? null : imagePathOf(row.id, "poster"),
10121
10883
  addedAt: row.addedAt,
10122
10884
  durationMs: file?.durationMs ?? null,
10123
10885
  playable: row.kind !== "series" && file !== void 0,
@@ -10264,10 +11026,214 @@ function createMediaLibraryProvider(store, scans) {
10264
11026
  getScanStatus: async () => scans.status()
10265
11027
  };
10266
11028
  }
10267
- var ARR_SERIES = "arr-series";
10268
- var ARR_MOVIES = "arr-movies";
10269
- var FOLDER = "folder";
10270
- function row(base) {
11029
+ //#endregion
11030
+ //#region src/enrich.ts
11031
+ /** The default order when settings name none (D1125): files next to the media, the arr app, then online. */
11032
+ var DEFAULT_STEPS = [
11033
+ "local",
11034
+ "arr",
11035
+ "tvmaze"
11036
+ ];
11037
+ /** After this many failed calls in one scan a provider is left alone until the next scan. */
11038
+ var PROVIDER_FAILURE_LIMIT = 3;
11039
+ function fill(into, from) {
11040
+ return {
11041
+ title: into.title ?? from.title,
11042
+ year: into.year ?? from.year,
11043
+ overview: into.overview ?? from.overview,
11044
+ tvdbId: into.tvdbId ?? from.tvdbId,
11045
+ tmdbId: into.tmdbId ?? from.tmdbId,
11046
+ imdbId: into.imdbId ?? from.imdbId,
11047
+ poster: into.poster ?? from.poster,
11048
+ fanart: into.fanart ?? from.fanart,
11049
+ season: into.season ?? from.season,
11050
+ episode: into.episode ?? from.episode
11051
+ };
11052
+ }
11053
+ function isArr(item) {
11054
+ return item.sourceId.startsWith("arr-");
11055
+ }
11056
+ /** What the arr app said about the item; a made-up title is no answer. */
11057
+ function arrLayer(item) {
11058
+ if (!isArr(item)) return NO_LOCAL;
11059
+ return {
11060
+ ...NO_LOCAL,
11061
+ title: item.titlePlaceholder ? null : item.title,
11062
+ year: item.year,
11063
+ overview: item.overview,
11064
+ tvdbId: item.tvdbId,
11065
+ tmdbId: item.tmdbId,
11066
+ imdbId: item.imdbId,
11067
+ poster: item.posterSource,
11068
+ fanart: item.fanartSource
11069
+ };
11070
+ }
11071
+ /** What the file name and folder said: the last step, always on. */
11072
+ function fileLayer(item) {
11073
+ return {
11074
+ ...NO_LOCAL,
11075
+ title: item.title,
11076
+ year: isArr(item) ? null : item.year
11077
+ };
11078
+ }
11079
+ var Enricher = class {
11080
+ steps;
11081
+ deps;
11082
+ failures = /* @__PURE__ */ new Map();
11083
+ seriesMatch = /* @__PURE__ */ new Map();
11084
+ matches = /* @__PURE__ */ new Map();
11085
+ constructor(steps, deps) {
11086
+ this.steps = steps;
11087
+ this.deps = deps;
11088
+ }
11089
+ provider(id) {
11090
+ if ((this.failures.get(id) ?? 0) >= PROVIDER_FAILURE_LIMIT) return null;
11091
+ return this.deps.providers.find((entry) => entry.id === id) ?? null;
11092
+ }
11093
+ failed(id, itemId, error) {
11094
+ const count = (this.failures.get(id) ?? 0) + 1;
11095
+ this.failures.set(id, count);
11096
+ this.deps.logger.warn("metadata provider failed: the field is left to the next step", {
11097
+ tags: { itemId },
11098
+ meta: {
11099
+ provider: id,
11100
+ error: error instanceof Error ? error.message : String(error),
11101
+ ...count >= PROVIDER_FAILURE_LIMIT ? { pausedForThisScan: true } : {}
11102
+ }
11103
+ });
11104
+ }
11105
+ async identify(provider, item, title, year) {
11106
+ const kind = item.kind === "movie" ? "movie" : "series";
11107
+ const key = `${provider.id}:id:${kind}:${foldTitle(title)}:${year ?? 0}`;
11108
+ const known = this.deps.cache.getMatch(key);
11109
+ if (known !== null) return known.found ? known.match : null;
11110
+ const pending = this.matches.get(key);
11111
+ if (pending !== void 0) return pending;
11112
+ const run = (async () => {
11113
+ try {
11114
+ const match = await provider.identify(kind, title, year);
11115
+ this.deps.cache.putMatch(key, match === null ? { found: false } : {
11116
+ found: true,
11117
+ match
11118
+ });
11119
+ return match;
11120
+ } catch (error) {
11121
+ this.failed(provider.id, item.id, error);
11122
+ return null;
11123
+ }
11124
+ })();
11125
+ this.matches.set(key, run);
11126
+ return run;
11127
+ }
11128
+ async episodesOf(provider, item, match) {
11129
+ const key = `${provider.id}:eps:${match.remoteId}`;
11130
+ const known = this.deps.cache.getEpisodes(key);
11131
+ if (known !== null) return known.episodes;
11132
+ try {
11133
+ const episodes = await provider.episodes(match);
11134
+ this.deps.cache.putEpisodes(key, { episodes: [...episodes] });
11135
+ return episodes;
11136
+ } catch (error) {
11137
+ this.failed(provider.id, item.id, error);
11138
+ return [];
11139
+ }
11140
+ }
11141
+ async onlineLayer(provider, item, acc, resolved) {
11142
+ if (item.kind !== "episode") {
11143
+ const match = await this.identify(provider, item, acc.title ?? item.title, acc.year ?? item.year);
11144
+ this.seriesMatch.set(`${provider.id}:${item.id}`, match);
11145
+ if (match === null) return NO_LOCAL;
11146
+ return {
11147
+ ...NO_LOCAL,
11148
+ title: match.title,
11149
+ year: match.year,
11150
+ overview: match.overview,
11151
+ tvdbId: match.tvdbId,
11152
+ tmdbId: match.tmdbId,
11153
+ imdbId: match.imdbId,
11154
+ poster: match.poster,
11155
+ fanart: match.fanart
11156
+ };
11157
+ }
11158
+ const parent = item.parentId === null ? void 0 : resolved.get(item.parentId);
11159
+ if (parent === void 0 || item.seasonNumber === null || item.episodeNumber === null) return NO_LOCAL;
11160
+ const known = this.seriesMatch.get(`${provider.id}:${parent.id}`);
11161
+ const match = known !== void 0 ? known : await this.identify(provider, parent, parent.title, parent.year);
11162
+ if (match === null) return NO_LOCAL;
11163
+ const found = (await this.episodesOf(provider, item, match)).find((entry) => entry.season === item.seasonNumber && entry.episode === item.episodeNumber);
11164
+ if (found === void 0) return NO_LOCAL;
11165
+ return {
11166
+ ...NO_LOCAL,
11167
+ title: found.title,
11168
+ overview: found.overview,
11169
+ poster: found.still
11170
+ };
11171
+ }
11172
+ canAsk(provider, item) {
11173
+ return provider.kinds.includes(item.kind === "movie" ? "movie" : "series");
11174
+ }
11175
+ needsOnline(item, acc) {
11176
+ if (item.kind === "episode") return acc.overview === null || acc.poster === null || item.titlePlaceholder && acc.title === null;
11177
+ return acc.overview === null || acc.poster === null;
11178
+ }
11179
+ async localLayer(item, firstEpisodeFile) {
11180
+ const { reader } = this.deps;
11181
+ if (item.kind === "series") {
11182
+ const file = firstEpisodeFile.get(item.id);
11183
+ return file === void 0 ? NO_LOCAL : localSeries(reader, seriesDirOf(file));
11184
+ }
11185
+ if (item.filePath === null) return NO_LOCAL;
11186
+ return item.kind === "movie" ? localMovie(reader, item.filePath) : localEpisode(reader, item.filePath);
11187
+ }
11188
+ async resolve(item, resolved, firstEpisodeFile) {
11189
+ let acc = NO_LOCAL;
11190
+ for (const step of this.steps) if (step === "local") acc = fill(acc, await this.localLayer(item, firstEpisodeFile));
11191
+ else if (step === "arr") acc = fill(acc, arrLayer(item));
11192
+ else {
11193
+ const provider = this.provider(step);
11194
+ if (provider !== null && this.canAsk(provider, item) && this.needsOnline(item, acc)) acc = fill(acc, await this.onlineLayer(provider, item, acc, resolved));
11195
+ }
11196
+ acc = fill(acc, fileLayer(item));
11197
+ const title = acc.title ?? item.title;
11198
+ return {
11199
+ ...item,
11200
+ title,
11201
+ sortTitle: sortKey(title),
11202
+ titleFold: foldTitle(title),
11203
+ year: acc.year,
11204
+ overview: acc.overview,
11205
+ tvdbId: acc.tvdbId,
11206
+ tmdbId: acc.tmdbId,
11207
+ imdbId: acc.imdbId,
11208
+ posterSource: acc.poster,
11209
+ fanartSource: acc.fanart,
11210
+ seasonNumber: item.seasonNumber ?? acc.season,
11211
+ episodeNumber: item.episodeNumber ?? acc.episode
11212
+ };
11213
+ }
11214
+ };
11215
+ /**
11216
+ * Resolve every item's metadata per field, first answer wins, in the order of `steps`
11217
+ * (default: sidecar files, the arr app, online providers) and the file name last (D1125).
11218
+ * Series and movies go first so an episode finds its show already identified.
11219
+ */
11220
+ async function enrichItems(items, steps, deps) {
11221
+ const firstEpisodeFile = /* @__PURE__ */ new Map();
11222
+ for (const item of items) if (item.kind === "episode" && item.parentId !== null && item.filePath !== null) {
11223
+ if (!firstEpisodeFile.has(item.parentId)) firstEpisodeFile.set(item.parentId, item.filePath);
11224
+ }
11225
+ const enricher = new Enricher(steps, deps);
11226
+ const resolved = /* @__PURE__ */ new Map();
11227
+ const ordered = [...items.filter((item) => item.kind !== "episode"), ...items.filter((item) => item.kind === "episode")];
11228
+ for (const item of ordered) {
11229
+ resolved.set(item.id, await enricher.resolve(item, resolved, firstEpisodeFile));
11230
+ await deps.checkpoint?.();
11231
+ }
11232
+ return items.map((item) => resolved.get(item.id) ?? item);
11233
+ }
11234
+ //#endregion
11235
+ //#region src/new-item.ts
11236
+ function newItem(base) {
10271
11237
  return {
10272
11238
  parentId: null,
10273
11239
  sortTitle: sortKey(base.title),
@@ -10283,14 +11249,159 @@ function row(base) {
10283
11249
  fanartSource: null,
10284
11250
  filePath: null,
10285
11251
  addedHint: null,
11252
+ titlePlaceholder: false,
10286
11253
  ...base
10287
11254
  };
10288
11255
  }
11256
+ //#endregion
11257
+ //#region src/folder-items.ts
11258
+ var FOLDER = "folder";
11259
+ /** `1x02`, `E02`, `Episode 2`, a bare `02 - Title`: only read inside a season folder. */
11260
+ function loneEpisodeNumber(baseName) {
11261
+ const match = /^(?:s\d{1,2})?[\s._-]*(?:e|ep|episode)[\s._-]*(\d{1,3})\b/i.exec(baseName) ?? /^(\d{1,3})(?:[\s._-]|$)/.exec(baseName);
11262
+ return match?.[1] === void 0 ? null : Number(match[1]);
11263
+ }
11264
+ function crossFormat(baseName) {
11265
+ const match = /(?:^|[\s._-])(\d{1,2})x(\d{2,3})(?:[\s._-]|$)/i.exec(baseName);
11266
+ return match?.[1] === void 0 || match[2] === void 0 ? null : {
11267
+ season: Number(match[1]),
11268
+ episode: Number(match[2])
11269
+ };
11270
+ }
11271
+ function within(root, dir) {
11272
+ const rel = (0, node_path.relative)(root, dir);
11273
+ return rel === "" || !rel.startsWith("..") && !rel.startsWith(node_path.sep);
11274
+ }
11275
+ async function tvshowDir(root, start, reader) {
11276
+ for (let dir = start; within(root, dir); dir = (0, node_path.dirname)(dir)) {
11277
+ if ((await reader.list(dir)).has("tvshow.nfo")) return dir;
11278
+ if (dir === root || (0, node_path.dirname)(dir) === dir) break;
11279
+ }
11280
+ return null;
11281
+ }
11282
+ async function classify(root, path, reader) {
11283
+ const parent = (0, node_path.dirname)(path);
11284
+ const file = (0, node_path.basename)(path);
11285
+ const stem = file.replace(/\.[A-Za-z0-9]+$/, "");
11286
+ const guess = guessFromFilename(file, "");
11287
+ const folderSeason = seasonOfFolder((0, node_path.basename)(parent));
11288
+ const cross = crossFormat(stem);
11289
+ const nfoDir = await tvshowDir(root, parent, reader);
11290
+ const season = guess.seasonNumber ?? cross?.season ?? folderSeason;
11291
+ let episode = guess.episodeNumber ?? cross?.episode ?? null;
11292
+ if (!(guess.kind === "episode" || cross !== null) && !(folderSeason !== null || nfoDir !== null)) return {
11293
+ path,
11294
+ kind: "movie",
11295
+ seriesDir: null,
11296
+ namedTitle: guess.title,
11297
+ season: null,
11298
+ episode: null,
11299
+ year: guess.year
11300
+ };
11301
+ if (episode === null) episode = loneEpisodeNumber(stem);
11302
+ let seriesDir = nfoDir;
11303
+ if (seriesDir === null) {
11304
+ if (folderSeason !== null) seriesDir = (0, node_path.dirname)(parent);
11305
+ else if (parent !== root) seriesDir = parent;
11306
+ }
11307
+ const prefix = guess.kind === "episode" ? guess.title : "";
11308
+ return {
11309
+ path,
11310
+ kind: "episode",
11311
+ seriesDir,
11312
+ namedTitle: prefix,
11313
+ season,
11314
+ episode,
11315
+ year: null
11316
+ };
11317
+ }
11318
+ /** The most frequent non-empty title, ties by name: the same set of files names a show the same way every scan. */
11319
+ function commonTitle(titles) {
11320
+ const counts = /* @__PURE__ */ new Map();
11321
+ for (const title of titles) if (title !== "") counts.set(title, (counts.get(title) ?? 0) + 1);
11322
+ return [...counts].toSorted((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]?.[0] ?? null;
11323
+ }
11324
+ /** A year-bearing folder (`Gamma (2019)`) names a movie better than a bare file name does. */
11325
+ function movieNamed(root, entry) {
11326
+ const folder = (0, node_path.dirname)(entry.path);
11327
+ if (folder !== root && within(root, folder)) {
11328
+ const named = guessFromFilename((0, node_path.basename)(folder), "");
11329
+ if (named.year !== null && named.title !== "" && (entry.year === null || entry.namedTitle === "")) return {
11330
+ title: named.title,
11331
+ year: named.year
11332
+ };
11333
+ }
11334
+ return {
11335
+ title: entry.namedTitle,
11336
+ year: entry.year
11337
+ };
11338
+ }
11339
+ /**
11340
+ * Group the video files of one folder root into series (by their show folder), seasons and
11341
+ * movies (one per file). Ids keep the scheme of the first folder source: a movie is
11342
+ * `folder:m:<hash of path>`, a show `folder:s:<hash of its folded title>`, an episode
11343
+ * `folder:e:<hash of path>`.
11344
+ */
11345
+ async function folderItems(root, paths, reader) {
11346
+ const classified = await Promise.all(paths.map((path) => classify(root, path, reader)));
11347
+ const out = [];
11348
+ const groups = /* @__PURE__ */ new Map();
11349
+ for (const entry of classified) {
11350
+ if (entry.kind === "movie") {
11351
+ const named = movieNamed(root, entry);
11352
+ const title = named.title === "" ? (0, node_path.basename)(entry.path).replace(/\.[^.]+$/, "") : named.title;
11353
+ out.push(newItem({
11354
+ id: itemId(FOLDER, "m", hashKey(entry.path)),
11355
+ kind: "movie",
11356
+ title,
11357
+ sourceId: FOLDER,
11358
+ topLevel: true,
11359
+ year: named.year,
11360
+ filePath: entry.path
11361
+ }));
11362
+ continue;
11363
+ }
11364
+ const key = entry.seriesDir ?? `name:${foldTitle(entry.namedTitle)}`;
11365
+ const group = groups.get(key);
11366
+ if (group === void 0) groups.set(key, [entry]);
11367
+ else group.push(entry);
11368
+ }
11369
+ for (const [key, members] of groups) {
11370
+ const seriesDir = key.startsWith("name:") ? null : key;
11371
+ const folderName = seriesDir === null || seriesDir === root ? null : (0, node_path.basename)(seriesDir);
11372
+ const folderGuess = folderName === null ? null : guessFromFilename(folderName, "");
11373
+ 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));
11374
+ const seriesId = itemId(FOLDER, "s", hashKey(foldTitle(title)));
11375
+ out.push(newItem({
11376
+ id: seriesId,
11377
+ kind: "series",
11378
+ title,
11379
+ sourceId: FOLDER,
11380
+ topLevel: true,
11381
+ year: folderGuess?.year ?? null
11382
+ }));
11383
+ for (const entry of members.toSorted((a, b) => a.path.localeCompare(b.path))) out.push(newItem({
11384
+ id: itemId(FOLDER, "e", hashKey(entry.path)),
11385
+ kind: "episode",
11386
+ title: `${title} S${entry.season ?? 0}E${entry.episode ?? 0}`,
11387
+ titlePlaceholder: true,
11388
+ sourceId: FOLDER,
11389
+ topLevel: false,
11390
+ parentId: seriesId,
11391
+ seasonNumber: entry.season,
11392
+ episodeNumber: entry.episode,
11393
+ filePath: entry.path
11394
+ }));
11395
+ }
11396
+ return out;
11397
+ }
11398
+ var ARR_SERIES = "arr-series";
11399
+ var ARR_MOVIES = "arr-movies";
10289
11400
  function seriesItems(series, source) {
10290
11401
  const out = [];
10291
11402
  for (const show of series) {
10292
11403
  const seriesKey = itemId(ARR_SERIES, "s", show.id);
10293
- out.push(row({
11404
+ out.push(newItem({
10294
11405
  id: seriesKey,
10295
11406
  kind: "series",
10296
11407
  title: show.title,
@@ -10305,13 +11416,15 @@ function seriesItems(series, source) {
10305
11416
  fanartSource: show.fanart,
10306
11417
  addedHint: show.addedAt
10307
11418
  }));
10308
- for (const episode of show.episodes) out.push(row({
11419
+ for (const episode of show.episodes) out.push(newItem({
10309
11420
  id: itemId(ARR_SERIES, "e", episode.id),
10310
11421
  kind: "episode",
10311
11422
  title: episode.title === "" ? `Episode ${episode.episodeNumber}` : episode.title,
11423
+ titlePlaceholder: episode.title === "",
10312
11424
  sourceId: ARR_SERIES,
10313
11425
  topLevel: false,
10314
11426
  parentId: seriesKey,
11427
+ posterSource: episode.still,
10315
11428
  seasonNumber: episode.seasonNumber,
10316
11429
  episodeNumber: episode.episodeNumber,
10317
11430
  filePath: episode.path === null ? null : mapPath(episode.path, source.pathFrom, source.pathTo),
@@ -10321,7 +11434,7 @@ function seriesItems(series, source) {
10321
11434
  return out;
10322
11435
  }
10323
11436
  function movieItems(movies, source) {
10324
- return movies.map((movie) => row({
11437
+ return movies.map((movie) => newItem({
10325
11438
  id: itemId(ARR_MOVIES, "m", movie.id),
10326
11439
  kind: "movie",
10327
11440
  title: movie.title,
@@ -10355,6 +11468,7 @@ async function scanLibrary(deps, sources) {
10355
11468
  if (parsed.success) existingItems.set(parsed.data.id, parsed.data);
10356
11469
  }
10357
11470
  const harvests = [];
11471
+ const reader = deps.reader ?? createLocalReader();
10358
11472
  const countOf = (sourceId) => [...existingItems.values()].filter((item) => item.sourceId === sourceId).length;
10359
11473
  const harvest = async (sourceId, read) => {
10360
11474
  try {
@@ -10406,14 +11520,43 @@ async function scanLibrary(deps, sources) {
10406
11520
  reason: dir.reason
10407
11521
  } });
10408
11522
  }
10409
- for (const file of walked.files) {
10410
- if (claimed.has(file.path)) continue;
10411
- found.push(...folderItems(file.path));
10412
- }
11523
+ found.push(...await folderItems(root, walked.files.map((file) => file.path).filter((path) => !claimed.has(path)), reader));
10413
11524
  }
10414
11525
  if (!allComplete) throw new Error("a folder root could not be read");
10415
11526
  return dedupe(found);
10416
11527
  });
11528
+ const cache = await MatchCache.load(db, deps.now);
11529
+ const saveMatches = async (atLeast) => {
11530
+ if (cache.pending === 0 || cache.pending < atLeast) return;
11531
+ try {
11532
+ await cache.flush(db);
11533
+ } catch (error) {
11534
+ logger.warn("metadata matches could not be saved: they are asked for again next scan", { meta: { error: error instanceof Error ? error.message : String(error) } });
11535
+ }
11536
+ };
11537
+ for (const [index, entry] of harvests.entries()) {
11538
+ try {
11539
+ const items = await enrichItems(entry.items, sources.metadataSteps ?? DEFAULT_STEPS, {
11540
+ reader,
11541
+ providers: deps.providers ?? [],
11542
+ cache,
11543
+ logger,
11544
+ checkpoint: () => saveMatches(20)
11545
+ });
11546
+ harvests[index] = {
11547
+ ...entry,
11548
+ items
11549
+ };
11550
+ } catch (error) {
11551
+ const message = error instanceof Error ? error.message : String(error);
11552
+ errors.push(`${entry.sourceId} metadata: ${message}`);
11553
+ logger.error("metadata step failed: the items keep what their source said", { meta: {
11554
+ sourceId: entry.sourceId,
11555
+ error: message
11556
+ } });
11557
+ }
11558
+ await saveMatches(1);
11559
+ }
10417
11560
  const writes = [];
10418
11561
  const seenIds = /* @__PURE__ */ new Set();
10419
11562
  for (const entry of harvests) for (const item of entry.items) {
@@ -10424,7 +11567,7 @@ async function scanLibrary(deps, sources) {
10424
11567
  }
10425
11568
  seenIds.add(item.id);
10426
11569
  const previous = existingItems.get(item.id);
10427
- const { addedHint, ...fields } = item;
11570
+ const { addedHint, titlePlaceholder: _placeholder, ...fields } = item;
10428
11571
  writes.push({
10429
11572
  ...fields,
10430
11573
  addedAt: previous?.addedAt ?? addedHint ?? startedAt,
@@ -10525,38 +11668,6 @@ function dedupe(items) {
10525
11668
  for (const item of items) if (!seen.has(item.id)) seen.set(item.id, item);
10526
11669
  return [...seen.values()];
10527
11670
  }
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
11671
  //#endregion
10561
11672
  //#region src/scan-controller.ts
10562
11673
  /** Runs scans one at a time: a second request while one runs is answered "already running", never queued. */
@@ -10651,6 +11762,30 @@ var BaseUrlSchema = string().transform((value, ctx) => {
10651
11762
  }
10652
11763
  return normalized;
10653
11764
  });
11765
+ /** The metadata steps, in the order they answer by default: sidecar files, the arr app, then TVmaze. */
11766
+ var METADATA_STEPS = [
11767
+ "local",
11768
+ "arr",
11769
+ "tvmaze"
11770
+ ];
11771
+ var DEFAULT_METADATA_ORDER = METADATA_STEPS;
11772
+ function isStep(value) {
11773
+ return METADATA_STEPS.some((step) => step === value);
11774
+ }
11775
+ /** The steps that are on, in the operator's order; a name left out of the list is off, an unknown one is ignored. */
11776
+ function resolveMetadataSteps(settings) {
11777
+ const on = {
11778
+ local: settings.metadataLocalEnabled,
11779
+ arr: settings.metadataArrEnabled,
11780
+ tvmaze: settings.metadataTvmazeEnabled
11781
+ };
11782
+ const out = [];
11783
+ for (const name of settings.metadataOrder.split(/[\s,]+/)) {
11784
+ const step = name.toLowerCase();
11785
+ if (isStep(step) && on[step] && !out.includes(step)) out.push(step);
11786
+ }
11787
+ return out;
11788
+ }
10654
11789
  var MediaLibrarySettingsSchema = object({
10655
11790
  seriesArrUrl: BaseUrlSchema.default(""),
10656
11791
  seriesArrKey: string().default(""),
@@ -10663,7 +11798,12 @@ var MediaLibrarySettingsSchema = object({
10663
11798
  moviesPathTo: string().default(""),
10664
11799
  /** Plain folders walked for files the arr apps do not know, one absolute path per line. */
10665
11800
  folderRoots: string().default(""),
10666
- rescanMinutes: number().int().min(0).default(60)
11801
+ rescanMinutes: number().int().min(0).default(60),
11802
+ /** The order the metadata steps are asked in, comma separated; the first answer to a field wins (D1125). */
11803
+ metadataOrder: string().default(DEFAULT_METADATA_ORDER.join(",")),
11804
+ metadataLocalEnabled: boolean().default(true),
11805
+ metadataArrEnabled: boolean().default(true),
11806
+ metadataTvmazeEnabled: boolean().default(true)
10667
11807
  });
10668
11808
  /** A source is on only when both its URL and key are set; a half-filled one is off, not guessed. */
10669
11809
  function resolveSources(settings) {
@@ -10676,7 +11816,8 @@ function resolveSources(settings) {
10676
11816
  return {
10677
11817
  series: pick(settings.seriesArrUrl, settings.seriesArrKey, settings.seriesPathFrom, settings.seriesPathTo),
10678
11818
  movies: pick(settings.moviesArrUrl, settings.moviesArrKey, settings.moviesPathFrom, settings.moviesPathTo),
10679
- folderRoots: settings.folderRoots.split("\n").map((line) => line.trim()).filter((line) => line !== "")
11819
+ folderRoots: settings.folderRoots.split("\n").map((line) => line.trim()).filter((line) => line !== ""),
11820
+ metadataSteps: resolveMetadataSteps(settings)
10680
11821
  };
10681
11822
  }
10682
11823
  var MEDIA_LIBRARY_CLUSTER_SCHEMA = { sections: [
@@ -10774,6 +11915,43 @@ var MEDIA_LIBRARY_CLUSTER_SCHEMA = { sections: [
10774
11915
  descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
10775
11916
  min: 0
10776
11917
  }]
11918
+ },
11919
+ {
11920
+ id: "metadata",
11921
+ title: "Metadata",
11922
+ titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.title",
11923
+ fields: [
11924
+ {
11925
+ type: "text",
11926
+ key: "metadataOrder",
11927
+ label: "Metadata order",
11928
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataOrder.label",
11929
+ description: "Comma separated, first answer to a field wins: local (files next to the media), arr, tvmaze. A name left out is off.",
11930
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataOrder.description"
11931
+ },
11932
+ {
11933
+ type: "boolean",
11934
+ key: "metadataLocalEnabled",
11935
+ label: "Read local files",
11936
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataLocalEnabled.label",
11937
+ description: "NFO files and posters next to the media.",
11938
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataLocalEnabled.description"
11939
+ },
11940
+ {
11941
+ type: "boolean",
11942
+ key: "metadataArrEnabled",
11943
+ label: "Use Sonarr and Radarr",
11944
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataArrEnabled.label"
11945
+ },
11946
+ {
11947
+ type: "boolean",
11948
+ key: "metadataTvmazeEnabled",
11949
+ label: "Look up series on TVmaze",
11950
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataTvmazeEnabled.label",
11951
+ description: "Fills what the other steps left empty. Needs no account; sends the series title to TVmaze.",
11952
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_metadata.metadataTvmazeEnabled.description"
11953
+ }
11954
+ ]
10777
11955
  }
10778
11956
  ] };
10779
11957
  //#endregion
@@ -10809,6 +11987,7 @@ var MediaLibraryAddon = class extends BaseAddon {
10809
11987
  const db = settingsStoreDb(ctx.api.settingsStore);
10810
11988
  const store = new LibraryStore(db, logger);
10811
11989
  await store.init();
11990
+ const ffmpeg = await ctx.deps.ensureFfmpeg();
10812
11991
  const scans = new ScanController({
10813
11992
  db,
10814
11993
  logger,
@@ -10825,7 +12004,8 @@ var MediaLibraryAddon = class extends BaseAddon {
10825
12004
  return null;
10826
12005
  }
10827
12006
  },
10828
- probe: createFfmpegProber(await ctx.deps.ensureFfmpeg()),
12007
+ probe: createFfmpegProber(ffmpeg),
12008
+ providers: [createTvmazeProvider({ fetch: httpRemoteFetch })],
10829
12009
  now: () => Date.now()
10830
12010
  }, async () => resolveSources(await this.readSettings()), logger);
10831
12011
  this.scans = scans;
@@ -10839,7 +12019,7 @@ var MediaLibraryAddon = class extends BaseAddon {
10839
12019
  };
10840
12020
  await ctx.dataPlane?.serve({
10841
12021
  prefix: FILE_PLANE_PREFIX,
10842
- access: "authenticated",
12022
+ access: "viewer",
10843
12023
  handler: createFilePlaneHandler({
10844
12024
  lookup: async (itemId) => (await store.playableFile(itemId))?.path ?? null,
10845
12025
  roots,
@@ -10848,7 +12028,7 @@ var MediaLibraryAddon = class extends BaseAddon {
10848
12028
  });
10849
12029
  await ctx.dataPlane?.serve({
10850
12030
  prefix: "img",
10851
- access: "authenticated",
12031
+ access: "viewer",
10852
12032
  handler: createImagePlaneHandler({
10853
12033
  source: (itemId, which) => store.imageSource(itemId, which),
10854
12034
  arrSource: async (sourceId) => {
@@ -10857,6 +12037,9 @@ var MediaLibraryAddon = class extends BaseAddon {
10857
12037
  },
10858
12038
  cacheDir: (0, node_path.join)(ctx.dataDir, IMG_CACHE_DIR),
10859
12039
  fetchImage: httpImageFetch,
12040
+ fetchRemote: httpRemoteFetch,
12041
+ roots,
12042
+ grabFrame: createFfmpegFrameGrabber(ffmpeg),
10860
12043
  logger
10861
12044
  })
10862
12045
  });