@dominevo/addon-media-library 0.1.8 → 0.1.10

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.
@@ -4,8 +4,8 @@ Object.defineProperties(exports, {
4
4
  });
5
5
  let node_fs_promises = require("node:fs/promises");
6
6
  let node_path = require("node:path");
7
- let node_fs = require("node:fs");
8
7
  let node_crypto = require("node:crypto");
8
+ let node_fs = require("node:fs");
9
9
  let node_child_process = require("node:child_process");
10
10
  let node_dns_promises = require("node:dns/promises");
11
11
  let node_net = require("node:net");
@@ -8690,6 +8690,17 @@ var AppEntrySchema = /* @__PURE__ */ discriminatedUnion("kind", [
8690
8690
  /* @__PURE__ */ object({
8691
8691
  kind: /* @__PURE__ */ literal("addon-page"),
8692
8692
  pageId: /* @__PURE__ */ string()
8693
+ }),
8694
+ /* @__PURE__ */ object({
8695
+ kind: /* @__PURE__ */ literal("rn-plugin"),
8696
+ /** Asset path of the bundle for iOS and Android, served at `/api/addon-assets/<addonId>/<path>`. */
8697
+ native: /* @__PURE__ */ string().min(1),
8698
+ /** Asset path of the bundle for the web viewer (same source; `react-native` maps to react-native-web). */
8699
+ web: /* @__PURE__ */ string().min(1),
8700
+ /** The host API the bundle was built against; the shell refuses a plugin newer than its own. */
8701
+ hostApi: /* @__PURE__ */ number().int().min(1),
8702
+ /** Cache key of the bundle on the device: a new value fetches it again. */
8703
+ version: /* @__PURE__ */ string().min(1)
8693
8704
  })
8694
8705
  ]);
8695
8706
  /**
@@ -8834,6 +8845,30 @@ var LibraryFileInfoSchema = /* @__PURE__ */ object({
8834
8845
  /** False while the file is catalogued but not probed yet, or the probe failed. */
8835
8846
  probed: /* @__PURE__ */ boolean()
8836
8847
  });
8848
+ /** One chapter of a file: seconds from the start; `title` is `null` when the file names none. */
8849
+ var MediaChapterSchema = /* @__PURE__ */ object({
8850
+ startSec: /* @__PURE__ */ number().nonnegative(),
8851
+ endSec: /* @__PURE__ */ number().nonnegative(),
8852
+ title: /* @__PURE__ */ string().nullable()
8853
+ });
8854
+ /**
8855
+ * A subtitle file next to the video. `path` is the relative hub path that serves it as WebVTT;
8856
+ * append `?offsetMs=<signed integer, at most 600000 either way>` to shift every cue (the subtitle delay).
8857
+ */
8858
+ var ExternalSubtitleSchema = /* @__PURE__ */ object({
8859
+ id: /* @__PURE__ */ string(),
8860
+ language: /* @__PURE__ */ string().nullable(),
8861
+ forced: /* @__PURE__ */ boolean(),
8862
+ /** The format of the file on disk; the served body is always WebVTT. */
8863
+ format: /* @__PURE__ */ _enum([
8864
+ "srt",
8865
+ "ass",
8866
+ "ssa",
8867
+ "vtt"
8868
+ ]),
8869
+ label: /* @__PURE__ */ string(),
8870
+ path: /* @__PURE__ */ string()
8871
+ });
8837
8872
  var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8838
8873
  overview: /* @__PURE__ */ string().nullable(),
8839
8874
  ids: /* @__PURE__ */ object({
@@ -8844,7 +8879,11 @@ var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8844
8879
  fanartPath: /* @__PURE__ */ string().nullable(),
8845
8880
  /** Relative hub path that direct-plays the file, with HTTP Range. `null` when not playable. */
8846
8881
  playPath: /* @__PURE__ */ string().nullable(),
8847
- file: /* @__PURE__ */ LibraryFileInfoSchema.nullable()
8882
+ file: /* @__PURE__ */ LibraryFileInfoSchema.nullable(),
8883
+ /** The file's chapters in order; empty when it has none or it is not probed yet. */
8884
+ chapters: /* @__PURE__ */ array(MediaChapterSchema).readonly(),
8885
+ /** Sidecar subtitle files found next to the video; empty when none. */
8886
+ externalSubtitles: /* @__PURE__ */ array(ExternalSubtitleSchema).readonly()
8848
8887
  });
