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