@dominevo/addon-media-library 0.1.7 → 0.1.9

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.
@@ -8811,7 +8811,12 @@ var MediaItemSummarySchema = /* @__PURE__ */ object({
8811
8811
  /** False when the catalogue lists it but no playable file is on disk. */
8812
8812
  playable: /* @__PURE__ */ boolean(),
8813
8813
  /** The caller's progress; `null` when they have none. Absent on a catalogue-only row (series). */
8814
- progress: /* @__PURE__ */ MediaProgressSchema.nullable()
8814
+ progress: /* @__PURE__ */ MediaProgressSchema.nullable(),
8815
+ /**
8816
+ * The caller's watchlist state, on series and movie rows (list, get and search). Absent on an
8817
+ * episode, which cannot be watchlisted.
8818
+ */
8819
+ watchlisted: /* @__PURE__ */ boolean().optional()
8815
8820
  });
8816
8821
  /** An episode of a season list: the summary plus its plot, read in the same query. */
8817
8822
  var MediaEpisodeSummarySchema = /* @__PURE__ */ MediaItemSummarySchema.extend({ overview: /* @__PURE__ */ string().nullable() });
@@ -8829,6 +8834,30 @@ var LibraryFileInfoSchema = /* @__PURE__ */ object({
8829
8834
  /** False while the file is catalogued but not probed yet, or the probe failed. */
8830
8835
  probed: /* @__PURE__ */ boolean()
8831
8836
  });
8837
+ /** One chapter of a file: seconds from the start; `title` is `null` when the file names none. */
8838
+ var MediaChapterSchema = /* @__PURE__ */ object({
8839
+ startSec: /* @__PURE__ */ number().nonnegative(),
8840
+ endSec: /* @__PURE__ */ number().nonnegative(),
8841
+ title: /* @__PURE__ */ string().nullable()
8842
+ });
8843
+ /**
8844
+ * A subtitle file next to the video. `path` is the relative hub path that serves it as WebVTT;
8845
+ * append `?offsetMs=<signed integer, at most 600000 either way>` to shift every cue (the subtitle delay).
8846
+ */
8847
+ var ExternalSubtitleSchema = /* @__PURE__ */ object({
8848
+ id: /* @__PURE__ */ string(),
8849
+ language: /* @__PURE__ */ string().nullable(),
8850
+ forced: /* @__PURE__ */ boolean(),
8851
+ /** The format of the file on disk; the served body is always WebVTT. */
8852
+ format: /* @__PURE__ */ _enum([
8853
+ "srt",
8854
+ "ass",
8855
+ "ssa",
8856
+ "vtt"
8857
+ ]),
8858
+ label: /* @__PURE__ */ string(),
8859
+ path: /* @__PURE__ */ string()
8860
+ });
8832
8861
  var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8833
8862
  overview: /* @__PURE__ */ string().nullable(),
8834
8863
  ids: /* @__PURE__ */ object({
@@ -8839,7 +8868,46 @@ var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8839
8868
  fanartPath: /* @__PURE__ */ string().nullable(),
8840
8869
  /** Relative hub path that direct-plays the file, with HTTP Range. `null` when not playable. */
8841
8870
  playPath: /* @__PURE__ */ string().nullable(),
8842
- file: /* @__PURE__ */ LibraryFileInfoSchema.nullable()
8871
+ file: /* @__PURE__ */ LibraryFileInfoSchema.nullable(),
8872
+ /** The file's chapters in order; empty when it has none or it is not probed yet. */
8873
+ chapters: /* @__PURE__ */ array(MediaChapterSchema).readonly(),
8874
+ /** Sidecar subtitle files found next to the video; empty when none. */
8875
+ externalSubtitles: /* @__PURE__ */ array(ExternalSubtitleSchema).readonly()
8876
+ });
8877
+ /**
8878
+ * A person of an item's credits. `photoPath` is an image-plane handle relative to the hub origin
8879
+ * (the same plane that serves posters), `null` when the source has no photo: a provider's own URL
8880
+ * never leaves the addon.
8881
+ */
8882
+ var MediaPersonSchema = /* @__PURE__ */ object({
8883
+ /** The metadata source's id of the person. */
8884
+ id: /* @__PURE__ */ number().int(),
8885
+ name: /* @__PURE__ */ string(),
8886
+ photoPath: /* @__PURE__ */ string().nullable()
8887
+ });
8888
+ var MediaCastMemberSchema = /* @__PURE__ */ MediaPersonSchema.extend({
8889
+ /** The role played; `null` when the source names none. */
8890
+ character: /* @__PURE__ */ string().nullable(),
8891
+ /** Billing order, 0 first. */
8892
+ order: /* @__PURE__ */ number().int().nonnegative()
8893
+ });
8894
+ /**
8895
+ * What the metadata source holds about an item beyond its plot. Nothing fetched yet answers empty
8896
+ * arrays and `null`s; a failed re-fetch never replaces what is stored.
8897
+ */
8898
+ var MediaItemDetailsSchema = /* @__PURE__ */ object({
8899
+ itemId: /* @__PURE__ */ string(),
8900
+ genres: /* @__PURE__ */ array(/* @__PURE__ */ string()).readonly(),
8901
+ /** `null` when the source does not know it. */
8902
+ runtimeMinutes: /* @__PURE__ */ number().int().positive().nullable(),
8903
+ /** The age rating for the server's region (`PG-13`, `TV-MA`, `12`), or `null`. */
8904
+ certification: /* @__PURE__ */ string().nullable(),
8905
+ creators: /* @__PURE__ */ array(MediaPersonSchema).readonly(),
8906
+ directors: /* @__PURE__ */ array(MediaPersonSchema).readonly(),
8907
+ writers: /* @__PURE__ */ array(MediaPersonSchema).readonly(),
8908
+ cast: /* @__PURE__ */ array(MediaCastMemberSchema).readonly(),
8909
+ /** Episodes only; empty on a series or a movie. */
8910
+ guestStars: /* @__PURE__ */ array(MediaCastMemberSchema).readonly()
8843
8911
  });
8844
8912
  var MediaSeasonSchema = /* @__PURE__ */ object({
8845
8913
  seasonNumber: /* @__PURE__ */ number().int(),
@@ -8908,6 +8976,24 @@ var mediaLibraryCapability = {
8908
8976
  limit: /* @__PURE__ */ number().int().positive().max(100).optional(),
8909
8977
  language: LanguageInputSchema
8910
8978
  }), /* @__PURE__ */ array(MediaItemSummarySchema).readonly(), { caller: "required" }),
8979
+ /** The caller's series and movies they watchlisted, the latest added first. */
8980
+ listWatchlist: /* @__PURE__ */ method(PageInputSchema, MediaItemPageSchema, { caller: "required" }),
8981
+ /**
8982
+ * Put a series or a movie on the caller's watchlist, or take it off. Idempotent: the answer is the
8983
+ * state now. An episode is refused (`watchlist-kind`).
8984
+ */
8985
+ setWatchlisted: /* @__PURE__ */ method(/* @__PURE__ */ object({
8986
+ itemId: /* @__PURE__ */ string().min(1),
8987
+ on: /* @__PURE__ */ boolean()
8988
+ }), /* @__PURE__ */ object({ on: /* @__PURE__ */ boolean() }), {
8989
+ kind: "mutation",
8990
+ caller: "required"
8991
+ }),
8992
+ /** Genres, runtime, rating, crew and cast of one item; `null` when the id is unknown. */
8993
+ getItemDetails: /* @__PURE__ */ method(/* @__PURE__ */ object({
8994
+ itemId: /* @__PURE__ */ string().min(1),
8995
+ language: LanguageInputSchema
8996
+ }), /* @__PURE__ */ MediaItemDetailsSchema.nullable(), { caller: "required" }),
8911
8997
  /** The caller's progress in one item; `null` when they have none. */
8912
8998
  getProgress: /* @__PURE__ */ method(/* @__PURE__ */ object({ itemId: /* @__PURE__ */ string().min(1) }), /* @__PURE__ */ MediaProgressSchema.nullable(), { caller: "required" }),