8849
8888
  /**
8850
8889
  * A person of an item's credits. `photoPath` is an image-plane handle relative to the hub origin
@@ -9050,6 +9089,23 @@ function buildAddressRoles() {
9050
9089
  }];
9051
9090
  }
9052
9091
  //#endregion
9092
+ //#region src/rn-app/plugin-version.ts
9093
+ /** Where the build writes the plugin, relative to the package root; these paths are the `rn-plugin` entry's assets. */
9094
+ var PLUGIN_NATIVE_ASSET = "dist/rn-app/index.native.js";
9095
+ var PLUGIN_WEB_ASSET = "dist/rn-app/index.web.js";
9096
+ /**
9097
+ * The cache key of the built plugin: the package version plus a hash of both bundles, so a rebuild
9098
+ * of the same package version still reaches a device that cached the old one. `null` when the
9099
+ * bundles are not built (a dev checkout): the plugin app is then not declared.
9100
+ */
9101
+ function readPluginVersion(packageDir) {
9102
+ const native = (0, node_path.join)(packageDir, PLUGIN_NATIVE_ASSET);
9103
+ const web = (0, node_path.join)(packageDir, PLUGIN_WEB_ASSET);
9104
+ if (!(0, node_fs.existsSync)(native) || !(0, node_fs.existsSync)(web)) return null;
9105
+ const pkg = JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(packageDir, "package.json"), "utf8"));
9106
+ return `${typeof pkg === "object" && pkg !== null && "version" in pkg && typeof pkg.version === "string" ? pkg.version : "0"}+${(0, node_crypto.createHash)("sha256").update((0, node_fs.readFileSync)(native)).update((0, node_fs.readFileSync)(web)).digest("hex").slice(0, 12)}`;
9107
+ }
9108
+ //#endregion
9053
9109
  //#region src/app-source.ts
9054
9110
  var APP_ID = "media";
9055
9111
  function buildApp() {
@@ -9074,6 +9130,38 @@ function buildApp() {
9074
9130
  settings: null
9075
9131
  };
9076
9132
  }
9133
+ var PLUGIN_APP_ID = "media-plugin";
9134
+ /** The host API the plugin bundle is built against (`hostApi` of its `index.tsx`). */
9135
+ var PLUGIN_HOST_API = 1;
9136
+ /**
9137
+ * The React Native plugin spike (planning#908), declared next to the native Media app and
9138
+ * admin-only until phase 2 replaces it. `version` is the build's cache key (`readPluginVersion`).
9139
+ */
9140
+ function buildPluginApp(version) {
9141
+ return {
9142
+ id: PLUGIN_APP_ID,
9143
+ label: {
9144
+ key: "media-library:apps.mediaPlugin",
9145
+ fallback: "Media (plugin)"
9146
+ },
9147
+ icon: {
9148
+ kind: "image",
9149
+ asset: "assets/app-icon.svg"
9150
+ },
9151
+ entry: {
9152
+ kind: "rn-plugin",
9153
+ native: PLUGIN_NATIVE_ASSET,
9154
+ web: PLUGIN_WEB_ASSET,
9155
+ hostApi: PLUGIN_HOST_API,
9156
+ version
9157
+ },
9158
+ reach: { kind: "hub" },
9159
+ adminOnly: true,
9160
+ nav: [],
9161
+ takesSharedSearch: false,
9162
+ settings: null
9163
+ };
9164
+ }
9077
9165
  //#endregion
9078
9166
  //#region src/arr-client.ts
9079
9167
  var ImageSchema$1 = object({
@@ -9907,7 +9995,7 @@ function pump(path, start, end, res, stallMs) {
9907
9995
  res.on("close", () => settle(sent > 0 && res.writableFinished ? "finished" : "client-closed"));
9908
9996
  });
9909
9997
  }
