@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.
@@ -8807,7 +8807,12 @@ var MediaItemSummarySchema = /* @__PURE__ */ object({
8807
8807
  /** False when the catalogue lists it but no playable file is on disk. */
8808
8808
  playable: /* @__PURE__ */ boolean(),
8809
8809
  /** The caller's progress; `null` when they have none. Absent on a catalogue-only row (series). */
8810
- progress: /* @__PURE__ */ MediaProgressSchema.nullable()
8810
+ progress: /* @__PURE__ */ MediaProgressSchema.nullable(),
8811
+ /**
8812
+ * The caller's watchlist state, on series and movie rows (list, get and search). Absent on an
8813
+ * episode, which cannot be watchlisted.
8814
+ */
8815
+ watchlisted: /* @__PURE__ */ boolean().optional()
8811
8816
  });
8812
8817
  /** An episode of a season list: the summary plus its plot, read in the same query. */
8813
8818
  var MediaEpisodeSummarySchema = /* @__PURE__ */ MediaItemSummarySchema.extend({ overview: /* @__PURE__ */ string().nullable() });
@@ -8825,6 +8830,30 @@ var LibraryFileInfoSchema = /* @__PURE__ */ object({
8825
8830
  /** False while the file is catalogued but not probed yet, or the probe failed. */
8826
8831
  probed: /* @__PURE__ */ boolean()
8827
8832
  });
8833
+ /** One chapter of a file: seconds from the start; `title` is `null` when the file names none. */
8834
+ var MediaChapterSchema = /* @__PURE__ */ object({
8835
+ startSec: /* @__PURE__ */ number().nonnegative(),
8836
+ endSec: /* @__PURE__ */ number().nonnegative(),
8837
+ title: /* @__PURE__ */ string().nullable()
8838
+ });
8839
+ /**
8840
+ * A subtitle file next to the video. `path` is the relative hub path that serves it as WebVTT;
8841
+ * append `?offsetMs=<signed integer, at most 600000 either way>` to shift every cue (the subtitle delay).
8842
+ */
8843
+ var ExternalSubtitleSchema = /* @__PURE__ */ object({
8844
+ id: /* @__PURE__ */ string(),
8845
+ language: /* @__PURE__ */ string().nullable(),
8846
+ forced: /* @__PURE__ */ boolean(),
8847
+ /** The format of the file on disk; the served body is always WebVTT. */
8848
+ format: /* @__PURE__ */ _enum([
8849
+ "srt",
8850
+ "ass",
8851
+ "ssa",
8852
+ "vtt"
8853
+ ]),
8854
+ label: /* @__PURE__ */ string(),
8855
+ path: /* @__PURE__ */ string()
8856
+ });
8828
8857
  var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8829
8858
  overview: /* @__PURE__ */ string().nullable(),
8830
8859
  ids: /* @__PURE__ */ object({
@@ -8835,7 +8864,46 @@ var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8835
8864
  fanartPath: /* @__PURE__ */ string().nullable(),
8836
8865
  /** Relative hub path that direct-plays the file, with HTTP Range. `null` when not playable. */
8837
8866
  playPath: /* @__PURE__ */ string().nullable(),
8838
- file: /* @__PURE__ */ LibraryFileInfoSchema.nullable()
8867
+ file: /* @__PURE__ */ LibraryFileInfoSchema.nullable(),
8868
+ /** The file's chapters in order; empty when it has none or it is not probed yet. */
8869
+ chapters: /* @__PURE__ */ array(MediaChapterSchema).readonly(),
8870
+ /** Sidecar subtitle files found next to the video; empty when none. */
8871
+ externalSubtitles: /* @__PURE__ */ array(ExternalSubtitleSchema).readonly()
8872
+ });
8873
+ /**
8874
+ * A person of an item's credits. `photoPath` is an image-plane handle relative to the hub origin
8875
+ * (the same plane that serves posters), `null` when the source has no photo: a provider's own URL
8876
+ * never leaves the addon.
8877
+ */
8878
+ var MediaPersonSchema = /* @__PURE__ */ object({
8879
+ /** The metadata source's id of the person. */
8880
+ id: /* @__PURE__ */ number().int(),
8881
+ name: /* @__PURE__ */ string(),
8882
+ photoPath: /* @__PURE__ */ string().nullable()
8883
+ });
8884
+ var MediaCastMemberSchema = /* @__PURE__ */ MediaPersonSchema.extend({
8885
+ /** The role played; `null` when the source names none. */
8886
+ character: /* @__PURE__ */ string().nullable(),
8887
+ /** Billing order, 0 first. */
8888
+ order: /* @__PURE__ */ number().int().nonnegative()
8889
+ });
8890
+ /**
8891
+ * What the metadata source holds about an item beyond its plot. Nothing fetched yet answers empty
8892
+ * arrays and `null`s; a failed re-fetch never replaces what is stored.
8893
+ */
8894
+ var MediaItemDetailsSchema = /* @__PURE__ */ object({
8895
+ itemId: /* @__PURE__ */ string(),
8896
+ genres: /* @__PURE__ */ array(/* @__PURE__ */ string()).readonly(),
8897
+ /** `null` when the source does not know it. */
8898
+ runtimeMinutes: /* @__PURE__ */ number().int().positive().nullable(),
8899
+ /** The age rating for the server's region (`PG-13`, `TV-MA`, `12`), or `null`. */
8900
+ certification: /* @__PURE__ */ string().nullable(),
8901
+ creators: /* @__PURE__ */ array(MediaPersonSchema).readonly(),
8902
+ directors: /* @__PURE__ */ array(MediaPersonSchema).readonly(),
8903
+ writers: /* @__PURE__ */ array(MediaPersonSchema).readonly(),
8904
+ cast: /* @__PURE__ */ array(MediaCastMemberSchema).readonly(),
8905
+ /** Episodes only; empty on a series or a movie. */
8906
+ guestStars: /* @__PURE__ */ array(MediaCastMemberSchema).readonly()
8839
8907
  });
8840
8908
  var MediaSeasonSchema = /* @__PURE__ */ object({
8841
8909
  seasonNumber: /* @__PURE__ */ number().int(),
@@ -8904,6 +8972,24 @@ var mediaLibraryCapability = {
8904
8972
  limit: /* @__PURE__ */ number().int().positive().max(100).optional(),
8905
8973
  language: LanguageInputSchema
8906
8974
  }), /* @__PURE__ */ array(MediaItemSummarySchema).readonly(), { caller: "required" }),
8975
+ /** The caller's series and movies they watchlisted, the latest added first. */
8976
+ listWatchlist: /* @__PURE__ */ method(PageInputSchema, MediaItemPageSchema, { caller: "required" }),
8977
+ /**
8978
+ * Put a series or a movie on the caller's watchlist, or take it off. Idempotent: the answer is the
8979
+ * state now. An episode is refused (`watchlist-kind`).
8980
+ */
8981
+ setWatchlisted: /* @__PURE__ */ method(/* @__PURE__ */ object({
8982
+ itemId: /* @__PURE__ */ string().min(1),
8983
+ on: /* @__PURE__ */ boolean()
8984
+ }), /* @__PURE__ */ object({ on: /* @__PURE__ */ boolean() }), {
8985
+ kind: "mutation",
8986
+ caller: "required"
8987
+ }),
8988
+ /** Genres, runtime, rating, crew and cast of one item; `null` when the id is unknown. */
8989
+ getItemDetails: /* @__PURE__ */ method(/* @__PURE__ */ object({
8990
+ itemId: /* @__PURE__ */ string().min(1),
8991
+ language: LanguageInputSchema
8992
+ }), /* @__PURE__ */ MediaItemDetailsSchema.nullable(), { caller: "required" }),
8907
8993
  /** The caller's progress in one item; `null` when they have none. */
8908
8994
  getProgress: /* @__PURE__ */ method(/* @__PURE__ */ object({ itemId: /* @__PURE__ */ string().min(1) }), /* @__PURE__ */ MediaProgressSchema.nullable(), { caller: "required" }),