8913
8999
  /**
@@ -9849,7 +9935,7 @@ function pump(path, start, end, res, stallMs) {
9849
9935
  res.on("close", () => settle(sent > 0 && res.writableFinished ? "finished" : "client-closed"));
9850
9936
  });
9851
9937
  }
9852
- function reject(res, status, extra) {
9938
+ function reject$1(res, status, extra) {
9853
9939
  res.writeHead(status, {
9854
9940
  "Content-Length": 0,
9855
9941
  ...extra
@@ -9861,18 +9947,18 @@ function createFilePlaneHandler(deps) {
9861
9947
  const stallMs = deps.stallMs ?? 3e4;
9862
9948
  return async (req, res) => {
9863
9949
  const method = req.method ?? "GET";
9864
- if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
9950
+ if (method !== "GET" && method !== "HEAD") return reject$1(res, 405, { Allow: "GET, HEAD" });
9865
9951
  const raw = (req.url ?? "/").split("?")[0] ?? "/";
9866
9952
  let itemId;
9867
9953
  try {
9868
9954
  itemId = decodeURIComponent(raw.replace(/^\//, ""));
9869
9955
  } catch {
9870
9956
  deps.logger.warn("file request refused: bad escape", { meta: { reason: "bad-id" } });
9871
- return reject(res, 404);
9957
+ return reject$1(res, 404);
9872
9958
  }
9873
9959
  if (!isItemId(itemId)) {
9874
9960
  deps.logger.warn("file request refused: not an item id", { meta: { reason: "bad-id" } });
9875
- return reject(res, 404);
9961
+ return reject$1(res, 404);
9876
9962
  }
9877
9963
  const tags = { itemId };
9878
9964
  const catalogued = await deps.lookup(itemId);
@@ -9881,7 +9967,7 @@ function createFilePlaneHandler(deps) {
9881
9967
  tags,
9882
9968
  meta: { reason: "not-catalogued" }
9883
9969
  });
9884
- return reject(res, 404);
9970
+ return reject$1(res, 404);
9885
9971
  }
9886
9972
  const path = await resolveServable(catalogued, await deps.roots());
9887
9973
  if (path === null) {
@@ -9889,7 +9975,7 @@ function createFilePlaneHandler(deps) {
9889
9975
  tags,
9890
9976
  meta: { reason: "outside-roots" }
9891
9977
  });
9892
- return reject(res, 404);
9978
+ return reject$1(res, 404);
9893
9979
  }
9894
9980
  let size;
9895
9981
  try {
@@ -9899,7 +9985,7 @@ function createFilePlaneHandler(deps) {
9899
9985
  tags,
9900
9986
  meta: { reason: "gone" }
9901
9987
  });
9902
- return reject(res, 404);
9988
+ return reject$1(res, 404);
9903
9989
  }
9904
9990
  const range = parseRange(headerOf(req.headers.range), size);
9905
9991
  if (range.kind === "unsatisfiable") {
@@ -9910,7 +9996,7 @@ function createFilePlaneHandler(deps) {
9910
9996
  size
9911
9997
  }
9912
9998
  });
9913
- return reject(res, 416, { "Content-Range": `bytes */${size}` });
9999
+ return reject$1(res, 416, { "Content-Range": `bytes */${size}` });
9914
10000
  }
9915
10001
  const start = range.kind === "range" ? range.start : 0;
9916
10002
  const end = range.kind === "range" ? range.end : size - 1;
@@ -9944,6 +10030,198 @@ function createFilePlaneHandler(deps) {
9944
10030
  function headerOf(value) {
9945
10031
  return Array.isArray(value) ? value[0] : value;
9946
10032
  }
10033
+ var TIMING = /(\d{1,2}:)?(\d{1,2}):(\d{2})[,.](\d{1,3})\s*-->\s*(\d{1,2}:)?(\d{1,2}):(\d{2})[,.](\d{1,3})/;
10034
+ function clock(hours, minutes, seconds, fraction) {
10035
+ return (((hours === void 0 ? 0 : Number(hours.slice(0, -1))) * 60 + Number(minutes)) * 60 + Number(seconds)) * 1e3 + Number(fraction.padEnd(3, "0"));
10036
+ }
10037
+ /** SRT and VTT share one cue shape: an optional id line, a timing line, text up to a blank line. */
10038
+ function parseTimedText(text) {
10039
+ const cues = [];
10040
+ for (const block of text.split(/\n{2,}/)) {
10041
+ const lines = block.split("\n");
10042
+ const at = lines.findIndex((line) => TIMING.test(line));
10043
+ if (at < 0) continue;
10044
+ const match = TIMING.exec(lines[at] ?? "");
10045
+ if (match === null) continue;
10046
+ const [, h1, m1, s1, f1, h2, m2, s2, f2] = match;
10047
+ if (m1 === void 0 || s1 === void 0 || f1 === void 0) continue;
10048
+ if (m2 === void 0 || s2 === void 0 || f2 === void 0) continue;
10049
+ const body = lines.slice(at + 1).join("\n").replace(/\{\\an?\d\}/g, "").trim();
10050
+ if (body === "") continue;
10051
+ cues.push({
10052
+ startMs: clock(h1, m1, s1, f1),
10053
+ endMs: clock(h2, m2, s2, f2),
10054
+ text: body
10055
+ });
10056
+ }
10057
+ return cues;
10058
+ }
10059
+ var ASS_TIME = /^(\d+):(\d{2}):(\d{2})[.:](\d{1,3})$/;
10060
+ function assClock(value) {
10061
+ const match = ASS_TIME.exec(value.trim());
10062
+ if (match === null) return null;
10063
+ const [, h, m, s, f] = match;
10064
+ if (h === void 0 || m === void 0 || s === void 0 || f === void 0) return null;
10065
+ const ms = f.length <= 2 ? Number(f.padEnd(2, "0")) * 10 : Number(f);
10066
+ return (Number(h) * 3600 + Number(m) * 60 + Number(s)) * 1e3 + ms;
10067
+ }
10068
+ /** Dialogue text with the styling dropped: override blocks gone, hard breaks kept. */
10069
+ function assText(raw) {
10070
+ return raw.replace(/\{[^}]*\}/g, "").replace(/\\[Nn]/g, "\n").replace(/\\h/g, " ").trim();
10071
+ }
10072
+ function parseAss(text) {
10073
+ let inEvents = false;
10074
+ let columns = [];
10075
+ const cues = [];
10076
+ for (const line of text.split("\n")) {
10077
+ const trimmed = line.trim();
10078
+ if (/^\[.*\]$/.test(trimmed)) {
10079
+ inEvents = trimmed.toLowerCase() === "[events]";
10080
+ continue;
10081
+ }
10082
+ if (!inEvents) continue;
10083
+ if (/^format:/i.test(trimmed)) {
10084
+ columns = trimmed.slice(trimmed.indexOf(":") + 1).split(",").map((name) => name.trim().toLowerCase());
10085
+ continue;
10086
+ }
10087
+ if (!/^dialogue:/i.test(trimmed)) continue;
10088
+ const startAt = columns.indexOf("start");
10089
+ const endAt = columns.indexOf("end");
10090
+ const textAt = columns.indexOf("text");
10091
+ if (startAt < 0 || endAt < 0 || textAt < 0) continue;
10092
+ const fields = trimmed.slice(trimmed.indexOf(":") + 1).split(",");
10093
+ const head = fields.slice(0, textAt);
10094
+ const rawText = fields.slice(textAt).join(",");
10095
+ if (/\{[^}]*\\p[1-9]/.test(rawText)) continue;
10096
+ const start = assClock(head[startAt] ?? "");
10097
+ const end = assClock(head[endAt] ?? "");
10098
+ const body = assText(rawText);
10099
+ if (start === null || end === null || body === "") continue;
10100
+ cues.push({
10101
+ startMs: start,
10102
+ endMs: end,
10103
+ text: body
10104
+ });
10105
+ }
10106
+ return cues.sort((a, b) => a.startMs - b.startMs);
10107
+ }
10108
+ function stamp(ms) {
10109
+ const total = Math.max(0, Math.round(ms));
10110
+ const pad = (value, width) => String(value).padStart(width, "0");
10111
+ const hours = Math.floor(total / 36e5);
10112
+ const minutes = Math.floor(total % 36e5 / 6e4);
10113
+ const seconds = Math.floor(total % 6e4 / 1e3);
10114
+ return `${pad(hours, 2)}:${pad(minutes, 2)}:${pad(seconds, 2)}.${pad(total % 1e3, 3)}`;
10115
+ }
10116
+ /**
10117
+ * One subtitle file as WebVTT, every cue moved by `offsetMs` (negative = earlier). A cue is clamped at 0
10118
+ * and dropped when nothing of it is left after the shift.
10119
+ */
10120
+ function toWebVtt(source, format, offsetMs = 0) {
10121
+ const text = source.replace(/^/, "").replace(/\r\n?/g, "\n");
10122
+ const cues = format === "ass" || format === "ssa" ? parseAss(text) : parseTimedText(text);
10123
+ const out = ["WEBVTT", ""];
10124
+ for (const cue of cues) {
10125
+ const start = Math.max(0, cue.startMs + offsetMs);
10126
+ const end = Math.max(0, cue.endMs + offsetMs);
10127
+ if (end <= start) continue;
10128
+ out.push(`${stamp(start)} --> ${stamp(end)}`, cue.text, "");
10129
+ }
10130
+ return out.join("\n");
10131
+ }
10132
+ function reject(res, status, extra) {
10133
+ res.writeHead(status, {
10134
+ "Content-Length": 0,
10135
+ ...extra
10136
+ });
10137
+ res.end();
10138
+ }
10139
+ /** `offsetMs` from a query: absent is 0; anything but a bounded signed integer is `null` (refused). */
10140
+ function parseOffsetMs(query) {
10141
+ const raw = new URLSearchParams(query).get("offsetMs");
10142
+ if (raw === null) return 0;
10143
+ if (!/^-?\d{1,7}$/.test(raw)) return null;
10144
+ const value = Number(raw);
10145
+ return Math.abs(value) <= 6e5 ? value : null;
10146
+ }
10147
+ /** The `subtitle` plane: `GET|HEAD /<itemId>/<sidecarId>[?offsetMs=N]` answers one sidecar as WebVTT. */
10148
+ function createSubtitlePlaneHandler(deps) {
10149
+ return async (req, res) => {
10150
+ const method = req.method ?? "GET";
10151
+ if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10152
+ const [rawPath = "/", query = ""] = (req.url ?? "/").split("?");
10153
+ const segments = rawPath.replace(/^\//, "").split("/");
10154
+ let itemId;
10155
+ let sidecar;
10156
+ try {
10157
+ if (segments.length !== 2) return reject(res, 404);
10158
+ itemId = decodeURIComponent(segments[0] ?? "");
10159
+ sidecar = decodeURIComponent(segments[1] ?? "");
10160
+ } catch {
10161
+ return reject(res, 404);
10162
+ }
10163
+ if (!isItemId(itemId)) {
10164
+ deps.logger.warn("subtitle request refused: not an item id", { meta: { reason: "bad-id" } });
10165
+ return reject(res, 404);
10166
+ }
10167
+ const tags = { itemId };
10168
+ const offsetMs = parseOffsetMs(query);
10169
+ if (offsetMs === null) {
10170
+ deps.logger.info("subtitle request refused: bad offset", {
10171
+ tags,
10172
+ meta: { reason: "bad-offset" }
10173
+ });
10174
+ return reject(res, 400);
10175
+ }
10176
+ const known = (await deps.sidecars(itemId))?.find((candidate) => candidate.id === sidecar);
10177
+ if (known === void 0) {
10178
+ deps.logger.info("subtitle request refused: not a sidecar of this item", {
10179
+ tags,
10180
+ meta: { reason: "not-a-sidecar" }
10181
+ });
10182
+ return reject(res, 404);
10183
+ }
10184
+ const path = await resolveServable(known.filePath, await deps.roots());
10185
+ if (path === null) {
10186
+ deps.logger.warn("subtitle request refused: outside the library roots", {
10187
+ tags,
10188
+ meta: { reason: "outside-roots" }
10189
+ });
10190
+ return reject(res, 404);
10191
+ }
10192
+ try {
10193
+ if ((await (0, node_fs_promises.stat)(path)).size > 5242880) {
10194
+ deps.logger.warn("subtitle request refused: file too large", {
10195
+ tags,
10196
+ meta: { reason: "too-large" }
10197
+ });
10198
+ return reject(res, 404);
10199
+ }
10200
+ const body = Buffer.from(toWebVtt(await (0, node_fs_promises.readFile)(path, "utf8"), known.format, offsetMs), "utf8");
10201
+ res.writeHead(200, {
10202
+ "Content-Type": "text/vtt; charset=utf-8",
10203
+ "Content-Length": body.length,
10204
+ "Cache-Control": "private, no-store"
10205
+ });
10206
+ if (method === "HEAD") res.end();
10207
+ else res.end(body);
10208
+ deps.logger.debug("subtitle served", {
10209
+ tags,
10210
+ meta: {
10211
+ sidecar,
10212
+ format: known.format,
10213
+ offsetMs
10214
+ }
10215
+ });
10216
+ } catch {
10217
+ deps.logger.warn("subtitle request refused: file vanished", {
10218
+ tags,
10219
+ meta: { reason: "gone" }
10220
+ });
10221
+ reject(res, 404);
10222
+ }
10223
+ };
10224
+ }
9947
10225
  //#endregion
9948
10226
  //#region src/folder-walker.ts
9949
10227
  var VIDEO_EXTENSIONS = new Set([
@@ -10050,6 +10328,71 @@ function parseRows(schema, rows, onInvalid) {
10050
10328
  return out;
10051
10329
  }
10052
10330
  //#endregion
10331
+ //#region src/item-details.ts
10332
+ /**
10333
+ * What a metadata source holds about one item beyond its plot: genres, runtime, rating, crew and
10334
+ * cast. Stored with the item (a JSON column), never handed to a client as is: a person's `photo` is
10335
+ * the SOURCE's https URL, and a client gets an image-plane handle instead (`personImageKey`).
10336
+ */
10337
+ var StoredPersonSchema = object({
10338
+ id: number().int(),
10339
+ name: string(),
10340
+ /** The source's https URL of the profile picture; `null` when it has none. Never sent to a client. */
10341
+ photo: string().nullable()
10342
+ });
10343
+ var StoredCastSchema = StoredPersonSchema.extend({
10344
+ character: string().nullable(),
10345
+ order: number().int().nonnegative()
10346
+ });
10347
+ var ItemDetailsSchema = object({
10348
+ /** Genre names by language tag (lower-case, as `translations`): a source answers them in the language it was asked. */
10349
+ genres: record(string(), array(string())),
10350
+ runtimeMinutes: number().int().positive().nullable(),
10351
+ certification: string().nullable(),
10352
+ creators: array(StoredPersonSchema),
10353
+ directors: array(StoredPersonSchema),
10354
+ writers: array(StoredPersonSchema),
10355
+ cast: array(StoredCastSchema),
10356
+ guestStars: array(StoredCastSchema)
10357
+ });
10358
+ var EMPTY_DETAILS = {
10359
+ genres: {},
10360
+ runtimeMinutes: null,
10361
+ certification: null,
10362
+ creators: [],
10363
+ directors: [],
10364
+ writers: [],
10365
+ cast: [],
10366
+ guestStars: []
10367
+ };
10368
+ var PERSON_KEY = /^person-(\d{1,12})$/;
10369
+ function personImageKey(personId) {
10370
+ return `person-${personId}`;
10371
+ }
10372
+ function isImageKind(value) {
10373
+ return value === "poster" || value === "fanart" || value !== void 0 && PERSON_KEY.test(value);
10374
+ }
10375
+ function isPersonPhotoUrl(value) {
10376
+ if (!URL.canParse(value)) return false;
10377
+ const url = new URL(value);
10378
+ return url.protocol === "https:" && url.hostname === "image.tmdb.org";
10379
+ }
10380
+ /** The person id an image key names, or `null` for a poster or a fanart. */
10381
+ function personIdOf(kind) {
10382
+ const found = PERSON_KEY.exec(kind);
10383
+ return found?.[1] === void 0 ? null : Number(found[1]);
10384
+ }
10385
+ /** The profile picture URL stored for `personId` among the credits of `details`, or `null`. */
10386
+ function personPhotoOf(details, personId) {
10387
+ return [
10388
+ ...details.cast,
10389
+ ...details.guestStars,
10390
+ ...details.creators,
10391
+ ...details.directors,
10392
+ ...details.writers
10393
+ ].find((person) => person.id === personId)?.photo ?? null;
10394
+ }
10395
+ //#endregion
10053
10396
  //#region src/metadata.ts
10054
10397
  /**
10055
10398
  * One language's text of an item: either field may be absent (a provider can translate the title and
@@ -10074,14 +10417,18 @@ var ProviderMatchSchema = object({
10074
10417
  poster: string().nullable(),
10075
10418
  fanart: string().nullable(),
10076
10419
  /** The title and overview in other languages, when the provider answered them with the match. */
10077
- translations: TranslationMapSchema.optional()
10420
+ translations: TranslationMapSchema.optional(),
10421
+ /** Genres, rating, crew and cast, answered with the match. Absent from a match cached before they were kept. */
10422
+ details: ItemDetailsSchema.optional()
10078
10423
  });
10079
10424
  var ProviderEpisodeSchema = object({
10080
10425
  season: number().int(),
10081
10426
  episode: number().int(),
10082
10427
  title: string().nullable(),
10083
10428
  overview: string().nullable(),
10084
- still: string().nullable()
10429
+ still: string().nullable(),
10430
+ /** The episode's own runtime, crew and guest stars, read from the season answer. Absent from a list cached before they were kept. */
10431
+ details: ItemDetailsSchema.optional()
10085
10432
  });
10086
10433
  /** The provider refused its credential: asking again cannot work until the operator fixes it. */
10087
10434
  var ProviderAuthError = class extends Error {
@@ -10203,6 +10550,7 @@ var ITEMS = "media-library:items";
10203
10550
  var FILES = "media-library:files";
10204
10551
  var PROGRESS = "media-library:progress";
10205
10552
  var PINS = "media-library:pins";
10553
+ var WATCHLIST = "media-library:watchlist";
10206
10554
  /** Item row: one series, movie or episode of the catalogue. */
10207
10555
  var ItemRowSchema = object({
10208
10556
  id: string(),
@@ -10217,6 +10565,8 @@ var ItemRowSchema = object({
10217
10565
  overview: string().nullable(),
10218
10566
  /** The title and overview in other languages; absent on a row written before they were kept. */
10219
10567
  translations: TranslationMapSchema.nullish(),
10568
+ /** Genres, rating, crew and cast; absent on a row written before they were kept, `null` when no source gave any. */
10569
+ details: ItemDetailsSchema.nullish(),
10220
10570
  tvdbId: number().int().nullable(),
10221
10571
  tmdbId: number().int().nullable(),
10222
10572
  imdbId: string().nullable(),
@@ -10242,6 +10592,8 @@ var FileRowSchema = object({
10242
10592
  container: string().nullable(),
10243
10593
  durationMs: number().int().nullable(),
10244
10594
  streams: array(LibraryStreamSchema),
10595
+ /** Absent on a row probed before chapters were read: the next scan probes it again. */
10596
+ chapters: array(MediaChapterSchema).nullish(),
10245
10597
  probeError: string().nullable()
10246
10598
  });
10247
10599
  var PinSourceSchema = _enum(["plex", "manual"]);
@@ -10262,6 +10614,12 @@ var ProgressRowSchema = object({
10262
10614
  updatedAt: number().int(),
10263
10615
  watched: boolean()
10264
10616
  });
10617
+ /** One series or movie a person put on their watchlist. */
10618
+ var WatchlistRowSchema = object({
10619
+ userId: string(),
10620
+ itemId: string(),
10621
+ addedAt: number().int()
10622
+ });
10265
10623
  var text$3 = (name, notNull = false) => ({
10266
10624
  name,
10267
10625
  type: "TEXT",
@@ -10291,6 +10649,10 @@ var COLLECTIONS = [
10291
10649
  name: "translations",
10292
10650
  type: "JSON"
10293
10651
  },
10652
+ {
10653
+ name: "details",
10654
+ type: "JSON"
10655
+ },
10294
10656
  int("tvdbId"),
10295
10657
  int("tmdbId"),
10296
10658
  text$3("imdbId"),
@@ -10349,6 +10711,10 @@ var COLLECTIONS = [
10349
10711
  type: "JSON",
10350
10712
  notNull: true
10351
10713
  },
10714
+ {
10715
+ name: "chapters",
10716
+ type: "JSON"
10717
+ },
10352
10718
  text$3("probeError")
10353
10719
  ]
10354
10720
  },
@@ -10390,6 +10756,20 @@ var COLLECTIONS = [
10390
10756
  "updatedAt"
10391
10757
  ]
10392
10758
  }]
10759
+ },
10760
+ {
10761
+ collection: WATCHLIST,
10762
+ primaryKey: ["userId", "itemId"],
10763
+ withoutRowid: true,
10764
+ columns: [
10765
+ text$3("userId", true),
10766
+ text$3("itemId", true),
10767
+ int("addedAt", true)
10768
+ ],
10769
+ indexes: [{
10770
+ name: "idx_media_watchlist_user",
10771
+ columns: ["userId", "addedAt"]
10772
+ }]
10393
10773
  }
10394
10774
  ];
10395
10775
  //#endregion
@@ -10657,6 +11037,7 @@ var NO_LOCAL = {
10657
11037
  year: null,
10658
11038
  overview: null,
10659
11039
  translations: null,
11040
+ details: null,
10660
11041
  tvdbId: null,
10661
11042
  tmdbId: null,
10662
11043
  imdbId: null,
@@ -10697,6 +11078,7 @@ function merge(first, second) {
10697
11078
  year: pick$1(first.year, second.year),
10698
11079
  overview: pick$1(first.overview, second.overview),
10699
11080
  translations: pick$1(first.translations, second.translations),
11081
+ details: pick$1(first.details, second.details),
10700
11082
  tvdbId: pick$1(first.tvdbId, second.tvdbId),
10701
11083
  tmdbId: pick$1(first.tmdbId, second.tmdbId),
10702
11084
  imdbId: pick$1(first.imdbId, second.imdbId),
@@ -10754,6 +11136,60 @@ async function localMovie(reader, filePath) {
10754
11136
  };
10755
11137
  }
10756
11138
  //#endregion
11139
+ //#region src/subtitle-sidecars.ts
11140
+ var FORMATS$1 = [
11141
+ "srt",
11142
+ "ass",
11143
+ "ssa",
11144
+ "vtt"
11145
+ ];
11146
+ var LANGUAGE = /^[a-z]{2,3}(?:-[a-z0-9]{2,4})?$/i;
11147
+ function formatOf(extension) {
11148
+ const bare = extension.slice(1).toLowerCase();
11149
+ return FORMATS$1.find((format) => format === bare) ?? null;
11150
+ }
11151
+ /** A stable id from the file name: it never carries a path, so a client cannot name one. */
11152
+ function sidecarId(fileName) {
11153
+ return (0, node_crypto.createHash)("sha1").update(fileName.toLowerCase()).digest("hex").slice(0, 10);
11154
+ }
11155
+ /**
11156
+ * The subtitle files of `videoPath` in its folder's `listing`: `<base>.srt`, `<base>.<lang>.srt`,
11157
+ * `<base>.<lang>.forced.srt` (also `.ass`, `.ssa`, `.vtt`). The base is matched case-insensitively and
11158
+ * must be followed by a dot, so `Movie2.srt` is not the sidecar of `Movie.mkv`.
11159
+ */
11160
+ function discoverSubtitles(videoPath, listing) {
11161
+ const dir = (0, node_path.dirname)(videoPath);
11162
+ const base = (0, node_path.basename)(videoPath, (0, node_path.extname)(videoPath)).toLowerCase();
11163
+ const found = [];
11164
+ for (const [lower, real] of listing) {
11165
+ const extension = (0, node_path.extname)(lower);
11166
+ const format = formatOf(extension);
11167
+ if (format === null || !lower.startsWith(`${base}.`)) continue;
11168
+ const middle = lower.slice(base.length + 1, lower.length - extension.length);
11169
+ const tokens = middle === "" ? [] : middle.split(".");
11170
+ let language = null;
11171
+ let forced = false;
11172
+ const extra = [];
11173
+ for (const token of tokens) if (token === "forced") forced = true;
11174
+ else if (language === null && extra.length === 0 && LANGUAGE.test(token)) language = token;
11175
+ else extra.push(token);
11176
+ const parts = [
11177
+ language,
11178
+ ...extra,
11179
+ forced ? "forced" : null
11180
+ ].filter((part) => part !== null);
11181
+ found.push({
11182
+ id: sidecarId(real),
11183
+ language,
11184
+ forced,
11185
+ format,
11186
+ label: parts.length === 0 ? "Subtitles" : parts.join(" "),
11187
+ filePath: (0, node_path.join)(dir, real)
11188
+ });
11189
+ }
11190
+ return found.sort((a, b) => a.filePath.localeCompare(b.filePath));
11191
+ }
11192
+ //#endregion
10757
11193
  //#region src/item-text.ts
10758
11194
  /**
10759
11195
  * A language tag as the translations are keyed: lower-case, region dropped (`it-IT` is `it`).
@@ -10795,31 +11231,49 @@ function sortByShownTitle(rows, requested, serverDefault) {
10795
11231
  return rows.toSorted((a, b) => collator.compare(keys.get(a) ?? "", keys.get(b) ?? ""));
10796
11232
  }
10797
11233
  var FILE_PLANE_PREFIX = "file";
11234
+ var SUBTITLE_PLANE_PREFIX = "subtitle";
10798
11235
  var HUB_PLANE_BASE = "/addon/media-library";
10799
11236
  var SEARCH_DEFAULT_LIMIT = 50;
10800
11237
  var RECENT_DEFAULT_LIMIT = 20;
10801
11238
  var CONTINUE_DEFAULT_LIMIT = 20;
10802
11239
  /** A rewound row is not "continue", so the read asks for a few more than it will show. */
10803
11240
  var CONTINUE_OVERFETCH = 3;
11241
+ /** Item ids resolved per read when a watchlist is larger than one query takes. */
11242
+ var WATCHLIST_RESOLVE_CHUNK = 500;
10804
11243
  function playPathOf(itemId) {
10805
11244
  return `${HUB_PLANE_BASE}/${FILE_PLANE_PREFIX}/${itemId}`;
10806
11245
  }
11246
+ function subtitlePathOf(itemId, sidecarId) {
11247
+ return `${HUB_PLANE_BASE}/${SUBTITLE_PLANE_PREFIX}/${itemId}/${sidecarId}`;
11248
+ }
10807
11249
  function imagePathOf(itemId, which) {
10808
11250
  return `${HUB_PLANE_BASE}/img/${itemId}/${which}`;
10809
11251
  }
10810
11252
  function isWatched(positionMs, durationMs) {
10811
11253
  return durationMs > 0 && positionMs / durationMs >= .9;
10812
11254
  }
11255
+ /** An episode cannot be watchlisted: the series is what a person follows. */
11256
+ var WatchlistKindError = class extends Error {
11257
+ code = "watchlist-kind";
11258
+ constructor(itemId) {
11259
+ super(`watchlist-kind: ${itemId} is an episode; only a series or a movie can be watchlisted`);
11260
+ this.name = "WatchlistKindError";
11261
+ }
11262
+ };
10813
11263
  var idList = (rows) => rows.map((row) => row.id);
10814
11264
  var LibraryStore = class {
10815
11265
  db;
10816
11266
  logger;
10817
11267
  serverLanguage;
11268
+ now;
11269
+ listDir;
10818
11270
  locks = /* @__PURE__ */ new Map();
10819
- constructor(db, logger, serverLanguage = () => "en") {
11271
+ constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir) {
10820
11272
  this.db = db;
10821
11273
  this.logger = logger;
10822
11274
  this.serverLanguage = serverLanguage;
11275
+ this.now = now;
11276
+ this.listDir = listDir;
10823
11277
  }
10824
11278
  async init() {
10825
11279
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -10840,6 +11294,9 @@ var LibraryStore = class {
10840
11294
  async queryFiles(filter) {
10841
11295
  return parseRows(FileRowSchema, await this.db.query(FILES, filter), this.invalid(FILES));
10842
11296
  }
11297
+ async queryWatchlist(filter) {
11298
+ return parseRows(WatchlistRowSchema, await this.db.query(WATCHLIST, filter), this.invalid(WATCHLIST));
11299
+ }
10843
11300
  async queryProgress(filter) {
10844
11301
  return parseRows(ProgressRowSchema, await this.db.query(PROGRESS, filter), this.invalid(PROGRESS));
10845
11302
  }
@@ -10854,9 +11311,15 @@ var LibraryStore = class {
10854
11311
  where: { userId },
10855
11312
  whereIn: { itemId: playableIds }
10856
11313
  })) progress.set(entry.itemId, entry);
11314
+ const followable = rows.filter((row) => row.kind !== "episode").map((row) => row.id);
11315
+ const watchlisted = /* @__PURE__ */ new Set();
11316
+ if (followable.length > 0) for (const entry of await this.queryWatchlist({
11317
+ where: { userId },
11318
+ whereIn: { itemId: followable }
11319
+ })) watchlisted.add(entry.itemId);
10857
11320
  const fallback = this.serverLanguage();
10858
11321
  return rows.map((row) => {
10859
- return toSummary(row, row.filePath === null ? void 0 : files.get(row.filePath), progress.get(row.id), resolveItemText(row, language, fallback).title);
11322
+ return toSummary(row, row.filePath === null ? void 0 : files.get(row.filePath), progress.get(row.id), resolveItemText(row, language, fallback).title, row.kind === "episode" ? void 0 : watchlisted.has(row.id));
10860
11323
  });
10861
11324
  }
10862
11325
  pageOf = async (kind, userId, limit, offset, language) => {
@@ -10975,9 +11438,24 @@ var LibraryStore = class {
10975
11438
  },
10976
11439
  fanartPath: row.fanartSource === null ? null : imagePathOf(row.id, "fanart"),
10977
11440
  playPath: file === void 0 ? null : playPathOf(row.id),
10978
- file: file === void 0 ? null : toFileInfo(file)
11441
+ file: file === void 0 ? null : toFileInfo(file),
11442
+ chapters: file?.chapters ?? [],
11443
+ externalSubtitles: (await this.subtitleSidecars(row.id)).map((sidecar) => ({
11444
+ id: sidecar.id,
11445
+ language: sidecar.language,
11446
+ forced: sidecar.forced,
11447
+ format: sidecar.format,
11448
+ label: sidecar.label,
11449
+ path: subtitlePathOf(row.id, sidecar.id)
11450
+ }))
10979
11451
  };
10980
11452
  }
11453
+ /** The subtitle files next to the video of `itemId`; empty when it has none or no file. */
11454
+ async subtitleSidecars(itemId) {
11455
+ const catalogued = await this.playableFile(itemId);
11456
+ if (catalogued === null) return [];
11457
+ return discoverSubtitles(catalogued.path, await this.listDir((0, node_path.dirname)(catalogued.path)));
11458
+ }
10981
11459
  /** The file a client may stream for `itemId`, or `null`: the path comes from here, never from the client. */
10982
11460
  async playableFile(itemId) {
10983
11461
  const [item] = await this.queryItems({
@@ -11001,6 +11479,14 @@ var LibraryStore = class {
11001
11479
  limit: 1
11002
11480
  });
11003
11481
  if (item === void 0) return [];
11482
+ const personId = personIdOf(which);
11483
+ if (personId !== null) {
11484
+ const photo = item.details === null || item.details === void 0 ? null : personPhotoOf(item.details, personId);
11485
+ return photo !== null && isPersonPhotoUrl(photo) ? [{
11486
+ kind: "remote",
11487
+ url: photo
11488
+ }] : [];
11489
+ }
11004
11490
  const out = [];
11005
11491
  const cover = which === "poster" ? item.posterSource : item.fanartSource;
11006
11492
  if (cover !== null) {
@@ -11036,6 +11522,86 @@ var LibraryStore = class {
11036
11522
  }
11037
11523
  return out;
11038
11524
  }
11525
+ /** The caller's series and movies on their watchlist, the latest added first. */
11526
+ async listWatchlist(userId, limit, offset, language) {
11527
+ const held = parseRows(WatchlistRowSchema, await queryAll(this.db, WATCHLIST, "itemId", { where: { userId } }), this.invalid(WATCHLIST)).toSorted((a, b) => b.addedAt - a.addedAt || a.itemId.localeCompare(b.itemId));
11528
+ if (held.length === 0) return {
11529
+ items: [],
11530
+ total: 0
11531
+ };
11532
+ const rows = /* @__PURE__ */ new Map();
11533
+ for (let at = 0; at < held.length; at += WATCHLIST_RESOLVE_CHUNK) {
11534
+ const ids = held.slice(at, at + WATCHLIST_RESOLVE_CHUNK).map((entry) => entry.itemId);
11535
+ for (const row of await this.queryItems({ whereIn: { id: ids } })) rows.set(row.id, row);
11536
+ }
11537
+ const resolved = held.flatMap((entry) => {
11538
+ const row = rows.get(entry.itemId);
11539
+ return row === void 0 ? [] : [row];
11540
+ });
11541
+ const start = offset ?? 0;
11542
+ const ordered = resolved.slice(start, start + (limit ?? 100));
11543
+ const total = resolved.length;
11544
+ return {
11545
+ items: await this.summaries(ordered, userId, language),
11546
+ total
11547
+ };
11548
+ }
11549
+ /** Put a series or a movie on the caller's watchlist, or take it off. Idempotent; an episode is refused. */
11550
+ setWatchlisted(userId, itemId, on) {
11551
+ return this.locked(`watchlist\u0000${userId}\u0000${itemId}`, async () => {
11552
+ if ((await this.requirePlayable(itemId)).kind === "episode") throw new WatchlistKindError(itemId);
11553
+ if (!on) {
11554
+ await this.db.deleteWhere(WATCHLIST, { where: {
11555
+ userId,
11556
+ itemId
11557
+ } });
11558
+ return { on: false };
11559
+ }
11560
+ const [held] = await this.queryWatchlist({
11561
+ where: {
11562
+ userId,
11563
+ itemId
11564
+ },
11565
+ limit: 1
11566
+ });
11567
+ if (held === void 0) await this.db.upsertMany(WATCHLIST, ["userId", "itemId"], [{
11568
+ userId,
11569
+ itemId,
11570
+ addedAt: this.now()
11571
+ }]);
11572
+ return { on: true };
11573
+ });
11574
+ }
11575
+ /** Genres, runtime, rating, crew and cast of one item, in the reader's language; empty when nothing was fetched. */
11576
+ async getItemDetails(itemId, language) {
11577
+ const [row] = await this.queryItems({
11578
+ where: { id: itemId },
11579
+ limit: 1
11580
+ });
11581
+ if (row === void 0) return null;
11582
+ const details = row.details ?? EMPTY_DETAILS;
11583
+ const person = (entry) => ({
11584
+ id: entry.id,
11585
+ name: entry.name,
11586
+ photoPath: entry.photo === null || !isPersonPhotoUrl(entry.photo) ? null : imagePathOf(row.id, personImageKey(entry.id))
11587
+ });
11588
+ const member = (entry) => ({
11589
+ ...person(entry),
11590
+ character: entry.character,
11591
+ order: entry.order
11592
+ });
11593
+ return {
11594
+ itemId: row.id,
11595
+ genres: genresOf(details, language, this.serverLanguage()),
11596
+ runtimeMinutes: details.runtimeMinutes,
11597
+ certification: details.certification,
11598
+ creators: details.creators.map(person),
11599
+ directors: details.directors.map(person),
11600
+ writers: details.writers.map(person),
11601
+ cast: details.cast.map(member),
11602
+ guestStars: details.guestStars.map(member)
11603
+ };
11604
+ }
11039
11605
  /** Serialise the read-compare-write of one (user, item) so two writes of one person cannot interleave. */
11040
11606
  async locked(key, run) {
11041
11607
  const next = (this.locks.get(key) ?? Promise.resolve()).then(run, run);
@@ -11185,6 +11751,21 @@ var LibraryStore = class {
11185
11751
  return entries;
11186
11752
  }
11187
11753
  };
11754
+ async function defaultListDir(dir) {
11755
+ try {
11756
+ return new Map((await (0, node_fs_promises.readdir)(dir)).map((name) => [name.toLowerCase(), name]));
11757
+ } catch {
11758
+ return /* @__PURE__ */ new Map();
11759
+ }
11760
+ }
11761
+ /** Genre names: the language asked for, else the server's, else whichever language the source answered. */
11762
+ function genresOf(details, requested, serverDefault) {
11763
+ for (const key of [languageKey(requested), languageKey(serverDefault)]) {
11764
+ const found = key === void 0 ? void 0 : details.genres[key];
11765
+ if (found !== void 0) return found;
11766
+ }
11767
+ return Object.values(details.genres)[0] ?? [];
11768
+ }
11188
11769
  function toProgress(row) {
11189
11770
  return {
11190
11771
  itemId: row.itemId,
@@ -11203,7 +11784,7 @@ function toFileInfo(file) {
11203
11784
  probed: file.probeOk
11204
11785
  };
11205
11786
  }
11206
- function toSummary(row, file, progress, title) {
11787
+ function toSummary(row, file, progress, title, watchlisted) {
11207
11788
  return {
11208
11789
  id: row.id,
11209
11790
  kind: row.kind,
@@ -11216,7 +11797,8 @@ function toSummary(row, file, progress, title) {
11216
11797
  addedAt: row.addedAt,
11217
11798
  durationMs: file?.durationMs ?? null,
11218
11799
  playable: row.kind !== "series" && file !== void 0,
11219
- progress: progress === void 0 ? null : toProgress(progress)
11800
+ progress: progress === void 0 ? null : toProgress(progress),
11801
+ ...watchlisted === void 0 ? {} : { watchlisted }
11220
11802
  };
11221
11803
  }
11222
11804
  //#endregion
@@ -12503,6 +13085,103 @@ var ServerLanguage = class {
12503
13085
  }
12504
13086
  };
12505
13087
  //#endregion
13088
+ //#region src/remote-fetch.ts
13089
+ var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
13090
+ var IMAGE_TIMEOUT_MS = 2e4;
13091
+ var MAX_REDIRECTS = 3;
13092
+ /** Read a response body, aborting as soon as it passes `cap`: the rest is never buffered. */
13093
+ async function readCapped(response, cap) {
13094
+ if (Number(response.headers.get("content-length") ?? "0") > cap) throw new Error("image too large");
13095
+ if (response.body === null) return Buffer.alloc(0);
13096
+ const reader = response.body.getReader();
13097
+ const chunks = [];
13098
+ let total = 0;
13099
+ for (;;) {
13100
+ const { done, value } = await reader.read();
13101
+ if (done) break;
13102
+ total += value.byteLength;
13103
+ if (total > cap) {
13104
+ await reader.cancel();
13105
+ throw new Error("image too large");
13106
+ }
13107
+ chunks.push(Buffer.from(value));
13108
+ }
13109
+ return Buffer.concat(chunks, total);
13110
+ }
13111
+ function v4Private(address) {
13112
+ const [a = 0, b = 0] = address.split(".").map(Number);
13113
+ 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;
13114
+ }
13115
+ /** Loopback, private, link-local, ULA, CGNAT, multicast and unspecified addresses, v4 and v6. */
13116
+ function isPrivateAddress(address) {
13117
+ const kind = (0, node_net.isIP)(address);
13118
+ if (kind === 4) return v4Private(address);
13119
+ if (kind !== 6) return true;
13120
+ const lower = address.toLowerCase();
13121
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
13122
+ if (mapped?.[1] !== void 0) return v4Private(mapped[1]);
13123
+ if (lower === "::" || lower === "::1") return true;
13124
+ return /^(fe[89ab]|f[cd]|ff)/.test(lower);
13125
+ }
13126
+ var resolveAll = async (host) => (await (0, node_dns_promises.lookup)(host, { all: true })).map((entry) => entry.address);
13127
+ /** The server asked to slow down. `retryAfterMs` is its `Retry-After`, or `null` when it named none. The message keeps the `HTTP 429` wording. */
13128
+ var RateLimitedError = class extends Error {
13129
+ retryAfterMs;
13130
+ constructor(retryAfterMs) {
13131
+ super("HTTP 429");
13132
+ this.retryAfterMs = retryAfterMs;
13133
+ this.name = "RateLimitedError";
13134
+ }
13135
+ };
13136
+ /** `Retry-After` as milliseconds: delta-seconds or an HTTP date; `null` when absent or unreadable. */
13137
+ function retryAfterMsOf(value, now = Date.now()) {
13138
+ if (value === null || value.trim() === "") return null;
13139
+ const seconds = Number(value);
13140
+ if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds * 1e3));
13141
+ const at = Date.parse(value);
13142
+ return Number.isNaN(at) ? null : Math.max(0, at - now);
13143
+ }
13144
+ /**
13145
+ * https only, at most 3 redirects each re-validated, every address the host resolves to must be
13146
+ * public, no credential, a bounded time and a streamed size cap.
13147
+ * A resolver answer can differ from the one `fetch` gets (rebinding): the host check narrows, not closes, that window.
13148
+ */
13149
+ function createRemoteFetch(deps = {}) {
13150
+ const doFetch = deps.fetchImpl ?? fetch;
13151
+ const resolve = deps.resolve ?? resolveAll;
13152
+ return async (start, init) => {
13153
+ let url = start;
13154
+ const startOrigin = isRemoteUrl(start) ? new URL(start).origin : "";
13155
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
13156
+ if (!isRemoteUrl(url)) throw new Error("only an https URL is fetched");
13157
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
13158
+ const addresses = (0, node_net.isIP)(host) === 0 ? await resolve(host) : [host];
13159
+ if (addresses.length === 0 || addresses.some(isPrivateAddress)) throw new Error("host refused: not a public address");
13160
+ const sameOrigin = new URL(url).origin === startOrigin;
13161
+ const response = await doFetch(url, {
13162
+ redirect: "manual",
13163
+ ...sameOrigin && init?.headers !== void 0 ? { headers: { ...init.headers } } : {},
13164
+ ...hop === 0 && init?.body !== void 0 ? {
13165
+ method: "POST",
13166
+ body: init.body
13167
+ } : {},
13168
+ signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
13169
+ });
13170
+ if (response.status >= 300 && response.status < 400) {
13171
+ const location = response.headers.get("location");
13172
+ if (location === null) throw new Error("redirect without a location");
13173
+ url = new URL(location, url).toString();
13174
+ continue;
13175
+ }
13176
+ if (response.status === 429) throw new RateLimitedError(retryAfterMsOf(response.headers.get("retry-after")));
13177
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
13178
+ return readCapped(response, MAX_IMAGE_BYTES);
13179
+ }
13180
+ throw new Error("too many redirects");
13181
+ };
13182
+ }
13183
+ var httpRemoteFetch = createRemoteFetch();
13184
+ //#endregion
12506
13185
  //#region src/tmdb.ts
12507
13186
  var TMDB_ID = "tmdb";
12508
13187
  var API$2 = "https://api.themoviedb.org/3";
@@ -12526,6 +13205,36 @@ var TranslationsSchema = object({ translations: array(object({
12526
13205
  overview: string().nullish()
12527
13206
  }).nullish()
12528
13207
  })) });
13208
+ var PersonSchema = object({
13209
+ id: number().int(),
13210
+ name: string().nullish(),
13211
+ profile_path: string().nullish()
13212
+ });
13213
+ /** A cast entry: a movie's `character`, a series' `roles[]` (aggregate credits), a guest star's `character`. */
13214
+ var CastEntrySchema = PersonSchema.extend({
13215
+ character: string().nullish(),
13216
+ roles: array(object({ character: string().nullish() })).nullish(),
13217
+ order: number().int().nullish()
13218
+ });
13219
+ /** A crew entry: a movie's `job`, a series' `jobs[]` (aggregate credits). */
13220
+ var CrewEntrySchema = PersonSchema.extend({
13221
+ job: string().nullish(),
13222
+ jobs: array(object({ job: string().nullish() })).nullish()
13223
+ });
13224
+ var CreditsSchema = object({
13225
+ cast: array(CastEntrySchema).nullish(),
13226
+ crew: array(CrewEntrySchema).nullish()
13227
+ });
13228
+ /** `release_dates` (movie): per country, a list of releases that may carry a certification. */
13229
+ var ReleaseDatesSchema = object({ results: array(object({
13230
+ iso_3166_1: string(),
13231
+ release_dates: array(object({ certification: string().nullish() }))
13232
+ })) });
13233
+ /** `content_ratings` (series): one rating per country. */
13234
+ var ContentRatingsSchema = object({ results: array(object({
13235
+ iso_3166_1: string(),
13236
+ rating: string().nullish()
13237
+ })) });
12529
13238
  var DetailsSchema = object({
12530
13239
  id: number().int(),
12531
13240
  title: string().nullish(),
@@ -12541,7 +13250,15 @@ var DetailsSchema = object({
12541
13250
  tvdb_id: number().int().nullish()
12542
13251
  }).nullish(),
12543
13252
  seasons: array(object({ season_number: number().int() })).nullish(),
12544
- translations: TranslationsSchema.nullish()
13253
+ translations: TranslationsSchema.nullish(),
13254
+ genres: array(object({ name: string().nullish() })).nullish(),
13255
+ runtime: number().nullish(),
13256
+ episode_run_time: array(number()).nullish(),
13257
+ created_by: array(PersonSchema).nullish(),
13258
+ credits: CreditsSchema.nullish(),
13259
+ aggregate_credits: CreditsSchema.nullish(),
13260
+ release_dates: ReleaseDatesSchema.nullish(),
13261
+ content_ratings: ContentRatingsSchema.nullish()
12545
13262
  });
12546
13263
  var FindSchema = object({
12547
13264
  movie_results: array(object({ id: number().int() })).default([]),
@@ -12552,8 +13269,13 @@ var SeasonSchema = object({ episodes: array(object({
12552
13269
  episode_number: number().int(),
12553
13270
  name: string().nullish(),
12554
13271
  overview: string().nullish(),
12555
- still_path: string().nullish()
13272
+ still_path: string().nullish(),
13273
+ runtime: number().nullish(),
13274
+ guest_stars: array(CastEntrySchema).nullish(),
13275
+ crew: array(CrewEntrySchema).nullish()
12556
13276
  })) });
13277
+ /** Waited when TMDB says 429 and names no time. */
13278
+ var TMDB_DEFAULT_RETRY_WAIT_MS = 2e3;
12557
13279
  /** TMDB's tag for a content language: English keeps the region it was always asked in, Chinese is the simplified catalogue, others are sent bare. */
12558
13280
  function tmdbLanguageOf(language) {
12559
13281
  if (language === "en") return DEFAULT_LANGUAGE;
@@ -12590,23 +13312,128 @@ function translationsOf(details) {
12590
13312
  }
12591
13313
  return out;
12592
13314
  }
13315
+ /**
13316
+ * The region a rating is read for: the tag's own region (`pt-BR` is BR), else the likely region of
13317
+ * its language from CLDR (`it` is IT, `ja` is JP), US when neither is known.
13318
+ */
13319
+ function tmdbRegionOf(language) {
13320
+ return (/^[A-Za-z]{2,3}[-_]([A-Za-z]{2})$/.exec(language)?.[1] ?? likelyRegionOf(languageKey(language)) ?? "US").toUpperCase();
13321
+ }
13322
+ function likelyRegionOf(language) {
13323
+ if (language === null || language === void 0 || language === "") return void 0;
13324
+ try {
13325
+ return new Intl.Locale(language).maximize().region;
13326
+ } catch {
13327
+ return;
13328
+ }
13329
+ }
13330
+ var photoOf = (path) => image("w185", path);
13331
+ var positive = (value) => value !== null && value !== void 0 && value > 0 ? Math.round(value) : null;
13332
+ function personsOf(crew, jobs) {
13333
+ const out = [];
13334
+ for (const entry of crew ?? []) {
13335
+ const held = [entry.job, ...(entry.jobs ?? []).map((job) => job.job)];
13336
+ const name = text(entry.name);
13337
+ if (name === null || !held.some((job) => job !== null && job !== void 0 && jobs.includes(job))) continue;
13338
+ if (out.some((person) => person.id === entry.id)) continue;
13339
+ out.push({
13340
+ id: entry.id,
13341
+ name,
13342
+ photo: photoOf(entry.profile_path)
13343
+ });
13344
+ }
13345
+ return out;
13346
+ }
13347
+ function castOf(cast) {
13348
+ const out = [];
13349
+ for (const [index, entry] of (cast ?? []).entries()) {
13350
+ const name = text(entry.name);
13351
+ if (name === null) continue;
13352
+ out.push({
13353
+ id: entry.id,
13354
+ name,
13355
+ photo: photoOf(entry.profile_path),
13356
+ character: text(entry.character ?? entry.roles?.[0]?.character),
13357
+ order: entry.order ?? index
13358
+ });
13359
+ }
13360
+ return out;
13361
+ }
13362
+ var DIRECTOR_JOBS = ["Director"];
13363
+ var WRITER_JOBS = [
13364
+ "Writer",
13365
+ "Screenplay",
13366
+ "Story",
13367
+ "Teleplay"
13368
+ ];
13369
+ /** Genres, runtime, rating, crew and cast of a details answer, all from the one call (`append_to_response`). */
13370
+ function itemDetailsOf(details, language, region) {
13371
+ const credits = details.credits ?? details.aggregate_credits;
13372
+ const names = (details.genres ?? []).flatMap((genre) => {
13373
+ const name = text(genre.name);
13374
+ return name === null ? [] : [name];
13375
+ });
13376
+ const key = languageKey(language);
13377
+ const certification = text(details.content_ratings?.results.find((entry) => entry.iso_3166_1 === region)?.rating) ?? details.release_dates?.results.find((entry) => entry.iso_3166_1 === region)?.release_dates.map((release) => text(release.certification)).find((value) => value !== null) ?? null;
13378
+ return {
13379
+ genres: key === void 0 || names.length === 0 ? {} : { [key]: names },
13380
+ runtimeMinutes: positive(details.runtime ?? details.episode_run_time?.[0]),
13381
+ certification,
13382
+ creators: (details.created_by ?? []).flatMap((entry) => {
13383
+ const name = text(entry.name);
13384
+ return name === null ? [] : [{
13385
+ id: entry.id,
13386
+ name,
13387
+ photo: photoOf(entry.profile_path)
13388
+ }];
13389
+ }),
13390
+ directors: personsOf(credits?.crew, DIRECTOR_JOBS),
13391
+ writers: personsOf(credits?.crew, WRITER_JOBS),
13392
+ cast: castOf(credits?.cast),
13393
+ guestStars: []
13394
+ };
13395
+ }
12593
13396
  var nameOf = (entry) => entry.title ?? entry.name ?? "";
12594
13397
  var yearIn = (entry) => yearOf$1(entry.release_date ?? entry.first_air_date);
12595
13398
  /** TMDB: movies and series, with the installation's own read token. All calls go through the shared remote fetch. */
12596
13399
  function createTmdbProvider(deps) {
12597
13400
  const language = deps.language ?? DEFAULT_LANGUAGE;
13401
+ const region = tmdbRegionOf(language);
12598
13402
  const headers = {
12599
13403
  Authorization: `Bearer ${deps.token}`,
12600
13404
  Accept: "application/json"
12601
13405
  };
12602
13406
  const segment = (kind) => kind === "movie" ? "movie" : "tv";
13407
+ const sleep = deps.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
13408
+ const clock = deps.now ?? Date.now;
13409
+ let nextSlot = 0;
13410
+ /** Reserve the next request slot, 50 ms after the previous one, and wait for it. */
13411
+ const pace = async () => {
13412
+ const slot = Math.max(clock(), nextSlot);
13413
+ nextSlot = slot + 50;
13414
+ const wait = slot - clock();
13415
+ if (wait > 0) await sleep(wait);
13416
+ };
13417
+ const get = async (url) => {
13418
+ await pace();
13419
+ try {
13420
+ return await deps.fetch(url, { headers });
13421
+ } catch (error) {
13422
+ if (!(error instanceof RateLimitedError)) throw error;
13423
+ const wait = error.retryAfterMs ?? TMDB_DEFAULT_RETRY_WAIT_MS;
13424
+ if (wait > 1e4) throw error;
13425
+ await sleep(wait);
13426
+ await pace();
13427
+ return deps.fetch(url, { headers });
13428
+ }
13429
+ };
12603
13430
  const call = async (path, query = {}) => {
12604
13431
  const params = new URLSearchParams({
12605
13432
  ...query,
12606
13433
  language
12607
13434
  });
12608
13435
  try {
12609
- const bytes = await deps.fetch(`${API$2}${path}?${params.toString()}`, { headers });
13436
+ const bytes = await get(`${API$2}${path}?${params.toString()}`);
12610
13437
  return JSON.parse(bytes.toString("utf8"));
12611
13438
  } catch (error) {
12612
13439
  if (error instanceof Error && /\b401\b/.test(error.message)) throw new ProviderAuthError(TMDB_REJECTED);
@@ -12624,11 +13451,12 @@ function createTmdbProvider(deps) {
12624
13451
  imdbId: text(details.external_ids?.imdb_id) ?? text(details.imdb_id),
12625
13452
  poster: image("w500", details.poster_path),
12626
13453
  fanart: image("w1280", details.backdrop_path),
12627
- translations: translationsOf(details)
13454
+ translations: translationsOf(details),
13455
+ details: itemDetailsOf(details, language, region)
12628
13456
  });
12629
13457
  const detailsOf = async (kind, id) => {
12630
13458
  try {
12631
- return matchOf(DetailsSchema.parse(await call(`/${segment(kind)}/${id}`, { append_to_response: "external_ids,translations" })));
13459
+ return matchOf(DetailsSchema.parse(await call(`/${segment(kind)}/${id}`, { append_to_response: kind === "movie" ? "external_ids,translations,credits,release_dates" : "external_ids,translations,aggregate_credits,content_ratings" })));
12632
13460
  } catch (error) {
12633
13461
  if (error instanceof Error && /\b404\b/.test(error.message)) return null;
12634
13462
  throw error;
@@ -12637,6 +13465,7 @@ function createTmdbProvider(deps) {
12637
13465
  return {
12638
13466
  id: TMDB_ID,
12639
13467
  translates: true,
13468
+ providesDetails: true,
12640
13469
  kinds: ["movie", "series"],
12641
13470
  lookupBy: [
12642
13471
  "tmdbId",
@@ -12677,7 +13506,17 @@ function createTmdbProvider(deps) {
12677
13506
  episode: entry.episode_number,
12678
13507
  title: text(entry.name),
12679
13508
  overview: text(entry.overview),
12680
- still: image("w300", entry.still_path)
13509
+ still: image("w300", entry.still_path),
13510
+ details: {
13511
+ genres: {},
13512
+ runtimeMinutes: positive(entry.runtime),
13513
+ certification: null,
13514
+ creators: [],
13515
+ directors: personsOf(entry.crew, DIRECTOR_JOBS),
13516
+ writers: personsOf(entry.crew, WRITER_JOBS),
13517
+ cast: [],
13518
+ guestStars: castOf(entry.guest_stars)
13519
+ }
12681
13520
  });
12682
13521
  }
12683
13522
  return out;
@@ -12985,85 +13824,6 @@ function createTvmazeProvider(deps) {
12985
13824
  };
12986
13825
  }
12987
13826
  //#endregion
12988
- //#region src/remote-fetch.ts
12989
- var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
12990
- var IMAGE_TIMEOUT_MS = 2e4;
12991
- var MAX_REDIRECTS = 3;
12992
- /** Read a response body, aborting as soon as it passes `cap`: the rest is never buffered. */
12993
- async function readCapped(response, cap) {
12994
- if (Number(response.headers.get("content-length") ?? "0") > cap) throw new Error("image too large");
12995
- if (response.body === null) return Buffer.alloc(0);
12996
- const reader = response.body.getReader();
12997
- const chunks = [];
12998
- let total = 0;
12999
- for (;;) {
13000
- const { done, value } = await reader.read();
13001
- if (done) break;
13002
- total += value.byteLength;
13003
- if (total > cap) {
13004
- await reader.cancel();
13005
- throw new Error("image too large");
13006
- }
13007
- chunks.push(Buffer.from(value));
13008
- }
13009
- return Buffer.concat(chunks, total);
13010
- }
13011
- function v4Private(address) {
13012
- const [a = 0, b = 0] = address.split(".").map(Number);
13013
- 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;
13014
- }
13015
- /** Loopback, private, link-local, ULA, CGNAT, multicast and unspecified addresses, v4 and v6. */
13016
- function isPrivateAddress(address) {
13017
- const kind = (0, node_net.isIP)(address);
13018
- if (kind === 4) return v4Private(address);
13019
- if (kind !== 6) return true;
13020
- const lower = address.toLowerCase();
13021
- const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
13022
- if (mapped?.[1] !== void 0) return v4Private(mapped[1]);
13023
- if (lower === "::" || lower === "::1") return true;
13024
- return /^(fe[89ab]|f[cd]|ff)/.test(lower);
13025
- }
13026
- var resolveAll = async (host) => (await (0, node_dns_promises.lookup)(host, { all: true })).map((entry) => entry.address);
13027
- /**
13028
- * https only, at most 3 redirects each re-validated, every address the host resolves to must be
13029
- * public, no credential, a bounded time and a streamed size cap.
13030
- * A resolver answer can differ from the one `fetch` gets (rebinding): the host check narrows, not closes, that window.
13031
- */
13032
- function createRemoteFetch(deps = {}) {
13033
- const doFetch = deps.fetchImpl ?? fetch;
13034
- const resolve = deps.resolve ?? resolveAll;
13035
- return async (start, init) => {
13036
- let url = start;
13037
- const startOrigin = isRemoteUrl(start) ? new URL(start).origin : "";
13038
- for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
13039
- if (!isRemoteUrl(url)) throw new Error("only an https URL is fetched");
13040
- const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
13041
- const addresses = (0, node_net.isIP)(host) === 0 ? await resolve(host) : [host];
13042
- if (addresses.length === 0 || addresses.some(isPrivateAddress)) throw new Error("host refused: not a public address");
13043
- const sameOrigin = new URL(url).origin === startOrigin;
13044
- const response = await doFetch(url, {
13045
- redirect: "manual",
13046
- ...sameOrigin && init?.headers !== void 0 ? { headers: { ...init.headers } } : {},
13047
- ...hop === 0 && init?.body !== void 0 ? {
13048
- method: "POST",
13049
- body: init.body
13050
- } : {},
13051
- signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
13052
- });
13053
- if (response.status >= 300 && response.status < 400) {
13054
- const location = response.headers.get("location");
13055
- if (location === null) throw new Error("redirect without a location");
13056
- url = new URL(location, url).toString();
13057
- continue;
13058
- }
13059
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
13060
- return readCapped(response, MAX_IMAGE_BYTES);
13061
- }
13062
- throw new Error("too many redirects");
13063
- };
13064
- }
13065
- var httpRemoteFetch = createRemoteFetch();
13066
- //#endregion
13067
13827
  //#region src/img-plane.ts
13068
13828
  var FAILED_GRAB_TTL_MS = 30 * 6e4;
13069
13829
  var FAILED_GRAB_MAX = 500;
@@ -13225,7 +13985,7 @@ function createImagePlaneHandler(deps) {
13225
13985
  } catch {
13226
13986
  return end(res, 404);
13227
13987
  }
13228
- if (parts.length !== 2 || !isItemId(itemId) || which !== "poster" && which !== "fanart") {
13988
+ if (parts.length !== 2 || !isItemId(itemId) || !isImageKind(which)) {
13229
13989
  deps.logger.warn("image request refused", { meta: { reason: "bad-request" } });
13230
13990
  return end(res, 404);
13231
13991
  }
@@ -13285,18 +14045,44 @@ function channelsOf(line) {
13285
14045
  return count?.[1] !== void 0 ? Number(count[1]) : null;
13286
14046
  }
13287
14047
  var STREAM_LINE = /^\s*Stream #\d+:(\d+)(?:\[[^\]]*\])?(?:\(([^)]*)\))?[^:]*: (Video|Audio|Subtitle): (.*)$/;
14048
+ var CHAPTER_LINE = /^\s*Chapter #\d+:\d+: start ([\d.]+), end ([\d.]+)/;
14049
+ var CHAPTER_TITLE = /^\s+title\s*:\s*(.*)$/;
13288
14050
  /** Parse the report `ffmpeg -i <file>` prints on stderr. A report that is not one yields no streams and no duration. */
13289
14051
  function parseFfmpegReport(report) {
13290
14052
  const lines = report.split("\n");
13291
14053
  let container = null;
13292
14054
  let durationMs = null;
13293
14055
  const streams = [];
14056
+ const chapters = [];
13294
14057
  let doviSeenFor = null;
14058
+ let inChapters = false;
13295
14059
  for (const line of lines) {
13296
14060
  const input = /^Input #\d+, ([^,]+(?:,[^,]+)*), from /.exec(line);
13297
14061
  if (input?.[1] !== void 0 && container === null) container = containerOf(input[1]);
13298
14062
  const duration = /^\s*Duration: (\d+):(\d{2}):(\d{2})\.(\d{2})/.exec(line);
13299
14063
  if (duration && durationMs === null) durationMs = (Number(duration[1]) * 3600 + Number(duration[2]) * 60 + Number(duration[3])) * 1e3 + Number(duration[4]) * 10;
14064
+ const chapter = CHAPTER_LINE.exec(line);
14065
+ if (chapter?.[1] !== void 0 && chapter[2] !== void 0) {
14066
+ const startSec = Number(chapter[1]);
14067
+ const endSec = Number(chapter[2]);
14068
+ if (Number.isFinite(startSec) && Number.isFinite(endSec) && endSec > startSec) chapters.push({
14069
+ startSec,
14070
+ endSec,
14071
+ title: null
14072
+ });
14073
+ continue;
14074
+ }
14075
+ const titled = CHAPTER_TITLE.exec(line);
14076
+ const last = chapters[chapters.length - 1];
14077
+ if (titled?.[1] !== void 0 && last !== void 0 && last.title === null && inChapters) {
14078
+ if (titled[1].trim() !== "") chapters[chapters.length - 1] = {
14079
+ ...last,
14080
+ title: titled[1].trim()
14081
+ };
14082
+ continue;
14083
+ }
14084
+ if (/^\s*Chapters:/.test(line)) inChapters = true;
14085
+ if (STREAM_LINE.test(line)) inChapters = false;
13300
14086
  if (/DOVI configuration record/.test(line) && streams.length > 0) {
13301
14087
  doviSeenFor = streams.length - 1;
13302
14088
  continue;
@@ -13337,7 +14123,8 @@ function parseFfmpegReport(report) {
13337
14123
  return {
13338
14124
  container,
13339
14125
  durationMs,
13340
- streams
14126
+ streams,
14127
+ chapters
13341
14128
  };
13342
14129
  }
13343
14130
  var PROBE_TIMEOUT_MS = 3e4;
@@ -13380,6 +14167,9 @@ function createMediaLibraryProvider(store, scans) {
13380
14167
  getItem: ({ itemId, language, caller }) => store.getItem(caller.userId, itemId, language),
13381
14168
  search: ({ query, limit, language, caller }) => store.search(caller.userId, query, limit, language),
13382
14169
  listRecentlyAdded: ({ limit, language, caller }) => store.listRecentlyAdded(caller.userId, limit, language),
14170
+ listWatchlist: ({ limit, offset, language, caller }) => store.listWatchlist(caller.userId, limit, offset, language),
14171
+ setWatchlisted: ({ itemId, on, caller }) => store.setWatchlisted(caller.userId, itemId, on),
14172
+ getItemDetails: ({ itemId, language }) => store.getItemDetails(itemId, language),
13383
14173
  getProgress: ({ itemId, caller }) => store.getProgress(caller.userId, itemId),
13384
14174
  setProgress: ({ caller, ...input }) => store.setProgress(caller.userId, input),
13385
14175
  markWatched: ({ caller, ...input }) => store.markWatched(caller.userId, input),
@@ -13400,6 +14190,7 @@ function fill(into, from) {
13400
14190
  year: into.year ?? from.year,
13401
14191
  overview: into.overview ?? from.overview,
13402
14192
  translations: into.translations ?? from.translations,
14193
+ details: into.details ?? from.details,
13403
14194
  tvdbId: into.tvdbId ?? from.tvdbId,
13404
14195
  tmdbId: into.tmdbId ?? from.tmdbId,
13405
14196
  imdbId: into.imdbId ?? from.imdbId,
@@ -13561,7 +14352,10 @@ var Enricher = class {
13561
14352
  cachedMatch(provider, key) {
13562
14353
  const known = this.deps.cache.getMatch(key);
13563
14354
  if (known === null) return null;
13564
- return known.found && provider.translates === true && known.match.translations === void 0 ? null : known;
14355
+ if (!known.found) return known;
14356
+ const predatesTranslations = provider.translates === true && known.match.translations === void 0;
14357
+ const predatesDetails = provider.providesDetails === true && known.match.details === void 0;
14358
+ return predatesTranslations || predatesDetails ? null : known;
13565
14359
  }
13566
14360
  /** A pinned id is asked for directly: an answer of "nothing" is final, never turned into a title guess. */
13567
14361
  async lookup(provider, ask, item, kind, pin) {
@@ -13641,14 +14435,15 @@ var Enricher = class {
13641
14435
  async episodesOf(provider, item, match) {
13642
14436
  const key = `${this.keyOf(provider)}:eps:${match.remoteId}`;
13643
14437
  const known = this.deps.cache.getEpisodes(key);
13644
- if (known !== null) return known.episodes;
14438
+ const predatesDetails = provider.providesDetails === true && known !== null && known.episodes.some((entry) => entry.details === void 0);
14439
+ if (known !== null && !predatesDetails) return known.episodes;
13645
14440
  try {
13646
14441
  const episodes = await provider.episodes(match);
13647
14442
  this.deps.cache.putEpisodes(key, { episodes: [...episodes] });
13648
14443
  return episodes;
13649
14444
  } catch (error) {
13650
14445
  this.failed(provider.id, item.id, error);
13651
- return [];
14446
+ return known?.episodes ?? [];
13652
14447
  }
13653
14448
  }
13654
14449
  async onlineLayer(provider, item, acc, resolved, held) {
@@ -13662,6 +14457,7 @@ var Enricher = class {
13662
14457
  year: match.year,
13663
14458
  overview: match.overview,
13664
14459
  translations: match.translations ?? null,
14460
+ details: match.details ?? null,
13665
14461
  tvdbId: match.tvdbId,
13666
14462
  tmdbId: match.tmdbId,
13667
14463
  imdbId: match.imdbId,
@@ -13684,15 +14480,16 @@ var Enricher = class {
13684
14480
  ...NO_LOCAL,
13685
14481
  title: found.title,
13686
14482
  overview: found.overview,
13687
- poster: found.still
14483
+ poster: found.still,
14484
+ details: found.details ?? null
13688
14485
  };
13689
14486
  }
13690
14487
  canAsk(provider, item) {
13691
14488
  return provider.kinds.includes(item.kind === "movie" ? "movie" : "series");
13692
14489
  }
13693
14490
  needsOnline(provider, item, acc) {
13694
- if (item.kind === "episode") return acc.overview === null || acc.poster === null || item.titlePlaceholder && acc.title === null;
13695
- return acc.overview === null || acc.poster === null || provider.translates === true && acc.translations === null;
14491
+ if (item.kind === "episode") return acc.overview === null || acc.poster === null || provider.providesDetails === true && acc.details === null || item.titlePlaceholder && acc.title === null;
14492
+ return acc.overview === null || acc.poster === null || provider.translates === true && acc.translations === null || provider.providesDetails === true && acc.details === null;
13696
14493
  }
13697
14494
  async localLayer(item, firstEpisodeFile) {
13698
14495
  const { reader } = this.deps;
@@ -13741,6 +14538,7 @@ var Enricher = class {
13741
14538
  year: acc.year,
13742
14539
  overview: acc.overview,
13743
14540
  translations: acc.translations,
14541
+ details: acc.details,
13744
14542
  tvdbId: acc.tvdbId,
13745
14543
  tmdbId: acc.tmdbId,
13746
14544
  imdbId: acc.imdbId,
@@ -13782,6 +14580,7 @@ function newItem(base) {
13782
14580
  episodeNumber: null,
13783
14581
  overview: null,
13784
14582
  translations: null,
14583
+ details: null,
13785
14584
  tvdbId: null,
13786
14585
  tmdbId: null,
13787
14586
  imdbId: null,
@@ -14133,6 +14932,7 @@ async function scanLibrary(deps, sources) {
14133
14932
  const { addedHint, titlePlaceholder: _placeholder, ...fields } = item;
14134
14933
  writes.push({
14135
14934
  ...fields,
14935
+ details: fields.details ?? previous?.details ?? null,
14136
14936
  addedAt: previous?.addedAt ?? addedHint ?? startedAt,
14137
14937
  seenAt: startedAt
14138
14938
  });
@@ -14147,6 +14947,7 @@ async function scanLibrary(deps, sources) {
14147
14947
  for (const entry of harvests) for (const item of entry.items) if (item.filePath !== null) filePaths.set(item.filePath, item.id);
14148
14948
  outcome.files = filePaths.size;
14149
14949
  const fileWrites = [];
14950
+ let chaptersReprobed = 0;
14150
14951
  for (const [path, id] of filePaths) {
14151
14952
  const stat = await deps.stat(path);
14152
14953
  if (stat === null) {
@@ -14161,10 +14962,14 @@ async function scanLibrary(deps, sources) {
14161
14962
  continue;
14162
14963
  }
14163
14964
  const known = knownFiles.get(path);
14164
- if (known !== void 0 && known.sizeBytes === stat.size && known.mtimeMs === stat.mtimeMs && (known.probeOk || deps.now() - known.probedAt < 216e5)) {
14965
+ const unchanged = known !== void 0 && known.sizeBytes === stat.size && known.mtimeMs === stat.mtimeMs;
14966
+ const chaptersKnown = known?.chapters != null;
14967
+ const chaptersOnly = unchanged && known.probeOk && !chaptersKnown;
14968
+ if (unchanged && (known.probeOk && chaptersKnown || !known.probeOk && deps.now() - known.probedAt < 216e5)) {
14165
14969
  outcome.reused += 1;
14166
14970
  continue;
14167
14971
  }
14972
+ if (chaptersOnly) chaptersReprobed += 1;
14168
14973
  try {
14169
14974
  const result = await deps.probe(path);
14170
14975
  fileWrites.push({
@@ -14176,11 +14981,24 @@ async function scanLibrary(deps, sources) {
14176
14981
  container: result.container,
14177
14982
  durationMs: result.durationMs,
14178
14983
  streams: [...result.streams],
14984
+ chapters: [...result.chapters],
14179
14985
  probeError: null
14180
14986
  });
14181
14987
  outcome.probed += 1;
14182
14988
  } catch (error) {
14183
14989
  const message = error instanceof Error ? error.message : String(error);
14990
+ if (chaptersOnly) {
14991
+ logger.warn("chapters probe failed: the earlier probe result is kept", {
14992
+ tags: { itemId: id },
14993
+ meta: {
14994
+ path,
14995
+ reason: "chapters-probe-failed",
14996
+ error: message
14997
+ }
14998
+ });
14999
+ outcome.skipped += 1;
15000
+ continue;
15001
+ }
14184
15002
  logger.warn("probe failed: the file stays catalogued, unprobed", {
14185
15003
  tags: { itemId: id },
14186
15004
  meta: {
@@ -14198,17 +15016,20 @@ async function scanLibrary(deps, sources) {
14198
15016
  container: null,
14199
15017
  durationMs: null,
14200
15018
  streams: [],
15019
+ chapters: [],
14201
15020
  probeError: message
14202
15021
  });
14203
15022
  outcome.skipped += 1;
14204
15023
  }
14205
15024
  }
14206
15025
  if (fileWrites.length > 0) await db.upsertMany(FILES, ["path"], fileWrites);
15026
+ if (chaptersReprobed > 0) logger.info("files probed again only to read their chapters", { meta: { count: chaptersReprobed } });
14207
15027
  for (const entry of harvests) {
14208
15028
  if (!entry.trusted) continue;
14209
15029
  const stale = [...existingItems.values()].filter((item) => item.sourceId === entry.sourceId && !seenIds.has(item.id));
14210
15030
  if (stale.length === 0) continue;
14211
15031
  await db.deleteWhere(ITEMS, { whereIn: { id: stale.map((item) => item.id) } });
15032
+ await db.deleteWhere(WATCHLIST, { whereIn: { itemId: stale.map((item) => item.id) } });
14212
15033
  logger.info("items no longer in their source were removed", { meta: {
14213
15034
  sourceId: entry.sourceId,
14214
15035
  removed: stale.length
@@ -14464,6 +15285,15 @@ var MediaLibraryAddon = class extends BaseAddon {
14464
15285
  logger
14465
15286
  })
14466
15287
  });
15288
+ await ctx.dataPlane?.serve({
15289
+ prefix: SUBTITLE_PLANE_PREFIX,
15290
+ access: "viewer",
15291
+ handler: createSubtitlePlaneHandler({
15292
+ sidecars: (itemId) => store.subtitleSidecars(itemId),
15293
+ roots,
15294
+ logger
15295
+ })
15296
+ });
14467
15297
  await ctx.dataPlane?.serve({
14468
15298
  prefix: "img",
14469
15299
  access: "viewer",