9910
- function reject(res, status, extra) {
9998
+ function reject$1(res, status, extra) {
9911
9999
  res.writeHead(status, {
9912
10000
  "Content-Length": 0,
9913
10001
  ...extra
@@ -9919,18 +10007,18 @@ function createFilePlaneHandler(deps) {
9919
10007
  const stallMs = deps.stallMs ?? 3e4;
9920
10008
  return async (req, res) => {
9921
10009
  const method = req.method ?? "GET";
9922
- if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10010
+ if (method !== "GET" && method !== "HEAD") return reject$1(res, 405, { Allow: "GET, HEAD" });
9923
10011
  const raw = (req.url ?? "/").split("?")[0] ?? "/";
9924
10012
  let itemId;
9925
10013
  try {
9926
10014
  itemId = decodeURIComponent(raw.replace(/^\//, ""));
9927
10015
  } catch {
9928
10016
  deps.logger.warn("file request refused: bad escape", { meta: { reason: "bad-id" } });
9929
- return reject(res, 404);
10017
+ return reject$1(res, 404);
9930
10018
  }
9931
10019
  if (!isItemId(itemId)) {
9932
10020
  deps.logger.warn("file request refused: not an item id", { meta: { reason: "bad-id" } });
9933
- return reject(res, 404);
10021
+ return reject$1(res, 404);
9934
10022
  }
9935
10023
  const tags = { itemId };
9936
10024
  const catalogued = await deps.lookup(itemId);
@@ -9939,7 +10027,7 @@ function createFilePlaneHandler(deps) {
9939
10027
  tags,
9940
10028
  meta: { reason: "not-catalogued" }
9941
10029
  });
9942
- return reject(res, 404);
10030
+ return reject$1(res, 404);
9943
10031
  }
9944
10032
  const path = await resolveServable(catalogued, await deps.roots());
9945
10033
  if (path === null) {
@@ -9947,7 +10035,7 @@ function createFilePlaneHandler(deps) {
9947
10035
  tags,
9948
10036
  meta: { reason: "outside-roots" }
9949
10037
  });
9950
- return reject(res, 404);
10038
+ return reject$1(res, 404);
9951
10039
  }
9952
10040
  let size;
9953
10041
  try {
@@ -9957,7 +10045,7 @@ function createFilePlaneHandler(deps) {
9957
10045
  tags,
9958
10046
  meta: { reason: "gone" }
9959
10047
  });
9960
- return reject(res, 404);
10048
+ return reject$1(res, 404);
9961
10049
  }
9962
10050
  const range = parseRange(headerOf(req.headers.range), size);
9963
10051
  if (range.kind === "unsatisfiable") {
@@ -9968,7 +10056,7 @@ function createFilePlaneHandler(deps) {
9968
10056
  size
9969
10057
  }
9970
10058
  });
9971
- return reject(res, 416, { "Content-Range": `bytes */${size}` });
10059
+ return reject$1(res, 416, { "Content-Range": `bytes */${size}` });
9972
10060
  }
9973
10061
  const start = range.kind === "range" ? range.start : 0;
9974
10062
  const end = range.kind === "range" ? range.end : size - 1;
@@ -10002,6 +10090,198 @@ function createFilePlaneHandler(deps) {
10002
10090
  function headerOf(value) {
10003
10091
  return Array.isArray(value) ? value[0] : value;
10004
10092
  }
10093
+ 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})/;
10094
+ function clock(hours, minutes, seconds, fraction) {
10095
+ return (((hours === void 0 ? 0 : Number(hours.slice(0, -1))) * 60 + Number(minutes)) * 60 + Number(seconds)) * 1e3 + Number(fraction.padEnd(3, "0"));
10096
+ }
10097
+ /** SRT and VTT share one cue shape: an optional id line, a timing line, text up to a blank line. */
10098
+ function parseTimedText(text) {
10099
+ const cues = [];
10100
+ for (const block of text.split(/\n{2,}/)) {
10101
+ const lines = block.split("\n");
10102
+ const at = lines.findIndex((line) => TIMING.test(line));
10103
+ if (at < 0) continue;
10104
+ const match = TIMING.exec(lines[at] ?? "");
10105
+ if (match === null) continue;
10106
+ const [, h1, m1, s1, f1, h2, m2, s2, f2] = match;
10107
+ if (m1 === void 0 || s1 === void 0 || f1 === void 0) continue;
10108
+ if (m2 === void 0 || s2 === void 0 || f2 === void 0) continue;
10109
+ const body = lines.slice(at + 1).join("\n").replace(/\{\\an?\d\}/g, "").trim();
10110
+ if (body === "") continue;
10111
+ cues.push({
10112
+ startMs: clock(h1, m1, s1, f1),
10113
+ endMs: clock(h2, m2, s2, f2),
10114
+ text: body
10115
+ });
10116
+ }
10117
+ return cues;
10118
+ }
10119
+ var ASS_TIME = /^(\d+):(\d{2}):(\d{2})[.:](\d{1,3})$/;
10120
+ function assClock(value) {
10121
+ const match = ASS_TIME.exec(value.trim());
10122
+ if (match === null) return null;
10123
+ const [, h, m, s, f] = match;
10124
+ if (h === void 0 || m === void 0 || s === void 0 || f === void 0) return null;
10125
+ const ms = f.length <= 2 ? Number(f.padEnd(2, "0")) * 10 : Number(f);
10126
+ return (Number(h) * 3600 + Number(m) * 60 + Number(s)) * 1e3 + ms;
10127
+ }
10128
+ /** Dialogue text with the styling dropped: override blocks gone, hard breaks kept. */
10129
+ function assText(raw) {
10130
+ return raw.replace(/\{[^}]*\}/g, "").replace(/\\[Nn]/g, "\n").replace(/\\h/g, " ").trim();
10131
+ }
10132
+ function parseAss(text) {
10133
+ let inEvents = false;
10134
+ let columns = [];
10135
+ const cues = [];
10136
+ for (const line of text.split("\n")) {
10137
+ const trimmed = line.trim();
10138
+ if (/^\[.*\]$/.test(trimmed)) {
10139
+ inEvents = trimmed.toLowerCase() === "[events]";
10140
+ continue;
10141
+ }
10142
+ if (!inEvents) continue;
10143
+ if (/^format:/i.test(trimmed)) {
10144
+ columns = trimmed.slice(trimmed.indexOf(":") + 1).split(",").map((name) => name.trim().toLowerCase());
10145
+ continue;
10146
+ }
10147
+ if (!/^dialogue:/i.test(trimmed)) continue;
10148
+ const startAt = columns.indexOf("start");
10149
+ const endAt = columns.indexOf("end");
10150
+ const textAt = columns.indexOf("text");
10151
+ if (startAt < 0 || endAt < 0 || textAt < 0) continue;
10152
+ const fields = trimmed.slice(trimmed.indexOf(":") + 1).split(",");
10153
+ const head = fields.slice(0, textAt);
10154
+ const rawText = fields.slice(textAt).join(",");
10155
+ if (/\{[^}]*\\p[1-9]/.test(rawText)) continue;
10156
+ const start = assClock(head[startAt] ?? "");
10157
+ const end = assClock(head[endAt] ?? "");
10158
+ const body = assText(rawText);
10159
+ if (start === null || end === null || body === "") continue;
10160
+ cues.push({
10161
+ startMs: start,
10162
+ endMs: end,
10163
+ text: body
10164
+ });
10165
+ }
10166
+ return cues.sort((a, b) => a.startMs - b.startMs);
10167
+ }
10168
+ function stamp(ms) {
10169
+ const total = Math.max(0, Math.round(ms));
10170
+ const pad = (value, width) => String(value).padStart(width, "0");
10171
+ const hours = Math.floor(total / 36e5);
10172
+ const minutes = Math.floor(total % 36e5 / 6e4);
10173
+ const seconds = Math.floor(total % 6e4 / 1e3);
10174
+ return `${pad(hours, 2)}:${pad(minutes, 2)}:${pad(seconds, 2)}.${pad(total % 1e3, 3)}`;
10175
+ }
10176
+ /**
10177
+ * One subtitle file as WebVTT, every cue moved by `offsetMs` (negative = earlier). A cue is clamped at 0
10178
+ * and dropped when nothing of it is left after the shift.
10179
+ */
10180
+ function toWebVtt(source, format, offsetMs = 0) {
10181
+ const text = source.replace(/^/, "").replace(/\r\n?/g, "\n");
10182
+ const cues = format === "ass" || format === "ssa" ? parseAss(text) : parseTimedText(text);
10183
+ const out = ["WEBVTT", ""];
10184
+ for (const cue of cues) {
10185
+ const start = Math.max(0, cue.startMs + offsetMs);
10186
+ const end = Math.max(0, cue.endMs + offsetMs);
10187
+ if (end <= start) continue;
10188
+ out.push(`${stamp(start)} --> ${stamp(end)}`, cue.text, "");
10189
+ }
10190
+ return out.join("\n");
10191
+ }
10192
+ function reject(res, status, extra) {
10193
+ res.writeHead(status, {
10194
+ "Content-Length": 0,
10195
+ ...extra
10196
+ });
10197
+ res.end();
10198
+ }
10199
+ /** `offsetMs` from a query: absent is 0; anything but a bounded signed integer is `null` (refused). */
10200
+ function parseOffsetMs(query) {
10201
+ const raw = new URLSearchParams(query).get("offsetMs");
10202
+ if (raw === null) return 0;
10203
+ if (!/^-?\d{1,7}$/.test(raw)) return null;
10204
+ const value = Number(raw);
10205
+ return Math.abs(value) <= 6e5 ? value : null;
10206
+ }
10207
+ /** The `subtitle` plane: `GET|HEAD /<itemId>/<sidecarId>[?offsetMs=N]` answers one sidecar as WebVTT. */
10208
+ function createSubtitlePlaneHandler(deps) {
10209
+ return async (req, res) => {
10210
+ const method = req.method ?? "GET";
10211
+ if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10212
+ const [rawPath = "/", query = ""] = (req.url ?? "/").split("?");
10213
+ const segments = rawPath.replace(/^\//, "").split("/");
10214
+ let itemId;
10215
+ let sidecar;
10216
+ try {
10217
+ if (segments.length !== 2) return reject(res, 404);
10218
+ itemId = decodeURIComponent(segments[0] ?? "");
10219
+ sidecar = decodeURIComponent(segments[1] ?? "");
10220
+ } catch {
10221
+ return reject(res, 404);
10222
+ }
10223
+ if (!isItemId(itemId)) {
10224
+ deps.logger.warn("subtitle request refused: not an item id", { meta: { reason: "bad-id" } });
10225
+ return reject(res, 404);
10226
+ }
10227
+ const tags = { itemId };
10228
+ const offsetMs = parseOffsetMs(query);
10229
+ if (offsetMs === null) {
10230
+ deps.logger.info("subtitle request refused: bad offset", {
10231
+ tags,
10232
+ meta: { reason: "bad-offset" }
10233
+ });
10234
+ return reject(res, 400);
10235
+ }
10236
+ const known = (await deps.sidecars(itemId))?.find((candidate) => candidate.id === sidecar);
10237
+ if (known === void 0) {
10238
+ deps.logger.info("subtitle request refused: not a sidecar of this item", {
10239
+ tags,
10240
+ meta: { reason: "not-a-sidecar" }
10241
+ });
10242
+ return reject(res, 404);
10243
+ }
10244
+ const path = await resolveServable(known.filePath, await deps.roots());
10245
+ if (path === null) {
10246
+ deps.logger.warn("subtitle request refused: outside the library roots", {
10247
+ tags,
10248
+ meta: { reason: "outside-roots" }
10249
+ });
10250
+ return reject(res, 404);
10251
+ }
10252
+ try {
10253
+ if ((await (0, node_fs_promises.stat)(path)).size > 5242880) {
10254
+ deps.logger.warn("subtitle request refused: file too large", {
10255
+ tags,
10256
+ meta: { reason: "too-large" }
10257
+ });
10258
+ return reject(res, 404);
10259
+ }
10260
+ const body = Buffer.from(toWebVtt(await (0, node_fs_promises.readFile)(path, "utf8"), known.format, offsetMs), "utf8");
10261
+ res.writeHead(200, {
10262
+ "Content-Type": "text/vtt; charset=utf-8",
10263
+ "Content-Length": body.length,
10264
+ "Cache-Control": "private, no-store"
10265
+ });
10266
+ if (method === "HEAD") res.end();
10267
+ else res.end(body);
10268
+ deps.logger.debug("subtitle served", {
10269
+ tags,
10270
+ meta: {
10271
+ sidecar,
10272
+ format: known.format,
10273
+ offsetMs
10274
+ }
10275
+ });
10276
+ } catch {
10277
+ deps.logger.warn("subtitle request refused: file vanished", {
10278
+ tags,
10279
+ meta: { reason: "gone" }
10280
+ });
10281
+ reject(res, 404);
10282
+ }
10283
+ };
10284
+ }
10005
10285
  //#endregion
10006
10286
  //#region src/folder-walker.ts
10007
10287
  var VIDEO_EXTENSIONS = new Set([
@@ -10372,6 +10652,8 @@ var FileRowSchema = object({
10372
10652
  container: string().nullable(),
10373
10653
  durationMs: number().int().nullable(),
10374
10654
  streams: array(LibraryStreamSchema),
10655
+ /** Absent on a row probed before chapters were read: the next scan probes it again. */
10656
+ chapters: array(MediaChapterSchema).nullish(),
10375
10657
  probeError: string().nullable()
10376
10658
  });
10377
10659
  var PinSourceSchema = _enum(["plex", "manual"]);
@@ -10489,6 +10771,10 @@ var COLLECTIONS = [
10489
10771
  type: "JSON",
10490
10772
  notNull: true
10491
10773
  },
10774
+ {
10775
+ name: "chapters",
10776
+ type: "JSON"
10777
+ },
10492
10778
  text$3("probeError")
10493
10779
  ]
10494
10780
  },
@@ -10910,6 +11196,60 @@ async function localMovie(reader, filePath) {
10910
11196
  };
10911
11197
  }
