@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.
@@ -1,7 +1,7 @@
1
- import { mkdir, open, readFile, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
1
+ import { mkdir, open, readFile, readdir, realpath, rename, rm, 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";
@@ -2890,7 +2890,7 @@ function initializeContext(params) {
2890
2890
  external: params?.external ?? void 0
2891
2891
  };
2892
2892
  }
2893
- function process(schema, ctx, _params = {
2893
+ function process$1(schema, ctx, _params = {
2894
2894
  path: [],
2895
2895
  schemaPath: []
2896
2896
  }) {
@@ -2927,7 +2927,7 @@ function process(schema, ctx, _params = {
2927
2927
  const parent = schema._zod.parent;
2928
2928
  if (parent) {
2929
2929
  if (!result.ref) result.ref = parent;
2930
- process(parent, ctx, params);
2930
+ process$1(parent, ctx, params);
2931
2931
  ctx.seen.get(parent).isParent = true;
2932
2932
  }
2933
2933
  }
@@ -3147,7 +3147,7 @@ var createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
3147
3147
  ...params,
3148
3148
  processors
3149
3149
  });
3150
- process(schema, ctx);
3150
+ process$1(schema, ctx);
3151
3151
  extractDefs(ctx, schema);
3152
3152
  return finalize(ctx, schema);
3153
3153
  };
@@ -3159,7 +3159,7 @@ var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) =
3159
3159
  io,
3160
3160
  processors
3161
3161
  });
3162
- process(schema, ctx);
3162
+ process$1(schema, ctx);
3163
3163
  extractDefs(ctx, schema);
3164
3164
  return finalize(ctx, schema);
3165
3165
  };
