@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.
@@ -1,7 +1,7 @@
1
1
  import { mkdir, open, readFile, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
2
2
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
- import { createReadStream } from "node:fs";
4
3
  import { createHash } from "node:crypto";
4
+ import { createReadStream, existsSync, readFileSync } from "node:fs";
5
5
  import { execFile } from "node:child_process";
6
6
  import { lookup } from "node:dns/promises";
7
7
  import { isIP } from "node:net";
@@ -8686,6 +8686,17 @@ var AppEntrySchema = /* @__PURE__ */ discriminatedUnion("kind", [
8686
8686
  /* @__PURE__ */ object({
8687
8687
  kind: /* @__PURE__ */ literal("addon-page"),
8688
8688
  pageId: /* @__PURE__ */ string()
8689
+ }),
8690
+ /* @__PURE__ */ object({
8691
+ kind: /* @__PURE__ */ literal("rn-plugin"),
8692
+ /** Asset path of the bundle for iOS and Android, served at `/api/addon-assets/<addonId>/<path>`. */
8693
+ native: /* @__PURE__ */ string().min(1),
8694
+ /** Asset path of the bundle for the web viewer (same source; `react-native` maps to react-native-web). */
8695
+ web: /* @__PURE__ */ string().min(1),
8696
+ /** The host API the bundle was built against; the shell refuses a plugin newer than its own. */
8697
+ hostApi: /* @__PURE__ */ number().int().min(1),
8698
+ /** Cache key of the bundle on the device: a new value fetches it again. */
8699
+ version: /* @__PURE__ */ string().min(1)
8689
8700
  })
8690
8701
  ]);
8691
8702
  /**
@@ -8830,6 +8841,30 @@ var LibraryFileInfoSchema = /* @__PURE__ */ object({
8830
8841
  /** False while the file is catalogued but not probed yet, or the probe failed. */
8831
8842
  probed: /* @__PURE__ */ boolean()
8832
8843
  });
8844
+ /** One chapter of a file: seconds from the start; `title` is `null` when the file names none. */
8845
+ var MediaChapterSchema = /* @__PURE__ */ object({
8846
+ startSec: /* @__PURE__ */ number().nonnegative(),
8847
+ endSec: /* @__PURE__ */ number().nonnegative(),
8848
+ title: /* @__PURE__ */ string().nullable()
8849
+ });
8850
+ /**
8851
+ * A subtitle file next to the video. `path` is the relative hub path that serves it as WebVTT;
8852
+ * append `?offsetMs=<signed integer, at most 600000 either way>` to shift every cue (the subtitle delay).
8853
+ */
8854
+ var ExternalSubtitleSchema = /* @__PURE__ */ object({
8855
+ id: /* @__PURE__ */ string(),
8856
+ language: /* @__PURE__ */ string().nullable(),
8857
+ forced: /* @__PURE__ */ boolean(),
8858
+ /** The format of the file on disk; the served body is always WebVTT. */
8859
+ format: /* @__PURE__ */ _enum([
8860
+ "srt",
8861
+ "ass",
8862
+ "ssa",
8863
+ "vtt"
8864
+ ]),
8865
+ label: /* @__PURE__ */ string(),
8866
+ path: /* @__PURE__ */ string()
8867
+ });
8833
8868
  var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8834
8869
  overview: /* @__PURE__ */ string().nullable(),
8835
8870
  ids: /* @__PURE__ */ object({
@@ -8840,7 +8875,11 @@ var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8840
8875
  fanartPath: /* @__PURE__ */ string().nullable(),
8841
8876
  /** Relative hub path that direct-plays the file, with HTTP Range. `null` when not playable. */
8842
8877
  playPath: /* @__PURE__ */ string().nullable(),
8843
- file: /* @__PURE__ */ LibraryFileInfoSchema.nullable()
8878
+ file: /* @__PURE__ */ LibraryFileInfoSchema.nullable(),
8879
+ /** The file's chapters in order; empty when it has none or it is not probed yet. */
8880
+ chapters: /* @__PURE__ */ array(MediaChapterSchema).readonly(),
8881
+ /** Sidecar subtitle files found next to the video; empty when none. */
8882
+ externalSubtitles: /* @__PURE__ */ array(ExternalSubtitleSchema).readonly()
8844
8883
  });
8845
8884
  /**
8846
8885
  * A person of an item's credits. `photoPath` is an image-plane handle relative to the hub origin
@@ -9046,6 +9085,23 @@ function buildAddressRoles() {
9046
9085
  }];
9047
9086
  }
9048
9087
  //#endregion
9088
+ //#region src/rn-app/plugin-version.ts
9089
+ /** Where the build writes the plugin, relative to the package root; these paths are the `rn-plugin` entry's assets. */
9090
+ var PLUGIN_NATIVE_ASSET = "dist/rn-app/index.native.js";
9091
+ var PLUGIN_WEB_ASSET = "dist/rn-app/index.web.js";
9092
+ /**
9093
+ * The cache key of the built plugin: the package version plus a hash of both bundles, so a rebuild
9094
+ * of the same package version still reaches a device that cached the old one. `null` when the
9095
+ * bundles are not built (a dev checkout): the plugin app is then not declared.
9096
+ */
9097
+ function readPluginVersion(packageDir) {
9098
+ const native = join(packageDir, PLUGIN_NATIVE_ASSET);
9099
+ const web = join(packageDir, PLUGIN_WEB_ASSET);
9100
+ if (!existsSync(native) || !existsSync(web)) return null;
9101
+ const pkg = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8"));
9102
+ return `${typeof pkg === "object" && pkg !== null && "version" in pkg && typeof pkg.version === "string" ? pkg.version : "0"}+${createHash("sha256").update(readFileSync(native)).update(readFileSync(web)).digest("hex").slice(0, 12)}`;
9103
+ }
9104
+ //#endregion
9049
9105
  //#region src/app-source.ts
9050
9106
  var APP_ID = "media";
9051
9107
  function buildApp() {
@@ -9070,6 +9126,38 @@ function buildApp() {
9070
9126
  settings: null
9071
9127
  };
9072
9128
  }
9129
+ var PLUGIN_APP_ID = "media-plugin";
9130
+ /** The host API the plugin bundle is built against (`hostApi` of its `index.tsx`). */
9131
+ var PLUGIN_HOST_API = 1;
9132
+ /**
9133
+ * The React Native plugin spike (planning#908), declared next to the native Media app and
9134
+ * admin-only until phase 2 replaces it. `version` is the build's cache key (`readPluginVersion`).
9135
+ */
9136
+ function buildPluginApp(version) {
9137
+ return {
9138
+ id: PLUGIN_APP_ID,
9139
+ label: {
9140
+ key: "media-library:apps.mediaPlugin",
9141
+ fallback: "Media (plugin)"
9142
+ },
9143
+ icon: {
9144
+ kind: "image",
9145
+ asset: "assets/app-icon.svg"
9146
+ },
9147
+ entry: {
9148
+ kind: "rn-plugin",
9149
+ native: PLUGIN_NATIVE_ASSET,
9150
+ web: PLUGIN_WEB_ASSET,
9151
+ hostApi: PLUGIN_HOST_API,
9152
+ version
9153
+ },
9154
+ reach: { kind: "hub" },
9155
+ adminOnly: true,
9156
+ nav: [],
9157
+ takesSharedSearch: false,
9158
+ settings: null
9159
+ };
9160
+ }
9073
9161
  //#endregion
9074
9162
  //#region src/arr-client.ts
9075
9163
  var ImageSchema$1 = object({
@@ -9903,7 +9991,7 @@ function pump(path, start, end, res, stallMs) {
9903
9991
  res.on("close", () => settle(sent > 0 && res.writableFinished ? "finished" : "client-closed"));
9904
9992
  });
9905
9993
  }
9906
- function reject(res, status, extra) {
9994
+ function reject$1(res, status, extra) {
9907
9995
  res.writeHead(status, {
9908
9996
  "Content-Length": 0,
9909
9997
  ...extra
@@ -9915,18 +10003,18 @@ function createFilePlaneHandler(deps) {
9915
10003
  const stallMs = deps.stallMs ?? 3e4;
9916
10004
  return async (req, res) => {
9917
10005
  const method = req.method ?? "GET";
9918
- if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10006
+ if (method !== "GET" && method !== "HEAD") return reject$1(res, 405, { Allow: "GET, HEAD" });
9919
10007
  const raw = (req.url ?? "/").split("?")[0] ?? "/";
9920
10008
  let itemId;
9921
10009
  try {
9922
10010
  itemId = decodeURIComponent(raw.replace(/^\//, ""));
9923
10011
  } catch {
9924
10012
  deps.logger.warn("file request refused: bad escape", { meta: { reason: "bad-id" } });
9925
- return reject(res, 404);
10013
+ return reject$1(res, 404);
9926
10014
  }
9927
10015
  if (!isItemId(itemId)) {
9928
10016
  deps.logger.warn("file request refused: not an item id", { meta: { reason: "bad-id" } });
9929
- return reject(res, 404);
10017
+ return reject$1(res, 404);
9930
10018
  }
9931
10019
  const tags = { itemId };
9932
10020
  const catalogued = await deps.lookup(itemId);
@@ -9935,7 +10023,7 @@ function createFilePlaneHandler(deps) {
9935
10023
  tags,
9936
10024
  meta: { reason: "not-catalogued" }
9937
10025
  });
9938
- return reject(res, 404);
10026
+ return reject$1(res, 404);
9939
10027
  }
9940
10028
  const path = await resolveServable(catalogued, await deps.roots());
9941
10029
  if (path === null) {
@@ -9943,7 +10031,7 @@ function createFilePlaneHandler(deps) {
9943
10031
  tags,
9944
10032
  meta: { reason: "outside-roots" }
9945
10033
  });
9946
- return reject(res, 404);
10034
+ return reject$1(res, 404);
9947
10035
  }
9948
10036
  let size;
9949
10037
  try {
@@ -9953,7 +10041,7 @@ function createFilePlaneHandler(deps) {
9953
10041
  tags,
9954
10042
  meta: { reason: "gone" }
9955
10043
  });
9956
- return reject(res, 404);
10044
+ return reject$1(res, 404);
9957
10045
  }
9958
10046
  const range = parseRange(headerOf(req.headers.range), size);
9959
10047
  if (range.kind === "unsatisfiable") {
@@ -9964,7 +10052,7 @@ function createFilePlaneHandler(deps) {
9964
10052
  size
9965
10053
  }
9966
10054
  });
9967
- return reject(res, 416, { "Content-Range": `bytes */${size}` });
10055
+ return reject$1(res, 416, { "Content-Range": `bytes */${size}` });
9968
10056
  }
9969
10057
  const start = range.kind === "range" ? range.start : 0;
9970
10058
  const end = range.kind === "range" ? range.end : size - 1;
@@ -9998,6 +10086,198 @@ function createFilePlaneHandler(deps) {
9998
10086
  function headerOf(value) {
9999
10087
  return Array.isArray(value) ? value[0] : value;
10000
10088
  }
10089
+ 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})/;
10090
+ function clock(hours, minutes, seconds, fraction) {
10091
+ return (((hours === void 0 ? 0 : Number(hours.slice(0, -1))) * 60 + Number(minutes)) * 60 + Number(seconds)) * 1e3 + Number(fraction.padEnd(3, "0"));
10092
+ }
10093
+ /** SRT and VTT share one cue shape: an optional id line, a timing line, text up to a blank line. */
10094
+ function parseTimedText(text) {
10095
+ const cues = [];
10096
+ for (const block of text.split(/\n{2,}/)) {
10097
+ const lines = block.split("\n");
10098
+ const at = lines.findIndex((line) => TIMING.test(line));
10099
+ if (at < 0) continue;
10100
+ const match = TIMING.exec(lines[at] ?? "");
10101
+ if (match === null) continue;
10102
+ const [, h1, m1, s1, f1, h2, m2, s2, f2] = match;
10103
+ if (m1 === void 0 || s1 === void 0 || f1 === void 0) continue;
10104
+ if (m2 === void 0 || s2 === void 0 || f2 === void 0) continue;
10105
+ const body = lines.slice(at + 1).join("\n").replace(/\{\\an?\d\}/g, "").trim();
10106
+ if (body === "") continue;
10107
+ cues.push({
10108
+ startMs: clock(h1, m1, s1, f1),
10109
+ endMs: clock(h2, m2, s2, f2),
10110
+ text: body
10111
+ });
10112
+ }
10113
+ return cues;
10114
+ }
10115
+ var ASS_TIME = /^(\d+):(\d{2}):(\d{2})[.:](\d{1,3})$/;
10116
+ function assClock(value) {
10117
+ const match = ASS_TIME.exec(value.trim());
10118
+ if (match === null) return null;
10119
+ const [, h, m, s, f] = match;
10120
+ if (h === void 0 || m === void 0 || s === void 0 || f === void 0) return null;
10121
+ const ms = f.length <= 2 ? Number(f.padEnd(2, "0")) * 10 : Number(f);
10122
+ return (Number(h) * 3600 + Number(m) * 60 + Number(s)) * 1e3 + ms;
10123
+ }
10124
+ /** Dialogue text with the styling dropped: override blocks gone, hard breaks kept. */
10125
+ function assText(raw) {
10126
+ return raw.replace(/\{[^}]*\}/g, "").replace(/\\[Nn]/g, "\n").replace(/\\h/g, " ").trim();
10127
+ }
10128
+ function parseAss(text) {
10129
+ let inEvents = false;
10130
+ let columns = [];
10131
+ const cues = [];
10132
+ for (const line of text.split("\n")) {
10133
+ const trimmed = line.trim();
10134
+ if (/^\[.*\]$/.test(trimmed)) {
10135
+ inEvents = trimmed.toLowerCase() === "[events]";
10136
+ continue;
10137
+ }
10138
+ if (!inEvents) continue;
10139
+ if (/^format:/i.test(trimmed)) {
10140
+ columns = trimmed.slice(trimmed.indexOf(":") + 1).split(",").map((name) => name.trim().toLowerCase());
10141
+ continue;
10142
+ }
10143
+ if (!/^dialogue:/i.test(trimmed)) continue;
10144
+ const startAt = columns.indexOf("start");
10145
+ const endAt = columns.indexOf("end");
10146
+ const textAt = columns.indexOf("text");
10147
+ if (startAt < 0 || endAt < 0 || textAt < 0) continue;
10148
+ const fields = trimmed.slice(trimmed.indexOf(":") + 1).split(",");
10149
+ const head = fields.slice(0, textAt);
10150
+ const rawText = fields.slice(textAt).join(",");
10151
+ if (/\{[^}]*\\p[1-9]/.test(rawText)) continue;
10152
+ const start = assClock(head[startAt] ?? "");
10153
+ const end = assClock(head[endAt] ?? "");
10154
+ const body = assText(rawText);
10155
+ if (start === null || end === null || body === "") continue;
10156
+ cues.push({
10157
+ startMs: start,
10158
+ endMs: end,
10159
+ text: body
10160
+ });
10161
+ }
10162
+ return cues.sort((a, b) => a.startMs - b.startMs);
10163
+ }
10164
+ function stamp(ms) {
10165
+ const total = Math.max(0, Math.round(ms));
10166
+ const pad = (value, width) => String(value).padStart(width, "0");
10167
+ const hours = Math.floor(total / 36e5);
10168
+ const minutes = Math.floor(total % 36e5 / 6e4);
10169
+ const seconds = Math.floor(total % 6e4 / 1e3);
10170
+ return `${pad(hours, 2)}:${pad(minutes, 2)}:${pad(seconds, 2)}.${pad(total % 1e3, 3)}`;
10171
+ }
10172
+ /**
10173
+ * One subtitle file as WebVTT, every cue moved by `offsetMs` (negative = earlier). A cue is clamped at 0
10174
+ * and dropped when nothing of it is left after the shift.
10175
+ */
10176
+ function toWebVtt(source, format, offsetMs = 0) {
10177
+ const text = source.replace(/^/, "").replace(/\r\n?/g, "\n");
10178
+ const cues = format === "ass" || format === "ssa" ? parseAss(text) : parseTimedText(text);
10179
+ const out = ["WEBVTT", ""];
10180
+ for (const cue of cues) {
10181
+ const start = Math.max(0, cue.startMs + offsetMs);
10182
+ const end = Math.max(0, cue.endMs + offsetMs);
10183
+ if (end <= start) continue;
10184
+ out.push(`${stamp(start)} --> ${stamp(end)}`, cue.text, "");
10185
+ }
10186
+ return out.join("\n");
10187
+ }
10188
+ function reject(res, status, extra) {
10189
+ res.writeHead(status, {
10190
+ "Content-Length": 0,
10191
+ ...extra
10192
+ });
10193
+ res.end();
10194
+ }
10195
+ /** `offsetMs` from a query: absent is 0; anything but a bounded signed integer is `null` (refused). */
10196
+ function parseOffsetMs(query) {
10197
+ const raw = new URLSearchParams(query).get("offsetMs");
10198
+ if (raw === null) return 0;
10199
+ if (!/^-?\d{1,7}$/.test(raw)) return null;
10200
+ const value = Number(raw);
10201
+ return Math.abs(value) <= 6e5 ? value : null;
10202
+ }
10203
+ /** The `subtitle` plane: `GET|HEAD /<itemId>/<sidecarId>[?offsetMs=N]` answers one sidecar as WebVTT. */
10204
+ function createSubtitlePlaneHandler(deps) {
10205
+ return async (req, res) => {
10206
+ const method = req.method ?? "GET";
10207
+ if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10208
+ const [rawPath = "/", query = ""] = (req.url ?? "/").split("?");
10209
+ const segments = rawPath.replace(/^\//, "").split("/");
10210
+ let itemId;
10211
+ let sidecar;
10212
+ try {
10213
+ if (segments.length !== 2) return reject(res, 404);
10214
+ itemId = decodeURIComponent(segments[0] ?? "");
10215
+ sidecar = decodeURIComponent(segments[1] ?? "");
10216
+ } catch {
10217
+ return reject(res, 404);
10218
+ }
10219
+ if (!isItemId(itemId)) {
10220
+ deps.logger.warn("subtitle request refused: not an item id", { meta: { reason: "bad-id" } });
10221
+ return reject(res, 404);
10222
+ }
10223
+ const tags = { itemId };
10224
+ const offsetMs = parseOffsetMs(query);
10225
+ if (offsetMs === null) {
10226
+ deps.logger.info("subtitle request refused: bad offset", {
10227
+ tags,
10228
+ meta: { reason: "bad-offset" }
10229
+ });
10230
+ return reject(res, 400);
10231
+ }
10232
+ const known = (await deps.sidecars(itemId))?.find((candidate) => candidate.id === sidecar);
10233
+ if (known === void 0) {
10234
+ deps.logger.info("subtitle request refused: not a sidecar of this item", {
10235
+ tags,
10236
+ meta: { reason: "not-a-sidecar" }
10237
+ });
10238
+ return reject(res, 404);
10239
+ }
10240
+ const path = await resolveServable(known.filePath, await deps.roots());
10241
+ if (path === null) {
10242
+ deps.logger.warn("subtitle request refused: outside the library roots", {
10243
+ tags,
10244
+ meta: { reason: "outside-roots" }
10245
+ });
10246
+ return reject(res, 404);
10247
+ }
10248
+ try {
10249
+ if ((await stat(path)).size > 5242880) {
10250
+ deps.logger.warn("subtitle request refused: file too large", {
10251
+ tags,
10252
+ meta: { reason: "too-large" }
10253
+ });
10254
+ return reject(res, 404);
10255
+ }
10256
+ const body = Buffer.from(toWebVtt(await readFile(path, "utf8"), known.format, offsetMs), "utf8");
10257
+ res.writeHead(200, {
10258
+ "Content-Type": "text/vtt; charset=utf-8",
10259
+ "Content-Length": body.length,
10260
+ "Cache-Control": "private, no-store"
10261
+ });
10262
+ if (method === "HEAD") res.end();
10263
+ else res.end(body);
10264
+ deps.logger.debug("subtitle served", {
10265
+ tags,
10266
+ meta: {
10267
+ sidecar,
10268
+ format: known.format,
10269
+ offsetMs
10270
+ }
10271
+ });
10272
+ } catch {
10273
+ deps.logger.warn("subtitle request refused: file vanished", {
10274
+ tags,
10275
+ meta: { reason: "gone" }
10276
+ });
10277
+ reject(res, 404);
10278
+ }
10279
+ };
10280
+ }
10001
10281
  //#endregion
10002
10282
  //#region src/folder-walker.ts
10003
10283
  var VIDEO_EXTENSIONS = new Set([
@@ -10368,6 +10648,8 @@ var FileRowSchema = object({
10368
10648
  container: string().nullable(),
10369
10649
  durationMs: number().int().nullable(),
10370
10650
  streams: array(LibraryStreamSchema),
10651
+ /** Absent on a row probed before chapters were read: the next scan probes it again. */
10652
+ chapters: array(MediaChapterSchema).nullish(),
10371
10653
  probeError: string().nullable()
10372
10654
  });
10373
10655
  var PinSourceSchema = _enum(["plex", "manual"]);
@@ -10485,6 +10767,10 @@ var COLLECTIONS = [
10485
10767
  type: "JSON",
10486
10768
  notNull: true
10487
10769
  },
10770
+ {
10771
+ name: "chapters",
10772
+ type: "JSON"
10773
+ },
10488
10774
  text$3("probeError")
10489
10775
  ]
10490
10776
  },
@@ -10906,6 +11192,60 @@ async function localMovie(reader, filePath) {
10906
11192
  };
10907
11193
  }
10908
11194
  //#endregion
11195
+ //#region src/subtitle-sidecars.ts
11196
+ var FORMATS$1 = [
11197
+ "srt",
11198
+ "ass",
11199
+ "ssa",
11200
+ "vtt"
11201
+ ];
11202
+ var LANGUAGE = /^[a-z]{2,3}(?:-[a-z0-9]{2,4})?$/i;
11203
+ function formatOf(extension) {
11204
+ const bare = extension.slice(1).toLowerCase();
11205
+ return FORMATS$1.find((format) => format === bare) ?? null;
11206
+ }
11207
+ /** A stable id from the file name: it never carries a path, so a client cannot name one. */
11208
+ function sidecarId(fileName) {
11209
+ return createHash("sha1").update(fileName.toLowerCase()).digest("hex").slice(0, 10);
11210
+ }
11211
+ /**
11212
+ * The subtitle files of `videoPath` in its folder's `listing`: `<base>.srt`, `<base>.<lang>.srt`,
11213
+ * `<base>.<lang>.forced.srt` (also `.ass`, `.ssa`, `.vtt`). The base is matched case-insensitively and
11214
+ * must be followed by a dot, so `Movie2.srt` is not the sidecar of `Movie.mkv`.
11215
+ */
11216
+ function discoverSubtitles(videoPath, listing) {
11217
+ const dir = dirname(videoPath);
11218
+ const base = basename(videoPath, extname(videoPath)).toLowerCase();
11219
+ const found = [];
11220
+ for (const [lower, real] of listing) {
11221
+ const extension = extname(lower);
11222
+ const format = formatOf(extension);
11223
+ if (format === null || !lower.startsWith(`${base}.`)) continue;
11224
+ const middle = lower.slice(base.length + 1, lower.length - extension.length);
11225
+ const tokens = middle === "" ? [] : middle.split(".");
11226
+ let language = null;
11227
+ let forced = false;
11228
+ const extra = [];
11229
+ for (const token of tokens) if (token === "forced") forced = true;
11230
+ else if (language === null && extra.length === 0 && LANGUAGE.test(token)) language = token;
11231
+ else extra.push(token);
11232
+ const parts = [
11233
+ language,
11234
+ ...extra,
11235
+ forced ? "forced" : null
11236
+ ].filter((part) => part !== null);
11237
+ found.push({
11238
+ id: sidecarId(real),
11239
+ language,
11240
+ forced,
11241
+ format,
11242
+ label: parts.length === 0 ? "Subtitles" : parts.join(" "),
11243
+ filePath: join(dir, real)
11244
+ });
11245
+ }
11246
+ return found.sort((a, b) => a.filePath.localeCompare(b.filePath));
11247
+ }
11248
+ //#endregion
10909
11249
  //#region src/item-text.ts
10910
11250
  /**
10911
11251
  * A language tag as the translations are keyed: lower-case, region dropped (`it-IT` is `it`).
@@ -10947,6 +11287,7 @@ function sortByShownTitle(rows, requested, serverDefault) {
10947
11287
  return rows.toSorted((a, b) => collator.compare(keys.get(a) ?? "", keys.get(b) ?? ""));
10948
11288
  }
10949
11289
  var FILE_PLANE_PREFIX = "file";
11290
+ var SUBTITLE_PLANE_PREFIX = "subtitle";
10950
11291
  var HUB_PLANE_BASE = "/addon/media-library";
10951
11292
  var SEARCH_DEFAULT_LIMIT = 50;
10952
11293
  var RECENT_DEFAULT_LIMIT = 20;
@@ -10958,6 +11299,9 @@ var WATCHLIST_RESOLVE_CHUNK = 500;
10958
11299
  function playPathOf(itemId) {
10959
11300
  return `${HUB_PLANE_BASE}/${FILE_PLANE_PREFIX}/${itemId}`;
10960
11301
  }
11302
+ function subtitlePathOf(itemId, sidecarId) {
11303
+ return `${HUB_PLANE_BASE}/${SUBTITLE_PLANE_PREFIX}/${itemId}/${sidecarId}`;
11304
+ }
10961
11305
  function imagePathOf(itemId, which) {
10962
11306
  return `${HUB_PLANE_BASE}/img/${itemId}/${which}`;
10963
11307
  }
@@ -10978,12 +11322,14 @@ var LibraryStore = class {
10978
11322
  logger;
10979
11323
  serverLanguage;
10980
11324
  now;
11325
+ listDir;
10981
11326
  locks = /* @__PURE__ */ new Map();
10982
- constructor(db, logger, serverLanguage = () => "en", now = Date.now) {
11327
+ constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir) {
10983
11328
  this.db = db;
10984
11329
  this.logger = logger;
10985
11330
  this.serverLanguage = serverLanguage;
10986
11331
  this.now = now;
11332
+ this.listDir = listDir;
10987
11333
  }
10988
11334
  async init() {
10989
11335
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -11148,9 +11494,24 @@ var LibraryStore = class {
11148
11494
  },
11149
11495
  fanartPath: row.fanartSource === null ? null : imagePathOf(row.id, "fanart"),
11150
11496
  playPath: file === void 0 ? null : playPathOf(row.id),
11151
- file: file === void 0 ? null : toFileInfo(file)
11497
+ file: file === void 0 ? null : toFileInfo(file),
11498
+ chapters: file?.chapters ?? [],
11499
+ externalSubtitles: (await this.subtitleSidecars(row.id)).map((sidecar) => ({
11500
+ id: sidecar.id,
11501
+ language: sidecar.language,
11502
+ forced: sidecar.forced,
11503
+ format: sidecar.format,
11504
+ label: sidecar.label,
11505
+ path: subtitlePathOf(row.id, sidecar.id)
11506
+ }))
11152
11507
  };
11153
11508
  }