10912
11198
  //#endregion
11199
+ //#region src/subtitle-sidecars.ts
11200
+ var FORMATS$1 = [
11201
+ "srt",
11202
+ "ass",
11203
+ "ssa",
11204
+ "vtt"
11205
+ ];
11206
+ var LANGUAGE = /^[a-z]{2,3}(?:-[a-z0-9]{2,4})?$/i;
11207
+ function formatOf(extension) {
11208
+ const bare = extension.slice(1).toLowerCase();
11209
+ return FORMATS$1.find((format) => format === bare) ?? null;
11210
+ }
11211
+ /** A stable id from the file name: it never carries a path, so a client cannot name one. */
11212
+ function sidecarId(fileName) {
11213
+ return (0, node_crypto.createHash)("sha1").update(fileName.toLowerCase()).digest("hex").slice(0, 10);
11214
+ }
11215
+ /**
11216
+ * The subtitle files of `videoPath` in its folder's `listing`: `<base>.srt`, `<base>.<lang>.srt`,
11217
+ * `<base>.<lang>.forced.srt` (also `.ass`, `.ssa`, `.vtt`). The base is matched case-insensitively and
11218
+ * must be followed by a dot, so `Movie2.srt` is not the sidecar of `Movie.mkv`.
11219
+ */
11220
+ function discoverSubtitles(videoPath, listing) {
11221
+ const dir = (0, node_path.dirname)(videoPath);
11222
+ const base = (0, node_path.basename)(videoPath, (0, node_path.extname)(videoPath)).toLowerCase();
11223
+ const found = [];
11224
+ for (const [lower, real] of listing) {
11225
+ const extension = (0, node_path.extname)(lower);
11226
+ const format = formatOf(extension);
11227
+ if (format === null || !lower.startsWith(`${base}.`)) continue;
11228
+ const middle = lower.slice(base.length + 1, lower.length - extension.length);
11229
+ const tokens = middle === "" ? [] : middle.split(".");
11230
+ let language = null;
11231
+ let forced = false;
11232
+ const extra = [];
11233
+ for (const token of tokens) if (token === "forced") forced = true;
11234
+ else if (language === null && extra.length === 0 && LANGUAGE.test(token)) language = token;
11235
+ else extra.push(token);
11236
+ const parts = [
11237
+ language,
11238
+ ...extra,
11239
+ forced ? "forced" : null
11240
+ ].filter((part) => part !== null);
11241
+ found.push({
11242
+ id: sidecarId(real),
11243
+ language,
11244
+ forced,
11245
+ format,
11246
+ label: parts.length === 0 ? "Subtitles" : parts.join(" "),
11247
+ filePath: (0, node_path.join)(dir, real)
11248
+ });
11249
+ }
11250
+ return found.sort((a, b) => a.filePath.localeCompare(b.filePath));
11251
+ }
11252
+ //#endregion
10913
11253
  //#region src/item-text.ts
