@dominevo/addon-media-library 0.1.9 → 0.1.11

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");
@@ -2894,7 +2894,7 @@ function initializeContext(params) {
2894
2894
  external: params?.external ?? void 0
2895
2895
  };
2896
2896
  }
2897
- function process(schema, ctx, _params = {
2897
+ function process$1(schema, ctx, _params = {
2898
2898
  path: [],
2899
2899
  schemaPath: []
2900
2900
  }) {
@@ -2931,7 +2931,7 @@ function process(schema, ctx, _params = {
2931
2931
  const parent = schema._zod.parent;
2932
2932
  if (parent) {
2933
2933
  if (!result.ref) result.ref = parent;
2934
- process(parent, ctx, params);
2934
+ process$1(parent, ctx, params);
2935
2935
  ctx.seen.get(parent).isParent = true;
2936
2936
  }
2937
2937
  }
@@ -3151,7 +3151,7 @@ var createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
3151
3151
  ...params,
3152
3152
  processors
3153
3153
  });
3154
- process(schema, ctx);
3154
+ process$1(schema, ctx);
3155
3155
  extractDefs(ctx, schema);
3156
3156
  return finalize(ctx, schema);
3157
3157
  };
@@ -3163,7 +3163,7 @@ var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) =
3163
3163
  io,
3164
3164
  processors
3165
3165
  });
3166
- process(schema, ctx);
3166
+ process$1(schema, ctx);
3167
3167
  extractDefs(ctx, schema);
3168
3168
  return finalize(ctx, schema);
3169
3169
  };