@@ -3263,7 +3263,7 @@ var arrayProcessor = (schema, ctx, _json, params) => {
3263
3263
  if (typeof minimum === "number") json.minItems = minimum;
3264
3264
  if (typeof maximum === "number") json.maxItems = maximum;
3265
3265
  json.type = "array";
3266
- json.items = process(def.element, ctx, {
3266
+ json.items = process$1(def.element, ctx, {
3267
3267
  ...params,
3268
3268
  path: [...params.path, "items"]
3269
3269
  });
@@ -3274,7 +3274,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
3274
3274
  json.type = "object";
3275
3275
  json.properties = {};
3276
3276
  const shape = def.shape;
3277
- for (const key in shape) json.properties[key] = process(shape[key], ctx, {
3277
+ for (const key in shape) json.properties[key] = process$1(shape[key], ctx, {
3278
3278
  ...params,
3279
3279
  path: [
3280
3280
  ...params.path,
@@ -3292,7 +3292,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
3292
3292
  if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
3293
3293
  else if (!def.catchall) {
3294
3294
  if (ctx.io === "output") json.additionalProperties = false;
3295
- } else if (def.catchall) json.additionalProperties = process(def.catchall, ctx, {
3295
+ } else if (def.catchall) json.additionalProperties = process$1(def.catchall, ctx, {
3296
3296
  ...params,
3297
3297
  path: [...params.path, "additionalProperties"]
3298
3298
  });
@@ -3300,7 +3300,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
3300
3300
  var unionProcessor = (schema, ctx, json, params) => {
3301
3301
  const def = schema._zod.def;
3302
3302
  const isExclusive = def.inclusive === false;
3303
- const options = def.options.map((x, i) => process(x, ctx, {
3303
+ const options = def.options.map((x, i) => process$1(x, ctx, {
3304
3304
  ...params,
3305
3305
  path: [
3306
3306
  ...params.path,
@@ -3313,7 +3313,7 @@ var unionProcessor = (schema, ctx, json, params) => {
3313
3313
  };
3314
3314
  var intersectionProcessor = (schema, ctx, json, params) => {
3315
3315
  const def = schema._zod.def;
3316
- const a = process(def.left, ctx, {
3316
+ const a = process$1(def.left, ctx, {
3317
3317
  ...params,
3318
3318
  path: [
3319
3319
  ...params.path,
@@ -3321,7 +3321,7 @@ var intersectionProcessor = (schema, ctx, json, params) => {
3321
3321
  0
3322
3322
  ]
3323
3323
  });
3324
- const b = process(def.right, ctx, {
3324
+ const b = process$1(def.right, ctx, {
3325
3325
  ...params,
3326
3326
  path: [
3327
3327
  ...params.path,
@@ -3339,7 +3339,7 @@ var recordProcessor = (schema, ctx, _json, params) => {
3339
3339
  const keyType = def.keyType;
3340
3340
  const patterns = keyType._zod.bag?.patterns;
3341
3341
  if (def.mode === "loose" && patterns && patterns.size > 0) {
3342
- const valueSchema = process(def.valueType, ctx, {
3342
+ const valueSchema = process$1(def.valueType, ctx, {
3343
3343
  ...params,
3344
3344
  path: [
3345
3345
  ...params.path,
@@ -3350,11 +3350,11 @@ var recordProcessor = (schema, ctx, _json, params) => {
3350
3350
  json.patternProperties = {};
3351
3351
  for (const pattern of patterns) json.patternProperties[pattern.source] = valueSchema;
3352
3352
  } else {
3353
- if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process(def.keyType, ctx, {
3353
+ if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process$1(def.keyType, ctx, {
3354
3354
  ...params,
3355
3355
  path: [...params.path, "propertyNames"]
3356
3356
  });
3357
- json.additionalProperties = process(def.valueType, ctx, {
3357
+ json.additionalProperties = process$1(def.valueType, ctx, {
3358
3358
  ...params,
3359
3359
  path: [...params.path, "additionalProperties"]
3360
3360
  });
@@ -3367,7 +3367,7 @@ var recordProcessor = (schema, ctx, _json, params) => {
3367
3367
  };
3368
3368
  var nullableProcessor = (schema, ctx, json, params) => {
3369
3369
  const def = schema._zod.def;
3370
- const inner = process(def.innerType, ctx, params);
3370
+ const inner = process$1(def.innerType, ctx, params);
3371
3371
  const seen = ctx.seen.get(schema);
3372
3372
  if (ctx.target === "openapi-3.0") {
3373
3373
  seen.ref = def.innerType;
@@ -3376,27 +3376,27 @@ var nullableProcessor = (schema, ctx, json, params) => {
3376
3376
  };
3377
3377
  var nonoptionalProcessor = (schema, ctx, _json, params) => {
3378
3378
  const def = schema._zod.def;
3379
- process(def.innerType, ctx, params);
3379
+ process$1(def.innerType, ctx, params);
3380
3380
  const seen = ctx.seen.get(schema);
3381
3381
  seen.ref = def.innerType;
3382
3382
  };
3383
3383
  var defaultProcessor = (schema, ctx, json, params) => {
3384
3384
  const def = schema._zod.def;
3385
- process(def.innerType, ctx, params);
3385
+ process$1(def.innerType, ctx, params);
3386
3386
  const seen = ctx.seen.get(schema);
3387
3387
  seen.ref = def.innerType;
3388
3388
  json.default = JSON.parse(JSON.stringify(def.defaultValue));
3389
3389
  };
3390
3390
  var prefaultProcessor = (schema, ctx, json, params) => {
3391
3391
  const def = schema._zod.def;
3392
- process(def.innerType, ctx, params);
3392
+ process$1(def.innerType, ctx, params);
3393
3393
  const seen = ctx.seen.get(schema);
3394
3394
  seen.ref = def.innerType;
3395
3395
  if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
3396
3396
  };
3397
3397
  var catchProcessor = (schema, ctx, json, params) => {
3398
3398
  const def = schema._zod.def;
3399
- process(def.innerType, ctx, params);
3399
+ process$1(def.innerType, ctx, params);
3400
3400
  const seen = ctx.seen.get(schema);
3401
3401
  seen.ref = def.innerType;
3402
3402
  let catchValue;
@@ -3411,20 +3411,20 @@ var pipeProcessor = (schema, ctx, _json, params) => {
3411
3411
  const def = schema._zod.def;
3412
3412
  const inIsTransform = def.in._zod.traits.has("$ZodTransform");
3413
3413
  const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
3414
- process(innerType, ctx, params);
3414
+ process$1(innerType, ctx, params);
3415
3415
  const seen = ctx.seen.get(schema);
3416
3416
  seen.ref = innerType;
3417
3417
  };
3418
3418
  var readonlyProcessor = (schema, ctx, json, params) => {
3419
3419
  const def = schema._zod.def;
3420
- process(def.innerType, ctx, params);
3420
+ process$1(def.innerType, ctx, params);
3421
3421
  const seen = ctx.seen.get(schema);
3422
3422
  seen.ref = def.innerType;
3423
3423
  json.readOnly = true;
3424
3424
  };
3425
3425
  var optionalProcessor = (schema, ctx, _json, params) => {
3426
3426
  const def = schema._zod.def;
3427
- process(def.innerType, ctx, params);
3427
+ process$1(def.innerType, ctx, params);
3428
3428
  const seen = ctx.seen.get(schema);
3429
3429
  seen.ref = def.innerType;
3430
3430
  };
@@ -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
  /**
@@ -8854,6 +8865,22 @@ var ExternalSubtitleSchema = /* @__PURE__ */ object({
8854
8865
  label: /* @__PURE__ */ string(),
8855
8866
  path: /* @__PURE__ */ string()
8856
8867
  });
8868
+ /**
8869
+ * Scrub thumbnails of the file. `path` is the relative hub path of the WebVTT index (cues point at
8870
+ * `sprite-N.jpg#xywh=x,y,w,h` beside it), set only when `status` is `ready`. `pending`: being generated in the
8871
+ * background, ask again later; `failed`: ffmpeg could not; `skipped`: the file has no duration or is too short;
8872
+ * `disabled`: the installation turned generation off.
8873
+ */
8874
+ var MediaTrickplaySchema = /* @__PURE__ */ object({
8875
+ status: /* @__PURE__ */ _enum([
8876
+ "ready",
8877
+ "pending",
8878
+ "failed",
8879
+ "skipped",
8880
+ "disabled"
8881
+ ]),
8882
+ path: /* @__PURE__ */ string().nullable()
8883
+ });
8857
8884
  var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8858
8885
  overview: /* @__PURE__ */ string().nullable(),
8859
8886
  ids: /* @__PURE__ */ object({
@@ -8868,7 +8895,9 @@ var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8868
8895
  /** The file's chapters in order; empty when it has none or it is not probed yet. */
8869
8896
  chapters: /* @__PURE__ */ array(MediaChapterSchema).readonly(),
8870
8897
  /** Sidecar subtitle files found next to the video; empty when none. */
8871
- externalSubtitles: /* @__PURE__ */ array(ExternalSubtitleSchema).readonly()
8898
+ externalSubtitles: /* @__PURE__ */ array(ExternalSubtitleSchema).readonly(),
8899
+ /** Scrub thumbnails of the file; `null` when the item has no file. */
8900
+ trickplay: /* @__PURE__ */ MediaTrickplaySchema.nullable()
8872
8901
  });
8873
8902
  /**
8874
8903
  * A person of an item's credits. `photoPath` is an image-plane handle relative to the hub origin
@@ -9074,6 +9103,23 @@ function buildAddressRoles() {
9074
9103
  }];
9075
9104
  }
9076
9105
  //#endregion
9106
+ //#region src/rn-app/plugin-version.ts
9107
+ /** Where the build writes the plugin, relative to the package root; these paths are the `rn-plugin` entry's assets. */
9108
+ var PLUGIN_NATIVE_ASSET = "dist/rn-app/index.native.js";
9109
+ var PLUGIN_WEB_ASSET = "dist/rn-app/index.web.js";
9110
+ /**
9111
+ * The cache key of the built plugin: the package version plus a hash of both bundles, so a rebuild
9112
+ * of the same package version still reaches a device that cached the old one. `null` when the
9113
+ * bundles are not built (a dev checkout): the plugin app is then not declared.
9114
+ */
9115
+ function readPluginVersion(packageDir) {
9116
+ const native = join(packageDir, PLUGIN_NATIVE_ASSET);
9117
+ const web = join(packageDir, PLUGIN_WEB_ASSET);
9118
+ if (!existsSync(native) || !existsSync(web)) return null;
9119
+ const pkg = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8"));
9120
+ 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)}`;
9121
+ }
9122
+ //#endregion
9077
9123
  //#region src/app-source.ts
9078
9124
  var APP_ID = "media";
9079
9125
  function buildApp() {
@@ -9098,6 +9144,38 @@ function buildApp() {
9098
9144
  settings: null
9099
9145
  };
9100
9146
  }
9147
+ var PLUGIN_APP_ID = "media-plugin";
9148
+ /** The host API the plugin bundle is built against (`hostApi` of its `index.tsx`). */
9149
+ var PLUGIN_HOST_API = 1;
9150
+ /**
9151
+ * The React Native plugin spike (planning#908), declared next to the native Media app and
9152
+ * admin-only until phase 2 replaces it. `version` is the build's cache key (`readPluginVersion`).
9153
+ */
9154
+ function buildPluginApp(version) {
9155
+ return {
9156
+ id: PLUGIN_APP_ID,
9157
+ label: {
9158
+ key: "media-library:apps.mediaPlugin",
9159
+ fallback: "Media (plugin)"
9160
+ },
9161
+ icon: {
9162
+ kind: "image",
9163
+ asset: "assets/app-icon.svg"
9164
+ },
9165
+ entry: {
9166
+ kind: "rn-plugin",
9167
+ native: PLUGIN_NATIVE_ASSET,
9168
+ web: PLUGIN_WEB_ASSET,
9169
+ hostApi: PLUGIN_HOST_API,
9170
+ version
9171
+ },
9172
+ reach: { kind: "hub" },
9173
+ adminOnly: true,
9174
+ nav: [],
9175
+ takesSharedSearch: false,
9176
+ settings: null
9177
+ };
9178
+ }
9101
9179
  //#endregion
9102
9180
  //#region src/arr-client.ts
9103
9181
  var ImageSchema$1 = object({
@@ -9384,6 +9462,8 @@ var MediaLibrarySettingsSchema = object({
9384
9462
  /** Plain folders walked for files the arr apps do not know, one absolute path per line. */
9385
9463
  folderRoots: string().default(""),
9386
9464
  rescanMinutes: number().int().min(0).default(60),
9465
+ /** Scrub thumbnails, generated in the background with ffmpeg and cached under the addon's data dir. */
9466
+ trickplay: boolean().default(true),
9387
9467
  /** The metadata chain, one row per step in the order they answer; the first answer to a field wins (D1125). */
9388
9468
  metadataProviders: array(MetadataProviderRowSchema).default(defaultProviderRows),
9389
9469
  /** The Plex import (a one-shot, re-runnable action): the server, a token, and how paths and users line up. */
@@ -9502,22 +9582,33 @@ var MEDIA_LIBRARY_CLUSTER_SCHEMA = { sections: [
9502
9582
  id: "folders",
9503
9583
  title: "Folders",
9504
9584
  titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.title",
9505
- fields: [{
9506
- type: "textarea",
9507
- key: "folderRoots",
9508
- label: "Folders to walk",
9509
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.label",
9510
- description: "One absolute path per line. Files the arr apps do not know are added from here.",
9511
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.description"
9512
- }, {
9513
- type: "number",
9514
- key: "rescanMinutes",
9515
- label: "Rescan every (minutes)",
9516
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.label",
9517
- description: "0 scans only when asked.",
9518
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
9519
- min: 0
9520
- }]
9585
+ fields: [
9586
+ {
9587
+ type: "textarea",
9588
+ key: "folderRoots",
9589
+ label: "Folders to walk",
9590
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.label",
9591
+ description: "One absolute path per line. Files the arr apps do not know are added from here.",
9592
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.description"
9593
+ },
9594
+ {
9595
+ type: "number",
9596
+ key: "rescanMinutes",
9597
+ label: "Rescan every (minutes)",
9598
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.label",
9599
+ description: "0 scans only when asked.",
9600
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
9601
+ min: 0
9602
+ },
9603
+ {
9604
+ type: "boolean",
9605
+ key: "trickplay",
9606
+ label: "Scrub thumbnails",
9607
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.label",
9608
+ description: "Generate preview pictures for the seek bar in the background, one ffmpeg at a time at low priority.",
9609
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.description"
9610
+ }
9611
+ ]
9521
9612
  },
9522
9613
  {
9523
9614
  id: "metadata",
@@ -9761,6 +9852,34 @@ function fillMissingKeys(rows, stored) {
9761
9852
  });
9762
9853
  }
9763
9854
  //#endregion
9855
+ //#region src/servable.ts
9856
+ /**
9857
+ * A file is servable only when its REAL path (symlinks resolved) is inside a configured root.
9858
+ * The path itself comes from the catalogue by item id; this is the second lock on the same door,
9859
+ * so a catalogue row that names `/etc/passwd`, or a symlink that points out of the library, serves nothing.
9860
+ */
9861
+ async function resolveServable(path, roots) {
9862
+ if (!isAbsolute(path) || path.includes("\0")) return null;
9863
+ let real;
9864
+ try {
9865
+ real = await realpath(path);
9866
+ } catch {
9867
+ return null;
9868
+ }
9869
+ for (const root of roots) {
9870
+ if (root === "") continue;
9871
+ let realRoot;
9872
+ try {
9873
+ realRoot = await realpath(root);
9874
+ } catch {
9875
+ continue;
9876
+ }
9877
+ const prefix = realRoot.endsWith(sep) ? realRoot : `${realRoot}${sep}`;
9878
+ if (real.startsWith(prefix)) return real;
9879
+ }
9880
+ return null;
9881
+ }
9882
+ //#endregion
9764
9883
  //#region src/naming.ts
9765
9884
  /** Case- and accent-insensitive form of a title, for search and ordering. */
9766
9885
  function foldTitle(title) {
@@ -9818,34 +9937,6 @@ function guessFromFilename(fileName, parentDir) {
9818
9937
  };
9819
9938
  }
9820
9939
  //#endregion
9821
- //#region src/servable.ts
9822
- /**
9823
- * A file is servable only when its REAL path (symlinks resolved) is inside a configured root.
9824
- * The path itself comes from the catalogue by item id; this is the second lock on the same door,
9825
- * so a catalogue row that names `/etc/passwd`, or a symlink that points out of the library, serves nothing.
9826
- */
9827
- async function resolveServable(path, roots) {
9828
- if (!isAbsolute(path) || path.includes("\0")) return null;
9829
- let real;
9830
- try {
9831
- real = await realpath(path);
9832
- } catch {
9833
- return null;
9834
- }
9835
- for (const root of roots) {
9836
- if (root === "") continue;
9837
- let realRoot;
9838
- try {
9839
- realRoot = await realpath(root);
9840
- } catch {
9841
- continue;
9842
- }
9843
- const prefix = realRoot.endsWith(sep) ? realRoot : `${realRoot}${sep}`;
9844
- if (real.startsWith(prefix)) return real;
9845
- }
9846
- return null;
9847
- }
9848
- //#endregion
9849
9940
  //#region src/file-plane.ts
9850
9941
  /**
9851
9942
  * Parse one `Range: bytes=…` header against a file of `size` bytes. A header this server does not
@@ -9931,7 +10022,7 @@ function pump(path, start, end, res, stallMs) {
9931
10022
  res.on("close", () => settle(sent > 0 && res.writableFinished ? "finished" : "client-closed"));
9932
10023
  });
9933
10024
  }
9934
- function reject$1(res, status, extra) {
10025
+ function reject$2(res, status, extra) {
9935
10026
  res.writeHead(status, {
9936
10027
  "Content-Length": 0,
9937
10028
  ...extra
@@ -9943,18 +10034,18 @@ function createFilePlaneHandler(deps) {
9943
10034
  const stallMs = deps.stallMs ?? 3e4;
9944
10035
  return async (req, res) => {
9945
10036
  const method = req.method ?? "GET";
9946
- if (method !== "GET" && method !== "HEAD") return reject$1(res, 405, { Allow: "GET, HEAD" });
10037
+ if (method !== "GET" && method !== "HEAD") return reject$2(res, 405, { Allow: "GET, HEAD" });
9947
10038
  const raw = (req.url ?? "/").split("?")[0] ?? "/";
9948
10039
  let itemId;
9949
10040
  try {
9950
10041
  itemId = decodeURIComponent(raw.replace(/^\//, ""));
9951
10042
  } catch {
9952
10043
  deps.logger.warn("file request refused: bad escape", { meta: { reason: "bad-id" } });
9953
- return reject$1(res, 404);
10044
+ return reject$2(res, 404);
9954
10045
  }
9955
10046
  if (!isItemId(itemId)) {
9956
10047
  deps.logger.warn("file request refused: not an item id", { meta: { reason: "bad-id" } });
9957
- return reject$1(res, 404);
10048
+ return reject$2(res, 404);
9958
10049
  }
9959
10050
  const tags = { itemId };
9960
10051
  const catalogued = await deps.lookup(itemId);
@@ -9963,7 +10054,7 @@ function createFilePlaneHandler(deps) {
9963
10054
  tags,
9964
10055
  meta: { reason: "not-catalogued" }
9965
10056
  });
9966
- return reject$1(res, 404);
10057
+ return reject$2(res, 404);
9967
10058
  }
9968
10059
  const path = await resolveServable(catalogued, await deps.roots());
9969
10060
  if (path === null) {
@@ -9971,7 +10062,7 @@ function createFilePlaneHandler(deps) {
9971
10062
  tags,
9972
10063
  meta: { reason: "outside-roots" }
9973
10064
  });
9974
- return reject$1(res, 404);
10065
+ return reject$2(res, 404);
9975
10066
  }
9976
10067
  let size;
9977
10068
  try {
@@ -9981,7 +10072,7 @@ function createFilePlaneHandler(deps) {
9981
10072
  tags,
9982
10073
  meta: { reason: "gone" }
9983
10074
  });
9984
- return reject$1(res, 404);
10075
+ return reject$2(res, 404);
9985
10076
  }
9986
10077
  const range = parseRange(headerOf(req.headers.range), size);
9987
10078
  if (range.kind === "unsatisfiable") {
@@ -9992,7 +10083,7 @@ function createFilePlaneHandler(deps) {
9992
10083
  size
9993
10084
  }
9994
10085
  });
9995
- return reject$1(res, 416, { "Content-Range": `bytes */${size}` });
10086
+ return reject$2(res, 416, { "Content-Range": `bytes */${size}` });
9996
10087
  }
9997
10088
  const start = range.kind === "range" ? range.start : 0;
9998
10089
  const end = range.kind === "range" ? range.end : size - 1;
@@ -10125,7 +10216,7 @@ function toWebVtt(source, format, offsetMs = 0) {
10125
10216
  }
10126
10217
  return out.join("\n");
10127
10218
  }
10128
- function reject(res, status, extra) {
10219
+ function reject$1(res, status, extra) {
10129
10220
  res.writeHead(status, {
10130
10221
  "Content-Length": 0,
10131
10222
  ...extra
@@ -10144,21 +10235,21 @@ function parseOffsetMs(query) {
10144
10235
  function createSubtitlePlaneHandler(deps) {
10145
10236
  return async (req, res) => {
10146
10237
  const method = req.method ?? "GET";
10147
- if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10238
+ if (method !== "GET" && method !== "HEAD") return reject$1(res, 405, { Allow: "GET, HEAD" });
10148
10239
  const [rawPath = "/", query = ""] = (req.url ?? "/").split("?");
10149
10240
  const segments = rawPath.replace(/^\//, "").split("/");
10150
10241
  let itemId;
10151
10242
  let sidecar;
10152
10243
  try {
10153
- if (segments.length !== 2) return reject(res, 404);
10244
+ if (segments.length !== 2) return reject$1(res, 404);
10154
10245
  itemId = decodeURIComponent(segments[0] ?? "");
10155
10246
  sidecar = decodeURIComponent(segments[1] ?? "");
10156
10247
  } catch {
10157
- return reject(res, 404);
10248
+ return reject$1(res, 404);
10158
10249
  }
10159
10250
  if (!isItemId(itemId)) {
10160
10251
  deps.logger.warn("subtitle request refused: not an item id", { meta: { reason: "bad-id" } });
10161
- return reject(res, 404);
10252
+ return reject$1(res, 404);
10162
10253
  }
10163
10254
  const tags = { itemId };
10164
10255
  const offsetMs = parseOffsetMs(query);
@@ -10167,7 +10258,7 @@ function createSubtitlePlaneHandler(deps) {
10167
10258
  tags,
10168
10259
  meta: { reason: "bad-offset" }
10169
10260
  });
10170
- return reject(res, 400);
10261
+ return reject$1(res, 400);
10171
10262
  }
10172
10263
  const known = (await deps.sidecars(itemId))?.find((candidate) => candidate.id === sidecar);
10173
10264
  if (known === void 0) {
@@ -10175,7 +10266,7 @@ function createSubtitlePlaneHandler(deps) {
10175
10266
  tags,
10176
10267
  meta: { reason: "not-a-sidecar" }
10177
10268
  });
10178
- return reject(res, 404);
10269
+ return reject$1(res, 404);
10179
10270
  }
10180
10271
  const path = await resolveServable(known.filePath, await deps.roots());
10181
10272
  if (path === null) {
@@ -10183,7 +10274,7 @@ function createSubtitlePlaneHandler(deps) {
10183
10274
  tags,
10184
10275
  meta: { reason: "outside-roots" }
10185
10276
  });
10186
- return reject(res, 404);
10277
+ return reject$1(res, 404);
10187
10278
  }
10188
10279
  try {
10189
10280
  if ((await stat(path)).size > 5242880) {
@@ -10191,7 +10282,7 @@ function createSubtitlePlaneHandler(deps) {
10191
10282
  tags,
10192
10283
  meta: { reason: "too-large" }
10193
10284
  });
10194
- return reject(res, 404);
10285
+ return reject$1(res, 404);
10195
10286
  }
10196
10287
  const body = Buffer.from(toWebVtt(await readFile(path, "utf8"), known.format, offsetMs), "utf8");
10197
10288
  res.writeHead(200, {
@@ -10214,6 +10305,408 @@ function createSubtitlePlaneHandler(deps) {
10214
10305
  tags,
10215
10306
  meta: { reason: "gone" }
10216
10307
  });
10308
+ reject$1(res, 404);
10309
+ }
10310
+ };
10311
+ }
10312
+ var TILES_PER_SHEET = 100;
10313
+ var GENERATE_TIMEOUT_MS = 3600 * 1e3;
10314
+ var INDEX_NAME = "index.vtt";
10315
+ /** The names a client may ask for inside one item's trickplay folder. */
10316
+ var TRICKPLAY_FILE_NAME = /^(?:index\.vtt|sprite-\d{1,4}\.jpg)$/;
10317
+ var FailureSchema = object({
10318
+ at: number(),
10319
+ attempts: number().int(),
10320
+ reason: string()
10321
+ });
10322
+ /** The height of one tile for a picture of this shape; even, as the encoder wants. */
10323
+ function tileHeightOf(width, height) {
10324
+ return Math.max(2, Math.round(320 * height / width / 2) * 2);
10325
+ }
10326
+ /** The ffmpeg arguments: one frame per interval, scaled, tiled into sheets of the grid, one JPEG per sheet. */
10327
+ function trickplayArgs(job) {
10328
+ return [
10329
+ "-hide_banner",
10330
+ "-nostdin",
10331
+ "-loglevel",
10332
+ "error",
10333
+ "-threads",
10334
+ "1",
10335
+ "-i",
10336
+ `file:${job.inputPath}`,
10337
+ "-an",
10338
+ "-sn",
10339
+ "-vf",
10340
+ `fps=1/10,scale=320:${job.tileHeight},tile=10x10`,
10341
+ "-q:v",
10342
+ "6",
10343
+ "-start_number",
10344
+ "0",
10345
+ join(job.outDir, "sprite-%d.jpg")
10346
+ ];
10347
+ }
10348
+ /** ffmpeg at the lowest priority (`nice`, where there is one), so a scrub image never takes a stream's CPU. */
10349
+ function createFfmpegTrickplayGenerator(binaryPath) {
10350
+ return (job) => new Promise((done, reject) => {
10351
+ const args = trickplayArgs(job);
10352
+ const [command, argv] = process.platform === "win32" ? [binaryPath, args] : ["nice", [
10353
+ "-n",
10354
+ "19",
10355
+ binaryPath,
10356
+ ...args
10357
+ ]];
10358
+ execFile(command, argv, {
10359
+ timeout: GENERATE_TIMEOUT_MS,
10360
+ maxBuffer: 1024 * 1024,
10361
+ encoding: "utf8"
10362
+ }, (error, _stdout, stderr) => {
10363
+ if (error === null) done();
10364
+ else reject(new Error(error.killed === true ? "ffmpeg timed out" : stderr.slice(0, 300) || error.message));
10365
+ });
10366
+ });
10367
+ }
10368
+ function timestamp(seconds) {
10369
+ const totalMs = Math.round(seconds * 1e3);
10370
+ const pad = (value, width) => String(value).padStart(width, "0");
10371
+ 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)}`;
10372
+ }
10373
+ /** The WebVTT index: one cue per interval, each pointing at its tile as `sprite-N.jpg#xywh=x,y,w,h`. */
10374
+ function buildTrickplayVtt(durationSec, tileHeight) {
10375
+ const frames = Math.ceil(durationSec / 10);
10376
+ const lines = ["WEBVTT", ""];
10377
+ for (let index = 0; index < frames; index += 1) {
10378
+ const slot = index % TILES_PER_SHEET;
10379
+ const x = slot % 10 * 320;
10380
+ const y = Math.floor(slot / 10) * tileHeight;
10381
+ const start = index * 10;
10382
+ const end = Math.min((index + 1) * 10, durationSec);
10383
+ lines.push(`${timestamp(start)} --> ${timestamp(end)}`, `sprite-${Math.floor(index / TILES_PER_SHEET)}.jpg#xywh=${x},${y},320,${tileHeight}`, "");
10384
+ }
10385
+ return lines.join("\n");
10386
+ }
10387
+ function fingerprintOf(source) {
10388
+ return `${source.sizeBytes}-${source.mtimeMs}`;
10389
+ }
10390
+ /** An item id is `source:kind:key`; the colons become underscores so the folder name is portable. */
10391
+ function folderOf(itemId) {
10392
+ return itemId.replaceAll(":", "_");
10393
+ }
10394
+ /**
10395
+ * The trickplay cache: sprite sheets and a WebVTT index per item, under the addon's data dir, keyed by the
10396
+ * file's size and mtime (a changed file generates anew). One ffmpeg at a time, in the background.
10397
+ */
10398
+ var TrickplayService = class {
10399
+ deps;
10400
+ queue = [];
10401
+ queued = /* @__PURE__ */ new Set();
10402
+ running = false;
10403
+ /** Files found outside the library roots: remembered (until restart) so they are not queued again. */
10404
+ outsideRoots = /* @__PURE__ */ new Set();
10405
+ idle = Promise.resolve();
10406
+ constructor(deps) {
10407
+ this.deps = deps;
10408
+ }
10409
+ keyOf(source) {
10410
+ return `${source.itemId}\u0000${fingerprintOf(source)}`;
10411
+ }
10412
+ itemDir(source) {
10413
+ return join(this.deps.cacheDir, folderOf(source.itemId));
10414
+ }
10415
+ readyDir(source) {
10416
+ return join(this.itemDir(source), fingerprintOf(source));
10417
+ }
10418
+ failurePath(source) {
10419
+ return join(this.itemDir(source), `${fingerprintOf(source)}.failed.json`);
10420
+ }
10421
+ /** The reason this file cannot have trickplay, or `null` when it can. */
10422
+ skipReason(source) {
10423
+ if (source.durationMs === null || source.durationMs <= 0) return "no-duration";
10424
+ if (source.durationMs / 1e3 < 30) return "too-short";
10425
+ if (source.width === null || source.height === null || source.width <= 0 || source.height <= 0) return "no-video-size";
10426
+ return null;
10427
+ }
10428
+ async readFailure(source) {
10429
+ try {
10430
+ return FailureSchema.parse(JSON.parse(await readFile(this.failurePath(source), "utf8")));
10431
+ } catch {
10432
+ return null;
10433
+ }
10434
+ }
10435
+ async isReady(source) {
10436
+ try {
10437
+ return (await stat(join(this.readyDir(source), INDEX_NAME))).isFile();
10438
+ } catch {
10439
+ return false;
10440
+ }
10441
+ }
10442
+ /**
10443
+ * What a client may be told about `source`, and (when nothing is ready) a request for the work: a run
10444
+ * is queued unless one is queued already, it failed for good, or it failed too recently to try again.
10445
+ */
10446
+ async request(source, basePath) {
10447
+ const tags = { itemId: source.itemId };
10448
+ if (!this.deps.enabled()) return {
10449
+ status: "disabled",
10450
+ path: null
10451
+ };
10452
+ if (await this.isReady(source)) return {
10453
+ status: "ready",
10454
+ path: `${basePath}/${INDEX_NAME}`
10455
+ };
10456
+ if (this.outsideRoots.has(this.keyOf(source))) return {
10457
+ status: "skipped",
10458
+ path: null
10459
+ };
10460
+ const skip = this.skipReason(source);
10461
+ if (skip !== null) {
10462
+ this.deps.logger.debug("trickplay not generated", {
10463
+ tags,
10464
+ meta: { reason: skip }
10465
+ });
10466
+ return {
10467
+ status: "skipped",
10468
+ path: null
10469
+ };
10470
+ }
10471
+ const failure = await this.readFailure(source);
10472
+ if (failure !== null) {
10473
+ if (failure.attempts >= 3) return {
10474
+ status: "failed",
10475
+ path: null
10476
+ };
10477
+ if (this.deps.now() - failure.at < 216e5) return {
10478
+ status: "failed",
10479
+ path: null
10480
+ };
10481
+ }
10482
+ this.enqueue(source);
10483
+ return {
10484
+ status: "pending",
10485
+ path: null
10486
+ };
10487
+ }
10488
+ /** Queue one file; a second request for the same file while it waits or runs changes nothing. */
10489
+ enqueue(source) {
10490
+ const key = `${source.itemId}\u0000${fingerprintOf(source)}`;
10491
+ if (this.queued.has(key)) return;
10492
+ this.queued.add(key);
10493
+ this.queue.push(source);
10494
+ this.deps.logger.debug("trickplay queued", {
10495
+ tags: { itemId: source.itemId },
10496
+ meta: { waiting: this.queue.length }
10497
+ });
10498
+ if (!this.running) {
10499
+ this.running = true;
10500
+ this.idle = this.drain();
10501
+ }
10502
+ }
10503
+ /** Resolves when the queue is empty and nothing runs. */
10504
+ settled() {
10505
+ return this.idle;
10506
+ }
10507
+ async drain() {
10508
+ try {
10509
+ for (let next = this.queue.shift(); next !== void 0; next = this.queue.shift()) try {
10510
+ await this.generateOne(next);
10511
+ } catch (error) {
10512
+ this.deps.logger.warn("trickplay run aborted", {
10513
+ tags: { itemId: next.itemId },
10514
+ meta: { reason: error instanceof Error ? error.message : String(error) }
10515
+ });
10516
+ } finally {
10517
+ this.queued.delete(`${next.itemId}\u0000${fingerprintOf(next)}`);
10518
+ }
10519
+ } finally {
10520
+ this.running = false;
10521
+ }
10522
+ }
10523
+ async generateOne(source) {
10524
+ const tags = { itemId: source.itemId };
10525
+ const { logger } = this.deps;
10526
+ if (!this.deps.enabled()) {
10527
+ logger.info("trickplay skipped", {
10528
+ tags,
10529
+ meta: { reason: "disabled" }
10530
+ });
10531
+ return;
10532
+ }
10533
+ if (await this.isReady(source)) return;
10534
+ const skip = this.skipReason(source);
10535
+ if (skip !== null || source.width === null || source.height === null || source.durationMs === null) {
10536
+ logger.info("trickplay skipped", {
10537
+ tags,
10538
+ meta: { reason: skip ?? "no-video-size" }
10539
+ });
10540
+ return;
10541
+ }
10542
+ const attempts = ((await this.readFailure(source))?.attempts ?? 0) + 1;
10543
+ if (!await this.deps.inRoots(source.path)) {
10544
+ this.outsideRoots.add(this.keyOf(source));
10545
+ logger.warn("trickplay skipped", {
10546
+ tags,
10547
+ meta: { reason: "outside-roots" }
10548
+ });
10549
+ return;
10550
+ }
10551
+ const finalDir = this.readyDir(source);
10552
+ const workDir = `${finalDir}.work`;
10553
+ const tileHeight = tileHeightOf(source.width, source.height);
10554
+ const startedAt = this.deps.now();
10555
+ try {
10556
+ await rm(workDir, {
10557
+ recursive: true,
10558
+ force: true
10559
+ });
10560
+ await mkdir(workDir, { recursive: true });
10561
+ await this.deps.generate({
10562
+ inputPath: source.path,
10563
+ outDir: workDir,
10564
+ tileHeight
10565
+ });
10566
+ const sheets = (await readdir(workDir)).filter((name) => /^sprite-\d+\.jpg$/.test(name));
10567
+ if (sheets.length === 0) throw new Error("ffmpeg wrote no sprite sheet");
10568
+ await writeFile(join(workDir, INDEX_NAME), buildTrickplayVtt(source.durationMs / 1e3, tileHeight), "utf8");
10569
+ await rm(finalDir, {
10570
+ recursive: true,
10571
+ force: true
10572
+ });
10573
+ await rename(workDir, finalDir);
10574
+ await rm(this.failurePath(source), { force: true });
10575
+ await this.pruneOthers(source);
10576
+ logger.info("trickplay generated", {
10577
+ tags,
10578
+ meta: {
10579
+ sheets: sheets.length,
10580
+ tileHeight,
10581
+ tookMs: this.deps.now() - startedAt
10582
+ }
10583
+ });
10584
+ } catch (error) {
10585
+ const reason = error instanceof Error ? error.message : String(error);
10586
+ try {
10587
+ await rm(workDir, {
10588
+ recursive: true,
10589
+ force: true
10590
+ });
10591
+ await mkdir(this.itemDir(source), { recursive: true });
10592
+ await writeFile(this.failurePath(source), JSON.stringify({
10593
+ at: this.deps.now(),
10594
+ attempts,
10595
+ reason
10596
+ }), "utf8");
10597
+ } catch (writeError) {
10598
+ logger.warn("trickplay failure could not be recorded", {
10599
+ tags,
10600
+ meta: { error: writeError instanceof Error ? writeError.message : String(writeError) }
10601
+ });
10602
+ }
10603
+ logger.warn("trickplay failed", {
10604
+ tags,
10605
+ meta: {
10606
+ reason,
10607
+ attempts,
10608
+ retry: attempts < 3
10609
+ }
10610
+ });
10611
+ }
10612
+ }
10613
+ /** A changed file leaves its old fingerprint behind: drop every other fingerprint of the item. */
10614
+ async pruneOthers(source) {
10615
+ const keep = fingerprintOf(source);
10616
+ for (const name of await readdir(this.itemDir(source))) if (name !== keep && name !== `${keep}.failed.json`) await rm(join(this.itemDir(source), name), {
10617
+ recursive: true,
10618
+ force: true
10619
+ });
10620
+ }
10621
+ /** The absolute path of a ready file of `source`'s current fingerprint, or `null` when it is not there. */
10622
+ async fileFor(source, name) {
10623
+ if (!TRICKPLAY_FILE_NAME.test(name)) return null;
10624
+ const path = join(this.readyDir(source), name);
10625
+ try {
10626
+ return (await stat(path)).isFile() ? path : null;
10627
+ } catch {
10628
+ return null;
10629
+ }
10630
+ }
10631
+ };
10632
+ //#endregion
10633
+ //#region src/trickplay-plane.ts
10634
+ function reject(res, status, extra) {
10635
+ res.writeHead(status, {
10636
+ "Content-Length": 0,
10637
+ ...extra
10638
+ });
10639
+ res.end();
10640
+ }
10641
+ /** The `trickplay` plane: `GET|HEAD /<itemId>/index.vtt` and `/<itemId>/sprite-<n>.jpg`. */
10642
+ function createTrickplayPlaneHandler(deps) {
10643
+ return async (req, res) => {
10644
+ const method = req.method ?? "GET";
10645
+ if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10646
+ const segments = ((req.url ?? "/").split("?")[0] ?? "/").replace(/^\//, "").split("/");
10647
+ let itemId;
10648
+ let name;
10649
+ try {
10650
+ if (segments.length !== 2) return reject(res, 404);
10651
+ itemId = decodeURIComponent(segments[0] ?? "");
10652
+ name = decodeURIComponent(segments[1] ?? "");
10653
+ } catch {
10654
+ return reject(res, 404);
10655
+ }
10656
+ if (!isItemId(itemId)) {
10657
+ deps.logger.warn("trickplay request refused: not an item id", { meta: { reason: "bad-id" } });
10658
+ return reject(res, 404);
10659
+ }
10660
+ const tags = { itemId };
10661
+ if (!TRICKPLAY_FILE_NAME.test(name)) {
10662
+ deps.logger.info("trickplay request refused: not a trickplay file", {
10663
+ tags,
10664
+ meta: { reason: "bad-name" }
10665
+ });
10666
+ return reject(res, 404);
10667
+ }
10668
+ const source = await deps.source(itemId);
10669
+ if (source === null) {
10670
+ deps.logger.info("trickplay request refused: the item has no file", {
10671
+ tags,
10672
+ meta: { reason: "no-file" }
10673
+ });
10674
+ return reject(res, 404);
10675
+ }
10676
+ if (await resolveServable(source.path, await deps.roots()) === null) {
10677
+ deps.logger.warn("trickplay request refused: outside the library roots", {
10678
+ tags,
10679
+ meta: { reason: "outside-roots" }
10680
+ });
10681
+ return reject(res, 404);
10682
+ }
10683
+ const path = await deps.cache.fileFor(source, name);
10684
+ if (path === null) {
10685
+ deps.logger.info("trickplay request refused: not generated yet", {
10686
+ tags,
10687
+ meta: { reason: "not-ready" }
10688
+ });
10689
+ return reject(res, 404);
10690
+ }
10691
+ try {
10692
+ const body = await readFile(path);
10693
+ const isIndex = name === "index.vtt";
10694
+ res.writeHead(200, {
10695
+ "Content-Type": isIndex ? "text/vtt; charset=utf-8" : "image/jpeg",
10696
+ "Content-Length": body.length,
10697
+ "Cache-Control": isIndex ? "private, no-store" : "private, max-age=3600"
10698
+ });
10699
+ if (method === "HEAD") res.end();
10700
+ else res.end(body);
10701
+ deps.logger.debug("trickplay served", {
10702
+ tags,
10703
+ meta: { name }
10704
+ });
10705
+ } catch {
10706
+ deps.logger.warn("trickplay request refused: file vanished", {
10707
+ tags,
10708
+ meta: { reason: "gone" }
10709
+ });
10217
10710
  reject(res, 404);
10218
10711
  }
10219
10712
  };
@@ -11228,6 +11721,7 @@ function sortByShownTitle(rows, requested, serverDefault) {
11228
11721
  }
11229
11722
  var FILE_PLANE_PREFIX = "file";
11230
11723
  var SUBTITLE_PLANE_PREFIX = "subtitle";
11724
+ var TRICKPLAY_PLANE_PREFIX = "trickplay";
11231
11725
  var HUB_PLANE_BASE = "/addon/media-library";
11232
11726
  var SEARCH_DEFAULT_LIMIT = 50;
11233
11727
  var RECENT_DEFAULT_LIMIT = 20;
@@ -11242,6 +11736,10 @@ function playPathOf(itemId) {
11242
11736
  function subtitlePathOf(itemId, sidecarId) {
11243
11737
  return `${HUB_PLANE_BASE}/${SUBTITLE_PLANE_PREFIX}/${itemId}/${sidecarId}`;
11244
11738
  }
11739
+ /** The base of one item's trickplay files: `<base>/index.vtt`, `<base>/sprite-<n>.jpg`. */
11740
+ function trickplayBaseOf(itemId) {
11741
+ return `${HUB_PLANE_BASE}/${TRICKPLAY_PLANE_PREFIX}/${itemId}`;
11742
+ }
11245
11743
  function imagePathOf(itemId, which) {
11246
11744
  return `${HUB_PLANE_BASE}/img/${itemId}/${which}`;
11247
11745
  }
@@ -11263,13 +11761,15 @@ var LibraryStore = class {
11263
11761
  serverLanguage;
11264
11762
  now;
11265
11763
  listDir;
11764
+ trickplay;
11266
11765
  locks = /* @__PURE__ */ new Map();
11267
- constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir) {
11766
+ constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir, trickplay = null) {
11268
11767
  this.db = db;
11269
11768
  this.logger = logger;
11270
11769
  this.serverLanguage = serverLanguage;
11271
11770
  this.now = now;
11272
11771
  this.listDir = listDir;
11772
+ this.trickplay = trickplay;
11273
11773
  }
11274
11774
  async init() {
11275
11775
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -11443,9 +11943,26 @@ var LibraryStore = class {
11443
11943
  format: sidecar.format,
11444
11944
  label: sidecar.label,
11445
11945
  path: subtitlePathOf(row.id, sidecar.id)
11446
- }))
11946
+ })),
11947
+ trickplay: file === void 0 || this.trickplay === null ? null : await this.trickplay.request(trickplaySourceOf(row.id, file), trickplayBaseOf(row.id))
11447
11948
  };
11448
11949
  }
11950
+ /** The catalogued file of `itemId` as the trickplay cache sees it; `null` when it has none. */
11951
+ async trickplaySource(itemId) {
11952
+ const catalogued = await this.playableFile(itemId);
11953
+ return catalogued === null ? null : trickplaySourceOf(itemId, catalogued.row);
11954
+ }
11955
+ /** Every catalogued file, for the sweep after a scan. */
11956
+ async trickplaySources() {
11957
+ const items = await this.queryAllItems();
11958
+ const files = new Map(parseRows(FileRowSchema, await queryAll(this.db, FILES, "path", {}), this.invalid(FILES)).map((file) => [file.path, file]));
11959
+ const sources = [];
11960
+ for (const item of items) {
11961
+ const file = item.filePath === null ? void 0 : files.get(item.filePath);
11962
+ if (file !== void 0) sources.push(trickplaySourceOf(item.id, file));
11963
+ }
11964
+ return sources;
11965
+ }
11449
11966
  /** The subtitle files next to the video of `itemId`; empty when it has none or no file. */
11450
11967
  async subtitleSidecars(itemId) {
11451
11968
  const catalogued = await this.playableFile(itemId);
@@ -11747,6 +12264,18 @@ var LibraryStore = class {
11747
12264
  return entries;
11748
12265
  }
11749
12266
  };
12267
+ function trickplaySourceOf(itemId, file) {
12268
+ const video = file.streams.find((stream) => stream.kind === "video");
12269
+ return {
12270
+ itemId,
12271
+ path: file.path,
12272
+ sizeBytes: file.sizeBytes,
12273
+ mtimeMs: file.mtimeMs,
12274
+ durationMs: file.probeOk ? file.durationMs : null,
12275
+ width: video?.width ?? null,
12276
+ height: video?.height ?? null
12277
+ };
12278
+ }
11750
12279
  async function defaultListDir(dir) {
11751
12280
  try {
11752
12281
  return new Map((await readdir(dir)).map((name) => [name.toLowerCase(), name]));
@@ -15055,6 +15584,7 @@ var ScanController = class {
15055
15584
  deps;
15056
15585
  sources;
15057
15586
  logger;
15587
+ afterScan;
15058
15588
  running = false;
15059
15589
  last = {
15060
15590
  running: false,
@@ -15067,10 +15597,11 @@ var ScanController = class {
15067
15597
  skipped: 0
15068
15598
  };
15069
15599
  timer = null;
15070
- constructor(deps, sources, logger) {
15600
+ constructor(deps, sources, logger, afterScan = async () => {}) {
15071
15601
  this.deps = deps;
15072
15602
  this.sources = sources;
15073
15603
  this.logger = logger;
15604
+ this.afterScan = afterScan;
15074
15605
  }
15075
15606
  status() {
15076
15607
  return {
@@ -15100,6 +15631,11 @@ var ScanController = class {
15100
15631
  } finally {
15101
15632
  this.running = false;
15102
15633
  }
15634
+ try {
15635
+ await this.afterScan();
15636
+ } catch (error) {
15637
+ this.logger.warn("after-scan work failed", { meta: { error: String(error) } });
15638
+ }
15103
15639
  }
15104
15640
  /** (Re)arm the rescan timer; `0` minutes turns it off. */
15105
15641
  schedule(minutes) {
@@ -15121,8 +15657,11 @@ var ScanController = class {
15121
15657
  * place in every item is kept here. Bytes leave through two data-plane routes served by item id.
15122
15658
  */
15123
15659
  var IMG_CACHE_DIR = "img-cache";
15660
+ var TRICKPLAY_CACHE_DIR = "trickplay";
15124
15661
  var MediaLibraryAddon = class extends BaseAddon {
15125
15662
  scans = null;
15663
+ /** The trickplay switch, held in memory: the generator reads it off the settings path. */
15664
+ trickplayOn = true;
15126
15665
  constructor() {
15127
15666
  super({});
15128
15667
  }
@@ -15137,6 +15676,7 @@ var MediaLibraryAddon = class extends BaseAddon {
15137
15676
  }
15138
15677
  async onScopedSettingsChanged() {
15139
15678
  const settings = await this.readSettings();
15679
+ this.trickplayOn = settings.trickplay;
15140
15680
  this.scans?.schedule(settings.rescanMinutes);
15141
15681
  this.scans?.start("settings");
15142
15682
  }
@@ -15192,9 +15732,26 @@ var MediaLibraryAddon = class extends BaseAddon {
15192
15732
  const db = settingsStoreDb(ctx.api.settingsStore);
15193
15733
  const serverLanguage = new ServerLanguage(async () => (await ctx.api.system.info.query()).defaultLanguage, () => Date.now(), logger);
15194
15734
  await serverLanguage.refresh();
15195
- const store = new LibraryStore(db, logger, () => serverLanguage.current());
15196
- await store.init();
15197
15735
  const ffmpeg = await ctx.deps.ensureFfmpeg();
15736
+ const roots = async () => {
15737
+ const settings = await this.readSettings();
15738
+ return [
15739
+ ...resolveSources(settings).folderRoots,
15740
+ settings.seriesPathTo || settings.seriesPathFrom,
15741
+ settings.moviesPathTo || settings.moviesPathFrom
15742
+ ].filter((root) => root !== "");
15743
+ };
15744
+ this.trickplayOn = (await this.readSettings()).trickplay;
15745
+ const trickplay = new TrickplayService({
15746
+ cacheDir: join(ctx.dataDir, TRICKPLAY_CACHE_DIR),
15747
+ generate: createFfmpegTrickplayGenerator(ffmpeg),
15748
+ enabled: () => this.trickplayOn,
15749
+ inRoots: async (path) => await resolveServable(path, await roots()) !== null,
15750
+ logger,
15751
+ now: () => Date.now()
15752
+ });
15753
+ const store = new LibraryStore(db, logger, () => serverLanguage.current(), void 0, void 0, trickplay);
15754
+ await store.init();
15198
15755
  const scans = new ScanController({
15199
15756
  db,
15200
15757
  logger,
@@ -15236,7 +15793,10 @@ var MediaLibraryAddon = class extends BaseAddon {
15236
15793
  }),
15237
15794
  createAnilist: () => createAnilistProvider({ fetch: httpRemoteFetch }),
15238
15795
  now: () => Date.now()
15239
- }, async () => resolveSources(await this.readSettings()), logger);
15796
+ }, async () => resolveSources(await this.readSettings()), logger, async () => {
15797
+ if (!this.trickplayOn) return;
15798
+ for (const source of await store.trickplaySources()) await trickplay.request(source, trickplayBaseOf(source.itemId));
15799
+ });
15240
15800
  this.scans = scans;
15241
15801
  const plexImports = new PlexImportController(logger, () => Date.now());
15242
15802
  const startPlex = async (mode) => {
@@ -15264,14 +15824,6 @@ var MediaLibraryAddon = class extends BaseAddon {
15264
15824
  message: started ? `Plex ${mode === "run" ? "import" : "preview"} started: read the report with plexImportStatus` : "A Plex import is already running"
15265
15825
  };
15266
15826
  };
15267
- const roots = async () => {
15268
- const settings = await this.readSettings();
15269
- return [
15270
- ...resolveSources(settings).folderRoots,
15271
- settings.seriesPathTo || settings.seriesPathFrom,
15272
- settings.moviesPathTo || settings.moviesPathFrom
15273
- ].filter((root) => root !== "");
15274
- };
15275
15827
  await ctx.dataPlane?.serve({
15276
15828
  prefix: FILE_PLANE_PREFIX,
15277
15829
  access: "viewer",
@@ -15290,6 +15842,16 @@ var MediaLibraryAddon = class extends BaseAddon {
15290
15842
  logger
15291
15843
  })
15292
15844
  });
15845
+ await ctx.dataPlane?.serve({
15846
+ prefix: TRICKPLAY_PLANE_PREFIX,
15847
+ access: "viewer",
15848
+ handler: createTrickplayPlaneHandler({
15849
+ source: (itemId) => store.trickplaySource(itemId),
15850
+ cache: trickplay,
15851
+ roots,
15852
+ logger
15853
+ })
15854
+ });
15293
15855
  await ctx.dataPlane?.serve({
15294
15856
  prefix: "img",
15295
15857
  access: "viewer",
@@ -15310,7 +15872,10 @@ var MediaLibraryAddon = class extends BaseAddon {
15310
15872
  const settings = await this.readSettings();
15311
15873
  scans.schedule(settings.rescanMinutes);
15312
15874
  scans.start("boot");
15313
- const apps = { listApps: async () => [buildApp()] };
15875
+ const apps = { listApps: async () => {
15876
+ const pluginVersion = readPluginVersion(join(__dirname, ".."));
15877
+ return pluginVersion === null ? [buildApp()] : [buildApp(), buildPluginApp(pluginVersion)];
15878
+ } };
15314
15879
  const addressRoles = { listAddressRoles: async () => buildAddressRoles() };
15315
15880
  logger.info("media-library initialized");
15316
15881
  return {