10914
11254
  /**
10915
11255
  * A language tag as the translations are keyed: lower-case, region dropped (`it-IT` is `it`).
@@ -10951,6 +11291,7 @@ function sortByShownTitle(rows, requested, serverDefault) {
10951
11291
  return rows.toSorted((a, b) => collator.compare(keys.get(a) ?? "", keys.get(b) ?? ""));
10952
11292
  }
10953
11293
  var FILE_PLANE_PREFIX = "file";
11294
+ var SUBTITLE_PLANE_PREFIX = "subtitle";
10954
11295
  var HUB_PLANE_BASE = "/addon/media-library";
10955
11296
  var SEARCH_DEFAULT_LIMIT = 50;
10956
11297
  var RECENT_DEFAULT_LIMIT = 20;
@@ -10962,6 +11303,9 @@ var WATCHLIST_RESOLVE_CHUNK = 500;
10962
11303
  function playPathOf(itemId) {
10963
11304
  return `${HUB_PLANE_BASE}/${FILE_PLANE_PREFIX}/${itemId}`;
10964
11305
  }
11306
+ function subtitlePathOf(itemId, sidecarId) {
11307
+ return `${HUB_PLANE_BASE}/${SUBTITLE_PLANE_PREFIX}/${itemId}/${sidecarId}`;
11308
+ }
10965
11309
  function imagePathOf(itemId, which) {
10966
11310
  return `${HUB_PLANE_BASE}/img/${itemId}/${which}`;
10967
11311
  }
@@ -10982,12 +11326,14 @@ var LibraryStore = class {
10982
11326
  logger;
10983
11327
  serverLanguage;
10984
11328
  now;
11329
+ listDir;
10985
11330
  locks = /* @__PURE__ */ new Map();
