@dominevo/addon-media-library 0.1.8 → 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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.1.9] - 2026-12-03
11
+
12
+ ### Changed
13
+
14
+ - The age rating is read for the likely country of the server language for every language, not only eleven
15
+ - Media library: reads each file's chapters, finds .srt/.ass/.ssa/.vtt subtitles next to the video and serves them as WebVTT with an optional delay
16
+
10
17
  ## [0.1.8] - 2026-12-03
11
18
 
12
19
  ### Changed
@@ -8834,6 +8834,30 @@ var LibraryFileInfoSchema = /* @__PURE__ */ object({
8834
8834
  /** False while the file is catalogued but not probed yet, or the probe failed. */
8835
8835
  probed: /* @__PURE__ */ boolean()
8836
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
+ });
8837
8861
  var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8838
8862
  overview: /* @__PURE__ */ string().nullable(),
8839
8863
  ids: /* @__PURE__ */ object({
@@ -8844,7 +8868,11 @@ var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8844
8868
  fanartPath: /* @__PURE__ */ string().nullable(),
8845
8869
  /** Relative hub path that direct-plays the file, with HTTP Range. `null` when not playable. */
8846
8870
  playPath: /* @__PURE__ */ string().nullable(),
8847
- 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()
8848
8876
  });
8849
8877
  /**
8850
8878
  * A person of an item's credits. `photoPath` is an image-plane handle relative to the hub origin
@@ -9907,7 +9935,7 @@ function pump(path, start, end, res, stallMs) {
9907
9935
  res.on("close", () => settle(sent > 0 && res.writableFinished ? "finished" : "client-closed"));
9908
9936
  });
9909
9937
  }
9910
- function reject(res, status, extra) {
9938
+ function reject$1(res, status, extra) {
9911
9939
  res.writeHead(status, {
9912
9940
  "Content-Length": 0,
9913
9941
  ...extra
@@ -9919,18 +9947,18 @@ function createFilePlaneHandler(deps) {
9919
9947
  const stallMs = deps.stallMs ?? 3e4;
9920
9948
  return async (req, res) => {
9921
9949
  const method = req.method ?? "GET";
9922
- 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" });
9923
9951
  const raw = (req.url ?? "/").split("?")[0] ?? "/";
9924
9952
  let itemId;
9925
9953
  try {
9926
9954
  itemId = decodeURIComponent(raw.replace(/^\//, ""));
9927
9955
  } catch {
9928
9956
  deps.logger.warn("file request refused: bad escape", { meta: { reason: "bad-id" } });
9929
- return reject(res, 404);
9957
+ return reject$1(res, 404);
9930
9958
  }
9931
9959
  if (!isItemId(itemId)) {
9932
9960
  deps.logger.warn("file request refused: not an item id", { meta: { reason: "bad-id" } });
9933
- return reject(res, 404);
9961
+ return reject$1(res, 404);
9934
9962
  }
9935
9963
  const tags = { itemId };
9936
9964
  const catalogued = await deps.lookup(itemId);
@@ -9939,7 +9967,7 @@ function createFilePlaneHandler(deps) {
9939
9967
  tags,
9940
9968
  meta: { reason: "not-catalogued" }
9941
9969
  });
9942
- return reject(res, 404);
9970
+ return reject$1(res, 404);
9943
9971
  }
9944
9972
  const path = await resolveServable(catalogued, await deps.roots());
9945
9973
  if (path === null) {
@@ -9947,7 +9975,7 @@ function createFilePlaneHandler(deps) {
9947
9975
  tags,
9948
9976
  meta: { reason: "outside-roots" }
9949
9977
  });
9950
- return reject(res, 404);
9978
+ return reject$1(res, 404);
9951
9979
  }
9952
9980
  let size;
9953
9981
  try {
@@ -9957,7 +9985,7 @@ function createFilePlaneHandler(deps) {
9957
9985
  tags,
9958
9986
  meta: { reason: "gone" }
9959
9987
  });
9960
- return reject(res, 404);
9988
+ return reject$1(res, 404);
9961
9989
  }
9962
9990
  const range = parseRange(headerOf(req.headers.range), size);
9963
9991
  if (range.kind === "unsatisfiable") {
@@ -9968,7 +9996,7 @@ function createFilePlaneHandler(deps) {
9968
9996
  size
9969
9997
  }
9970
9998
  });
9971
- return reject(res, 416, { "Content-Range": `bytes */${size}` });
9999
+ return reject$1(res, 416, { "Content-Range": `bytes */${size}` });
9972
10000
  }
9973
10001
  const start = range.kind === "range" ? range.start : 0;
9974
10002
  const end = range.kind === "range" ? range.end : size - 1;
@@ -10002,6 +10030,198 @@ function createFilePlaneHandler(deps) {
10002
10030
  function headerOf(value) {
10003
10031
  return Array.isArray(value) ? value[0] : value;
10004
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
+ }
10005
10225
  //#endregion
10006
10226
  //#region src/folder-walker.ts
10007
10227
  var VIDEO_EXTENSIONS = new Set([
@@ -10372,6 +10592,8 @@ var FileRowSchema = object({
10372
10592
  container: string().nullable(),
10373
10593
  durationMs: number().int().nullable(),
10374
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(),
10375
10597
  probeError: string().nullable()
10376
10598
  });
10377
10599
  var PinSourceSchema = _enum(["plex", "manual"]);
@@ -10489,6 +10711,10 @@ var COLLECTIONS = [
10489
10711
  type: "JSON",
10490
10712
  notNull: true
10491
10713
  },
10714
+ {
10715
+ name: "chapters",
10716
+ type: "JSON"
10717
+ },
10492
10718
  text$3("probeError")
10493
10719
  ]
10494
10720
  },
@@ -10910,6 +11136,60 @@ async function localMovie(reader, filePath) {
10910
11136
  };
10911
11137
  }
10912
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
10913
11193
  //#region src/item-text.ts
10914
11194
  /**
10915
11195
  * A language tag as the translations are keyed: lower-case, region dropped (`it-IT` is `it`).
@@ -10951,6 +11231,7 @@ function sortByShownTitle(rows, requested, serverDefault) {
10951
11231
  return rows.toSorted((a, b) => collator.compare(keys.get(a) ?? "", keys.get(b) ?? ""));
10952
11232
  }
10953
11233
  var FILE_PLANE_PREFIX = "file";
11234
+ var SUBTITLE_PLANE_PREFIX = "subtitle";
10954
11235
  var HUB_PLANE_BASE = "/addon/media-library";
10955
11236
  var SEARCH_DEFAULT_LIMIT = 50;
10956
11237
  var RECENT_DEFAULT_LIMIT = 20;
@@ -10962,6 +11243,9 @@ var WATCHLIST_RESOLVE_CHUNK = 500;
10962
11243
  function playPathOf(itemId) {
10963
11244
  return `${HUB_PLANE_BASE}/${FILE_PLANE_PREFIX}/${itemId}`;
10964
11245
  }
11246
+ function subtitlePathOf(itemId, sidecarId) {
11247
+ return `${HUB_PLANE_BASE}/${SUBTITLE_PLANE_PREFIX}/${itemId}/${sidecarId}`;
11248
+ }
10965
11249
  function imagePathOf(itemId, which) {
10966
11250
  return `${HUB_PLANE_BASE}/img/${itemId}/${which}`;
10967
11251
  }
@@ -10982,12 +11266,14 @@ var LibraryStore = class {
10982
11266
  logger;
10983
11267
  serverLanguage;
10984
11268
  now;
11269
+ listDir;
10985
11270
  locks = /* @__PURE__ */ new Map();
10986
- constructor(db, logger, serverLanguage = () => "en", now = Date.now) {
11271
+ constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir) {
10987
11272
  this.db = db;
10988
11273
  this.logger = logger;
10989
11274
  this.serverLanguage = serverLanguage;
10990
11275
  this.now = now;
11276
+ this.listDir = listDir;
10991
11277
  }
10992
11278
  async init() {
10993
11279
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -11152,9 +11438,24 @@ var LibraryStore = class {
11152
11438
  },
11153
11439
  fanartPath: row.fanartSource === null ? null : imagePathOf(row.id, "fanart"),
11154
11440
  playPath: file === void 0 ? null : playPathOf(row.id),
11155
- 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
+ }))
11156
11451
  };
11157
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
+ }
11158
11459
  /** The file a client may stream for `itemId`, or `null`: the path comes from here, never from the client. */
11159
11460
  async playableFile(itemId) {
11160
11461
  const [item] = await this.queryItems({
@@ -11450,6 +11751,13 @@ var LibraryStore = class {
11450
11751
  return entries;
11451
11752
  }
11452
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
+ }
11453
11761
  /** Genre names: the language asked for, else the server's, else whichever language the source answered. */
11454
11762
  function genresOf(details, requested, serverDefault) {
11455
11763
  for (const key of [languageKey(requested), languageKey(serverDefault)]) {
@@ -13004,22 +13312,20 @@ function translationsOf(details) {
13004
13312
  }
13005
13313
  return out;
13006
13314
  }
13007
- /** The region a rating is read for: the server language's own country (`it` is IT), US when unknown. */
13008
- var REGION_OF_LANGUAGE = {
13009
- en: "US",
13010
- it: "IT",
13011
- de: "DE",
13012
- fr: "FR",
13013
- es: "ES",
13014
- pt: "PT",
13015
- nl: "NL",
13016
- ja: "JP",
13017
- zh: "CN",
13018
- ru: "RU",
13019
- pl: "PL"
13020
- };
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
+ */
13021
13319
  function tmdbRegionOf(language) {
13022
- return (/^[A-Za-z]{2,3}[-_]([A-Za-z]{2})$/.exec(language)?.[1] ?? REGION_OF_LANGUAGE[languageKey(language) ?? ""] ?? "US").toUpperCase();
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
+ }
13023
13329
  }
13024
13330
  var photoOf = (path) => image("w185", path);
13025
13331
  var positive = (value) => value !== null && value !== void 0 && value > 0 ? Math.round(value) : null;
@@ -13739,18 +14045,44 @@ function channelsOf(line) {
13739
14045
  return count?.[1] !== void 0 ? Number(count[1]) : null;
13740
14046
  }
13741
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*(.*)$/;
13742
14050
  /** Parse the report `ffmpeg -i <file>` prints on stderr. A report that is not one yields no streams and no duration. */
13743
14051
  function parseFfmpegReport(report) {
13744
14052
  const lines = report.split("\n");
13745
14053
  let container = null;
13746
14054
  let durationMs = null;
13747
14055
  const streams = [];
14056
+ const chapters = [];
13748
14057
  let doviSeenFor = null;
14058
+ let inChapters = false;
13749
14059
  for (const line of lines) {
13750
14060
  const input = /^Input #\d+, ([^,]+(?:,[^,]+)*), from /.exec(line);
13751
14061
  if (input?.[1] !== void 0 && container === null) container = containerOf(input[1]);
13752
14062
  const duration = /^\s*Duration: (\d+):(\d{2}):(\d{2})\.(\d{2})/.exec(line);
13753
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;
13754
14086
  if (/DOVI configuration record/.test(line) && streams.length > 0) {
13755
14087
  doviSeenFor = streams.length - 1;
13756
14088
  continue;
@@ -13791,7 +14123,8 @@ function parseFfmpegReport(report) {
13791
14123
  return {
13792
14124
  container,
13793
14125
  durationMs,
13794
- streams
14126
+ streams,
14127
+ chapters
13795
14128
  };
13796
14129
  }
13797
14130
  var PROBE_TIMEOUT_MS = 3e4;
@@ -14614,6 +14947,7 @@ async function scanLibrary(deps, sources) {
14614
14947
  for (const entry of harvests) for (const item of entry.items) if (item.filePath !== null) filePaths.set(item.filePath, item.id);
14615
14948
  outcome.files = filePaths.size;
14616
14949
  const fileWrites = [];
14950
+ let chaptersReprobed = 0;
14617
14951
  for (const [path, id] of filePaths) {
14618
14952
  const stat = await deps.stat(path);
14619
14953
  if (stat === null) {
@@ -14628,10 +14962,14 @@ async function scanLibrary(deps, sources) {
14628
14962
  continue;
14629
14963
  }
14630
14964
  const known = knownFiles.get(path);
14631
- 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)) {
14632
14969
  outcome.reused += 1;
14633
14970
  continue;
14634
14971
  }
14972
+ if (chaptersOnly) chaptersReprobed += 1;
14635
14973
  try {
14636
14974
  const result = await deps.probe(path);
14637
14975
  fileWrites.push({
@@ -14643,11 +14981,24 @@ async function scanLibrary(deps, sources) {
14643
14981
  container: result.container,
14644
14982
  durationMs: result.durationMs,
14645
14983
  streams: [...result.streams],
14984
+ chapters: [...result.chapters],
14646
14985
  probeError: null
14647
14986
  });
14648
14987
  outcome.probed += 1;
14649
14988
  } catch (error) {
14650
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
+ }
14651
15002
  logger.warn("probe failed: the file stays catalogued, unprobed", {
14652
15003
  tags: { itemId: id },
14653
15004
  meta: {
@@ -14665,12 +15016,14 @@ async function scanLibrary(deps, sources) {
14665
15016
  container: null,
14666
15017
  durationMs: null,
14667
15018
  streams: [],
15019
+ chapters: [],
14668
15020
  probeError: message
14669
15021
  });
14670
15022
  outcome.skipped += 1;
14671
15023
  }
14672
15024
  }
14673
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 } });
14674
15027
  for (const entry of harvests) {
14675
15028
  if (!entry.trusted) continue;
14676
15029
  const stale = [...existingItems.values()].filter((item) => item.sourceId === entry.sourceId && !seenIds.has(item.id));
@@ -14932,6 +15285,15 @@ var MediaLibraryAddon = class extends BaseAddon {
14932
15285
  logger
14933
15286
  })
14934
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
+ });
14935
15297
  await ctx.dataPlane?.serve({
14936
15298
  prefix: "img",
14937
15299
  access: "viewer",
@@ -8830,6 +8830,30 @@ var LibraryFileInfoSchema = /* @__PURE__ */ object({
8830
8830
  /** False while the file is catalogued but not probed yet, or the probe failed. */
8831
8831
  probed: /* @__PURE__ */ boolean()
8832
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
+ });
8833
8857
  var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8834
8858
  overview: /* @__PURE__ */ string().nullable(),
8835
8859
  ids: /* @__PURE__ */ object({
@@ -8840,7 +8864,11 @@ var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8840
8864
  fanartPath: /* @__PURE__ */ string().nullable(),
8841
8865
  /** Relative hub path that direct-plays the file, with HTTP Range. `null` when not playable. */
8842
8866
  playPath: /* @__PURE__ */ string().nullable(),
8843
- 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()
8844
8872
  });
8845
8873
  /**
8846
8874
  * A person of an item's credits. `photoPath` is an image-plane handle relative to the hub origin
@@ -9903,7 +9931,7 @@ function pump(path, start, end, res, stallMs) {
9903
9931
  res.on("close", () => settle(sent > 0 && res.writableFinished ? "finished" : "client-closed"));
9904
9932
  });
9905
9933
  }
9906
- function reject(res, status, extra) {
9934
+ function reject$1(res, status, extra) {
9907
9935
  res.writeHead(status, {
9908
9936
  "Content-Length": 0,
9909
9937
  ...extra
@@ -9915,18 +9943,18 @@ function createFilePlaneHandler(deps) {
9915
9943
  const stallMs = deps.stallMs ?? 3e4;
9916
9944
  return async (req, res) => {
9917
9945
  const method = req.method ?? "GET";
9918
- 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" });
9919
9947
  const raw = (req.url ?? "/").split("?")[0] ?? "/";
9920
9948
  let itemId;
9921
9949
  try {
9922
9950
  itemId = decodeURIComponent(raw.replace(/^\//, ""));
9923
9951
  } catch {
9924
9952
  deps.logger.warn("file request refused: bad escape", { meta: { reason: "bad-id" } });
9925
- return reject(res, 404);
9953
+ return reject$1(res, 404);
9926
9954
  }
9927
9955
  if (!isItemId(itemId)) {
9928
9956
  deps.logger.warn("file request refused: not an item id", { meta: { reason: "bad-id" } });
9929
- return reject(res, 404);
9957
+ return reject$1(res, 404);
9930
9958
  }
9931
9959
  const tags = { itemId };
9932
9960
  const catalogued = await deps.lookup(itemId);
@@ -9935,7 +9963,7 @@ function createFilePlaneHandler(deps) {
9935
9963
  tags,
9936
9964
  meta: { reason: "not-catalogued" }
9937
9965
  });
9938
- return reject(res, 404);
9966
+ return reject$1(res, 404);
9939
9967
  }
9940
9968
  const path = await resolveServable(catalogued, await deps.roots());
9941
9969
  if (path === null) {
@@ -9943,7 +9971,7 @@ function createFilePlaneHandler(deps) {
9943
9971
  tags,
9944
9972
  meta: { reason: "outside-roots" }
9945
9973
  });
9946
- return reject(res, 404);
9974
+ return reject$1(res, 404);
9947
9975
  }
9948
9976
  let size;
9949
9977
  try {
@@ -9953,7 +9981,7 @@ function createFilePlaneHandler(deps) {
9953
9981
  tags,
9954
9982
  meta: { reason: "gone" }
9955
9983
  });
9956
- return reject(res, 404);
9984
+ return reject$1(res, 404);
9957
9985
  }
9958
9986
  const range = parseRange(headerOf(req.headers.range), size);
9959
9987
  if (range.kind === "unsatisfiable") {
@@ -9964,7 +9992,7 @@ function createFilePlaneHandler(deps) {
9964
9992
  size
9965
9993
  }
9966
9994
  });
9967
- return reject(res, 416, { "Content-Range": `bytes */${size}` });
9995
+ return reject$1(res, 416, { "Content-Range": `bytes */${size}` });
9968
9996
  }
9969
9997
  const start = range.kind === "range" ? range.start : 0;
9970
9998
  const end = range.kind === "range" ? range.end : size - 1;
@@ -9998,6 +10026,198 @@ function createFilePlaneHandler(deps) {
9998
10026
  function headerOf(value) {
9999
10027
  return Array.isArray(value) ? value[0] : value;
10000
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
+ }
10001
10221
  //#endregion
10002
10222
  //#region src/folder-walker.ts
10003
10223
  var VIDEO_EXTENSIONS = new Set([
@@ -10368,6 +10588,8 @@ var FileRowSchema = object({
10368
10588
  container: string().nullable(),
10369
10589
  durationMs: number().int().nullable(),
10370
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(),
10371
10593
  probeError: string().nullable()
10372
10594
  });
10373
10595
  var PinSourceSchema = _enum(["plex", "manual"]);
@@ -10485,6 +10707,10 @@ var COLLECTIONS = [
10485
10707
  type: "JSON",
10486
10708
  notNull: true
10487
10709
  },
10710
+ {
10711
+ name: "chapters",
10712
+ type: "JSON"
10713
+ },
10488
10714
  text$3("probeError")
10489
10715
  ]
10490
10716
  },
@@ -10906,6 +11132,60 @@ async function localMovie(reader, filePath) {
10906
11132
  };
10907
11133
  }
10908
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
10909
11189
  //#region src/item-text.ts
10910
11190
  /**
10911
11191
  * A language tag as the translations are keyed: lower-case, region dropped (`it-IT` is `it`).
@@ -10947,6 +11227,7 @@ function sortByShownTitle(rows, requested, serverDefault) {
10947
11227
  return rows.toSorted((a, b) => collator.compare(keys.get(a) ?? "", keys.get(b) ?? ""));
10948
11228
  }
10949
11229
  var FILE_PLANE_PREFIX = "file";
11230
+ var SUBTITLE_PLANE_PREFIX = "subtitle";
10950
11231
  var HUB_PLANE_BASE = "/addon/media-library";
10951
11232
  var SEARCH_DEFAULT_LIMIT = 50;
10952
11233
  var RECENT_DEFAULT_LIMIT = 20;
@@ -10958,6 +11239,9 @@ var WATCHLIST_RESOLVE_CHUNK = 500;
10958
11239
  function playPathOf(itemId) {
10959
11240
  return `${HUB_PLANE_BASE}/${FILE_PLANE_PREFIX}/${itemId}`;
10960
11241
  }
11242
+ function subtitlePathOf(itemId, sidecarId) {
11243
+ return `${HUB_PLANE_BASE}/${SUBTITLE_PLANE_PREFIX}/${itemId}/${sidecarId}`;
11244
+ }
10961
11245
  function imagePathOf(itemId, which) {
10962
11246
  return `${HUB_PLANE_BASE}/img/${itemId}/${which}`;
10963
11247
  }
@@ -10978,12 +11262,14 @@ var LibraryStore = class {
10978
11262
  logger;
10979
11263
  serverLanguage;
10980
11264
  now;
11265
+ listDir;
10981
11266
  locks = /* @__PURE__ */ new Map();
10982
- constructor(db, logger, serverLanguage = () => "en", now = Date.now) {
11267
+ constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir) {
10983
11268
  this.db = db;
10984
11269
  this.logger = logger;
10985
11270
  this.serverLanguage = serverLanguage;
10986
11271
  this.now = now;
11272
+ this.listDir = listDir;
10987
11273
  }
10988
11274
  async init() {
10989
11275
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -11148,9 +11434,24 @@ var LibraryStore = class {
11148
11434
  },
11149
11435
  fanartPath: row.fanartSource === null ? null : imagePathOf(row.id, "fanart"),
11150
11436
  playPath: file === void 0 ? null : playPathOf(row.id),
11151
- 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
+ }))
11152
11447
  };
11153
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
+ }
11154
11455
  /** The file a client may stream for `itemId`, or `null`: the path comes from here, never from the client. */
11155
11456
  async playableFile(itemId) {
11156
11457
  const [item] = await this.queryItems({
@@ -11446,6 +11747,13 @@ var LibraryStore = class {
11446
11747
  return entries;
11447
11748
  }
11448
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
+ }
11449
11757
  /** Genre names: the language asked for, else the server's, else whichever language the source answered. */
11450
11758
  function genresOf(details, requested, serverDefault) {
11451
11759
  for (const key of [languageKey(requested), languageKey(serverDefault)]) {
@@ -13000,22 +13308,20 @@ function translationsOf(details) {
13000
13308
  }
13001
13309
  return out;
13002
13310
  }
13003
- /** The region a rating is read for: the server language's own country (`it` is IT), US when unknown. */
13004
- var REGION_OF_LANGUAGE = {
13005
- en: "US",
13006
- it: "IT",
13007
- de: "DE",
13008
- fr: "FR",
13009
- es: "ES",
13010
- pt: "PT",
13011
- nl: "NL",
13012
- ja: "JP",
13013
- zh: "CN",
13014
- ru: "RU",
13015
- pl: "PL"
13016
- };
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
+ */
13017
13315
  function tmdbRegionOf(language) {
13018
- return (/^[A-Za-z]{2,3}[-_]([A-Za-z]{2})$/.exec(language)?.[1] ?? REGION_OF_LANGUAGE[languageKey(language) ?? ""] ?? "US").toUpperCase();
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
+ }
13019
13325
  }
13020
13326
  var photoOf = (path) => image("w185", path);
13021
13327
  var positive = (value) => value !== null && value !== void 0 && value > 0 ? Math.round(value) : null;
@@ -13735,18 +14041,44 @@ function channelsOf(line) {
13735
14041
  return count?.[1] !== void 0 ? Number(count[1]) : null;
13736
14042
  }
13737
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*(.*)$/;
13738
14046
  /** Parse the report `ffmpeg -i <file>` prints on stderr. A report that is not one yields no streams and no duration. */
13739
14047
  function parseFfmpegReport(report) {
13740
14048
  const lines = report.split("\n");
13741
14049
  let container = null;
13742
14050
  let durationMs = null;
13743
14051
  const streams = [];
14052
+ const chapters = [];
13744
14053
  let doviSeenFor = null;
14054
+ let inChapters = false;
13745
14055
  for (const line of lines) {
13746
14056
  const input = /^Input #\d+, ([^,]+(?:,[^,]+)*), from /.exec(line);
13747
14057
  if (input?.[1] !== void 0 && container === null) container = containerOf(input[1]);
13748
14058
  const duration = /^\s*Duration: (\d+):(\d{2}):(\d{2})\.(\d{2})/.exec(line);
13749
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;
13750
14082
  if (/DOVI configuration record/.test(line) && streams.length > 0) {
13751
14083
  doviSeenFor = streams.length - 1;
13752
14084
  continue;
@@ -13787,7 +14119,8 @@ function parseFfmpegReport(report) {
13787
14119
  return {
13788
14120
  container,
13789
14121
  durationMs,
13790
- streams
14122
+ streams,
14123
+ chapters
13791
14124
  };
13792
14125
  }
13793
14126
  var PROBE_TIMEOUT_MS = 3e4;
@@ -14610,6 +14943,7 @@ async function scanLibrary(deps, sources) {
14610
14943
  for (const entry of harvests) for (const item of entry.items) if (item.filePath !== null) filePaths.set(item.filePath, item.id);
14611
14944
  outcome.files = filePaths.size;
14612
14945
  const fileWrites = [];
14946
+ let chaptersReprobed = 0;
14613
14947
  for (const [path, id] of filePaths) {
14614
14948
  const stat = await deps.stat(path);
14615
14949
  if (stat === null) {
@@ -14624,10 +14958,14 @@ async function scanLibrary(deps, sources) {
14624
14958
  continue;
14625
14959
  }
14626
14960
  const known = knownFiles.get(path);
14627
- 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)) {
14628
14965
  outcome.reused += 1;
14629
14966
  continue;
14630
14967
  }
14968
+ if (chaptersOnly) chaptersReprobed += 1;
14631
14969
  try {
14632
14970
  const result = await deps.probe(path);
14633
14971
  fileWrites.push({
@@ -14639,11 +14977,24 @@ async function scanLibrary(deps, sources) {
14639
14977
  container: result.container,
14640
14978
  durationMs: result.durationMs,
14641
14979
  streams: [...result.streams],
14980
+ chapters: [...result.chapters],
14642
14981
  probeError: null
14643
14982
  });
14644
14983
  outcome.probed += 1;
14645
14984
  } catch (error) {
14646
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
+ }
14647
14998
  logger.warn("probe failed: the file stays catalogued, unprobed", {
14648
14999
  tags: { itemId: id },
14649
15000
  meta: {
@@ -14661,12 +15012,14 @@ async function scanLibrary(deps, sources) {
14661
15012
  container: null,
14662
15013
  durationMs: null,
14663
15014
  streams: [],
15015
+ chapters: [],
14664
15016
  probeError: message
14665
15017
  });
14666
15018
  outcome.skipped += 1;
14667
15019
  }
14668
15020
  }
14669
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 } });
14670
15023
  for (const entry of harvests) {
14671
15024
  if (!entry.trusted) continue;
14672
15025
  const stale = [...existingItems.values()].filter((item) => item.sourceId === entry.sourceId && !seenIds.has(item.id));
@@ -14928,6 +15281,15 @@ var MediaLibraryAddon = class extends BaseAddon {
14928
15281
  logger
14929
15282
  })
14930
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
+ });
14931
15293
  await ctx.dataPlane?.serve({
14932
15294
  prefix: "img",
14933
15295
  access: "viewer",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dominevo/addon-media-library",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "description": "The self-hosted media library: a catalogue built from the arr apps and plain folders, probed files, per-user progress, direct play with Range and a native /media app in the viewer.",
5
5
  "keywords": [
6
6
  "dominevo",
@@ -58,7 +58,7 @@
58
58
  }
59
59
  ],
60
60
  "requires": {
61
- "server": ">=0.1.59"
61
+ "server": ">=0.1.63"
62
62
  }
63
63
  },
64
64
  "files": [