8909
8995
  /**
@@ -9845,7 +9931,7 @@ function pump(path, start, end, res, stallMs) {
9845
9931
  res.on("close", () => settle(sent > 0 && res.writableFinished ? "finished" : "client-closed"));
9846
9932
  });
9847
9933
  }
9848
- function reject(res, status, extra) {
9934
+ function reject$1(res, status, extra) {
9849
9935
  res.writeHead(status, {
9850
9936
  "Content-Length": 0,
9851
9937
  ...extra
@@ -9857,18 +9943,18 @@ function createFilePlaneHandler(deps) {
9857
9943
  const stallMs = deps.stallMs ?? 3e4;
9858
9944
  return async (req, res) => {
9859
9945
  const method = req.method ?? "GET";
9860
- if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
9946
+ if (method !== "GET" && method !== "HEAD") return reject$1(res, 405, { Allow: "GET, HEAD" });
9861
9947
  const raw = (req.url ?? "/").split("?")[0] ?? "/";
9862
9948
  let itemId;
9863
9949
  try {
9864
9950
  itemId = decodeURIComponent(raw.replace(/^\//, ""));
9865
9951
  } catch {
9866
9952
  deps.logger.warn("file request refused: bad escape", { meta: { reason: "bad-id" } });
9867
- return reject(res, 404);
9953
+ return reject$1(res, 404);
9868
9954
  }
9869
9955
  if (!isItemId(itemId)) {
9870
9956
  deps.logger.warn("file request refused: not an item id", { meta: { reason: "bad-id" } });
9871
- return reject(res, 404);
9957
+ return reject$1(res, 404);
9872
9958
  }
9873
9959
  const tags = { itemId };
9874
9960
  const catalogued = await deps.lookup(itemId);
@@ -9877,7 +9963,7 @@ function createFilePlaneHandler(deps) {
9877
9963
  tags,
9878
9964
  meta: { reason: "not-catalogued" }
9879
9965
  });
9880
- return reject(res, 404);
9966
+ return reject$1(res, 404);
9881
9967
  }
9882
9968
  const path = await resolveServable(catalogued, await deps.roots());
9883
9969
  if (path === null) {
@@ -9885,7 +9971,7 @@ function createFilePlaneHandler(deps) {
9885
9971
  tags,
9886
9972
  meta: { reason: "outside-roots" }
9887
9973
  });
9888
- return reject(res, 404);
9974
+ return reject$1(res, 404);
9889
9975
  }
9890
9976
  let size;
9891
9977
  try {
@@ -9895,7 +9981,7 @@ function createFilePlaneHandler(deps) {
9895
9981
  tags,
9896
9982
  meta: { reason: "gone" }
9897
9983
  });
9898
- return reject(res, 404);
9984
+ return reject$1(res, 404);
9899
9985
  }
9900
9986
  const range = parseRange(headerOf(req.headers.range), size);
9901
9987
  if (range.kind === "unsatisfiable") {
@@ -9906,7 +9992,7 @@ function createFilePlaneHandler(deps) {
9906
9992
  size
9907
9993
  }
9908
9994
  });
9909
- return reject(res, 416, { "Content-Range": `bytes */${size}` });
9995
+ return reject$1(res, 416, { "Content-Range": `bytes */${size}` });
9910
9996
  }
9911
9997
  const start = range.kind === "range" ? range.start : 0;
9912
9998
  const end = range.kind === "range" ? range.end : size - 1;
@@ -9940,6 +10026,198 @@ function createFilePlaneHandler(deps) {
9940
10026
  function headerOf(value) {
9941
10027
  return Array.isArray(value) ? value[0] : value;
9942
10028
  }
10029
+ 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})/;
10030
+ function clock(hours, minutes, seconds, fraction) {
10031
+ return (((hours === void 0 ? 0 : Number(hours.slice(0, -1))) * 60 + Number(minutes)) * 60 + Number(seconds)) * 1e3 + Number(fraction.padEnd(3, "0"));
10032
+ }
10033
+ /** SRT and VTT share one cue shape: an optional id line, a timing line, text up to a blank line. */
10034
+ function parseTimedText(text) {
10035
+ const cues = [];
10036
+ for (const block of text.split(/\n{2,}/)) {
10037
+ const lines = block.split("\n");
10038
+ const at = lines.findIndex((line) => TIMING.test(line));
10039
+ if (at < 0) continue;
10040
+ const match = TIMING.exec(lines[at] ?? "");
10041
+ if (match === null) continue;
10042
+ const [, h1, m1, s1, f1, h2, m2, s2, f2] = match;
10043
+ if (m1 === void 0 || s1 === void 0 || f1 === void 0) continue;
10044
+ if (m2 === void 0 || s2 === void 0 || f2 === void 0) continue;
10045
+ const body = lines.slice(at + 1).join("\n").replace(/\{\\an?\d\}/g, "").trim();
10046
+ if (body === "") continue;
10047
+ cues.push({
10048
+ startMs: clock(h1, m1, s1, f1),
10049
+ endMs: clock(h2, m2, s2, f2),
10050
+ text: body
10051
+ });
10052
+ }
10053
+ return cues;
10054
+ }
10055
+ var ASS_TIME = /^(\d+):(\d{2}):(\d{2})[.:](\d{1,3})$/;
10056
+ function assClock(value) {
10057
+ const match = ASS_TIME.exec(value.trim());
10058
+ if (match === null) return null;
10059
+ const [, h, m, s, f] = match;
10060
+ if (h === void 0 || m === void 0 || s === void 0 || f === void 0) return null;
10061
+ const ms = f.length <= 2 ? Number(f.padEnd(2, "0")) * 10 : Number(f);
10062
+ return (Number(h) * 3600 + Number(m) * 60 + Number(s)) * 1e3 + ms;
10063
+ }
10064
+ /** Dialogue text with the styling dropped: override blocks gone, hard breaks kept. */
10065
+ function assText(raw) {
10066
+ return raw.replace(/\{[^}]*\}/g, "").replace(/\\[Nn]/g, "\n").replace(/\\h/g, " ").trim();
10067
+ }
10068
+ function parseAss(text) {
10069
+ let inEvents = false;
10070
+ let columns = [];
10071
+ const cues = [];
10072
+ for (const line of text.split("\n")) {
10073
+ const trimmed = line.trim();
10074
+ if (/^\[.*\]$/.test(trimmed)) {
10075
+ inEvents = trimmed.toLowerCase() === "[events]";
10076
+ continue;
10077
+ }
10078
+ if (!inEvents) continue;
10079
+ if (/^format:/i.test(trimmed)) {
10080
+ columns = trimmed.slice(trimmed.indexOf(":") + 1).split(",").map((name) => name.trim().toLowerCase());
10081
+ continue;
10082
+ }
10083
+ if (!/^dialogue:/i.test(trimmed)) continue;
10084
+ const startAt = columns.indexOf("start");
10085
+ const endAt = columns.indexOf("end");
10086
+ const textAt = columns.indexOf("text");
10087
+ if (startAt < 0 || endAt < 0 || textAt < 0) continue;
10088
+ const fields = trimmed.slice(trimmed.indexOf(":") + 1).split(",");
10089
+ const head = fields.slice(0, textAt);
10090
+ const rawText = fields.slice(textAt).join(",");
10091
+ if (/\{[^}]*\\p[1-9]/.test(rawText)) continue;
10092
+ const start = assClock(head[startAt] ?? "");
10093
+ const end = assClock(head[endAt] ?? "");
10094
+ const body = assText(rawText);
10095
+ if (start === null || end === null || body === "") continue;
10096
+ cues.push({
10097
+ startMs: start,
10098
+ endMs: end,
10099
+ text: body
10100
+ });
10101
+ }
10102
+ return cues.sort((a, b) => a.startMs - b.startMs);
10103
+ }
10104
+ function stamp(ms) {
10105
+ const total = Math.max(0, Math.round(ms));
10106
+ const pad = (value, width) => String(value).padStart(width, "0");
10107
+ const hours = Math.floor(total / 36e5);
10108
+ const minutes = Math.floor(total % 36e5 / 6e4);
10109
+ const seconds = Math.floor(total % 6e4 / 1e3);
10110
+ return `${pad(hours, 2)}:${pad(minutes, 2)}:${pad(seconds, 2)}.${pad(total % 1e3, 3)}`;
10111
+ }
10112
+ /**
10113
+ * One subtitle file as WebVTT, every cue moved by `offsetMs` (negative = earlier). A cue is clamped at 0
10114
+ * and dropped when nothing of it is left after the shift.
10115
+ */
10116
+ function toWebVtt(source, format, offsetMs = 0) {
10117
+ const text = source.replace(/^/, "").replace(/\r\n?/g, "\n");
10118
+ const cues = format === "ass" || format === "ssa" ? parseAss(text) : parseTimedText(text);
10119
+ const out = ["WEBVTT", ""];
10120
+ for (const cue of cues) {
10121
+ const start = Math.max(0, cue.startMs + offsetMs);
10122
+ const end = Math.max(0, cue.endMs + offsetMs);
10123
+ if (end <= start) continue;
10124
+ out.push(`${stamp(start)} --> ${stamp(end)}`, cue.text, "");
10125
+ }
10126
+ return out.join("\n");
10127
+ }
10128
+ function reject(res, status, extra) {
10129
+ res.writeHead(status, {
10130
+ "Content-Length": 0,
10131
+ ...extra
10132
+ });
10133
+ res.end();
10134
+ }
10135
+ /** `offsetMs` from a query: absent is 0; anything but a bounded signed integer is `null` (refused). */
10136
+ function parseOffsetMs(query) {
10137
+ const raw = new URLSearchParams(query).get("offsetMs");
10138
+ if (raw === null) return 0;
10139
+ if (!/^-?\d{1,7}$/.test(raw)) return null;
10140
+ const value = Number(raw);
10141
+ return Math.abs(value) <= 6e5 ? value : null;
10142
+ }
10143
+ /** The `subtitle` plane: `GET|HEAD /<itemId>/<sidecarId>[?offsetMs=N]` answers one sidecar as WebVTT. */
10144
+ function createSubtitlePlaneHandler(deps) {
10145
+ return async (req, res) => {
10146
+ const method = req.method ?? "GET";
10147
+ if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10148
+ const [rawPath = "/", query = ""] = (req.url ?? "/").split("?");
10149
+ const segments = rawPath.replace(/^\//, "").split("/");
10150
+ let itemId;
10151
+ let sidecar;
10152
+ try {
10153
+ if (segments.length !== 2) return reject(res, 404);
10154
+ itemId = decodeURIComponent(segments[0] ?? "");
10155
+ sidecar = decodeURIComponent(segments[1] ?? "");
10156
+ } catch {
10157
+ return reject(res, 404);
10158
+ }
10159
+ if (!isItemId(itemId)) {
10160
+ deps.logger.warn("subtitle request refused: not an item id", { meta: { reason: "bad-id" } });
10161
+ return reject(res, 404);
10162
+ }
10163
+ const tags = { itemId };
10164
+ const offsetMs = parseOffsetMs(query);
10165
+ if (offsetMs === null) {
10166
+ deps.logger.info("subtitle request refused: bad offset", {
10167
+ tags,
10168
+ meta: { reason: "bad-offset" }
10169
+ });
10170
+ return reject(res, 400);
10171
+ }
10172
+ const known = (await deps.sidecars(itemId))?.find((candidate) => candidate.id === sidecar);
10173
+ if (known === void 0) {
10174
+ deps.logger.info("subtitle request refused: not a sidecar of this item", {
10175
+ tags,
10176
+ meta: { reason: "not-a-sidecar" }
10177
+ });
10178
+ return reject(res, 404);
10179
+ }
10180
+ const path = await resolveServable(known.filePath, await deps.roots());
10181
+ if (path === null) {
10182
+ deps.logger.warn("subtitle request refused: outside the library roots", {
10183
+ tags,
10184
+ meta: { reason: "outside-roots" }
10185
+ });
10186
+ return reject(res, 404);
10187
+ }
10188
+ try {
10189
+ if ((await stat(path)).size > 5242880) {
10190
+ deps.logger.warn("subtitle request refused: file too large", {
10191
+ tags,
10192
+ meta: { reason: "too-large" }
10193
+ });
10194
+ return reject(res, 404);
10195
+ }
10196
+ const body = Buffer.from(toWebVtt(await readFile(path, "utf8"), known.format, offsetMs), "utf8");
10197
+ res.writeHead(200, {
10198
+ "Content-Type": "text/vtt; charset=utf-8",
10199
+ "Content-Length": body.length,
10200
+ "Cache-Control": "private, no-store"
10201
+ });
10202
+ if (method === "HEAD") res.end();
10203
+ else res.end(body);
10204
+ deps.logger.debug("subtitle served", {
10205
+ tags,
10206
+ meta: {
10207
+ sidecar,
10208
+ format: known.format,
10209
+ offsetMs
10210
+ }
10211
+ });
10212
+ } catch {
10213
+ deps.logger.warn("subtitle request refused: file vanished", {
10214
+ tags,
10215
+ meta: { reason: "gone" }
10216
+ });
10217
+ reject(res, 404);
10218
+ }
10219
+ };
10220
+ }
9943
10221
  //#endregion
9944
10222
  //#region src/folder-walker.ts
9945
10223
  var VIDEO_EXTENSIONS = new Set([
@@ -10046,6 +10324,71 @@ function parseRows(schema, rows, onInvalid) {
10046
10324
  return out;
10047
10325
  }
10048
10326
  //#endregion
10327
+ //#region src/item-details.ts
10328
+ /**
10329
+ * What a metadata source holds about one item beyond its plot: genres, runtime, rating, crew and
10330
+ * cast. Stored with the item (a JSON column), never handed to a client as is: a person's `photo` is
10331
+ * the SOURCE's https URL, and a client gets an image-plane handle instead (`personImageKey`).
10332
+ */
10333
+ var StoredPersonSchema = object({
10334
+ id: number().int(),
10335
+ name: string(),
10336
+ /** The source's https URL of the profile picture; `null` when it has none. Never sent to a client. */
10337
+ photo: string().nullable()
10338
+ });
10339
+ var StoredCastSchema = StoredPersonSchema.extend({
10340
+ character: string().nullable(),
10341
+ order: number().int().nonnegative()
10342
+ });
10343
+ var ItemDetailsSchema = object({
10344
+ /** Genre names by language tag (lower-case, as `translations`): a source answers them in the language it was asked. */
10345
+ genres: record(string(), array(string())),
10346
+ runtimeMinutes: number().int().positive().nullable(),
10347
+ certification: string().nullable(),
10348
+ creators: array(StoredPersonSchema),
10349
+ directors: array(StoredPersonSchema),
10350
+ writers: array(StoredPersonSchema),
10351
+ cast: array(StoredCastSchema),
10352
+ guestStars: array(StoredCastSchema)
10353
+ });
10354
+ var EMPTY_DETAILS = {
10355
+ genres: {},
10356
+ runtimeMinutes: null,
10357
+ certification: null,
10358
+ creators: [],
10359
+ directors: [],
10360
+ writers: [],
10361
+ cast: [],
10362
+ guestStars: []
10363
+ };
10364
+ var PERSON_KEY = /^person-(\d{1,12})$/;
10365
+ function personImageKey(personId) {
10366
+ return `person-${personId}`;
10367
+ }
10368
+ function isImageKind(value) {
10369
+ return value === "poster" || value === "fanart" || value !== void 0 && PERSON_KEY.test(value);
10370
+ }
10371
+ function isPersonPhotoUrl(value) {
10372
+ if (!URL.canParse(value)) return false;
10373
+ const url = new URL(value);
10374
+ return url.protocol === "https:" && url.hostname === "image.tmdb.org";
10375
+ }
10376
+ /** The person id an image key names, or `null` for a poster or a fanart. */
10377
+ function personIdOf(kind) {
10378
+ const found = PERSON_KEY.exec(kind);
10379
+ return found?.[1] === void 0 ? null : Number(found[1]);
10380
+ }
10381
+ /** The profile picture URL stored for `personId` among the credits of `details`, or `null`. */
10382
+ function personPhotoOf(details, personId) {
10383
+ return [
10384
+ ...details.cast,
10385
+ ...details.guestStars,
10386
+ ...details.creators,
10387
+ ...details.directors,
10388
+ ...details.writers
10389
+ ].find((person) => person.id === personId)?.photo ?? null;
10390
+ }
10391
+ //#endregion
10049
10392
  //#region src/metadata.ts
10050
10393
  /**
10051
10394
  * One language's text of an item: either field may be absent (a provider can translate the title and
@@ -10070,14 +10413,18 @@ var ProviderMatchSchema = object({
10070
10413
  poster: string().nullable(),
10071
10414
  fanart: string().nullable(),
10072
10415
  /** The title and overview in other languages, when the provider answered them with the match. */
10073
- translations: TranslationMapSchema.optional()
10416
+ translations: TranslationMapSchema.optional(),
10417
+ /** Genres, rating, crew and cast, answered with the match. Absent from a match cached before they were kept. */
10418
+ details: ItemDetailsSchema.optional()
10074
10419
  });
10075
10420
  var ProviderEpisodeSchema = object({
10076
10421
  season: number().int(),
10077
10422
  episode: number().int(),
10078
10423
  title: string().nullable(),
10079
10424
  overview: string().nullable(),
10080
- still: string().nullable()
10425
+ still: string().nullable(),
10426
+ /** The episode's own runtime, crew and guest stars, read from the season answer. Absent from a list cached before they were kept. */
10427
+ details: ItemDetailsSchema.optional()
10081
10428
  });
10082
10429
  /** The provider refused its credential: asking again cannot work until the operator fixes it. */
10083
10430
  var ProviderAuthError = class extends Error {
@@ -10199,6 +10546,7 @@ var ITEMS = "media-library:items";
10199
10546
  var FILES = "media-library:files";
10200
10547
  var PROGRESS = "media-library:progress";
10201
10548
  var PINS = "media-library:pins";
10549
+ var WATCHLIST = "media-library:watchlist";
10202
10550
  /** Item row: one series, movie or episode of the catalogue. */
10203
10551
  var ItemRowSchema = object({
10204
10552
  id: string(),
@@ -10213,6 +10561,8 @@ var ItemRowSchema = object({
10213
10561
  overview: string().nullable(),
10214
10562
  /** The title and overview in other languages; absent on a row written before they were kept. */
10215
10563
  translations: TranslationMapSchema.nullish(),
10564
+ /** Genres, rating, crew and cast; absent on a row written before they were kept, `null` when no source gave any. */
10565
+ details: ItemDetailsSchema.nullish(),
10216
10566
  tvdbId: number().int().nullable(),
10217
10567
  tmdbId: number().int().nullable(),
10218
10568
  imdbId: string().nullable(),
@@ -10238,6 +10588,8 @@ var FileRowSchema = object({
10238
10588
  container: string().nullable(),
10239
10589
  durationMs: number().int().nullable(),
10240
10590
  streams: array(LibraryStreamSchema),
10591
+ /** Absent on a row probed before chapters were read: the next scan probes it again. */
10592
+ chapters: array(MediaChapterSchema).nullish(),
10241
10593
  probeError: string().nullable()
10242
10594
  });
10243
10595
  var PinSourceSchema = _enum(["plex", "manual"]);
@@ -10258,6 +10610,12 @@ var ProgressRowSchema = object({
10258
10610
  updatedAt: number().int(),
10259
10611
  watched: boolean()
10260
10612
  });
10613
+ /** One series or movie a person put on their watchlist. */
10614
+ var WatchlistRowSchema = object({
10615
+ userId: string(),
10616
+ itemId: string(),
10617
+ addedAt: number().int()
10618
+ });
10261
10619
  var text$3 = (name, notNull = false) => ({
10262
10620
  name,
10263
10621
  type: "TEXT",
@@ -10287,6 +10645,10 @@ var COLLECTIONS = [
10287
10645
  name: "translations",
10288
10646
  type: "JSON"
10289
10647
  },
10648
+ {
10649
+ name: "details",
10650
+ type: "JSON"
10651
+ },
10290
10652
  int("tvdbId"),
10291
10653
  int("tmdbId"),
10292
10654
  text$3("imdbId"),
@@ -10345,6 +10707,10 @@ var COLLECTIONS = [
10345
10707
  type: "JSON",
10346
10708
  notNull: true
10347
10709
  },
10710
+ {
10711
+ name: "chapters",
10712
+ type: "JSON"
10713
+ },
10348
10714
  text$3("probeError")
10349
10715
  ]
10350
10716
  },
@@ -10386,6 +10752,20 @@ var COLLECTIONS = [
10386
10752
  "updatedAt"
10387
10753
  ]
10388
10754
  }]
10755
+ },
10756
+ {
10757
+ collection: WATCHLIST,
10758
+ primaryKey: ["userId", "itemId"],
10759
+ withoutRowid: true,
10760
+ columns: [
10761
+ text$3("userId", true),
10762
+ text$3("itemId", true),
10763
+ int("addedAt", true)
10764
+ ],
10765
+ indexes: [{
10766
+ name: "idx_media_watchlist_user",
10767
+ columns: ["userId", "addedAt"]
10768
+ }]
10389
10769
  }
10390
10770
  ];
10391
10771
  //#endregion
@@ -10653,6 +11033,7 @@ var NO_LOCAL = {
10653
11033
  year: null,
10654
11034
  overview: null,
10655
11035
  translations: null,
11036
+ details: null,
10656
11037
  tvdbId: null,
10657
11038
  tmdbId: null,
10658
11039
  imdbId: null,
@@ -10693,6 +11074,7 @@ function merge(first, second) {
10693
11074
  year: pick$1(first.year, second.year),
10694
11075
  overview: pick$1(first.overview, second.overview),
10695
11076
  translations: pick$1(first.translations, second.translations),
11077
+ details: pick$1(first.details, second.details),
10696
11078
  tvdbId: pick$1(first.tvdbId, second.tvdbId),
10697
11079
  tmdbId: pick$1(first.tmdbId, second.tmdbId),
10698
11080
  imdbId: pick$1(first.imdbId, second.imdbId),
@@ -10750,6 +11132,60 @@ async function localMovie(reader, filePath) {
10750
11132
  };
10751
11133
  }
10752
11134
  //#endregion
11135
+ //#region src/subtitle-sidecars.ts
11136
+ var FORMATS$1 = [
11137
+ "srt",
11138
+ "ass",
11139
+ "ssa",
11140
+ "vtt"
11141
+ ];
11142
+ var LANGUAGE = /^[a-z]{2,3}(?:-[a-z0-9]{2,4})?$/i;
11143
+ function formatOf(extension) {
11144
+ const bare = extension.slice(1).toLowerCase();
11145
+ return FORMATS$1.find((format) => format === bare) ?? null;
11146
+ }
11147
+ /** A stable id from the file name: it never carries a path, so a client cannot name one. */
11148
+ function sidecarId(fileName) {
11149
+ return createHash("sha1").update(fileName.toLowerCase()).digest("hex").slice(0, 10);
11150
+ }
11151
+ /**
11152
+ * The subtitle files of `videoPath` in its folder's `listing`: `<base>.srt`, `<base>.<lang>.srt`,
11153
+ * `<base>.<lang>.forced.srt` (also `.ass`, `.ssa`, `.vtt`). The base is matched case-insensitively and
11154
+ * must be followed by a dot, so `Movie2.srt` is not the sidecar of `Movie.mkv`.
11155
+ */
11156
+ function discoverSubtitles(videoPath, listing) {
11157
+ const dir = dirname(videoPath);
11158
+ const base = basename(videoPath, extname(videoPath)).toLowerCase();
11159
+ const found = [];
11160
+ for (const [lower, real] of listing) {
11161
+ const extension = extname(lower);
11162
+ const format = formatOf(extension);
11163
+ if (format === null || !lower.startsWith(`${base}.`)) continue;
11164
+ const middle = lower.slice(base.length + 1, lower.length - extension.length);
11165
+ const tokens = middle === "" ? [] : middle.split(".");
11166
+ let language = null;
11167
+ let forced = false;
11168
+ const extra = [];
11169
+ for (const token of tokens) if (token === "forced") forced = true;
11170
+ else if (language === null && extra.length === 0 && LANGUAGE.test(token)) language = token;
11171
+ else extra.push(token);
11172
+ const parts = [
11173
+ language,
11174
+ ...extra,
11175
+ forced ? "forced" : null
11176
+ ].filter((part) => part !== null);
11177
+ found.push({
11178
+ id: sidecarId(real),
11179
+ language,
11180
+ forced,
11181
+ format,
11182
+ label: parts.length === 0 ? "Subtitles" : parts.join(" "),
11183
+ filePath: join(dir, real)
11184
+ });
11185
+ }
11186
+ return found.sort((a, b) => a.filePath.localeCompare(b.filePath));
11187
+ }
11188
+ //#endregion
10753
11189
  //#region src/item-text.ts
10754
11190
  /**
10755
11191
  * A language tag as the translations are keyed: lower-case, region dropped (`it-IT` is `it`).
@@ -10791,31 +11227,49 @@ function sortByShownTitle(rows, requested, serverDefault) {
10791
11227
  return rows.toSorted((a, b) => collator.compare(keys.get(a) ?? "", keys.get(b) ?? ""));
10792
11228
  }
10793
11229
  var FILE_PLANE_PREFIX = "file";
11230
+ var SUBTITLE_PLANE_PREFIX = "subtitle";
10794
11231
  var HUB_PLANE_BASE = "/addon/media-library";
10795
11232
  var SEARCH_DEFAULT_LIMIT = 50;
10796
11233
  var RECENT_DEFAULT_LIMIT = 20;
10797
11234
  var CONTINUE_DEFAULT_LIMIT = 20;
10798
11235
  /** A rewound row is not "continue", so the read asks for a few more than it will show. */
10799
11236
  var CONTINUE_OVERFETCH = 3;
11237
+ /** Item ids resolved per read when a watchlist is larger than one query takes. */
11238
+ var WATCHLIST_RESOLVE_CHUNK = 500;
10800
11239
  function playPathOf(itemId) {
10801
11240
  return `${HUB_PLANE_BASE}/${FILE_PLANE_PREFIX}/${itemId}`;
10802
11241
  }
11242
+ function subtitlePathOf(itemId, sidecarId) {
11243
+ return `${HUB_PLANE_BASE}/${SUBTITLE_PLANE_PREFIX}/${itemId}/${sidecarId}`;
11244
+ }
10803
11245
  function imagePathOf(itemId, which) {
10804
11246
  return `${HUB_PLANE_BASE}/img/${itemId}/${which}`;
10805
11247
  }
10806
11248
  function isWatched(positionMs, durationMs) {
10807
11249
  return durationMs > 0 && positionMs / durationMs >= .9;
10808
11250
  }
11251
+ /** An episode cannot be watchlisted: the series is what a person follows. */
11252
+ var WatchlistKindError = class extends Error {
11253
+ code = "watchlist-kind";
11254
+ constructor(itemId) {
11255
+ super(`watchlist-kind: ${itemId} is an episode; only a series or a movie can be watchlisted`);
11256
+ this.name = "WatchlistKindError";
11257
+ }
11258
+ };
10809
11259
  var idList = (rows) => rows.map((row) => row.id);
10810
11260
  var LibraryStore = class {
10811
11261
  db;
10812
11262
  logger;
10813
11263
  serverLanguage;
11264
+ now;
11265
+ listDir;
10814
11266
  locks = /* @__PURE__ */ new Map();
10815
- constructor(db, logger, serverLanguage = () => "en") {
11267
+ constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir) {
10816
11268
  this.db = db;
10817
11269
  this.logger = logger;
10818
11270
  this.serverLanguage = serverLanguage;
11271
+ this.now = now;
11272
+ this.listDir = listDir;
10819
11273
  }
10820
11274
  async init() {
10821
11275
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -10836,6 +11290,9 @@ var LibraryStore = class {
10836
11290
  async queryFiles(filter) {
10837
11291
  return parseRows(FileRowSchema, await this.db.query(FILES, filter), this.invalid(FILES));
10838
11292
  }
11293
+ async queryWatchlist(filter) {
11294
+ return parseRows(WatchlistRowSchema, await this.db.query(WATCHLIST, filter), this.invalid(WATCHLIST));
11295
+ }
10839
11296
  async queryProgress(filter) {
10840
11297
  return parseRows(ProgressRowSchema, await this.db.query(PROGRESS, filter), this.invalid(PROGRESS));
10841
11298
  }
@@ -10850,9 +11307,15 @@ var LibraryStore = class {
10850
11307
  where: { userId },
10851
11308
  whereIn: { itemId: playableIds }
10852
11309
  })) progress.set(entry.itemId, entry);
11310
+ const followable = rows.filter((row) => row.kind !== "episode").map((row) => row.id);
11311
+ const watchlisted = /* @__PURE__ */ new Set();
11312
+ if (followable.length > 0) for (const entry of await this.queryWatchlist({
11313
+ where: { userId },
11314
+ whereIn: { itemId: followable }
11315
+ })) watchlisted.add(entry.itemId);
10853
11316
  const fallback = this.serverLanguage();
10854
11317
  return rows.map((row) => {
10855
- return toSummary(row, row.filePath === null ? void 0 : files.get(row.filePath), progress.get(row.id), resolveItemText(row, language, fallback).title);
11318
+ 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));
10856
11319
  });
10857
11320
  }
10858
11321
  pageOf = async (kind, userId, limit, offset, language) => {
@@ -10971,9 +11434,24 @@ var LibraryStore = class {
10971
11434
  },
10972
11435
  fanartPath: row.fanartSource === null ? null : imagePathOf(row.id, "fanart"),
10973
11436
  playPath: file === void 0 ? null : playPathOf(row.id),
10974
- file: file === void 0 ? null : toFileInfo(file)
11437
+ file: file === void 0 ? null : toFileInfo(file),
11438
+ chapters: file?.chapters ?? [],
11439
+ externalSubtitles: (await this.subtitleSidecars(row.id)).map((sidecar) => ({
11440
+ id: sidecar.id,
11441
+ language: sidecar.language,
11442
+ forced: sidecar.forced,
11443
+ format: sidecar.format,
11444
+ label: sidecar.label,
11445
+ path: subtitlePathOf(row.id, sidecar.id)
11446
+ }))
10975
11447
  };
10976
11448
  }
11449
+ /** The subtitle files next to the video of `itemId`; empty when it has none or no file. */
11450
+ async subtitleSidecars(itemId) {
11451
+ const catalogued = await this.playableFile(itemId);
11452
+ if (catalogued === null) return [];
11453
+ return discoverSubtitles(catalogued.path, await this.listDir(dirname(catalogued.path)));
11454
+ }
10977
11455
  /** The file a client may stream for `itemId`, or `null`: the path comes from here, never from the client. */
10978
11456
  async playableFile(itemId) {
10979
11457
  const [item] = await this.queryItems({
@@ -10997,6 +11475,14 @@ var LibraryStore = class {
10997
11475
  limit: 1
10998
11476
  });
10999
11477
  if (item === void 0) return [];
11478
+ const personId = personIdOf(which);
11479
+ if (personId !== null) {
11480
+ const photo = item.details === null || item.details === void 0 ? null : personPhotoOf(item.details, personId);
11481
+ return photo !== null && isPersonPhotoUrl(photo) ? [{
11482
+ kind: "remote",
11483
+ url: photo
11484
+ }] : [];
11485
+ }
11000
11486
  const out = [];
11001
11487
  const cover = which === "poster" ? item.posterSource : item.fanartSource;
11002
11488
  if (cover !== null) {
@@ -11032,6 +11518,86 @@ var LibraryStore = class {
11032
11518
  }
11033
11519
  return out;
11034
11520
  }
11521
+ /** The caller's series and movies on their watchlist, the latest added first. */
11522
+ async listWatchlist(userId, limit, offset, language) {
11523
+ 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));
11524
+ if (held.length === 0) return {
11525
+ items: [],
11526
+ total: 0
11527
+ };
11528
+ const rows = /* @__PURE__ */ new Map();
11529
+ for (let at = 0; at < held.length; at += WATCHLIST_RESOLVE_CHUNK) {
11530
+ const ids = held.slice(at, at + WATCHLIST_RESOLVE_CHUNK).map((entry) => entry.itemId);
11531
+ for (const row of await this.queryItems({ whereIn: { id: ids } })) rows.set(row.id, row);
11532
+ }
11533
+ const resolved = held.flatMap((entry) => {
11534
+ const row = rows.get(entry.itemId);
11535
+ return row === void 0 ? [] : [row];
11536
+ });
11537
+ const start = offset ?? 0;
11538
+ const ordered = resolved.slice(start, start + (limit ?? 100));
11539
+ const total = resolved.length;
11540
+ return {
11541
+ items: await this.summaries(ordered, userId, language),
11542
+ total
11543
+ };
11544
+ }
11545
+ /** Put a series or a movie on the caller's watchlist, or take it off. Idempotent; an episode is refused. */
11546
+ setWatchlisted(userId, itemId, on) {
11547
+ return this.locked(`watchlist\u0000${userId}\u0000${itemId}`, async () => {
11548
+ if ((await this.requirePlayable(itemId)).kind === "episode") throw new WatchlistKindError(itemId);
11549
+ if (!on) {
11550
+ await this.db.deleteWhere(WATCHLIST, { where: {
11551
+ userId,
11552
+ itemId
11553
+ } });
11554
+ return { on: false };
11555
+ }
11556
+ const [held] = await this.queryWatchlist({
11557
+ where: {
11558
+ userId,
11559
+ itemId
11560
+ },
11561
+ limit: 1
11562
+ });
11563
+ if (held === void 0) await this.db.upsertMany(WATCHLIST, ["userId", "itemId"], [{
11564
+ userId,
11565
+ itemId,
11566
+ addedAt: this.now()
11567
+ }]);
11568
+ return { on: true };
11569
+ });
11570
+ }
11571
+ /** Genres, runtime, rating, crew and cast of one item, in the reader's language; empty when nothing was fetched. */
11572
+ async getItemDetails(itemId, language) {
11573
+ const [row] = await this.queryItems({
11574
+ where: { id: itemId },
11575
+ limit: 1
11576
+ });
11577
+ if (row === void 0) return null;
11578
+ const details = row.details ?? EMPTY_DETAILS;
11579
+ const person = (entry) => ({
11580
+ id: entry.id,
11581
+ name: entry.name,
11582
+ photoPath: entry.photo === null || !isPersonPhotoUrl(entry.photo) ? null : imagePathOf(row.id, personImageKey(entry.id))
11583
+ });
11584
+ const member = (entry) => ({
11585
+ ...person(entry),
11586
+ character: entry.character,
11587
+ order: entry.order
11588
+ });
11589
+ return {
11590
+ itemId: row.id,
11591
+ genres: genresOf(details, language, this.serverLanguage()),
11592
+ runtimeMinutes: details.runtimeMinutes,
11593
+ certification: details.certification,
11594
+ creators: details.creators.map(person),
11595
+ directors: details.directors.map(person),
11596
+ writers: details.writers.map(person),
11597
+ cast: details.cast.map(member),
11598
+ guestStars: details.guestStars.map(member)
11599
+ };
11600
+ }
11035
11601
  /** Serialise the read-compare-write of one (user, item) so two writes of one person cannot interleave. */
11036
11602
  async locked(key, run) {
11037
11603
  const next = (this.locks.get(key) ?? Promise.resolve()).then(run, run);
@@ -11181,6 +11747,21 @@ var LibraryStore = class {
11181
11747
  return entries;
11182
11748
  }
11183
11749
  };
11750
+ async function defaultListDir(dir) {
11751
+ try {
11752
+ return new Map((await readdir(dir)).map((name) => [name.toLowerCase(), name]));
11753
+ } catch {
11754
+ return /* @__PURE__ */ new Map();
11755
+ }
11756
+ }
11757
+ /** Genre names: the language asked for, else the server's, else whichever language the source answered. */
11758
+ function genresOf(details, requested, serverDefault) {
11759
+ for (const key of [languageKey(requested), languageKey(serverDefault)]) {
11760
+ const found = key === void 0 ? void 0 : details.genres[key];
11761
+ if (found !== void 0) return found;
11762
+ }
11763
+ return Object.values(details.genres)[0] ?? [];
11764
+ }
11184
11765
  function toProgress(row) {
11185
11766
  return {
11186
11767
  itemId: row.itemId,
@@ -11199,7 +11780,7 @@ function toFileInfo(file) {
11199
11780
  probed: file.probeOk
11200
11781
  };
11201
11782
  }
11202
- function toSummary(row, file, progress, title) {
11783
+ function toSummary(row, file, progress, title, watchlisted) {
11203
11784
  return {
11204
11785
  id: row.id,
11205
11786
  kind: row.kind,
@@ -11212,7 +11793,8 @@ function toSummary(row, file, progress, title) {
11212
11793
  addedAt: row.addedAt,
11213
11794
  durationMs: file?.durationMs ?? null,
11214
11795
  playable: row.kind !== "series" && file !== void 0,
11215
- progress: progress === void 0 ? null : toProgress(progress)
11796
+ progress: progress === void 0 ? null : toProgress(progress),
11797
+ ...watchlisted === void 0 ? {} : { watchlisted }
11216
11798
  };
11217
11799
  }
11218
11800
  //#endregion
@@ -12499,6 +13081,103 @@ var ServerLanguage = class {
12499
13081
  }
12500
13082
  };
12501
13083
  //#endregion
13084
+ //#region src/remote-fetch.ts
13085
+ var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
13086
+ var IMAGE_TIMEOUT_MS = 2e4;
13087
+ var MAX_REDIRECTS = 3;
13088
+ /** Read a response body, aborting as soon as it passes `cap`: the rest is never buffered. */
13089
+ async function readCapped(response, cap) {
13090
+ if (Number(response.headers.get("content-length") ?? "0") > cap) throw new Error("image too large");
13091
+ if (response.body === null) return Buffer.alloc(0);
13092
+ const reader = response.body.getReader();
13093
+ const chunks = [];
13094
+ let total = 0;
13095
+ for (;;) {
13096
+ const { done, value } = await reader.read();
13097
+ if (done) break;
13098
+ total += value.byteLength;
13099
+ if (total > cap) {
13100
+ await reader.cancel();
13101
+ throw new Error("image too large");
13102
+ }
13103
+ chunks.push(Buffer.from(value));
13104
+ }
13105
+ return Buffer.concat(chunks, total);
13106
+ }
13107
+ function v4Private(address) {
13108
+ const [a = 0, b = 0] = address.split(".").map(Number);
13109
+ 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;
13110
+ }
13111
+ /** Loopback, private, link-local, ULA, CGNAT, multicast and unspecified addresses, v4 and v6. */
13112
+ function isPrivateAddress(address) {
13113
+ const kind = isIP(address);
13114
+ if (kind === 4) return v4Private(address);
13115
+ if (kind !== 6) return true;
13116
+ const lower = address.toLowerCase();
13117
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
13118
+ if (mapped?.[1] !== void 0) return v4Private(mapped[1]);
13119
+ if (lower === "::" || lower === "::1") return true;
13120
+ return /^(fe[89ab]|f[cd]|ff)/.test(lower);
13121
+ }
13122
+ var resolveAll = async (host) => (await lookup(host, { all: true })).map((entry) => entry.address);
13123
+ /** The server asked to slow down. `retryAfterMs` is its `Retry-After`, or `null` when it named none. The message keeps the `HTTP 429` wording. */
13124
+ var RateLimitedError = class extends Error {
13125
+ retryAfterMs;
13126
+ constructor(retryAfterMs) {
13127
+ super("HTTP 429");
13128
+ this.retryAfterMs = retryAfterMs;
13129
+ this.name = "RateLimitedError";
13130
+ }
13131
+ };
13132
+ /** `Retry-After` as milliseconds: delta-seconds or an HTTP date; `null` when absent or unreadable. */
13133
+ function retryAfterMsOf(value, now = Date.now()) {
13134
+ if (value === null || value.trim() === "") return null;
13135
+ const seconds = Number(value);
13136
+ if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds * 1e3));
13137
+ const at = Date.parse(value);
13138
+ return Number.isNaN(at) ? null : Math.max(0, at - now);
13139
+ }
13140
+ /**
13141
+ * https only, at most 3 redirects each re-validated, every address the host resolves to must be
13142
+ * public, no credential, a bounded time and a streamed size cap.
13143
+ * A resolver answer can differ from the one `fetch` gets (rebinding): the host check narrows, not closes, that window.
13144
+ */
13145
+ function createRemoteFetch(deps = {}) {
13146
+ const doFetch = deps.fetchImpl ?? fetch;
13147
+ const resolve = deps.resolve ?? resolveAll;
13148
+ return async (start, init) => {
13149
+ let url = start;
13150
+ const startOrigin = isRemoteUrl(start) ? new URL(start).origin : "";
13151
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
13152
+ if (!isRemoteUrl(url)) throw new Error("only an https URL is fetched");
13153
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
13154
+ const addresses = isIP(host) === 0 ? await resolve(host) : [host];
13155
+ if (addresses.length === 0 || addresses.some(isPrivateAddress)) throw new Error("host refused: not a public address");
13156
+ const sameOrigin = new URL(url).origin === startOrigin;
13157
+ const response = await doFetch(url, {
13158
+ redirect: "manual",
13159
+ ...sameOrigin && init?.headers !== void 0 ? { headers: { ...init.headers } } : {},
13160
+ ...hop === 0 && init?.body !== void 0 ? {
13161
+ method: "POST",
13162
+ body: init.body
13163
+ } : {},
13164
+ signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
13165
+ });
13166
+ if (response.status >= 300 && response.status < 400) {
13167
+ const location = response.headers.get("location");
13168
+ if (location === null) throw new Error("redirect without a location");
13169
+ url = new URL(location, url).toString();
13170
+ continue;
13171
+ }
13172
+ if (response.status === 429) throw new RateLimitedError(retryAfterMsOf(response.headers.get("retry-after")));
13173
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
13174
+ return readCapped(response, MAX_IMAGE_BYTES);
13175
+ }
13176
+ throw new Error("too many redirects");
13177
+ };
13178
+ }
13179
+ var httpRemoteFetch = createRemoteFetch();
13180
+ //#endregion
12502
13181
  //#region src/tmdb.ts
12503
13182
  var TMDB_ID = "tmdb";
12504
13183
  var API$2 = "https://api.themoviedb.org/3";
@@ -12522,6 +13201,36 @@ var TranslationsSchema = object({ translations: array(object({
12522
13201
  overview: string().nullish()
12523
13202
  }).nullish()
12524
13203
  })) });
13204
+ var PersonSchema = object({
13205
+ id: number().int(),
13206
+ name: string().nullish(),
13207
+ profile_path: string().nullish()
13208
+ });
13209
+ /** A cast entry: a movie's `character`, a series' `roles[]` (aggregate credits), a guest star's `character`. */
13210
+ var CastEntrySchema = PersonSchema.extend({
13211
+ character: string().nullish(),
13212
+ roles: array(object({ character: string().nullish() })).nullish(),
13213
+ order: number().int().nullish()
13214
+ });
13215
+ /** A crew entry: a movie's `job`, a series' `jobs[]` (aggregate credits). */
13216
+ var CrewEntrySchema = PersonSchema.extend({
13217
+ job: string().nullish(),
13218
+ jobs: array(object({ job: string().nullish() })).nullish()
13219
+ });
13220
+ var CreditsSchema = object({
13221
+ cast: array(CastEntrySchema).nullish(),
13222
+ crew: array(CrewEntrySchema).nullish()
13223
+ });
13224
+ /** `release_dates` (movie): per country, a list of releases that may carry a certification. */
13225
+ var ReleaseDatesSchema = object({ results: array(object({
13226
+ iso_3166_1: string(),
13227
+ release_dates: array(object({ certification: string().nullish() }))
13228
+ })) });
13229
+ /** `content_ratings` (series): one rating per country. */
13230
+ var ContentRatingsSchema = object({ results: array(object({
13231
+ iso_3166_1: string(),
13232
+ rating: string().nullish()
13233
+ })) });
12525
13234
  var DetailsSchema = object({
12526
13235
  id: number().int(),
12527
13236
  title: string().nullish(),
@@ -12537,7 +13246,15 @@ var DetailsSchema = object({
12537
13246
  tvdb_id: number().int().nullish()
12538
13247
  }).nullish(),
12539
13248
  seasons: array(object({ season_number: number().int() })).nullish(),
12540
- translations: TranslationsSchema.nullish()
13249
+ translations: TranslationsSchema.nullish(),
13250
+ genres: array(object({ name: string().nullish() })).nullish(),
13251
+ runtime: number().nullish(),
13252
+ episode_run_time: array(number()).nullish(),
13253
+ created_by: array(PersonSchema).nullish(),
13254
+ credits: CreditsSchema.nullish(),
13255
+ aggregate_credits: CreditsSchema.nullish(),
13256
+ release_dates: ReleaseDatesSchema.nullish(),
13257
+ content_ratings: ContentRatingsSchema.nullish()
12541
13258
  });
12542
13259
  var FindSchema = object({
12543
13260
  movie_results: array(object({ id: number().int() })).default([]),
@@ -12548,8 +13265,13 @@ var SeasonSchema = object({ episodes: array(object({
12548
13265
  episode_number: number().int(),
12549
13266
  name: string().nullish(),
12550
13267
  overview: string().nullish(),
12551
- still_path: string().nullish()
13268
+ still_path: string().nullish(),
13269
+ runtime: number().nullish(),
13270
+ guest_stars: array(CastEntrySchema).nullish(),
13271
+ crew: array(CrewEntrySchema).nullish()
12552
13272
  })) });
13273
+ /** Waited when TMDB says 429 and names no time. */
13274
+ var TMDB_DEFAULT_RETRY_WAIT_MS = 2e3;
12553
13275
  /** 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. */
12554
13276
  function tmdbLanguageOf(language) {
12555
13277
  if (language === "en") return DEFAULT_LANGUAGE;
@@ -12586,23 +13308,128 @@ function translationsOf(details) {
12586
13308
  }
12587
13309
  return out;
12588
13310
  }
13311
+ /**
13312
+ * The region a rating is read for: the tag's own region (`pt-BR` is BR), else the likely region of
13313
+ * its language from CLDR (`it` is IT, `ja` is JP), US when neither is known.
13314
+ */
13315
+ function tmdbRegionOf(language) {
13316
+ return (/^[A-Za-z]{2,3}[-_]([A-Za-z]{2})$/.exec(language)?.[1] ?? likelyRegionOf(languageKey(language)) ?? "US").toUpperCase();
13317
+ }
13318
+ function likelyRegionOf(language) {
13319
+ if (language === null || language === void 0 || language === "") return void 0;
13320
+ try {
13321
+ return new Intl.Locale(language).maximize().region;
13322
+ } catch {
13323
+ return;
13324
+ }
13325
+ }
13326
+ var photoOf = (path) => image("w185", path);
13327
+ var positive = (value) => value !== null && value !== void 0 && value > 0 ? Math.round(value) : null;
13328
+ function personsOf(crew, jobs) {
13329
+ const out = [];
13330
+ for (const entry of crew ?? []) {
13331
+ const held = [entry.job, ...(entry.jobs ?? []).map((job) => job.job)];
13332
+ const name = text(entry.name);
13333
+ if (name === null || !held.some((job) => job !== null && job !== void 0 && jobs.includes(job))) continue;
13334
+ if (out.some((person) => person.id === entry.id)) continue;
13335
+ out.push({
13336
+ id: entry.id,
13337
+ name,
13338
+ photo: photoOf(entry.profile_path)
13339
+ });
13340
+ }
13341
+ return out;
13342
+ }
13343
+ function castOf(cast) {
13344
+ const out = [];
13345
+ for (const [index, entry] of (cast ?? []).entries()) {
13346
+ const name = text(entry.name);
13347
+ if (name === null) continue;
13348
+ out.push({
13349
+ id: entry.id,
13350
+ name,
13351
+ photo: photoOf(entry.profile_path),
13352
+ character: text(entry.character ?? entry.roles?.[0]?.character),
13353
+ order: entry.order ?? index
13354
+ });
13355
+ }
13356
+ return out;
13357
+ }
13358
+ var DIRECTOR_JOBS = ["Director"];
13359
+ var WRITER_JOBS = [
13360
+ "Writer",
13361
+ "Screenplay",
13362
+ "Story",
13363
+ "Teleplay"
13364
+ ];
13365
+ /** Genres, runtime, rating, crew and cast of a details answer, all from the one call (`append_to_response`). */
13366
+ function itemDetailsOf(details, language, region) {
13367
+ const credits = details.credits ?? details.aggregate_credits;
13368
+ const names = (details.genres ?? []).flatMap((genre) => {
13369
+ const name = text(genre.name);
13370
+ return name === null ? [] : [name];
13371
+ });
13372
+ const key = languageKey(language);
13373
+ 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;
13374
+ return {
13375
+ genres: key === void 0 || names.length === 0 ? {} : { [key]: names },
13376
+ runtimeMinutes: positive(details.runtime ?? details.episode_run_time?.[0]),
13377
+ certification,
13378
+ creators: (details.created_by ?? []).flatMap((entry) => {
13379
+ const name = text(entry.name);
13380
+ return name === null ? [] : [{
13381
+ id: entry.id,
13382
+ name,
13383
+ photo: photoOf(entry.profile_path)
13384
+ }];
13385
+ }),
13386
+ directors: personsOf(credits?.crew, DIRECTOR_JOBS),
13387
+ writers: personsOf(credits?.crew, WRITER_JOBS),
13388
+ cast: castOf(credits?.cast),
13389
+ guestStars: []
13390
+ };
13391
+ }
12589
13392
  var nameOf = (entry) => entry.title ?? entry.name ?? "";
12590
13393
  var yearIn = (entry) => yearOf$1(entry.release_date ?? entry.first_air_date);
12591
13394
  /** TMDB: movies and series, with the installation's own read token. All calls go through the shared remote fetch. */
12592
13395
  function createTmdbProvider(deps) {
12593
13396
  const language = deps.language ?? DEFAULT_LANGUAGE;
13397
+ const region = tmdbRegionOf(language);
12594
13398
  const headers = {
12595
13399
  Authorization: `Bearer ${deps.token}`,
12596
13400
  Accept: "application/json"
12597
13401
  };
12598
13402
  const segment = (kind) => kind === "movie" ? "movie" : "tv";
13403
+ const sleep = deps.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
13404
+ const clock = deps.now ?? Date.now;
13405
+ let nextSlot = 0;
13406
+ /** Reserve the next request slot, 50 ms after the previous one, and wait for it. */
13407
+ const pace = async () => {
13408
+ const slot = Math.max(clock(), nextSlot);
13409
+ nextSlot = slot + 50;
13410
+ const wait = slot - clock();
13411
+ if (wait > 0) await sleep(wait);
13412
+ };
13413
+ const get = async (url) => {
13414
+ await pace();
13415
+ try {
13416
+ return await deps.fetch(url, { headers });
13417
+ } catch (error) {
13418
+ if (!(error instanceof RateLimitedError)) throw error;
13419
+ const wait = error.retryAfterMs ?? TMDB_DEFAULT_RETRY_WAIT_MS;
13420
+ if (wait > 1e4) throw error;
13421
+ await sleep(wait);
13422
+ await pace();
13423
+ return deps.fetch(url, { headers });
13424
+ }
13425
+ };
12599
13426
  const call = async (path, query = {}) => {
12600
13427
  const params = new URLSearchParams({
12601
13428
  ...query,
12602
13429
  language
12603
13430
  });
12604
13431
  try {
12605
- const bytes = await deps.fetch(`${API$2}${path}?${params.toString()}`, { headers });
13432
+ const bytes = await get(`${API$2}${path}?${params.toString()}`);
12606
13433
  return JSON.parse(bytes.toString("utf8"));
12607
13434
  } catch (error) {
12608
13435
  if (error instanceof Error && /\b401\b/.test(error.message)) throw new ProviderAuthError(TMDB_REJECTED);
@@ -12620,11 +13447,12 @@ function createTmdbProvider(deps) {
12620
13447
  imdbId: text(details.external_ids?.imdb_id) ?? text(details.imdb_id),
12621
13448
  poster: image("w500", details.poster_path),
12622
13449
  fanart: image("w1280", details.backdrop_path),
12623
- translations: translationsOf(details)
13450
+ translations: translationsOf(details),
13451
+ details: itemDetailsOf(details, language, region)
12624
13452
  });
12625
13453
  const detailsOf = async (kind, id) => {
12626
13454
  try {
12627
- return matchOf(DetailsSchema.parse(await call(`/${segment(kind)}/${id}`, { append_to_response: "external_ids,translations" })));
13455
+ 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" })));
12628
13456
  } catch (error) {
12629
13457
  if (error instanceof Error && /\b404\b/.test(error.message)) return null;
12630
13458
  throw error;
@@ -12633,6 +13461,7 @@ function createTmdbProvider(deps) {
12633
13461
  return {
12634
13462
  id: TMDB_ID,
12635
13463
  translates: true,
13464
+ providesDetails: true,
12636
13465
  kinds: ["movie", "series"],
12637
13466
  lookupBy: [
12638
13467
  "tmdbId",
@@ -12673,7 +13502,17 @@ function createTmdbProvider(deps) {
12673
13502
  episode: entry.episode_number,
12674
13503
  title: text(entry.name),
12675
13504
  overview: text(entry.overview),
12676
- still: image("w300", entry.still_path)
13505
+ still: image("w300", entry.still_path),
13506
+ details: {
13507
+ genres: {},
13508
+ runtimeMinutes: positive(entry.runtime),
13509
+ certification: null,
13510
+ creators: [],
13511
+ directors: personsOf(entry.crew, DIRECTOR_JOBS),
13512
+ writers: personsOf(entry.crew, WRITER_JOBS),
13513
+ cast: [],
13514
+ guestStars: castOf(entry.guest_stars)
13515
+ }
12677
13516
  });
12678
13517
  }
12679
13518
  return out;
@@ -12981,85 +13820,6 @@ function createTvmazeProvider(deps) {
12981
13820
  };
12982
13821
  }
12983
13822
  //#endregion
12984
- //#region src/remote-fetch.ts
12985
- var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
12986
- var IMAGE_TIMEOUT_MS = 2e4;
12987
- var MAX_REDIRECTS = 3;
12988
- /** Read a response body, aborting as soon as it passes `cap`: the rest is never buffered. */
12989
- async function readCapped(response, cap) {
12990
- if (Number(response.headers.get("content-length") ?? "0") > cap) throw new Error("image too large");
12991
- if (response.body === null) return Buffer.alloc(0);
12992
- const reader = response.body.getReader();
12993
- const chunks = [];
12994
- let total = 0;
12995
- for (;;) {
12996
- const { done, value } = await reader.read();
12997
- if (done) break;
12998
- total += value.byteLength;
12999
- if (total > cap) {
13000
- await reader.cancel();
13001
- throw new Error("image too large");
13002
- }
13003
- chunks.push(Buffer.from(value));
13004
- }
13005
- return Buffer.concat(chunks, total);
13006
- }
13007
- function v4Private(address) {
13008
- const [a = 0, b = 0] = address.split(".").map(Number);
13009
- 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;
13010
- }
13011
- /** Loopback, private, link-local, ULA, CGNAT, multicast and unspecified addresses, v4 and v6. */
13012
- function isPrivateAddress(address) {
13013
- const kind = isIP(address);
13014
- if (kind === 4) return v4Private(address);
13015
- if (kind !== 6) return true;
13016
- const lower = address.toLowerCase();
13017
- const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
13018
- if (mapped?.[1] !== void 0) return v4Private(mapped[1]);
13019
- if (lower === "::" || lower === "::1") return true;
13020
- return /^(fe[89ab]|f[cd]|ff)/.test(lower);
13021
- }
13022
- var resolveAll = async (host) => (await lookup(host, { all: true })).map((entry) => entry.address);
13023
- /**
13024
- * https only, at most 3 redirects each re-validated, every address the host resolves to must be
13025
- * public, no credential, a bounded time and a streamed size cap.
13026
- * A resolver answer can differ from the one `fetch` gets (rebinding): the host check narrows, not closes, that window.
13027
- */
13028
- function createRemoteFetch(deps = {}) {
13029
- const doFetch = deps.fetchImpl ?? fetch;
13030
- const resolve = deps.resolve ?? resolveAll;
13031
- return async (start, init) => {
13032
- let url = start;
13033
- const startOrigin = isRemoteUrl(start) ? new URL(start).origin : "";
13034
- for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
13035
- if (!isRemoteUrl(url)) throw new Error("only an https URL is fetched");
13036
- const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
13037
- const addresses = isIP(host) === 0 ? await resolve(host) : [host];
13038
- if (addresses.length === 0 || addresses.some(isPrivateAddress)) throw new Error("host refused: not a public address");
13039
- const sameOrigin = new URL(url).origin === startOrigin;
13040
- const response = await doFetch(url, {
13041
- redirect: "manual",
13042
- ...sameOrigin && init?.headers !== void 0 ? { headers: { ...init.headers } } : {},
13043
- ...hop === 0 && init?.body !== void 0 ? {
13044
- method: "POST",
13045
- body: init.body
13046
- } : {},
13047
- signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
13048
- });
13049
- if (response.status >= 300 && response.status < 400) {
13050
- const location = response.headers.get("location");
13051
- if (location === null) throw new Error("redirect without a location");
13052
- url = new URL(location, url).toString();
13053
- continue;
13054
- }
13055
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
13056
- return readCapped(response, MAX_IMAGE_BYTES);
13057
- }
13058
- throw new Error("too many redirects");
13059
- };
13060
- }
13061
- var httpRemoteFetch = createRemoteFetch();
13062
- //#endregion
13063
13823
  //#region src/img-plane.ts
13064
13824
  var FAILED_GRAB_TTL_MS = 30 * 6e4;
13065
13825
  var FAILED_GRAB_MAX = 500;
@@ -13221,7 +13981,7 @@ function createImagePlaneHandler(deps) {
13221
13981
  } catch {
13222
13982
  return end(res, 404);
13223
13983
  }
13224
- if (parts.length !== 2 || !isItemId(itemId) || which !== "poster" && which !== "fanart") {
13984
+ if (parts.length !== 2 || !isItemId(itemId) || !isImageKind(which)) {
13225
13985
  deps.logger.warn("image request refused", { meta: { reason: "bad-request" } });
13226
13986
  return end(res, 404);
13227
13987
  }
@@ -13281,18 +14041,44 @@ function channelsOf(line) {
13281
14041
  return count?.[1] !== void 0 ? Number(count[1]) : null;
13282
14042
  }
13283
14043
  var STREAM_LINE = /^\s*Stream #\d+:(\d+)(?:\[[^\]]*\])?(?:\(([^)]*)\))?[^:]*: (Video|Audio|Subtitle): (.*)$/;
14044
+ var CHAPTER_LINE = /^\s*Chapter #\d+:\d+: start ([\d.]+), end ([\d.]+)/;
14045
+ var CHAPTER_TITLE = /^\s+title\s*:\s*(.*)$/;
13284
14046
  /** Parse the report `ffmpeg -i <file>` prints on stderr. A report that is not one yields no streams and no duration. */
13285
14047
  function parseFfmpegReport(report) {
13286
14048
  const lines = report.split("\n");
13287
14049
  let container = null;
13288
14050
  let durationMs = null;
13289
14051
  const streams = [];
14052
+ const chapters = [];
13290
14053
  let doviSeenFor = null;
14054
+ let inChapters = false;
13291
14055
  for (const line of lines) {
13292
14056
  const input = /^Input #\d+, ([^,]+(?:,[^,]+)*), from /.exec(line);
13293
14057
  if (input?.[1] !== void 0 && container === null) container = containerOf(input[1]);
13294
14058
  const duration = /^\s*Duration: (\d+):(\d{2}):(\d{2})\.(\d{2})/.exec(line);
13295
14059
  if (duration && durationMs === null) durationMs = (Number(duration[1]) * 3600 + Number(duration[2]) * 60 + Number(duration[3])) * 1e3 + Number(duration[4]) * 10;
14060
+ const chapter = CHAPTER_LINE.exec(line);
14061
+ if (chapter?.[1] !== void 0 && chapter[2] !== void 0) {
14062
+ const startSec = Number(chapter[1]);
14063
+ const endSec = Number(chapter[2]);
14064
+ if (Number.isFinite(startSec) && Number.isFinite(endSec) && endSec > startSec) chapters.push({
14065
+ startSec,
14066
+ endSec,
14067
+ title: null
14068
+ });
14069
+ continue;
14070
+ }
14071
+ const titled = CHAPTER_TITLE.exec(line);
14072
+ const last = chapters[chapters.length - 1];
14073
+ if (titled?.[1] !== void 0 && last !== void 0 && last.title === null && inChapters) {
14074
+ if (titled[1].trim() !== "") chapters[chapters.length - 1] = {
14075
+ ...last,
14076
+ title: titled[1].trim()
14077
+ };
14078
+ continue;
14079
+ }
14080
+ if (/^\s*Chapters:/.test(line)) inChapters = true;
14081
+ if (STREAM_LINE.test(line)) inChapters = false;
13296
14082
  if (/DOVI configuration record/.test(line) && streams.length > 0) {
13297
14083
  doviSeenFor = streams.length - 1;
13298
14084
  continue;
@@ -13333,7 +14119,8 @@ function parseFfmpegReport(report) {
13333
14119
  return {
13334
14120
  container,
13335
14121
  durationMs,
13336
- streams
14122
+ streams,
14123
+ chapters
13337
14124
  };
13338
14125
  }
13339
14126
  var PROBE_TIMEOUT_MS = 3e4;
@@ -13376,6 +14163,9 @@ function createMediaLibraryProvider(store, scans) {
13376
14163
  getItem: ({ itemId, language, caller }) => store.getItem(caller.userId, itemId, language),
13377
14164
  search: ({ query, limit, language, caller }) => store.search(caller.userId, query, limit, language),
13378
14165
  listRecentlyAdded: ({ limit, language, caller }) => store.listRecentlyAdded(caller.userId, limit, language),
14166
+ listWatchlist: ({ limit, offset, language, caller }) => store.listWatchlist(caller.userId, limit, offset, language),
14167
+ setWatchlisted: ({ itemId, on, caller }) => store.setWatchlisted(caller.userId, itemId, on),
14168
+ getItemDetails: ({ itemId, language }) => store.getItemDetails(itemId, language),
13379
14169
  getProgress: ({ itemId, caller }) => store.getProgress(caller.userId, itemId),
13380
14170
  setProgress: ({ caller, ...input }) => store.setProgress(caller.userId, input),
13381
14171
  markWatched: ({ caller, ...input }) => store.markWatched(caller.userId, input),
@@ -13396,6 +14186,7 @@ function fill(into, from) {
13396
14186
  year: into.year ?? from.year,
13397
14187
  overview: into.overview ?? from.overview,
13398
14188
  translations: into.translations ?? from.translations,
14189
+ details: into.details ?? from.details,
13399
14190
  tvdbId: into.tvdbId ?? from.tvdbId,
13400
14191
  tmdbId: into.tmdbId ?? from.tmdbId,
13401
14192
  imdbId: into.imdbId ?? from.imdbId,
@@ -13557,7 +14348,10 @@ var Enricher = class {
13557
14348
  cachedMatch(provider, key) {
13558
14349
  const known = this.deps.cache.getMatch(key);
13559
14350
  if (known === null) return null;
13560
- return known.found && provider.translates === true && known.match.translations === void 0 ? null : known;
14351
+ if (!known.found) return known;
14352
+ const predatesTranslations = provider.translates === true && known.match.translations === void 0;
14353
+ const predatesDetails = provider.providesDetails === true && known.match.details === void 0;
14354
+ return predatesTranslations || predatesDetails ? null : known;
13561
14355
  }
13562
14356
  /** A pinned id is asked for directly: an answer of "nothing" is final, never turned into a title guess. */
13563
14357
  async lookup(provider, ask, item, kind, pin) {
@@ -13637,14 +14431,15 @@ var Enricher = class {
13637
14431
  async episodesOf(provider, item, match) {
13638
14432
  const key = `${this.keyOf(provider)}:eps:${match.remoteId}`;
13639
14433
  const known = this.deps.cache.getEpisodes(key);
13640
- if (known !== null) return known.episodes;
14434
+ const predatesDetails = provider.providesDetails === true && known !== null && known.episodes.some((entry) => entry.details === void 0);
14435
+ if (known !== null && !predatesDetails) return known.episodes;
13641
14436
  try {
13642
14437
  const episodes = await provider.episodes(match);
13643
14438
  this.deps.cache.putEpisodes(key, { episodes: [...episodes] });
13644
14439
  return episodes;
13645
14440
  } catch (error) {
13646
14441
  this.failed(provider.id, item.id, error);
13647
- return [];
14442
+ return known?.episodes ?? [];
13648
14443
  }
13649
14444
  }
13650
14445
  async onlineLayer(provider, item, acc, resolved, held) {
@@ -13658,6 +14453,7 @@ var Enricher = class {
13658
14453
  year: match.year,
13659
14454
  overview: match.overview,
13660
14455
  translations: match.translations ?? null,
14456
+ details: match.details ?? null,
13661
14457
  tvdbId: match.tvdbId,
13662
14458
  tmdbId: match.tmdbId,
13663
14459
  imdbId: match.imdbId,
@@ -13680,15 +14476,16 @@ var Enricher = class {
13680
14476
  ...NO_LOCAL,
13681
14477
  title: found.title,
13682
14478
  overview: found.overview,
13683
- poster: found.still
14479
+ poster: found.still,
14480
+ details: found.details ?? null
13684
14481
  };
13685
14482
  }
13686
14483
  canAsk(provider, item) {
13687
14484
  return provider.kinds.includes(item.kind === "movie" ? "movie" : "series");
13688
14485
  }
13689
14486
  needsOnline(provider, item, acc) {
13690
- if (item.kind === "episode") return acc.overview === null || acc.poster === null || item.titlePlaceholder && acc.title === null;
13691
- return acc.overview === null || acc.poster === null || provider.translates === true && acc.translations === null;
14487
+ if (item.kind === "episode") return acc.overview === null || acc.poster === null || provider.providesDetails === true && acc.details === null || item.titlePlaceholder && acc.title === null;
14488
+ return acc.overview === null || acc.poster === null || provider.translates === true && acc.translations === null || provider.providesDetails === true && acc.details === null;
13692
14489
  }
13693
14490
  async localLayer(item, firstEpisodeFile) {
13694
14491
  const { reader } = this.deps;
@@ -13737,6 +14534,7 @@ var Enricher = class {
13737
14534
  year: acc.year,
13738
14535
  overview: acc.overview,
13739
14536
  translations: acc.translations,
14537
+ details: acc.details,
13740
14538
  tvdbId: acc.tvdbId,
13741
14539
  tmdbId: acc.tmdbId,
13742
14540
  imdbId: acc.imdbId,
@@ -13778,6 +14576,7 @@ function newItem(base) {
13778
14576
  episodeNumber: null,
13779
14577
  overview: null,
13780
14578
  translations: null,
14579
+ details: null,
13781
14580
  tvdbId: null,
13782
14581
  tmdbId: null,
13783
14582
  imdbId: null,
@@ -14129,6 +14928,7 @@ async function scanLibrary(deps, sources) {
14129
14928
  const { addedHint, titlePlaceholder: _placeholder, ...fields } = item;
14130
14929
  writes.push({
14131
14930
  ...fields,
14931
+ details: fields.details ?? previous?.details ?? null,
14132
14932
  addedAt: previous?.addedAt ?? addedHint ?? startedAt,
14133
14933
  seenAt: startedAt
14134
14934
  });
@@ -14143,6 +14943,7 @@ async function scanLibrary(deps, sources) {
14143
14943
  for (const entry of harvests) for (const item of entry.items) if (item.filePath !== null) filePaths.set(item.filePath, item.id);
14144
14944
  outcome.files = filePaths.size;
14145
14945
  const fileWrites = [];
14946
+ let chaptersReprobed = 0;
14146
14947
  for (const [path, id] of filePaths) {
14147
14948
  const stat = await deps.stat(path);
14148
14949
  if (stat === null) {
@@ -14157,10 +14958,14 @@ async function scanLibrary(deps, sources) {
14157
14958
  continue;
14158
14959
  }
14159
14960
  const known = knownFiles.get(path);
14160
- if (known !== void 0 && known.sizeBytes === stat.size && known.mtimeMs === stat.mtimeMs && (known.probeOk || deps.now() - known.probedAt < 216e5)) {
14961
+ const unchanged = known !== void 0 && known.sizeBytes === stat.size && known.mtimeMs === stat.mtimeMs;
14962
+ const chaptersKnown = known?.chapters != null;
14963
+ const chaptersOnly = unchanged && known.probeOk && !chaptersKnown;
14964
+ if (unchanged && (known.probeOk && chaptersKnown || !known.probeOk && deps.now() - known.probedAt < 216e5)) {
14161
14965
  outcome.reused += 1;
14162
14966
  continue;
14163
14967
  }
14968
+ if (chaptersOnly) chaptersReprobed += 1;
14164
14969
  try {
14165
14970
  const result = await deps.probe(path);
14166
14971
  fileWrites.push({
@@ -14172,11 +14977,24 @@ async function scanLibrary(deps, sources) {
14172
14977
  container: result.container,
14173
14978
  durationMs: result.durationMs,
14174
14979
  streams: [...result.streams],
14980
+ chapters: [...result.chapters],
14175
14981
  probeError: null
14176
14982
  });
14177
14983
  outcome.probed += 1;
14178
14984
  } catch (error) {
14179
14985
  const message = error instanceof Error ? error.message : String(error);
14986
+ if (chaptersOnly) {
14987
+ logger.warn("chapters probe failed: the earlier probe result is kept", {
14988
+ tags: { itemId: id },
14989
+ meta: {
14990
+ path,
14991
+ reason: "chapters-probe-failed",
14992
+ error: message
14993
+ }
14994
+ });
14995
+ outcome.skipped += 1;
14996
+ continue;
14997
+ }
14180
14998
  logger.warn("probe failed: the file stays catalogued, unprobed", {
14181
14999
  tags: { itemId: id },
14182
15000
  meta: {
@@ -14194,17 +15012,20 @@ async function scanLibrary(deps, sources) {
14194
15012
  container: null,
14195
15013
  durationMs: null,
14196
15014
  streams: [],
15015
+ chapters: [],
14197
15016
  probeError: message
14198
15017
  });
14199
15018
  outcome.skipped += 1;
14200
15019
  }
14201
15020
  }
14202
15021
  if (fileWrites.length > 0) await db.upsertMany(FILES, ["path"], fileWrites);
15022
+ if (chaptersReprobed > 0) logger.info("files probed again only to read their chapters", { meta: { count: chaptersReprobed } });
14203
15023
  for (const entry of harvests) {
14204
15024
  if (!entry.trusted) continue;
14205
15025
  const stale = [...existingItems.values()].filter((item) => item.sourceId === entry.sourceId && !seenIds.has(item.id));
14206
15026
  if (stale.length === 0) continue;
14207
15027
  await db.deleteWhere(ITEMS, { whereIn: { id: stale.map((item) => item.id) } });
15028
+ await db.deleteWhere(WATCHLIST, { whereIn: { itemId: stale.map((item) => item.id) } });
14208
15029
  logger.info("items no longer in their source were removed", { meta: {
14209
15030
  sourceId: entry.sourceId,
14210
15031
  removed: stale.length
@@ -14460,6 +15281,15 @@ var MediaLibraryAddon = class extends BaseAddon {
14460
15281
  logger
14461
15282
  })
14462
15283
  });
15284
+ await ctx.dataPlane?.serve({
15285
+ prefix: SUBTITLE_PLANE_PREFIX,
15286
+ access: "viewer",
15287
+ handler: createSubtitlePlaneHandler({
15288
+ sidecars: (itemId) => store.subtitleSidecars(itemId),
15289
+ roots,
15290
+ logger
15291
+ })
15292
+ });
14463
15293
  await ctx.dataPlane?.serve({
14464
15294
  prefix: "img",
14465
15295
  access: "viewer",