10986
- constructor(db, logger, serverLanguage = () => "en", now = Date.now) {
11331
+ constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir) {
10987
11332
  this.db = db;
10988
11333
  this.logger = logger;
10989
11334
  this.serverLanguage = serverLanguage;
10990
11335
  this.now = now;
11336
+ this.listDir = listDir;
10991
11337
  }
10992
11338
  async init() {
10993
11339
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -11152,9 +11498,24 @@ var LibraryStore = class {
11152
11498
  },
11153
11499
  fanartPath: row.fanartSource === null ? null : imagePathOf(row.id, "fanart"),
11154
11500
  playPath: file === void 0 ? null : playPathOf(row.id),
11155
- file: file === void 0 ? null : toFileInfo(file)
11501
+ file: file === void 0 ? null : toFileInfo(file),
11502
+ chapters: file?.chapters ?? [],
11503
+ externalSubtitles: (await this.subtitleSidecars(row.id)).map((sidecar) => ({
11504
+ id: sidecar.id,
11505
+ language: sidecar.language,
11506
+ forced: sidecar.forced,
11507
+ format: sidecar.format,
11508
+ label: sidecar.label,
11509
+ path: subtitlePathOf(row.id, sidecar.id)
11510
+ }))
11156
11511
  };
11157
11512
  }
11513
+ /** The subtitle files next to the video of `itemId`; empty when it has none or no file. */
11514
+ async subtitleSidecars(itemId) {
11515
+ const catalogued = await this.playableFile(itemId);
11516
+ if (catalogued === null) return [];
11517
+ return discoverSubtitles(catalogued.path, await this.listDir((0, node_path.dirname)(catalogued.path)));
11518
+ }
11158
11519
  /** The file a client may stream for `itemId`, or `null`: the path comes from here, never from the client. */