@@ -3267,7 +3267,7 @@ var arrayProcessor = (schema, ctx, _json, params) => {
3267
3267
  if (typeof minimum === "number") json.minItems = minimum;
3268
3268
  if (typeof maximum === "number") json.maxItems = maximum;
3269
3269
  json.type = "array";
3270
- json.items = process(def.element, ctx, {
3270
+ json.items = process$1(def.element, ctx, {
3271
3271
  ...params,
3272
3272
  path: [...params.path, "items"]
3273
3273
  });
@@ -3278,7 +3278,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
3278
3278
  json.type = "object";
3279
3279
  json.properties = {};
3280
3280
  const shape = def.shape;
3281
- for (const key in shape) json.properties[key] = process(shape[key], ctx, {
3281
+ for (const key in shape) json.properties[key] = process$1(shape[key], ctx, {
3282
3282
  ...params,
3283
3283
  path: [
3284
3284
  ...params.path,
@@ -3296,7 +3296,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
3296
3296
  if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
3297
3297
  else if (!def.catchall) {
3298
3298
  if (ctx.io === "output") json.additionalProperties = false;
3299
- } else if (def.catchall) json.additionalProperties = process(def.catchall, ctx, {
3299
+ } else if (def.catchall) json.additionalProperties = process$1(def.catchall, ctx, {
3300
3300
  ...params,
3301
3301
  path: [...params.path, "additionalProperties"]
3302
3302
  });
@@ -3304,7 +3304,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
3304
3304
  var unionProcessor = (schema, ctx, json, params) => {
3305
3305
  const def = schema._zod.def;
3306
3306
  const isExclusive = def.inclusive === false;
3307
- const options = def.options.map((x, i) => process(x, ctx, {
3307
+ const options = def.options.map((x, i) => process$1(x, ctx, {
3308
3308
  ...params,
3309
3309
  path: [
3310
3310
  ...params.path,
@@ -3317,7 +3317,7 @@ var unionProcessor = (schema, ctx, json, params) => {
3317
3317
  };
3318
3318
  var intersectionProcessor = (schema, ctx, json, params) => {
3319
3319
  const def = schema._zod.def;
3320
- const a = process(def.left, ctx, {
3320
+ const a = process$1(def.left, ctx, {
3321
3321
  ...params,
3322
3322
  path: [
3323
3323
  ...params.path,
@@ -3325,7 +3325,7 @@ var intersectionProcessor = (schema, ctx, json, params) => {
3325
3325
  0
3326
3326
  ]
3327
3327
  });
3328
- const b = process(def.right, ctx, {
3328
+ const b = process$1(def.right, ctx, {
3329
3329
  ...params,
3330
3330
  path: [
3331
3331
  ...params.path,
@@ -3343,7 +3343,7 @@ var recordProcessor = (schema, ctx, _json, params) => {
3343
3343
  const keyType = def.keyType;
3344
3344
  const patterns = keyType._zod.bag?.patterns;
3345
3345
  if (def.mode === "loose" && patterns && patterns.size > 0) {
3346
- const valueSchema = process(def.valueType, ctx, {
3346
+ const valueSchema = process$1(def.valueType, ctx, {
3347
3347
  ...params,
3348
3348
  path: [
3349
3349
  ...params.path,
@@ -3354,11 +3354,11 @@ var recordProcessor = (schema, ctx, _json, params) => {
3354
3354
  json.patternProperties = {};
3355
3355
  for (const pattern of patterns) json.patternProperties[pattern.source] = valueSchema;
3356
3356
  } else {
3357
- if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process(def.keyType, ctx, {
3357
+ if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process$1(def.keyType, ctx, {
3358
3358
  ...params,
3359
3359
  path: [...params.path, "propertyNames"]
3360
3360
  });
3361
- json.additionalProperties = process(def.valueType, ctx, {
3361
+ json.additionalProperties = process$1(def.valueType, ctx, {
3362
3362
  ...params,
3363
3363
  path: [...params.path, "additionalProperties"]
3364
3364
  });
@@ -3371,7 +3371,7 @@ var recordProcessor = (schema, ctx, _json, params) => {
3371
3371
  };
3372
3372
  var nullableProcessor = (schema, ctx, json, params) => {
3373
3373
  const def = schema._zod.def;
3374
- const inner = process(def.innerType, ctx, params);
3374
+ const inner = process$1(def.innerType, ctx, params);
3375
3375
  const seen = ctx.seen.get(schema);
3376
3376
  if (ctx.target === "openapi-3.0") {
3377
3377
  seen.ref = def.innerType;
@@ -3380,27 +3380,27 @@ var nullableProcessor = (schema, ctx, json, params) => {
3380
3380
  };
3381
3381
  var nonoptionalProcessor = (schema, ctx, _json, params) => {
3382
3382
  const def = schema._zod.def;
3383
- process(def.innerType, ctx, params);
3383
+ process$1(def.innerType, ctx, params);
3384
3384
  const seen = ctx.seen.get(schema);
3385
3385
  seen.ref = def.innerType;
3386
3386
  };
3387
3387
  var defaultProcessor = (schema, ctx, json, params) => {
3388
3388
  const def = schema._zod.def;
3389
- process(def.innerType, ctx, params);
3389
+ process$1(def.innerType, ctx, params);
3390
3390
  const seen = ctx.seen.get(schema);
3391
3391
  seen.ref = def.innerType;
3392
3392
  json.default = JSON.parse(JSON.stringify(def.defaultValue));
3393
3393
  };
3394
3394
  var prefaultProcessor = (schema, ctx, json, params) => {
3395
3395
  const def = schema._zod.def;
3396
- process(def.innerType, ctx, params);
3396
+ process$1(def.innerType, ctx, params);
3397
3397
  const seen = ctx.seen.get(schema);
3398
3398
  seen.ref = def.innerType;
3399
3399
  if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
3400
3400
  };
3401
3401
  var catchProcessor = (schema, ctx, json, params) => {
3402
3402
  const def = schema._zod.def;
3403
- process(def.innerType, ctx, params);
3403
+ process$1(def.innerType, ctx, params);
3404
3404
  const seen = ctx.seen.get(schema);
3405
3405
  seen.ref = def.innerType;
3406
3406
  let catchValue;
@@ -3415,20 +3415,20 @@ var pipeProcessor = (schema, ctx, _json, params) => {
3415
3415
  const def = schema._zod.def;
3416
3416
  const inIsTransform = def.in._zod.traits.has("$ZodTransform");
3417
3417
  const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
3418
- process(innerType, ctx, params);
3418
+ process$1(innerType, ctx, params);
3419
3419
  const seen = ctx.seen.get(schema);
3420
3420
  seen.ref = innerType;
3421
3421
  };
3422
3422
  var readonlyProcessor = (schema, ctx, json, params) => {
3423
3423
  const def = schema._zod.def;
3424
- process(def.innerType, ctx, params);
3424
+ process$1(def.innerType, ctx, params);
3425
3425
  const seen = ctx.seen.get(schema);
3426
3426
  seen.ref = def.innerType;
3427
3427
  json.readOnly = true;
3428
3428
  };
3429
3429
  var optionalProcessor = (schema, ctx, _json, params) => {
3430
3430
  const def = schema._zod.def;
3431
- process(def.innerType, ctx, params);
3431
+ process$1(def.innerType, ctx, params);
3432
3432
  const seen = ctx.seen.get(schema);
3433
3433
  seen.ref = def.innerType;
3434
3434
  };
@@ -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
  /**
@@ -8858,6 +8869,22 @@ var ExternalSubtitleSchema = /* @__PURE__ */ object({
8858
8869
  label: /* @__PURE__ */ string(),
8859
8870
  path: /* @__PURE__ */ string()
8860
8871
  });
8872
+ /**
8873
+ * Scrub thumbnails of the file. `path` is the relative hub path of the WebVTT index (cues point at
8874
+ * `sprite-N.jpg#xywh=x,y,w,h` beside it), set only when `status` is `ready`. `pending`: being generated in the
8875
+ * background, ask again later; `failed`: ffmpeg could not; `skipped`: the file has no duration or is too short;
8876
+ * `disabled`: the installation turned generation off.
8877
+ */
8878
+ var MediaTrickplaySchema = /* @__PURE__ */ object({
8879
+ status: /* @__PURE__ */ _enum([
8880
+ "ready",
8881
+ "pending",
8882
+ "failed",
8883
+ "skipped",
8884
+ "disabled"
8885
+ ]),
8886
+ path: /* @__PURE__ */ string().nullable()
8887
+ });
8861
8888
  var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8862
8889
  overview: /* @__PURE__ */ string().nullable(),
8863
8890
  ids: /* @__PURE__ */ object({
@@ -8872,7 +8899,9 @@ var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8872
8899
  /** The file's chapters in order; empty when it has none or it is not probed yet. */
8873
8900
  chapters: /* @__PURE__ */ array(MediaChapterSchema).readonly(),
8874
8901
  /** Sidecar subtitle files found next to the video; empty when none. */
8875
- externalSubtitles: /* @__PURE__ */ array(ExternalSubtitleSchema).readonly()
8902
+ externalSubtitles: /* @__PURE__ */ array(ExternalSubtitleSchema).readonly(),
8903
+ /** Scrub thumbnails of the file; `null` when the item has no file. */
8904
+ trickplay: /* @__PURE__ */ MediaTrickplaySchema.nullable()
8876
8905
  });
8877
8906
  /**
8878
8907
  * A person of an item's credits. `photoPath` is an image-plane handle relative to the hub origin
@@ -9078,6 +9107,23 @@ function buildAddressRoles() {
9078
9107
  }];
9079
9108
  }
9080
9109
  //#endregion
9110
+ //#region src/rn-app/plugin-version.ts
9111
+ /** Where the build writes the plugin, relative to the package root; these paths are the `rn-plugin` entry's assets. */
9112
+ var PLUGIN_NATIVE_ASSET = "dist/rn-app/index.native.js";
9113
+ var PLUGIN_WEB_ASSET = "dist/rn-app/index.web.js";
9114
+ /**
9115
+ * The cache key of the built plugin: the package version plus a hash of both bundles, so a rebuild
9116
+ * of the same package version still reaches a device that cached the old one. `null` when the
9117
+ * bundles are not built (a dev checkout): the plugin app is then not declared.
9118
+ */
9119
+ function readPluginVersion(packageDir) {
9120
+ const native = (0, node_path.join)(packageDir, PLUGIN_NATIVE_ASSET);
9121
+ const web = (0, node_path.join)(packageDir, PLUGIN_WEB_ASSET);
9122
+ if (!(0, node_fs.existsSync)(native) || !(0, node_fs.existsSync)(web)) return null;
9123
+ const pkg = JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(packageDir, "package.json"), "utf8"));
9124
+ 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)}`;
9125
+ }
9126
+ //#endregion
9081
9127
  //#region src/app-source.ts
9082
9128
  var APP_ID = "media";
9083
9129
  function buildApp() {
@@ -9102,6 +9148,38 @@ function buildApp() {
9102
9148
  settings: null
9103
9149
  };
9104
9150
  }
9151
+ var PLUGIN_APP_ID = "media-plugin";
9152
+ /** The host API the plugin bundle is built against (`hostApi` of its `index.tsx`). */
9153
+ var PLUGIN_HOST_API = 1;
9154
+ /**
9155
+ * The React Native plugin spike (planning#908), declared next to the native Media app and
9156
+ * admin-only until phase 2 replaces it. `version` is the build's cache key (`readPluginVersion`).
9157
+ */
9158
+ function buildPluginApp(version) {
9159
+ return {
9160
+ id: PLUGIN_APP_ID,
9161
+ label: {
9162
+ key: "media-library:apps.mediaPlugin",
9163
+ fallback: "Media (plugin)"
9164
+ },
9165
+ icon: {
9166
+ kind: "image",
9167
+ asset: "assets/app-icon.svg"
9168
+ },
9169
+ entry: {
9170
+ kind: "rn-plugin",
9171
+ native: PLUGIN_NATIVE_ASSET,
9172
+ web: PLUGIN_WEB_ASSET,
9173
+ hostApi: PLUGIN_HOST_API,
9174
+ version
9175
+ },
9176
+ reach: { kind: "hub" },
9177
+ adminOnly: true,
9178
+ nav: [],
9179
+ takesSharedSearch: false,
9180
+ settings: null
9181
+ };
9182
+ }
9105
9183
  //#endregion
9106
9184
  //#region src/arr-client.ts
9107
9185
  var ImageSchema$1 = object({
@@ -9388,6 +9466,8 @@ var MediaLibrarySettingsSchema = object({
9388
9466
  /** Plain folders walked for files the arr apps do not know, one absolute path per line. */
9389
9467
  folderRoots: string().default(""),
9390
9468
  rescanMinutes: number().int().min(0).default(60),
9469
+ /** Scrub thumbnails, generated in the background with ffmpeg and cached under the addon's data dir. */
9470
+ trickplay: boolean().default(true),
9391
9471
  /** The metadata chain, one row per step in the order they answer; the first answer to a field wins (D1125). */
9392
9472
  metadataProviders: array(MetadataProviderRowSchema).default(defaultProviderRows),
9393
9473
  /** The Plex import (a one-shot, re-runnable action): the server, a token, and how paths and users line up. */
@@ -9506,22 +9586,33 @@ var MEDIA_LIBRARY_CLUSTER_SCHEMA = { sections: [
9506
9586
  id: "folders",
9507
9587
  title: "Folders",
9508
9588
  titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.title",
9509
- fields: [{
9510
- type: "textarea",
9511
- key: "folderRoots",
9512
- label: "Folders to walk",
9513
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.label",
9514
- description: "One absolute path per line. Files the arr apps do not know are added from here.",
9515
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.description"
9516
- }, {
9517
- type: "number",
9518
- key: "rescanMinutes",
9519
- label: "Rescan every (minutes)",
9520
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.label",
9521
- description: "0 scans only when asked.",
9522
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
9523
- min: 0
9524
- }]
9589
+ fields: [
9590
+ {
9591
+ type: "textarea",
9592
+ key: "folderRoots",
9593
+ label: "Folders to walk",
9594
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.label",
9595
+ description: "One absolute path per line. Files the arr apps do not know are added from here.",
9596
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.description"
9597
+ },
9598
+ {
9599
+ type: "number",
9600
+ key: "rescanMinutes",
9601
+ label: "Rescan every (minutes)",
9602
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.label",
9603
+ description: "0 scans only when asked.",
9604
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
9605
+ min: 0
9606
+ },
9607
+ {
9608
+ type: "boolean",
9609
+ key: "trickplay",
9610
+ label: "Scrub thumbnails",
9611
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.label",
9612
+ description: "Generate preview pictures for the seek bar in the background, one ffmpeg at a time at low priority.",
9613
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.description"
9614
+ }
9615
+ ]
9525
9616
  },
9526
9617
  {
9527
9618
  id: "metadata",
@@ -9765,6 +9856,34 @@ function fillMissingKeys(rows, stored) {
9765
9856
  });
9766
9857
  }
9767
9858
  //#endregion
9859
+ //#region src/servable.ts
9860
+ /**
9861
+ * A file is servable only when its REAL path (symlinks resolved) is inside a configured root.
9862
+ * The path itself comes from the catalogue by item id; this is the second lock on the same door,
9863
+ * so a catalogue row that names `/etc/passwd`, or a symlink that points out of the library, serves nothing.
9864
+ */
9865
+ async function resolveServable(path, roots) {
9866
+ if (!(0, node_path.isAbsolute)(path) || path.includes("\0")) return null;
9867
+ let real;
9868
+ try {
9869
+ real = await (0, node_fs_promises.realpath)(path);
9870
+ } catch {
9871
+ return null;
9872
+ }
9873
+ for (const root of roots) {
9874
+ if (root === "") continue;
9875
+ let realRoot;
9876
+ try {
9877
+ realRoot = await (0, node_fs_promises.realpath)(root);
9878
+ } catch {
9879
+ continue;
9880
+ }
9881
+ const prefix = realRoot.endsWith(node_path.sep) ? realRoot : `${realRoot}${node_path.sep}`;
9882
+ if (real.startsWith(prefix)) return real;
9883
+ }
9884
+ return null;
9885
+ }
9886
+ //#endregion
9768
9887
  //#region src/naming.ts
9769
9888
  /** Case- and accent-insensitive form of a title, for search and ordering. */
9770
9889
  function foldTitle(title) {
@@ -9822,34 +9941,6 @@ function guessFromFilename(fileName, parentDir) {
9822
9941
  };
9823
9942
  }
9824
9943
  //#endregion
9825
- //#region src/servable.ts
9826
- /**
9827
- * A file is servable only when its REAL path (symlinks resolved) is inside a configured root.
9828
- * The path itself comes from the catalogue by item id; this is the second lock on the same door,
9829
- * so a catalogue row that names `/etc/passwd`, or a symlink that points out of the library, serves nothing.
9830
- */
9831
- async function resolveServable(path, roots) {
9832
- if (!(0, node_path.isAbsolute)(path) || path.includes("\0")) return null;
9833
- let real;
9834
- try {
9835
- real = await (0, node_fs_promises.realpath)(path);
9836
- } catch {
9837
- return null;
9838
- }
9839
- for (const root of roots) {
9840
- if (root === "") continue;
9841
- let realRoot;
9842
- try {
9843
- realRoot = await (0, node_fs_promises.realpath)(root);
9844
- } catch {
9845
- continue;
9846
- }
9847
- const prefix = realRoot.endsWith(node_path.sep) ? realRoot : `${realRoot}${node_path.sep}`;
9848
- if (real.startsWith(prefix)) return real;
9849
- }
9850
- return null;
9851
- }
9852
- //#endregion
9853
9944
  //#region src/file-plane.ts
9854
9945
  /**
9855
9946
  * Parse one `Range: bytes=…` header against a file of `size` bytes. A header this server does not
@@ -9935,7 +10026,7 @@ function pump(path, start, end, res, stallMs) {
9935
10026
  res.on("close", () => settle(sent > 0 && res.writableFinished ? "finished" : "client-closed"));
9936
10027
  });
9937
10028
  }
9938
- function reject$1(res, status, extra) {
10029
+ function reject$2(res, status, extra) {
9939
10030
  res.writeHead(status, {
9940
10031
  "Content-Length": 0,
9941
10032
  ...extra
@@ -9947,18 +10038,18 @@ function createFilePlaneHandler(deps) {
9947
10038
  const stallMs = deps.stallMs ?? 3e4;
9948
10039
  return async (req, res) => {
9949
10040
  const method = req.method ?? "GET";
9950
- if (method !== "GET" && method !== "HEAD") return reject$1(res, 405, { Allow: "GET, HEAD" });
10041
+ if (method !== "GET" && method !== "HEAD") return reject$2(res, 405, { Allow: "GET, HEAD" });
9951
10042
  const raw = (req.url ?? "/").split("?")[0] ?? "/";
9952
10043
  let itemId;
9953
10044
  try {
9954
10045
  itemId = decodeURIComponent(raw.replace(/^\//, ""));
9955
10046
  } catch {
9956
10047
  deps.logger.warn("file request refused: bad escape", { meta: { reason: "bad-id" } });
9957
- return reject$1(res, 404);
10048
+ return reject$2(res, 404);
9958
10049
  }
9959
10050
  if (!isItemId(itemId)) {
9960
10051
  deps.logger.warn("file request refused: not an item id", { meta: { reason: "bad-id" } });
9961
- return reject$1(res, 404);
10052
+ return reject$2(res, 404);
9962
10053
  }
9963
10054
  const tags = { itemId };
9964
10055
  const catalogued = await deps.lookup(itemId);
@@ -9967,7 +10058,7 @@ function createFilePlaneHandler(deps) {
9967
10058
  tags,
9968
10059
  meta: { reason: "not-catalogued" }
9969
10060
  });
9970
- return reject$1(res, 404);
10061
+ return reject$2(res, 404);
9971
10062
  }
9972
10063
  const path = await resolveServable(catalogued, await deps.roots());
9973
10064
  if (path === null) {
@@ -9975,7 +10066,7 @@ function createFilePlaneHandler(deps) {
9975
10066
  tags,
9976
10067
  meta: { reason: "outside-roots" }
9977
10068
  });
9978
- return reject$1(res, 404);
10069
+ return reject$2(res, 404);
9979
10070
  }
9980
10071
  let size;
9981
10072
  try {
@@ -9985,7 +10076,7 @@ function createFilePlaneHandler(deps) {
9985
10076
  tags,
9986
10077
  meta: { reason: "gone" }
9987
10078
  });
9988
- return reject$1(res, 404);
10079
+ return reject$2(res, 404);
9989
10080
  }
9990
10081
  const range = parseRange(headerOf(req.headers.range), size);
9991
10082
  if (range.kind === "unsatisfiable") {
@@ -9996,7 +10087,7 @@ function createFilePlaneHandler(deps) {
9996
10087
  size
9997
10088
  }
9998
10089
  });
9999
- return reject$1(res, 416, { "Content-Range": `bytes */${size}` });
10090
+ return reject$2(res, 416, { "Content-Range": `bytes */${size}` });
10000
10091
  }
10001
10092
  const start = range.kind === "range" ? range.start : 0;
10002
10093
  const end = range.kind === "range" ? range.end : size - 1;
@@ -10129,7 +10220,7 @@ function toWebVtt(source, format, offsetMs = 0) {
10129
10220
  }
10130
10221
  return out.join("\n");
10131
10222
  }
10132
- function reject(res, status, extra) {
10223
+ function reject$1(res, status, extra) {
10133
10224
  res.writeHead(status, {
10134
10225
  "Content-Length": 0,
10135
10226
  ...extra
@@ -10148,21 +10239,21 @@ function parseOffsetMs(query) {
10148
10239
  function createSubtitlePlaneHandler(deps) {
10149
10240
  return async (req, res) => {
10150
10241
  const method = req.method ?? "GET";
10151
- if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10242
+ if (method !== "GET" && method !== "HEAD") return reject$1(res, 405, { Allow: "GET, HEAD" });
10152
10243
  const [rawPath = "/", query = ""] = (req.url ?? "/").split("?");
10153
10244
  const segments = rawPath.replace(/^\//, "").split("/");
10154
10245
  let itemId;
10155
10246
  let sidecar;
10156
10247
  try {
10157
- if (segments.length !== 2) return reject(res, 404);
10248
+ if (segments.length !== 2) return reject$1(res, 404);
10158
10249
  itemId = decodeURIComponent(segments[0] ?? "");
10159
10250
  sidecar = decodeURIComponent(segments[1] ?? "");
10160
10251
  } catch {
10161
- return reject(res, 404);
10252
+ return reject$1(res, 404);
10162
10253
  }
10163
10254
  if (!isItemId(itemId)) {
10164
10255
  deps.logger.warn("subtitle request refused: not an item id", { meta: { reason: "bad-id" } });
10165
- return reject(res, 404);
10256
+ return reject$1(res, 404);
10166
10257
  }
10167
10258
  const tags = { itemId };
10168
10259
  const offsetMs = parseOffsetMs(query);
@@ -10171,7 +10262,7 @@ function createSubtitlePlaneHandler(deps) {
10171
10262
  tags,
10172
10263
  meta: { reason: "bad-offset" }
10173
10264
  });
10174
- return reject(res, 400);
10265
+ return reject$1(res, 400);
10175
10266
  }
10176
10267
  const known = (await deps.sidecars(itemId))?.find((candidate) => candidate.id === sidecar);
10177
10268
  if (known === void 0) {
@@ -10179,7 +10270,7 @@ function createSubtitlePlaneHandler(deps) {
10179
10270
  tags,
10180
10271
  meta: { reason: "not-a-sidecar" }
10181
10272
  });
10182
- return reject(res, 404);
10273
+ return reject$1(res, 404);
10183
10274
  }
10184
10275
  const path = await resolveServable(known.filePath, await deps.roots());
10185
10276
  if (path === null) {
@@ -10187,7 +10278,7 @@ function createSubtitlePlaneHandler(deps) {
10187
10278
  tags,
10188
10279
  meta: { reason: "outside-roots" }
10189
10280
  });
10190
- return reject(res, 404);
10281
+ return reject$1(res, 404);
10191
10282
  }
10192
10283
  try {
10193
10284
  if ((await (0, node_fs_promises.stat)(path)).size > 5242880) {
@@ -10195,7 +10286,7 @@ function createSubtitlePlaneHandler(deps) {
10195
10286
  tags,
10196
10287
  meta: { reason: "too-large" }
10197
10288
  });
10198
- return reject(res, 404);
10289
+ return reject$1(res, 404);
10199
10290
  }
10200
10291
  const body = Buffer.from(toWebVtt(await (0, node_fs_promises.readFile)(path, "utf8"), known.format, offsetMs), "utf8");
10201
10292
  res.writeHead(200, {
@@ -10218,6 +10309,408 @@ function createSubtitlePlaneHandler(deps) {
10218
10309
  tags,
10219
10310
  meta: { reason: "gone" }
10220
10311
  });
10312
+ reject$1(res, 404);
10313
+ }
10314
+ };
10315
+ }
10316
+ var TILES_PER_SHEET = 100;
10317
+ var GENERATE_TIMEOUT_MS = 3600 * 1e3;
10318
+ var INDEX_NAME = "index.vtt";
10319
+ /** The names a client may ask for inside one item's trickplay folder. */
10320
+ var TRICKPLAY_FILE_NAME = /^(?:index\.vtt|sprite-\d{1,4}\.jpg)$/;
10321
+ var FailureSchema = object({
10322
+ at: number(),
10323
+ attempts: number().int(),
10324
+ reason: string()
10325
+ });
10326
+ /** The height of one tile for a picture of this shape; even, as the encoder wants. */
10327
+ function tileHeightOf(width, height) {
10328
+ return Math.max(2, Math.round(320 * height / width / 2) * 2);
10329
+ }
10330
+ /** The ffmpeg arguments: one frame per interval, scaled, tiled into sheets of the grid, one JPEG per sheet. */
10331
+ function trickplayArgs(job) {
10332
+ return [
10333
+ "-hide_banner",
10334
+ "-nostdin",
10335
+ "-loglevel",
10336
+ "error",
10337
+ "-threads",
10338
+ "1",
10339
+ "-i",
10340
+ `file:${job.inputPath}`,
10341
+ "-an",
10342
+ "-sn",
10343
+ "-vf",
10344
+ `fps=1/10,scale=320:${job.tileHeight},tile=10x10`,
10345
+ "-q:v",
10346
+ "6",
10347
+ "-start_number",
10348
+ "0",
10349
+ (0, node_path.join)(job.outDir, "sprite-%d.jpg")
10350
+ ];
10351
+ }
10352
+ /** ffmpeg at the lowest priority (`nice`, where there is one), so a scrub image never takes a stream's CPU. */
10353
+ function createFfmpegTrickplayGenerator(binaryPath) {
10354
+ return (job) => new Promise((done, reject) => {
10355
+ const args = trickplayArgs(job);
10356
+ const [command, argv] = process.platform === "win32" ? [binaryPath, args] : ["nice", [
10357
+ "-n",
10358
+ "19",
10359
+ binaryPath,
10360
+ ...args
10361
+ ]];
10362
+ (0, node_child_process.execFile)(command, argv, {
10363
+ timeout: GENERATE_TIMEOUT_MS,
10364
+ maxBuffer: 1024 * 1024,
10365
+ encoding: "utf8"
10366
+ }, (error, _stdout, stderr) => {
10367
+ if (error === null) done();
10368
+ else reject(new Error(error.killed === true ? "ffmpeg timed out" : stderr.slice(0, 300) || error.message));
10369
+ });
10370
+ });
10371
+ }
10372
+ function timestamp(seconds) {
10373
+ const totalMs = Math.round(seconds * 1e3);
10374
+ const pad = (value, width) => String(value).padStart(width, "0");
10375
+ return `${pad(Math.floor(totalMs / 36e5), 2)}:${pad(Math.floor(totalMs / 6e4) % 60, 2)}:${pad(Math.floor(totalMs / 1e3) % 60, 2)}.${pad(totalMs % 1e3, 3)}`;
10376
+ }
10377
+ /** The WebVTT index: one cue per interval, each pointing at its tile as `sprite-N.jpg#xywh=x,y,w,h`. */
10378
+ function buildTrickplayVtt(durationSec, tileHeight) {
10379
+ const frames = Math.ceil(durationSec / 10);
10380
+ const lines = ["WEBVTT", ""];
10381
+ for (let index = 0; index < frames; index += 1) {
10382
+ const slot = index % TILES_PER_SHEET;
10383
+ const x = slot % 10 * 320;
10384
+ const y = Math.floor(slot / 10) * tileHeight;
10385
+ const start = index * 10;
10386
+ const end = Math.min((index + 1) * 10, durationSec);
10387
+ lines.push(`${timestamp(start)} --> ${timestamp(end)}`, `sprite-${Math.floor(index / TILES_PER_SHEET)}.jpg#xywh=${x},${y},320,${tileHeight}`, "");
10388
+ }
10389
+ return lines.join("\n");
10390
+ }
10391
+ function fingerprintOf(source) {
10392
+ return `${source.sizeBytes}-${source.mtimeMs}`;
10393
+ }
10394
+ /** An item id is `source:kind:key`; the colons become underscores so the folder name is portable. */
10395
+ function folderOf(itemId) {
10396
+ return itemId.replaceAll(":", "_");
10397
+ }
10398
+ /**
10399
+ * The trickplay cache: sprite sheets and a WebVTT index per item, under the addon's data dir, keyed by the
10400
+ * file's size and mtime (a changed file generates anew). One ffmpeg at a time, in the background.
10401
+ */
10402
+ var TrickplayService = class {
10403
+ deps;
10404
+ queue = [];
10405
+ queued = /* @__PURE__ */ new Set();
10406
+ running = false;
10407
+ /** Files found outside the library roots: remembered (until restart) so they are not queued again. */
10408
+ outsideRoots = /* @__PURE__ */ new Set();
10409
+ idle = Promise.resolve();
10410
+ constructor(deps) {
10411
+ this.deps = deps;
10412
+ }
10413
+ keyOf(source) {
10414
+ return `${source.itemId}\u0000${fingerprintOf(source)}`;
10415
+ }
10416
+ itemDir(source) {
10417
+ return (0, node_path.join)(this.deps.cacheDir, folderOf(source.itemId));
10418
+ }
10419
+ readyDir(source) {
10420
+ return (0, node_path.join)(this.itemDir(source), fingerprintOf(source));
10421
+ }
10422
+ failurePath(source) {
10423
+ return (0, node_path.join)(this.itemDir(source), `${fingerprintOf(source)}.failed.json`);
10424
+ }
10425
+ /** The reason this file cannot have trickplay, or `null` when it can. */
10426
+ skipReason(source) {
10427
+ if (source.durationMs === null || source.durationMs <= 0) return "no-duration";
10428
+ if (source.durationMs / 1e3 < 30) return "too-short";
10429
+ if (source.width === null || source.height === null || source.width <= 0 || source.height <= 0) return "no-video-size";
10430
+ return null;
10431
+ }
10432
+ async readFailure(source) {
10433
+ try {
10434
+ return FailureSchema.parse(JSON.parse(await (0, node_fs_promises.readFile)(this.failurePath(source), "utf8")));
10435
+ } catch {
10436
+ return null;
10437
+ }
10438
+ }
10439
+ async isReady(source) {
10440
+ try {
10441
+ return (await (0, node_fs_promises.stat)((0, node_path.join)(this.readyDir(source), INDEX_NAME))).isFile();
10442
+ } catch {
10443
+ return false;
10444
+ }
10445
+ }
10446
+ /**
10447
+ * What a client may be told about `source`, and (when nothing is ready) a request for the work: a run
10448
+ * is queued unless one is queued already, it failed for good, or it failed too recently to try again.
10449
+ */
10450
+ async request(source, basePath) {
10451
+ const tags = { itemId: source.itemId };
10452
+ if (!this.deps.enabled()) return {
10453
+ status: "disabled",
10454
+ path: null
10455
+ };
10456
+ if (await this.isReady(source)) return {
10457
+ status: "ready",
10458
+ path: `${basePath}/${INDEX_NAME}`
10459
+ };
10460
+ if (this.outsideRoots.has(this.keyOf(source))) return {
10461
+ status: "skipped",
10462
+ path: null
10463
+ };
10464
+ const skip = this.skipReason(source);
10465
+ if (skip !== null) {
10466
+ this.deps.logger.debug("trickplay not generated", {
10467
+ tags,
10468
+ meta: { reason: skip }
10469
+ });
10470
+ return {
10471
+ status: "skipped",
10472
+ path: null
10473
+ };
10474
+ }
10475
+ const failure = await this.readFailure(source);
10476
+ if (failure !== null) {
10477
+ if (failure.attempts >= 3) return {
10478
+ status: "failed",
10479
+ path: null
10480
+ };
10481
+ if (this.deps.now() - failure.at < 216e5) return {
10482
+ status: "failed",
10483
+ path: null
10484
+ };
10485
+ }
10486
+ this.enqueue(source);
10487
+ return {
10488
+ status: "pending",
10489
+ path: null
10490
+ };
10491
+ }
10492
+ /** Queue one file; a second request for the same file while it waits or runs changes nothing. */
10493
+ enqueue(source) {
10494
+ const key = `${source.itemId}\u0000${fingerprintOf(source)}`;
10495
+ if (this.queued.has(key)) return;
10496
+ this.queued.add(key);
10497
+ this.queue.push(source);
10498
+ this.deps.logger.debug("trickplay queued", {
10499
+ tags: { itemId: source.itemId },
10500
+ meta: { waiting: this.queue.length }
10501
+ });
10502
+ if (!this.running) {
10503
+ this.running = true;
10504
+ this.idle = this.drain();
10505
+ }
10506
+ }
10507
+ /** Resolves when the queue is empty and nothing runs. */
10508
+ settled() {
10509
+ return this.idle;
10510
+ }
10511
+ async drain() {
10512
+ try {
10513
+ for (let next = this.queue.shift(); next !== void 0; next = this.queue.shift()) try {
10514
+ await this.generateOne(next);
10515
+ } catch (error) {
10516
+ this.deps.logger.warn("trickplay run aborted", {
10517
+ tags: { itemId: next.itemId },
10518
+ meta: { reason: error instanceof Error ? error.message : String(error) }
10519
+ });
10520
+ } finally {
10521
+ this.queued.delete(`${next.itemId}\u0000${fingerprintOf(next)}`);
10522
+ }
10523
+ } finally {
10524
+ this.running = false;
10525
+ }
10526
+ }
10527
+ async generateOne(source) {
10528
+ const tags = { itemId: source.itemId };
10529
+ const { logger } = this.deps;
10530
+ if (!this.deps.enabled()) {
10531
+ logger.info("trickplay skipped", {
10532
+ tags,
10533
+ meta: { reason: "disabled" }
10534
+ });
10535
+ return;
10536
+ }
10537
+ if (await this.isReady(source)) return;
10538
+ const skip = this.skipReason(source);
10539
+ if (skip !== null || source.width === null || source.height === null || source.durationMs === null) {
10540
+ logger.info("trickplay skipped", {
10541
+ tags,
10542
+ meta: { reason: skip ?? "no-video-size" }
10543
+ });
10544
+ return;
10545
+ }
10546
+ const attempts = ((await this.readFailure(source))?.attempts ?? 0) + 1;
10547
+ if (!await this.deps.inRoots(source.path)) {
10548
+ this.outsideRoots.add(this.keyOf(source));
10549
+ logger.warn("trickplay skipped", {
10550
+ tags,
10551
+ meta: { reason: "outside-roots" }
10552
+ });
10553
+ return;
10554
+ }
10555
+ const finalDir = this.readyDir(source);
10556
+ const workDir = `${finalDir}.work`;
10557
+ const tileHeight = tileHeightOf(source.width, source.height);
10558
+ const startedAt = this.deps.now();
10559
+ try {
10560
+ await (0, node_fs_promises.rm)(workDir, {
10561
+ recursive: true,
10562
+ force: true
10563
+ });
10564
+ await (0, node_fs_promises.mkdir)(workDir, { recursive: true });
10565
+ await this.deps.generate({
10566
+ inputPath: source.path,
10567
+ outDir: workDir,
10568
+ tileHeight
10569
+ });
10570
+ const sheets = (await (0, node_fs_promises.readdir)(workDir)).filter((name) => /^sprite-\d+\.jpg$/.test(name));
10571
+ if (sheets.length === 0) throw new Error("ffmpeg wrote no sprite sheet");
10572
+ await (0, node_fs_promises.writeFile)((0, node_path.join)(workDir, INDEX_NAME), buildTrickplayVtt(source.durationMs / 1e3, tileHeight), "utf8");
10573
+ await (0, node_fs_promises.rm)(finalDir, {
10574
+ recursive: true,
10575
+ force: true
10576
+ });
10577
+ await (0, node_fs_promises.rename)(workDir, finalDir);
10578
+ await (0, node_fs_promises.rm)(this.failurePath(source), { force: true });
10579
+ await this.pruneOthers(source);
10580
+ logger.info("trickplay generated", {
10581
+ tags,
10582
+ meta: {
10583
+ sheets: sheets.length,
10584
+ tileHeight,
10585
+ tookMs: this.deps.now() - startedAt
10586
+ }
10587
+ });
10588
+ } catch (error) {
10589
+ const reason = error instanceof Error ? error.message : String(error);
10590
+ try {
10591
+ await (0, node_fs_promises.rm)(workDir, {
10592
+ recursive: true,
10593
+ force: true
10594
+ });
10595
+ await (0, node_fs_promises.mkdir)(this.itemDir(source), { recursive: true });
10596
+ await (0, node_fs_promises.writeFile)(this.failurePath(source), JSON.stringify({
10597
+ at: this.deps.now(),
10598
+ attempts,
10599
+ reason
10600
+ }), "utf8");
10601
+ } catch (writeError) {
10602
+ logger.warn("trickplay failure could not be recorded", {
10603
+ tags,
10604
+ meta: { error: writeError instanceof Error ? writeError.message : String(writeError) }
10605
+ });
10606
+ }
10607
+ logger.warn("trickplay failed", {
10608
+ tags,
10609
+ meta: {
10610
+ reason,
10611
+ attempts,
10612
+ retry: attempts < 3
10613
+ }
10614
+ });
10615
+ }
10616
+ }
10617
+ /** A changed file leaves its old fingerprint behind: drop every other fingerprint of the item. */
10618
+ async pruneOthers(source) {
10619
+ const keep = fingerprintOf(source);
10620
+ for (const name of await (0, node_fs_promises.readdir)(this.itemDir(source))) if (name !== keep && name !== `${keep}.failed.json`) await (0, node_fs_promises.rm)((0, node_path.join)(this.itemDir(source), name), {
10621
+ recursive: true,
10622
+ force: true
10623
+ });
10624
+ }
10625
+ /** The absolute path of a ready file of `source`'s current fingerprint, or `null` when it is not there. */
10626
+ async fileFor(source, name) {
10627
+ if (!TRICKPLAY_FILE_NAME.test(name)) return null;
10628
+ const path = (0, node_path.join)(this.readyDir(source), name);
10629
+ try {
10630
+ return (await (0, node_fs_promises.stat)(path)).isFile() ? path : null;
10631
+ } catch {
10632
+ return null;
10633
+ }
10634
+ }
10635
+ };
10636
+ //#endregion
10637
+ //#region src/trickplay-plane.ts
10638
+ function reject(res, status, extra) {
10639
+ res.writeHead(status, {
10640
+ "Content-Length": 0,
10641
+ ...extra
10642
+ });
10643
+ res.end();
10644
+ }
10645
+ /** The `trickplay` plane: `GET|HEAD /<itemId>/index.vtt` and `/<itemId>/sprite-<n>.jpg`. */
10646
+ function createTrickplayPlaneHandler(deps) {
10647
+ return async (req, res) => {
10648
+ const method = req.method ?? "GET";
10649
+ if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10650
+ const segments = ((req.url ?? "/").split("?")[0] ?? "/").replace(/^\//, "").split("/");
10651
+ let itemId;
10652
+ let name;
10653
+ try {
10654
+ if (segments.length !== 2) return reject(res, 404);
10655
+ itemId = decodeURIComponent(segments[0] ?? "");
10656
+ name = decodeURIComponent(segments[1] ?? "");
10657
+ } catch {
10658
+ return reject(res, 404);
10659
+ }
10660
+ if (!isItemId(itemId)) {
10661
+ deps.logger.warn("trickplay request refused: not an item id", { meta: { reason: "bad-id" } });
10662
+ return reject(res, 404);
10663
+ }
10664
+ const tags = { itemId };
10665
+ if (!TRICKPLAY_FILE_NAME.test(name)) {
10666
+ deps.logger.info("trickplay request refused: not a trickplay file", {
10667
+ tags,
10668
+ meta: { reason: "bad-name" }
10669
+ });
10670
+ return reject(res, 404);
10671
+ }
10672
+ const source = await deps.source(itemId);
10673
+ if (source === null) {
10674
+ deps.logger.info("trickplay request refused: the item has no file", {
10675
+ tags,
10676
+ meta: { reason: "no-file" }
10677
+ });
10678
+ return reject(res, 404);
10679
+ }
10680
+ if (await resolveServable(source.path, await deps.roots()) === null) {
10681
+ deps.logger.warn("trickplay request refused: outside the library roots", {
10682
+ tags,
10683
+ meta: { reason: "outside-roots" }
10684
+ });
10685
+ return reject(res, 404);
10686
+ }
10687
+ const path = await deps.cache.fileFor(source, name);
10688
+ if (path === null) {
10689
+ deps.logger.info("trickplay request refused: not generated yet", {
10690
+ tags,
10691
+ meta: { reason: "not-ready" }
10692
+ });
10693
+ return reject(res, 404);
10694
+ }
10695
+ try {
10696
+ const body = await (0, node_fs_promises.readFile)(path);
10697
+ const isIndex = name === "index.vtt";
10698
+ res.writeHead(200, {
10699
+ "Content-Type": isIndex ? "text/vtt; charset=utf-8" : "image/jpeg",
10700
+ "Content-Length": body.length,
10701
+ "Cache-Control": isIndex ? "private, no-store" : "private, max-age=3600"
10702
+ });
10703
+ if (method === "HEAD") res.end();
10704
+ else res.end(body);
10705
+ deps.logger.debug("trickplay served", {
10706
+ tags,
10707
+ meta: { name }
10708
+ });
10709
+ } catch {
10710
+ deps.logger.warn("trickplay request refused: file vanished", {
10711
+ tags,
10712
+ meta: { reason: "gone" }
10713
+ });
10221
10714
  reject(res, 404);
10222
10715
  }
10223
10716
  };
@@ -11232,6 +11725,7 @@ function sortByShownTitle(rows, requested, serverDefault) {
11232
11725
  }
11233
11726
  var FILE_PLANE_PREFIX = "file";
11234
11727
  var SUBTITLE_PLANE_PREFIX = "subtitle";
11728
+ var TRICKPLAY_PLANE_PREFIX = "trickplay";
11235
11729
  var HUB_PLANE_BASE = "/addon/media-library";
11236
11730
  var SEARCH_DEFAULT_LIMIT = 50;
11237
11731
  var RECENT_DEFAULT_LIMIT = 20;
@@ -11246,6 +11740,10 @@ function playPathOf(itemId) {
11246
11740
  function subtitlePathOf(itemId, sidecarId) {
11247
11741
  return `${HUB_PLANE_BASE}/${SUBTITLE_PLANE_PREFIX}/${itemId}/${sidecarId}`;
11248
11742
  }
11743
+ /** The base of one item's trickplay files: `<base>/index.vtt`, `<base>/sprite-<n>.jpg`. */
11744
+ function trickplayBaseOf(itemId) {
11745
+ return `${HUB_PLANE_BASE}/${TRICKPLAY_PLANE_PREFIX}/${itemId}`;
11746
+ }
11249
11747
  function imagePathOf(itemId, which) {
11250
11748
  return `${HUB_PLANE_BASE}/img/${itemId}/${which}`;
11251
11749
  }
@@ -11267,13 +11765,15 @@ var LibraryStore = class {
11267
11765
  serverLanguage;
11268
11766
  now;
11269
11767
  listDir;
11768
+ trickplay;
11270
11769
  locks = /* @__PURE__ */ new Map();
11271
- constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir) {
11770
+ constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir, trickplay = null) {
11272
11771
  this.db = db;
11273
11772
  this.logger = logger;
11274
11773
  this.serverLanguage = serverLanguage;
11275
11774
  this.now = now;
11276
11775
  this.listDir = listDir;
11776
+ this.trickplay = trickplay;
11277
11777
  }
11278
11778
  async init() {
11279
11779
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -11447,9 +11947,26 @@ var LibraryStore = class {
11447
11947
  format: sidecar.format,
11448
11948
  label: sidecar.label,
11449
11949
  path: subtitlePathOf(row.id, sidecar.id)
11450
- }))
11950
+ })),
11951
+ trickplay: file === void 0 || this.trickplay === null ? null : await this.trickplay.request(trickplaySourceOf(row.id, file), trickplayBaseOf(row.id))
11451
11952
  };
11452
11953
  }
11954
+ /** The catalogued file of `itemId` as the trickplay cache sees it; `null` when it has none. */
11955
+ async trickplaySource(itemId) {
11956
+ const catalogued = await this.playableFile(itemId);
11957
+ return catalogued === null ? null : trickplaySourceOf(itemId, catalogued.row);
11958
+ }
11959
+ /** Every catalogued file, for the sweep after a scan. */
11960
+ async trickplaySources() {
11961
+ const items = await this.queryAllItems();
11962
+ const files = new Map(parseRows(FileRowSchema, await queryAll(this.db, FILES, "path", {}), this.invalid(FILES)).map((file) => [file.path, file]));
11963
+ const sources = [];
11964
+ for (const item of items) {
11965
+ const file = item.filePath === null ? void 0 : files.get(item.filePath);
11966
+ if (file !== void 0) sources.push(trickplaySourceOf(item.id, file));
11967
+ }
11968
+ return sources;
11969
+ }
11453
11970
  /** The subtitle files next to the video of `itemId`; empty when it has none or no file. */
11454
11971
  async subtitleSidecars(itemId) {
11455
11972
  const catalogued = await this.playableFile(itemId);
@@ -11751,6 +12268,18 @@ var LibraryStore = class {
11751
12268
  return entries;
11752
12269
  }
11753
12270
  };
12271
+ function trickplaySourceOf(itemId, file) {
12272
+ const video = file.streams.find((stream) => stream.kind === "video");
12273
+ return {
12274
+ itemId,
12275
+ path: file.path,
12276
+ sizeBytes: file.sizeBytes,
12277
+ mtimeMs: file.mtimeMs,
12278
+ durationMs: file.probeOk ? file.durationMs : null,
12279
+ width: video?.width ?? null,
12280
+ height: video?.height ?? null
12281
+ };
12282
+ }
11754
12283
  async function defaultListDir(dir) {
11755
12284
  try {
11756
12285
  return new Map((await (0, node_fs_promises.readdir)(dir)).map((name) => [name.toLowerCase(), name]));
@@ -15059,6 +15588,7 @@ var ScanController = class {
15059
15588
  deps;
15060
15589
  sources;
15061
15590
  logger;
15591
+ afterScan;
15062
15592
  running = false;
15063
15593
  last = {
15064
15594
  running: false,
@@ -15071,10 +15601,11 @@ var ScanController = class {
15071
15601
  skipped: 0
15072
15602
  };
15073
15603
  timer = null;
15074
- constructor(deps, sources, logger) {
15604
+ constructor(deps, sources, logger, afterScan = async () => {}) {
15075
15605
  this.deps = deps;
15076
15606
  this.sources = sources;
15077
15607
  this.logger = logger;
15608
+ this.afterScan = afterScan;
15078
15609
  }
15079
15610
  status() {
15080
15611
  return {
@@ -15104,6 +15635,11 @@ var ScanController = class {
15104
15635
  } finally {
15105
15636
  this.running = false;
15106
15637
  }
15638
+ try {
15639
+ await this.afterScan();
15640
+ } catch (error) {
15641
+ this.logger.warn("after-scan work failed", { meta: { error: String(error) } });
15642
+ }
15107
15643
  }
15108
15644
  /** (Re)arm the rescan timer; `0` minutes turns it off. */
15109
15645
  schedule(minutes) {
@@ -15125,8 +15661,11 @@ var ScanController = class {
15125
15661
  * place in every item is kept here. Bytes leave through two data-plane routes served by item id.
15126
15662
  */
15127
15663
  var IMG_CACHE_DIR = "img-cache";
15664
+ var TRICKPLAY_CACHE_DIR = "trickplay";
15128
15665
  var MediaLibraryAddon = class extends BaseAddon {
15129
15666
  scans = null;
15667
+ /** The trickplay switch, held in memory: the generator reads it off the settings path. */
15668
+ trickplayOn = true;
15130
15669
  constructor() {
15131
15670
  super({});
15132
15671
  }
@@ -15141,6 +15680,7 @@ var MediaLibraryAddon = class extends BaseAddon {
15141
15680
  }
15142
15681
  async onScopedSettingsChanged() {
15143
15682
  const settings = await this.readSettings();
15683
+ this.trickplayOn = settings.trickplay;
15144
15684
  this.scans?.schedule(settings.rescanMinutes);
15145
15685
  this.scans?.start("settings");
15146
15686
  }
@@ -15196,9 +15736,26 @@ var MediaLibraryAddon = class extends BaseAddon {
15196
15736
  const db = settingsStoreDb(ctx.api.settingsStore);
15197
15737
  const serverLanguage = new ServerLanguage(async () => (await ctx.api.system.info.query()).defaultLanguage, () => Date.now(), logger);
15198
15738
  await serverLanguage.refresh();
15199
- const store = new LibraryStore(db, logger, () => serverLanguage.current());
15200
- await store.init();
15201
15739
  const ffmpeg = await ctx.deps.ensureFfmpeg();
15740
+ const roots = async () => {
15741
+ const settings = await this.readSettings();
15742
+ return [
15743
+ ...resolveSources(settings).folderRoots,
15744
+ settings.seriesPathTo || settings.seriesPathFrom,
15745
+ settings.moviesPathTo || settings.moviesPathFrom
15746
+ ].filter((root) => root !== "");
15747
+ };
15748
+ this.trickplayOn = (await this.readSettings()).trickplay;
15749
+ const trickplay = new TrickplayService({
15750
+ cacheDir: (0, node_path.join)(ctx.dataDir, TRICKPLAY_CACHE_DIR),
15751
+ generate: createFfmpegTrickplayGenerator(ffmpeg),
15752
+ enabled: () => this.trickplayOn,
15753
+ inRoots: async (path) => await resolveServable(path, await roots()) !== null,
15754
+ logger,
15755
+ now: () => Date.now()
15756
+ });
15757
+ const store = new LibraryStore(db, logger, () => serverLanguage.current(), void 0, void 0, trickplay);
15758
+ await store.init();
15202
15759
  const scans = new ScanController({
15203
15760
  db,
15204
15761
  logger,
@@ -15240,7 +15797,10 @@ var MediaLibraryAddon = class extends BaseAddon {
15240
15797
  }),
15241
15798
  createAnilist: () => createAnilistProvider({ fetch: httpRemoteFetch }),
15242
15799
  now: () => Date.now()
15243
- }, async () => resolveSources(await this.readSettings()), logger);
15800
+ }, async () => resolveSources(await this.readSettings()), logger, async () => {
15801
+ if (!this.trickplayOn) return;
15802
+ for (const source of await store.trickplaySources()) await trickplay.request(source, trickplayBaseOf(source.itemId));
15803
+ });
15244
15804
  this.scans = scans;
15245
15805
  const plexImports = new PlexImportController(logger, () => Date.now());
15246
15806
  const startPlex = async (mode) => {
@@ -15268,14 +15828,6 @@ var MediaLibraryAddon = class extends BaseAddon {
15268
15828
  message: started ? `Plex ${mode === "run" ? "import" : "preview"} started: read the report with plexImportStatus` : "A Plex import is already running"
15269
15829
  };
15270
15830
  };
15271
- const roots = async () => {
15272
- const settings = await this.readSettings();
15273
- return [
15274
- ...resolveSources(settings).folderRoots,
15275
- settings.seriesPathTo || settings.seriesPathFrom,
15276
- settings.moviesPathTo || settings.moviesPathFrom
15277
- ].filter((root) => root !== "");
15278
- };
15279
15831
  await ctx.dataPlane?.serve({
15280
15832
  prefix: FILE_PLANE_PREFIX,
15281
15833
  access: "viewer",
@@ -15294,6 +15846,16 @@ var MediaLibraryAddon = class extends BaseAddon {
15294
15846
  logger
15295
15847
  })
15296
15848
  });
15849
+ await ctx.dataPlane?.serve({
15850
+ prefix: TRICKPLAY_PLANE_PREFIX,
15851
+ access: "viewer",
15852
+ handler: createTrickplayPlaneHandler({
15853
+ source: (itemId) => store.trickplaySource(itemId),
15854
+ cache: trickplay,
15855
+ roots,
15856
+ logger
15857
+ })
15858
+ });
15297
15859
  await ctx.dataPlane?.serve({
15298
15860
  prefix: "img",
15299
15861
  access: "viewer",
@@ -15314,7 +15876,10 @@ var MediaLibraryAddon = class extends BaseAddon {
15314
15876
  const settings = await this.readSettings();
15315
15877
  scans.schedule(settings.rescanMinutes);
15316
15878
  scans.start("boot");
15317
- const apps = { listApps: async () => [buildApp()] };
15879
+ const apps = { listApps: async () => {
15880
+ const pluginVersion = readPluginVersion((0, node_path.join)(__dirname, ".."));
15881
+ return pluginVersion === null ? [buildApp()] : [buildApp(), buildPluginApp(pluginVersion)];
15882
+ } };
15318
15883
  const addressRoles = { listAddressRoles: async () => buildAddressRoles() };
15319
15884
  logger.info("media-library initialized");
15320
15885
  return {