11509
+ /** The subtitle files next to the video of `itemId`; empty when it has none or no file. */
11510
+ async subtitleSidecars(itemId) {
11511
+ const catalogued = await this.playableFile(itemId);
11512
+ if (catalogued === null) return [];
11513
+ return discoverSubtitles(catalogued.path, await this.listDir(dirname(catalogued.path)));
11514
+ }
11154
11515
  /** The file a client may stream for `itemId`, or `null`: the path comes from here, never from the client. */
11155
11516
  async playableFile(itemId) {
11156
11517
  const [item] = await this.queryItems({
@@ -11446,6 +11807,13 @@ var LibraryStore = class {
11446
11807
  return entries;
11447
11808
  }
11448
11809
  };
11810
+ async function defaultListDir(dir) {
11811
+ try {
11812
+ return new Map((await readdir(dir)).map((name) => [name.toLowerCase(), name]));
11813
+ } catch {
11814
+ return /* @__PURE__ */ new Map();
11815
+ }
11816
+ }
11449
11817
  /** Genre names: the language asked for, else the server's, else whichever language the source answered. */
11450
11818
  function genresOf(details, requested, serverDefault) {
11451
11819
  for (const key of [languageKey(requested), languageKey(serverDefault)]) {
@@ -13000,22 +13368,20 @@ function translationsOf(details) {
13000
13368
  }
13001
13369
  return out;
13002
13370
  }
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
- };
13371
+ /**
13372
+ * The region a rating is read for: the tag's own region (`pt-BR` is BR), else the likely region of
13373
+ * its language from CLDR (`it` is IT, `ja` is JP), US when neither is known.
13374
+ */
13017
13375
  function tmdbRegionOf(language) {
13018
- return (/^[A-Za-z]{2,3}[-_]([A-Za-z]{2})$/.exec(language)?.[1] ?? REGION_OF_LANGUAGE[languageKey(language) ?? ""] ?? "US").toUpperCase();
13376
+ return (/^[A-Za-z]{2,3}[-_]([A-Za-z]{2})$/.exec(language)?.[1] ?? likelyRegionOf(languageKey(language)) ?? "US").toUpperCase();
13377
+ }
13378
+ function likelyRegionOf(language) {
13379
+ if (language === null || language === void 0 || language === "") return void 0;
13380
+ try {
13381
+ return new Intl.Locale(language).maximize().region;
13382
+ } catch {
13383
+ return;
13384
+ }
13019
13385
  }
13020
13386
  var photoOf = (path) => image("w185", path);
13021
13387
  var positive = (value) => value !== null && value !== void 0 && value > 0 ? Math.round(value) : null;
@@ -13735,18 +14101,44 @@ function channelsOf(line) {
13735
14101
  return count?.[1] !== void 0 ? Number(count[1]) : null;
13736
14102
  }
13737
14103
  var STREAM_LINE = /^\s*Stream #\d+:(\d+)(?:\[[^\]]*\])?(?:\(([^)]*)\))?[^:]*: (Video|Audio|Subtitle): (.*)$/;
14104
+ var CHAPTER_LINE = /^\s*Chapter #\d+:\d+: start ([\d.]+), end ([\d.]+)/;
14105
+ var CHAPTER_TITLE = /^\s+title\s*:\s*(.*)$/;
13738
14106
  /** Parse the report `ffmpeg -i <file>` prints on stderr. A report that is not one yields no streams and no duration. */
13739
14107
  function parseFfmpegReport(report) {
13740
14108
  const lines = report.split("\n");
13741
14109
  let container = null;
13742
14110
  let durationMs = null;
13743
14111
  const streams = [];
14112
+ const chapters = [];
13744
14113
  let doviSeenFor = null;
14114
+ let inChapters = false;
13745
14115
  for (const line of lines) {
13746
14116
  const input = /^Input #\d+, ([^,]+(?:,[^,]+)*), from /.exec(line);
13747
14117
  if (input?.[1] !== void 0 && container === null) container = containerOf(input[1]);
13748
14118
  const duration = /^\s*Duration: (\d+):(\d{2}):(\d{2})\.(\d{2})/.exec(line);
13749
14119
  if (duration && durationMs === null) durationMs = (Number(duration[1]) * 3600 + Number(duration[2]) * 60 + Number(duration[3])) * 1e3 + Number(duration[4]) * 10;
14120
+ const chapter = CHAPTER_LINE.exec(line);
14121
+ if (chapter?.[1] !== void 0 && chapter[2] !== void 0) {
14122
+ const startSec = Number(chapter[1]);
14123
+ const endSec = Number(chapter[2]);
14124
+ if (Number.isFinite(startSec) && Number.isFinite(endSec) && endSec > startSec) chapters.push({
14125
+ startSec,
14126
+ endSec,
14127
+ title: null
14128
+ });
14129
+ continue;
14130
+ }
14131
+ const titled = CHAPTER_TITLE.exec(line);
14132
+ const last = chapters[chapters.length - 1];
14133
+ if (titled?.[1] !== void 0 && last !== void 0 && last.title === null && inChapters) {
14134
+ if (titled[1].trim() !== "") chapters[chapters.length - 1] = {
14135
+ ...last,
14136
+ title: titled[1].trim()
14137
+ };
14138
+ continue;
14139
+ }
14140
+ if (/^\s*Chapters:/.test(line)) inChapters = true;
14141
+ if (STREAM_LINE.test(line)) inChapters = false;
13750
14142
  if (/DOVI configuration record/.test(line) && streams.length > 0) {
13751
14143
  doviSeenFor = streams.length - 1;
13752
14144
  continue;
@@ -13787,7 +14179,8 @@ function parseFfmpegReport(report) {
13787
14179
  return {
13788
14180
  container,
13789
14181
  durationMs,
13790
- streams
14182
+ streams,
14183
+ chapters
13791
14184
  };
13792
14185
  }
13793
14186
  var PROBE_TIMEOUT_MS = 3e4;
@@ -14610,6 +15003,7 @@ async function scanLibrary(deps, sources) {
14610
15003
  for (const entry of harvests) for (const item of entry.items) if (item.filePath !== null) filePaths.set(item.filePath, item.id);
14611
15004
  outcome.files = filePaths.size;
14612
15005
  const fileWrites = [];
15006
+ let chaptersReprobed = 0;
14613
15007
  for (const [path, id] of filePaths) {
14614
15008
  const stat = await deps.stat(path);
14615
15009
  if (stat === null) {
@@ -14624,10 +15018,14 @@ async function scanLibrary(deps, sources) {
14624
15018
  continue;
14625
15019
  }
14626
15020
  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)) {
15021
+ const unchanged = known !== void 0 && known.sizeBytes === stat.size && known.mtimeMs === stat.mtimeMs;
15022
+ const chaptersKnown = known?.chapters != null;
15023
+ const chaptersOnly = unchanged && known.probeOk && !chaptersKnown;
15024
+ if (unchanged && (known.probeOk && chaptersKnown || !known.probeOk && deps.now() - known.probedAt < 216e5)) {
14628
15025
  outcome.reused += 1;
14629
15026
  continue;
14630
15027
  }
15028
+ if (chaptersOnly) chaptersReprobed += 1;
14631
15029
  try {
14632
15030
  const result = await deps.probe(path);
14633
15031
  fileWrites.push({
@@ -14639,11 +15037,24 @@ async function scanLibrary(deps, sources) {
14639
15037
  container: result.container,
14640
15038
  durationMs: result.durationMs,
14641
15039
  streams: [...result.streams],
15040
+ chapters: [...result.chapters],
14642
15041
  probeError: null
14643
15042
  });
14644
15043
  outcome.probed += 1;
14645
15044
  } catch (error) {
14646
15045
  const message = error instanceof Error ? error.message : String(error);
15046
+ if (chaptersOnly) {
15047
+ logger.warn("chapters probe failed: the earlier probe result is kept", {
15048
+ tags: { itemId: id },
15049
+ meta: {
15050
+ path,
15051
+ reason: "chapters-probe-failed",
15052
+ error: message
15053
+ }
15054
+ });
15055
+ outcome.skipped += 1;
15056
+ continue;
15057
+ }
14647
15058
  logger.warn("probe failed: the file stays catalogued, unprobed", {
14648
15059
  tags: { itemId: id },
14649
15060
  meta: {
@@ -14661,12 +15072,14 @@ async function scanLibrary(deps, sources) {
14661
15072
  container: null,
14662
15073
  durationMs: null,
14663
15074
  streams: [],
15075
+ chapters: [],
14664
15076
  probeError: message
14665
15077
  });
14666
15078
  outcome.skipped += 1;
14667
15079
  }
14668
15080
  }
14669
15081
  if (fileWrites.length > 0) await db.upsertMany(FILES, ["path"], fileWrites);
15082
+ if (chaptersReprobed > 0) logger.info("files probed again only to read their chapters", { meta: { count: chaptersReprobed } });
14670
15083
  for (const entry of harvests) {
14671
15084
  if (!entry.trusted) continue;
14672
15085
  const stale = [...existingItems.values()].filter((item) => item.sourceId === entry.sourceId && !seenIds.has(item.id));
@@ -14928,6 +15341,15 @@ var MediaLibraryAddon = class extends BaseAddon {
14928
15341
  logger
14929
15342
  })
14930
15343
  });
15344
+ await ctx.dataPlane?.serve({
15345
+ prefix: SUBTITLE_PLANE_PREFIX,
15346
+ access: "viewer",
15347
+ handler: createSubtitlePlaneHandler({
15348
+ sidecars: (itemId) => store.subtitleSidecars(itemId),
15349
+ roots,
15350
+ logger
15351
+ })
15352
+ });
14931
15353
  await ctx.dataPlane?.serve({
14932
15354
  prefix: "img",
14933
15355
  access: "viewer",
@@ -14948,7 +15370,10 @@ var MediaLibraryAddon = class extends BaseAddon {
14948
15370
  const settings = await this.readSettings();
14949
15371
  scans.schedule(settings.rescanMinutes);
14950
15372
  scans.start("boot");
14951
- const apps = { listApps: async () => [buildApp()] };
15373
+ const apps = { listApps: async () => {
15374
+ const pluginVersion = readPluginVersion(join(__dirname, ".."));
15375
+ return pluginVersion === null ? [buildApp()] : [buildApp(), buildPluginApp(pluginVersion)];
15376
+ } };
14952
15377
  const addressRoles = { listAddressRoles: async () => buildAddressRoles() };
14953
15378
  logger.info("media-library initialized");
14954
15379
  return {