11159
11520
  async playableFile(itemId) {
11160
11521
  const [item] = await this.queryItems({
@@ -11450,6 +11811,13 @@ var LibraryStore = class {
11450
11811
  return entries;
11451
11812
  }
11452
11813
  };
11814
+ async function defaultListDir(dir) {
11815
+ try {
11816
+ return new Map((await (0, node_fs_promises.readdir)(dir)).map((name) => [name.toLowerCase(), name]));
11817
+ } catch {
11818
+ return /* @__PURE__ */ new Map();
11819
+ }
11820
+ }
11453
11821
  /** Genre names: the language asked for, else the server's, else whichever language the source answered. */
11454
11822
  function genresOf(details, requested, serverDefault) {
11455
11823
  for (const key of [languageKey(requested), languageKey(serverDefault)]) {
@@ -13004,22 +13372,20 @@ function translationsOf(details) {
13004
13372
  }
13005
13373
  return out;
13006
13374
  }
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
- };
13375
+ /**
13376
+ * The region a rating is read for: the tag's own region (`pt-BR` is BR), else the likely region of
13377
+ * its language from CLDR (`it` is IT, `ja` is JP), US when neither is known.
13378
+ */
13021
13379
  function tmdbRegionOf(language) {
13022
- return (/^[A-Za-z]{2,3}[-_]([A-Za-z]{2})$/.exec(language)?.[1] ?? REGION_OF_LANGUAGE[languageKey(language) ?? ""] ?? "US").toUpperCase();
13380
+ return (/^[A-Za-z]{2,3}[-_]([A-Za-z]{2})$/.exec(language)?.[1] ?? likelyRegionOf(languageKey(language)) ?? "US").toUpperCase();
13381
+ }
13382
+ function likelyRegionOf(language) {
13383
+ if (language === null || language === void 0 || language === "") return void 0;
13384
+ try {
13385
+ return new Intl.Locale(language).maximize().region;
13386
+ } catch {
13387
+ return;
13388
+ }
13023
13389
  }
13024
13390
  var photoOf = (path) => image("w185", path);
13025
13391
  var positive = (value) => value !== null && value !== void 0 && value > 0 ? Math.round(value) : null;
@@ -13739,18 +14105,44 @@ function channelsOf(line) {
13739
14105
  return count?.[1] !== void 0 ? Number(count[1]) : null;
13740
14106
  }
13741
14107
  var STREAM_LINE = /^\s*Stream #\d+:(\d+)(?:\[[^\]]*\])?(?:\(([^)]*)\))?[^:]*: (Video|Audio|Subtitle): (.*)$/;
14108
+ var CHAPTER_LINE = /^\s*Chapter #\d+:\d+: start ([\d.]+), end ([\d.]+)/;
14109
+ var CHAPTER_TITLE = /^\s+title\s*:\s*(.*)$/;
13742
14110
  /** Parse the report `ffmpeg -i <file>` prints on stderr. A report that is not one yields no streams and no duration. */
13743
14111
  function parseFfmpegReport(report) {
13744
14112
  const lines = report.split("\n");
13745
14113
  let container = null;
13746
14114
  let durationMs = null;
13747
14115
  const streams = [];
14116
+ const chapters = [];
13748
14117
  let doviSeenFor = null;
14118
+ let inChapters = false;
13749
14119
  for (const line of lines) {
13750
14120
  const input = /^Input #\d+, ([^,]+(?:,[^,]+)*), from /.exec(line);
13751
14121
  if (input?.[1] !== void 0 && container === null) container = containerOf(input[1]);
13752
14122
  const duration = /^\s*Duration: (\d+):(\d{2}):(\d{2})\.(\d{2})/.exec(line);
13753
14123
  if (duration && durationMs === null) durationMs = (Number(duration[1]) * 3600 + Number(duration[2]) * 60 + Number(duration[3])) * 1e3 + Number(duration[4]) * 10;
14124
+ const chapter = CHAPTER_LINE.exec(line);
14125
+ if (chapter?.[1] !== void 0 && chapter[2] !== void 0) {
14126
+ const startSec = Number(chapter[1]);
14127
+ const endSec = Number(chapter[2]);
14128
+ if (Number.isFinite(startSec) && Number.isFinite(endSec) && endSec > startSec) chapters.push({
14129
+ startSec,
14130
+ endSec,
14131
+ title: null
14132
+ });
14133
+ continue;
14134
+ }
14135
+ const titled = CHAPTER_TITLE.exec(line);
14136
+ const last = chapters[chapters.length - 1];
14137
+ if (titled?.[1] !== void 0 && last !== void 0 && last.title === null && inChapters) {
14138
+ if (titled[1].trim() !== "") chapters[chapters.length - 1] = {
14139
+ ...last,
14140
+ title: titled[1].trim()
14141
+ };
14142
+ continue;
14143
+ }
14144
+ if (/^\s*Chapters:/.test(line)) inChapters = true;
14145
+ if (STREAM_LINE.test(line)) inChapters = false;
13754
14146
  if (/DOVI configuration record/.test(line) && streams.length > 0) {
13755
14147
  doviSeenFor = streams.length - 1;
13756
14148
  continue;
@@ -13791,7 +14183,8 @@ function parseFfmpegReport(report) {
13791
14183
  return {
13792
14184
  container,
13793
14185
  durationMs,
13794
- streams
14186
+ streams,
14187
+ chapters
13795
14188
  };
13796
14189
  }
13797
14190
  var PROBE_TIMEOUT_MS = 3e4;
@@ -14614,6 +15007,7 @@ async function scanLibrary(deps, sources) {
14614
15007
  for (const entry of harvests) for (const item of entry.items) if (item.filePath !== null) filePaths.set(item.filePath, item.id);
14615
15008
  outcome.files = filePaths.size;
14616
15009
  const fileWrites = [];
15010
+ let chaptersReprobed = 0;
14617
15011
  for (const [path, id] of filePaths) {
14618
15012
  const stat = await deps.stat(path);
14619
15013
  if (stat === null) {
@@ -14628,10 +15022,14 @@ async function scanLibrary(deps, sources) {
14628
15022
  continue;
14629
15023
  }
14630
15024
  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)) {
15025
+ const unchanged = known !== void 0 && known.sizeBytes === stat.size && known.mtimeMs === stat.mtimeMs;
15026
+ const chaptersKnown = known?.chapters != null;
15027
+ const chaptersOnly = unchanged && known.probeOk && !chaptersKnown;
15028
+ if (unchanged && (known.probeOk && chaptersKnown || !known.probeOk && deps.now() - known.probedAt < 216e5)) {
14632
15029
  outcome.reused += 1;
14633
15030
  continue;
14634
15031
  }
15032
+ if (chaptersOnly) chaptersReprobed += 1;
14635
15033
  try {
14636
15034
  const result = await deps.probe(path);
14637
15035
  fileWrites.push({
@@ -14643,11 +15041,24 @@ async function scanLibrary(deps, sources) {
14643
15041
  container: result.container,
14644
15042
  durationMs: result.durationMs,
14645
15043
  streams: [...result.streams],
15044
+ chapters: [...result.chapters],
14646
15045
  probeError: null
14647
15046
  });
14648
15047
  outcome.probed += 1;
14649
15048
  } catch (error) {
14650
15049
  const message = error instanceof Error ? error.message : String(error);
15050
+ if (chaptersOnly) {
15051
+ logger.warn("chapters probe failed: the earlier probe result is kept", {
15052
+ tags: { itemId: id },
15053
+ meta: {
15054
+ path,
15055
+ reason: "chapters-probe-failed",
15056
+ error: message
15057
+ }
15058
+ });
15059
+ outcome.skipped += 1;
15060
+ continue;
15061
+ }
14651
15062
  logger.warn("probe failed: the file stays catalogued, unprobed", {
14652
15063
  tags: { itemId: id },
14653
15064
  meta: {
@@ -14665,12 +15076,14 @@ async function scanLibrary(deps, sources) {
14665
15076
  container: null,
14666
15077
  durationMs: null,
14667
15078
  streams: [],
15079
+ chapters: [],
14668
15080
  probeError: message
14669
15081
  });
14670
15082
  outcome.skipped += 1;
14671
15083
  }
14672
15084
  }
14673
15085
  if (fileWrites.length > 0) await db.upsertMany(FILES, ["path"], fileWrites);
15086
+ if (chaptersReprobed > 0) logger.info("files probed again only to read their chapters", { meta: { count: chaptersReprobed } });
14674
15087
  for (const entry of harvests) {
14675
15088
  if (!entry.trusted) continue;
14676
15089
  const stale = [...existingItems.values()].filter((item) => item.sourceId === entry.sourceId && !seenIds.has(item.id));
@@ -14932,6 +15345,15 @@ var MediaLibraryAddon = class extends BaseAddon {
14932
15345
  logger
14933
15346
  })
14934
15347
  });
15348
+ await ctx.dataPlane?.serve({
15349
+ prefix: SUBTITLE_PLANE_PREFIX,
15350
+ access: "viewer",
15351
+ handler: createSubtitlePlaneHandler({
15352
+ sidecars: (itemId) => store.subtitleSidecars(itemId),
15353
+ roots,
15354
+ logger
15355
+ })
15356
+ });
14935
15357
  await ctx.dataPlane?.serve({
14936
15358
  prefix: "img",
14937
15359
  access: "viewer",
@@ -14952,7 +15374,10 @@ var MediaLibraryAddon = class extends BaseAddon {
14952
15374
  const settings = await this.readSettings();
14953
15375
  scans.schedule(settings.rescanMinutes);
14954
15376
  scans.start("boot");
14955
- const apps = { listApps: async () => [buildApp()] };
15377
+ const apps = { listApps: async () => {
15378
+ const pluginVersion = readPluginVersion((0, node_path.join)(__dirname, ".."));
15379
+ return pluginVersion === null ? [buildApp()] : [buildApp(), buildPluginApp(pluginVersion)];
15380
+ } };
14956
15381
  const addressRoles = { listAddressRoles: async () => buildAddressRoles() };
14957
15382
  logger.info("media-library initialized");
14958
15383
  return {