@dominevo/addon-media-library 0.1.6 → 0.1.8

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.
@@ -8811,7 +8811,12 @@ var MediaItemSummarySchema = /* @__PURE__ */ object({
8811
8811
  /** False when the catalogue lists it but no playable file is on disk. */
8812
8812
  playable: /* @__PURE__ */ boolean(),
8813
8813
  /** The caller's progress; `null` when they have none. Absent on a catalogue-only row (series). */
8814
- progress: /* @__PURE__ */ MediaProgressSchema.nullable()
8814
+ progress: /* @__PURE__ */ MediaProgressSchema.nullable(),
8815
+ /**
8816
+ * The caller's watchlist state, on series and movie rows (list, get and search). Absent on an
8817
+ * episode, which cannot be watchlisted.
8818
+ */
8819
+ watchlisted: /* @__PURE__ */ boolean().optional()
8815
8820
  });
8816
8821
  /** An episode of a season list: the summary plus its plot, read in the same query. */
8817
8822
  var MediaEpisodeSummarySchema = /* @__PURE__ */ MediaItemSummarySchema.extend({ overview: /* @__PURE__ */ string().nullable() });
@@ -8841,6 +8846,41 @@ var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8841
8846
  playPath: /* @__PURE__ */ string().nullable(),
8842
8847
  file: /* @__PURE__ */ LibraryFileInfoSchema.nullable()
8843
8848
  });
8849
+ /**
8850
+ * A person of an item's credits. `photoPath` is an image-plane handle relative to the hub origin
8851
+ * (the same plane that serves posters), `null` when the source has no photo: a provider's own URL
8852
+ * never leaves the addon.
8853
+ */
8854
+ var MediaPersonSchema = /* @__PURE__ */ object({
8855
+ /** The metadata source's id of the person. */
8856
+ id: /* @__PURE__ */ number().int(),
8857
+ name: /* @__PURE__ */ string(),
8858
+ photoPath: /* @__PURE__ */ string().nullable()
8859
+ });
8860
+ var MediaCastMemberSchema = /* @__PURE__ */ MediaPersonSchema.extend({
8861
+ /** The role played; `null` when the source names none. */
8862
+ character: /* @__PURE__ */ string().nullable(),
8863
+ /** Billing order, 0 first. */
8864
+ order: /* @__PURE__ */ number().int().nonnegative()
8865
+ });
8866
+ /**
8867
+ * What the metadata source holds about an item beyond its plot. Nothing fetched yet answers empty
8868
+ * arrays and `null`s; a failed re-fetch never replaces what is stored.
8869
+ */
8870
+ var MediaItemDetailsSchema = /* @__PURE__ */ object({
8871
+ itemId: /* @__PURE__ */ string(),
8872
+ genres: /* @__PURE__ */ array(/* @__PURE__ */ string()).readonly(),
8873
+ /** `null` when the source does not know it. */
8874
+ runtimeMinutes: /* @__PURE__ */ number().int().positive().nullable(),
8875
+ /** The age rating for the server's region (`PG-13`, `TV-MA`, `12`), or `null`. */
8876
+ certification: /* @__PURE__ */ string().nullable(),
8877
+ creators: /* @__PURE__ */ array(MediaPersonSchema).readonly(),
8878
+ directors: /* @__PURE__ */ array(MediaPersonSchema).readonly(),
8879
+ writers: /* @__PURE__ */ array(MediaPersonSchema).readonly(),
8880
+ cast: /* @__PURE__ */ array(MediaCastMemberSchema).readonly(),
8881
+ /** Episodes only; empty on a series or a movie. */
8882
+ guestStars: /* @__PURE__ */ array(MediaCastMemberSchema).readonly()
8883
+ });
8844
8884
  var MediaSeasonSchema = /* @__PURE__ */ object({
8845
8885
  seasonNumber: /* @__PURE__ */ number().int(),
8846
8886
  episodeCount: /* @__PURE__ */ number().int().nonnegative(),
@@ -8908,6 +8948,24 @@ var mediaLibraryCapability = {
8908
8948
  limit: /* @__PURE__ */ number().int().positive().max(100).optional(),
8909
8949
  language: LanguageInputSchema
8910
8950
  }), /* @__PURE__ */ array(MediaItemSummarySchema).readonly(), { caller: "required" }),
8951
+ /** The caller's series and movies they watchlisted, the latest added first. */
8952
+ listWatchlist: /* @__PURE__ */ method(PageInputSchema, MediaItemPageSchema, { caller: "required" }),
8953
+ /**
8954
+ * Put a series or a movie on the caller's watchlist, or take it off. Idempotent: the answer is the
8955
+ * state now. An episode is refused (`watchlist-kind`).
8956
+ */
8957
+ setWatchlisted: /* @__PURE__ */ method(/* @__PURE__ */ object({
8958
+ itemId: /* @__PURE__ */ string().min(1),
8959
+ on: /* @__PURE__ */ boolean()
8960
+ }), /* @__PURE__ */ object({ on: /* @__PURE__ */ boolean() }), {
8961
+ kind: "mutation",
8962
+ caller: "required"
8963
+ }),
8964
+ /** Genres, runtime, rating, crew and cast of one item; `null` when the id is unknown. */
8965
+ getItemDetails: /* @__PURE__ */ method(/* @__PURE__ */ object({
8966
+ itemId: /* @__PURE__ */ string().min(1),
8967
+ language: LanguageInputSchema
8968
+ }), /* @__PURE__ */ MediaItemDetailsSchema.nullable(), { caller: "required" }),
8911
8969
  /** The caller's progress in one item; `null` when they have none. */
8912
8970
  getProgress: /* @__PURE__ */ method(/* @__PURE__ */ object({ itemId: /* @__PURE__ */ string().min(1) }), /* @__PURE__ */ MediaProgressSchema.nullable(), { caller: "required" }),
8913
8971
  /**
@@ -10050,6 +10108,71 @@ function parseRows(schema, rows, onInvalid) {
10050
10108
  return out;
10051
10109
  }
10052
10110
  //#endregion
10111
+ //#region src/item-details.ts
10112
+ /**
10113
+ * What a metadata source holds about one item beyond its plot: genres, runtime, rating, crew and
10114
+ * cast. Stored with the item (a JSON column), never handed to a client as is: a person's `photo` is
10115
+ * the SOURCE's https URL, and a client gets an image-plane handle instead (`personImageKey`).
10116
+ */
10117
+ var StoredPersonSchema = object({
10118
+ id: number().int(),
10119
+ name: string(),
10120
+ /** The source's https URL of the profile picture; `null` when it has none. Never sent to a client. */
10121
+ photo: string().nullable()
10122
+ });
10123
+ var StoredCastSchema = StoredPersonSchema.extend({
10124
+ character: string().nullable(),
10125
+ order: number().int().nonnegative()
10126
+ });
10127
+ var ItemDetailsSchema = object({
10128
+ /** Genre names by language tag (lower-case, as `translations`): a source answers them in the language it was asked. */
10129
+ genres: record(string(), array(string())),
10130
+ runtimeMinutes: number().int().positive().nullable(),
10131
+ certification: string().nullable(),
10132
+ creators: array(StoredPersonSchema),
10133
+ directors: array(StoredPersonSchema),
10134
+ writers: array(StoredPersonSchema),
10135
+ cast: array(StoredCastSchema),
10136
+ guestStars: array(StoredCastSchema)
10137
+ });
10138
+ var EMPTY_DETAILS = {
10139
+ genres: {},
10140
+ runtimeMinutes: null,
10141
+ certification: null,
10142
+ creators: [],
10143
+ directors: [],
10144
+ writers: [],
10145
+ cast: [],
10146
+ guestStars: []
10147
+ };
10148
+ var PERSON_KEY = /^person-(\d{1,12})$/;
10149
+ function personImageKey(personId) {
10150
+ return `person-${personId}`;
10151
+ }
10152
+ function isImageKind(value) {
10153
+ return value === "poster" || value === "fanart" || value !== void 0 && PERSON_KEY.test(value);
10154
+ }
10155
+ function isPersonPhotoUrl(value) {
10156
+ if (!URL.canParse(value)) return false;
10157
+ const url = new URL(value);
10158
+ return url.protocol === "https:" && url.hostname === "image.tmdb.org";
10159
+ }
10160
+ /** The person id an image key names, or `null` for a poster or a fanart. */
10161
+ function personIdOf(kind) {
10162
+ const found = PERSON_KEY.exec(kind);
10163
+ return found?.[1] === void 0 ? null : Number(found[1]);
10164
+ }
10165
+ /** The profile picture URL stored for `personId` among the credits of `details`, or `null`. */
10166
+ function personPhotoOf(details, personId) {
10167
+ return [
10168
+ ...details.cast,
10169
+ ...details.guestStars,
10170
+ ...details.creators,
10171
+ ...details.directors,
10172
+ ...details.writers
10173
+ ].find((person) => person.id === personId)?.photo ?? null;
10174
+ }
10175
+ //#endregion
10053
10176
  //#region src/metadata.ts
10054
10177
  /**
10055
10178
  * One language's text of an item: either field may be absent (a provider can translate the title and
@@ -10074,14 +10197,18 @@ var ProviderMatchSchema = object({
10074
10197
  poster: string().nullable(),
10075
10198
  fanart: string().nullable(),
10076
10199
  /** The title and overview in other languages, when the provider answered them with the match. */
10077
- translations: TranslationMapSchema.optional()
10200
+ translations: TranslationMapSchema.optional(),
10201
+ /** Genres, rating, crew and cast, answered with the match. Absent from a match cached before they were kept. */
10202
+ details: ItemDetailsSchema.optional()
10078
10203
  });
10079
10204
  var ProviderEpisodeSchema = object({
10080
10205
  season: number().int(),
10081
10206
  episode: number().int(),
10082
10207
  title: string().nullable(),
10083
10208
  overview: string().nullable(),
10084
- still: string().nullable()
10209
+ still: string().nullable(),
10210
+ /** The episode's own runtime, crew and guest stars, read from the season answer. Absent from a list cached before they were kept. */
10211
+ details: ItemDetailsSchema.optional()
10085
10212
  });
10086
10213
  /** The provider refused its credential: asking again cannot work until the operator fixes it. */
10087
10214
  var ProviderAuthError = class extends Error {
@@ -10203,6 +10330,7 @@ var ITEMS = "media-library:items";
10203
10330
  var FILES = "media-library:files";
10204
10331
  var PROGRESS = "media-library:progress";
10205
10332
  var PINS = "media-library:pins";
10333
+ var WATCHLIST = "media-library:watchlist";
10206
10334
  /** Item row: one series, movie or episode of the catalogue. */
10207
10335
  var ItemRowSchema = object({
10208
10336
  id: string(),
@@ -10217,6 +10345,8 @@ var ItemRowSchema = object({
10217
10345
  overview: string().nullable(),
10218
10346
  /** The title and overview in other languages; absent on a row written before they were kept. */
10219
10347
  translations: TranslationMapSchema.nullish(),
10348
+ /** Genres, rating, crew and cast; absent on a row written before they were kept, `null` when no source gave any. */
10349
+ details: ItemDetailsSchema.nullish(),
10220
10350
  tvdbId: number().int().nullable(),
10221
10351
  tmdbId: number().int().nullable(),
10222
10352
  imdbId: string().nullable(),
@@ -10262,6 +10392,12 @@ var ProgressRowSchema = object({
10262
10392
  updatedAt: number().int(),
10263
10393
  watched: boolean()
10264
10394
  });
10395
+ /** One series or movie a person put on their watchlist. */
10396
+ var WatchlistRowSchema = object({
10397
+ userId: string(),
10398
+ itemId: string(),
10399
+ addedAt: number().int()
10400
+ });
10265
10401
  var text$3 = (name, notNull = false) => ({
10266
10402
  name,
10267
10403
  type: "TEXT",
@@ -10291,6 +10427,10 @@ var COLLECTIONS = [
10291
10427
  name: "translations",
10292
10428
  type: "JSON"
10293
10429
  },
10430
+ {
10431
+ name: "details",
10432
+ type: "JSON"
10433
+ },
10294
10434
  int("tvdbId"),
10295
10435
  int("tmdbId"),
10296
10436
  text$3("imdbId"),
@@ -10390,6 +10530,20 @@ var COLLECTIONS = [
10390
10530
  "updatedAt"
10391
10531
  ]
10392
10532
  }]
10533
+ },
10534
+ {
10535
+ collection: WATCHLIST,
10536
+ primaryKey: ["userId", "itemId"],
10537
+ withoutRowid: true,
10538
+ columns: [
10539
+ text$3("userId", true),
10540
+ text$3("itemId", true),
10541
+ int("addedAt", true)
10542
+ ],
10543
+ indexes: [{
10544
+ name: "idx_media_watchlist_user",
10545
+ columns: ["userId", "addedAt"]
10546
+ }]
10393
10547
  }
10394
10548
  ];
10395
10549
  //#endregion
@@ -10657,6 +10811,7 @@ var NO_LOCAL = {
10657
10811
  year: null,
10658
10812
  overview: null,
10659
10813
  translations: null,
10814
+ details: null,
10660
10815
  tvdbId: null,
10661
10816
  tmdbId: null,
10662
10817
  imdbId: null,
@@ -10697,6 +10852,7 @@ function merge(first, second) {
10697
10852
  year: pick$1(first.year, second.year),
10698
10853
  overview: pick$1(first.overview, second.overview),
10699
10854
  translations: pick$1(first.translations, second.translations),
10855
+ details: pick$1(first.details, second.details),
10700
10856
  tvdbId: pick$1(first.tvdbId, second.tvdbId),
10701
10857
  tmdbId: pick$1(first.tmdbId, second.tmdbId),
10702
10858
  imdbId: pick$1(first.imdbId, second.imdbId),
@@ -10781,6 +10937,19 @@ function resolveItemText(row, requested, serverDefault) {
10781
10937
  overview: overview ?? row.overview
10782
10938
  };
10783
10939
  }
10940
+ /**
10941
+ * `rows` in A–Z order of the title each reader sees (`resolveItemText`, minus a leading article), compared with the
10942
+ * collator of the reader's language (`en` when none). A stable sort: equal titles keep the order
10943
+ * the rows came in (the caller's read order: item id for `queryAllItems`), so a page cut is deterministic.
10944
+ */
10945
+ function sortByShownTitle(rows, requested, serverDefault) {
10946
+ const collator = new Intl.Collator(languageKey(requested) ?? "en", {
10947
+ sensitivity: "base",
10948
+ numeric: true
10949
+ });
10950
+ const keys = new Map(rows.map((row) => [row, sortKey(resolveItemText(row, requested, serverDefault).title)]));
10951
+ return rows.toSorted((a, b) => collator.compare(keys.get(a) ?? "", keys.get(b) ?? ""));
10952
+ }
10784
10953
  var FILE_PLANE_PREFIX = "file";
10785
10954
  var HUB_PLANE_BASE = "/addon/media-library";
10786
10955
  var SEARCH_DEFAULT_LIMIT = 50;
@@ -10788,6 +10957,8 @@ var RECENT_DEFAULT_LIMIT = 20;
10788
10957
  var CONTINUE_DEFAULT_LIMIT = 20;
10789
10958
  /** A rewound row is not "continue", so the read asks for a few more than it will show. */
10790
10959
  var CONTINUE_OVERFETCH = 3;
10960
+ /** Item ids resolved per read when a watchlist is larger than one query takes. */
10961
+ var WATCHLIST_RESOLVE_CHUNK = 500;
10791
10962
  function playPathOf(itemId) {
10792
10963
  return `${HUB_PLANE_BASE}/${FILE_PLANE_PREFIX}/${itemId}`;
10793
10964
  }
@@ -10797,16 +10968,26 @@ function imagePathOf(itemId, which) {
10797
10968
  function isWatched(positionMs, durationMs) {
10798
10969
  return durationMs > 0 && positionMs / durationMs >= .9;
10799
10970
  }
10971
+ /** An episode cannot be watchlisted: the series is what a person follows. */
10972
+ var WatchlistKindError = class extends Error {
10973
+ code = "watchlist-kind";
10974
+ constructor(itemId) {
10975
+ super(`watchlist-kind: ${itemId} is an episode; only a series or a movie can be watchlisted`);
10976
+ this.name = "WatchlistKindError";
10977
+ }
10978
+ };
10800
10979
  var idList = (rows) => rows.map((row) => row.id);
10801
10980
  var LibraryStore = class {
10802
10981
  db;
10803
10982
  logger;
10804
10983
  serverLanguage;
10984
+ now;
10805
10985
  locks = /* @__PURE__ */ new Map();
10806
- constructor(db, logger, serverLanguage = () => "en") {
10986
+ constructor(db, logger, serverLanguage = () => "en", now = Date.now) {
10807
10987
  this.db = db;
10808
10988
  this.logger = logger;
10809
10989
  this.serverLanguage = serverLanguage;
10990
+ this.now = now;
10810
10991
  }
10811
10992
  async init() {
10812
10993
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -10827,6 +11008,9 @@ var LibraryStore = class {
10827
11008
  async queryFiles(filter) {
10828
11009
  return parseRows(FileRowSchema, await this.db.query(FILES, filter), this.invalid(FILES));
10829
11010
  }
11011
+ async queryWatchlist(filter) {
11012
+ return parseRows(WatchlistRowSchema, await this.db.query(WATCHLIST, filter), this.invalid(WATCHLIST));
11013
+ }
10830
11014
  async queryProgress(filter) {
10831
11015
  return parseRows(ProgressRowSchema, await this.db.query(PROGRESS, filter), this.invalid(PROGRESS));
10832
11016
  }
@@ -10841,31 +11025,27 @@ var LibraryStore = class {
10841
11025
  where: { userId },
10842
11026
  whereIn: { itemId: playableIds }
10843
11027
  })) progress.set(entry.itemId, entry);
11028
+ const followable = rows.filter((row) => row.kind !== "episode").map((row) => row.id);
11029
+ const watchlisted = /* @__PURE__ */ new Set();
11030
+ if (followable.length > 0) for (const entry of await this.queryWatchlist({
11031
+ where: { userId },
11032
+ whereIn: { itemId: followable }
11033
+ })) watchlisted.add(entry.itemId);
10844
11034
  const fallback = this.serverLanguage();
10845
11035
  return rows.map((row) => {
10846
- return toSummary(row, row.filePath === null ? void 0 : files.get(row.filePath), progress.get(row.id), resolveItemText(row, language, fallback).title);
11036
+ return toSummary(row, row.filePath === null ? void 0 : files.get(row.filePath), progress.get(row.id), resolveItemText(row, language, fallback).title, row.kind === "episode" ? void 0 : watchlisted.has(row.id));
10847
11037
  });
10848
11038
  }
10849
11039
  pageOf = async (kind, userId, limit, offset, language) => {
10850
- const rows = await this.queryItems({
10851
- where: {
10852
- kind,
10853
- topLevel: true
10854
- },
10855
- orderBy: {
10856
- field: "sortTitle",
10857
- direction: "asc"
10858
- },
10859
- limit: limit ?? 100,
10860
- offset: offset ?? 0
10861
- });
10862
- const total = await this.db.count(ITEMS, { where: {
11040
+ const all = await this.queryAllItems({ where: {
10863
11041
  kind,
10864
11042
  topLevel: true
10865
11043
  } });
11044
+ const start = offset ?? 0;
11045
+ const page = sortByShownTitle(all, language, this.serverLanguage()).slice(start, start + (limit ?? 100));
10866
11046
  return {
10867
- items: await this.summaries(rows, userId, language),
10868
- total
11047
+ items: await this.summaries(page, userId, language),
11048
+ total: all.length
10869
11049
  };
10870
11050
  };
10871
11051
  listSeries(userId, limit, offset, language) {
@@ -10888,15 +11068,9 @@ var LibraryStore = class {
10888
11068
  async search(userId, query, limit, language) {
10889
11069
  const needle = foldTitle(query);
10890
11070
  if (needle === "") return [];
10891
- const rows = await this.queryItems({
10892
- where: { topLevel: true },
10893
- orderBy: {
10894
- field: "sortTitle",
10895
- direction: "asc"
10896
- }
10897
- });
11071
+ const rows = await this.queryAllItems({ where: { topLevel: true } });
10898
11072
  const fallback = this.serverLanguage();
10899
- const hits = rows.filter((row) => row.titleFold.includes(needle) || foldTitle(resolveItemText(row, language, fallback).title).includes(needle)).slice(0, limit ?? SEARCH_DEFAULT_LIMIT);
11073
+ const hits = sortByShownTitle(rows.filter((row) => row.titleFold.includes(needle) || foldTitle(resolveItemText(row, language, fallback).title).includes(needle)), language, fallback).slice(0, limit ?? SEARCH_DEFAULT_LIMIT);
10900
11074
  return this.summaries(hits, userId, language);
10901
11075
  }
10902
11076
  episodesOf(seriesId) {
@@ -11004,6 +11178,14 @@ var LibraryStore = class {
11004
11178
  limit: 1
11005
11179
  });
11006
11180
  if (item === void 0) return [];
11181
+ const personId = personIdOf(which);
11182
+ if (personId !== null) {
11183
+ const photo = item.details === null || item.details === void 0 ? null : personPhotoOf(item.details, personId);
11184
+ return photo !== null && isPersonPhotoUrl(photo) ? [{
11185
+ kind: "remote",
11186
+ url: photo
11187
+ }] : [];
11188
+ }
11007
11189
  const out = [];
11008
11190
  const cover = which === "poster" ? item.posterSource : item.fanartSource;
11009
11191
  if (cover !== null) {
@@ -11016,7 +11198,7 @@ var LibraryStore = class {
11016
11198
  kind: "remote",
11017
11199
  url: cover
11018
11200
  });
11019
- else if (cover.startsWith("/")) out.push({
11201
+ else if (cover.startsWith("/") || cover.startsWith("http://")) out.push({
11020
11202
  kind: "arr",
11021
11203
  path: cover,
11022
11204
  sourceId: item.sourceId
@@ -11039,6 +11221,86 @@ var LibraryStore = class {
11039
11221
  }
11040
11222
  return out;
11041
11223
  }
11224
+ /** The caller's series and movies on their watchlist, the latest added first. */
11225
+ async listWatchlist(userId, limit, offset, language) {
11226
+ const held = parseRows(WatchlistRowSchema, await queryAll(this.db, WATCHLIST, "itemId", { where: { userId } }), this.invalid(WATCHLIST)).toSorted((a, b) => b.addedAt - a.addedAt || a.itemId.localeCompare(b.itemId));
11227
+ if (held.length === 0) return {
11228
+ items: [],
11229
+ total: 0
11230
+ };
11231
+ const rows = /* @__PURE__ */ new Map();
11232
+ for (let at = 0; at < held.length; at += WATCHLIST_RESOLVE_CHUNK) {
11233
+ const ids = held.slice(at, at + WATCHLIST_RESOLVE_CHUNK).map((entry) => entry.itemId);
11234
+ for (const row of await this.queryItems({ whereIn: { id: ids } })) rows.set(row.id, row);
11235
+ }
11236
+ const resolved = held.flatMap((entry) => {
11237
+ const row = rows.get(entry.itemId);
11238
+ return row === void 0 ? [] : [row];
11239
+ });
11240
+ const start = offset ?? 0;
11241
+ const ordered = resolved.slice(start, start + (limit ?? 100));
11242
+ const total = resolved.length;
11243
+ return {
11244
+ items: await this.summaries(ordered, userId, language),
11245
+ total
11246
+ };
11247
+ }
11248
+ /** Put a series or a movie on the caller's watchlist, or take it off. Idempotent; an episode is refused. */
11249
+ setWatchlisted(userId, itemId, on) {
11250
+ return this.locked(`watchlist\u0000${userId}\u0000${itemId}`, async () => {
11251
+ if ((await this.requirePlayable(itemId)).kind === "episode") throw new WatchlistKindError(itemId);
11252
+ if (!on) {
11253
+ await this.db.deleteWhere(WATCHLIST, { where: {
11254
+ userId,
11255
+ itemId
11256
+ } });
11257
+ return { on: false };
11258
+ }
11259
+ const [held] = await this.queryWatchlist({
11260
+ where: {
11261
+ userId,
11262
+ itemId
11263
+ },
11264
+ limit: 1
11265
+ });
11266
+ if (held === void 0) await this.db.upsertMany(WATCHLIST, ["userId", "itemId"], [{
11267
+ userId,
11268
+ itemId,
11269
+ addedAt: this.now()
11270
+ }]);
11271
+ return { on: true };
11272
+ });
11273
+ }
11274
+ /** Genres, runtime, rating, crew and cast of one item, in the reader's language; empty when nothing was fetched. */
11275
+ async getItemDetails(itemId, language) {
11276
+ const [row] = await this.queryItems({
11277
+ where: { id: itemId },
11278
+ limit: 1
11279
+ });
11280
+ if (row === void 0) return null;
11281
+ const details = row.details ?? EMPTY_DETAILS;
11282
+ const person = (entry) => ({
11283
+ id: entry.id,
11284
+ name: entry.name,
11285
+ photoPath: entry.photo === null || !isPersonPhotoUrl(entry.photo) ? null : imagePathOf(row.id, personImageKey(entry.id))
11286
+ });
11287
+ const member = (entry) => ({
11288
+ ...person(entry),
11289
+ character: entry.character,
11290
+ order: entry.order
11291
+ });
11292
+ return {
11293
+ itemId: row.id,
11294
+ genres: genresOf(details, language, this.serverLanguage()),
11295
+ runtimeMinutes: details.runtimeMinutes,
11296
+ certification: details.certification,
11297
+ creators: details.creators.map(person),
11298
+ directors: details.directors.map(person),
11299
+ writers: details.writers.map(person),
11300
+ cast: details.cast.map(member),
11301
+ guestStars: details.guestStars.map(member)
11302
+ };
11303
+ }
11042
11304
  /** Serialise the read-compare-write of one (user, item) so two writes of one person cannot interleave. */
11043
11305
  async locked(key, run) {
11044
11306
  const next = (this.locks.get(key) ?? Promise.resolve()).then(run, run);
@@ -11188,6 +11450,14 @@ var LibraryStore = class {
11188
11450
  return entries;
11189
11451
  }
11190
11452
  };
11453
+ /** Genre names: the language asked for, else the server's, else whichever language the source answered. */
11454
+ function genresOf(details, requested, serverDefault) {
11455
+ for (const key of [languageKey(requested), languageKey(serverDefault)]) {
11456
+ const found = key === void 0 ? void 0 : details.genres[key];
11457
+ if (found !== void 0) return found;
11458
+ }
11459
+ return Object.values(details.genres)[0] ?? [];
11460
+ }
11191
11461
  function toProgress(row) {
11192
11462
  return {
11193
11463
  itemId: row.itemId,
@@ -11206,7 +11476,7 @@ function toFileInfo(file) {
11206
11476
  probed: file.probeOk
11207
11477
  };
11208
11478
  }
11209
- function toSummary(row, file, progress, title) {
11479
+ function toSummary(row, file, progress, title, watchlisted) {
11210
11480
  return {
11211
11481
  id: row.id,
11212
11482
  kind: row.kind,
@@ -11219,7 +11489,8 @@ function toSummary(row, file, progress, title) {
11219
11489
  addedAt: row.addedAt,
11220
11490
  durationMs: file?.durationMs ?? null,
11221
11491
  playable: row.kind !== "series" && file !== void 0,
11222
- progress: progress === void 0 ? null : toProgress(progress)
11492
+ progress: progress === void 0 ? null : toProgress(progress),
11493
+ ...watchlisted === void 0 ? {} : { watchlisted }
11223
11494
  };
11224
11495
  }
11225
11496
  //#endregion
@@ -12506,6 +12777,103 @@ var ServerLanguage = class {
12506
12777
  }
12507
12778
  };
12508
12779
  //#endregion
12780
+ //#region src/remote-fetch.ts
12781
+ var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
12782
+ var IMAGE_TIMEOUT_MS = 2e4;
12783
+ var MAX_REDIRECTS = 3;
12784
+ /** Read a response body, aborting as soon as it passes `cap`: the rest is never buffered. */
12785
+ async function readCapped(response, cap) {
12786
+ if (Number(response.headers.get("content-length") ?? "0") > cap) throw new Error("image too large");
12787
+ if (response.body === null) return Buffer.alloc(0);
12788
+ const reader = response.body.getReader();
12789
+ const chunks = [];
12790
+ let total = 0;
12791
+ for (;;) {
12792
+ const { done, value } = await reader.read();
12793
+ if (done) break;
12794
+ total += value.byteLength;
12795
+ if (total > cap) {
12796
+ await reader.cancel();
12797
+ throw new Error("image too large");
12798
+ }
12799
+ chunks.push(Buffer.from(value));
12800
+ }
12801
+ return Buffer.concat(chunks, total);
12802
+ }
12803
+ function v4Private(address) {
12804
+ const [a = 0, b = 0] = address.split(".").map(Number);
12805
+ return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a >= 224;
12806
+ }
12807
+ /** Loopback, private, link-local, ULA, CGNAT, multicast and unspecified addresses, v4 and v6. */
12808
+ function isPrivateAddress(address) {
12809
+ const kind = (0, node_net.isIP)(address);
12810
+ if (kind === 4) return v4Private(address);
12811
+ if (kind !== 6) return true;
12812
+ const lower = address.toLowerCase();
12813
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
12814
+ if (mapped?.[1] !== void 0) return v4Private(mapped[1]);
12815
+ if (lower === "::" || lower === "::1") return true;
12816
+ return /^(fe[89ab]|f[cd]|ff)/.test(lower);
12817
+ }
12818
+ var resolveAll = async (host) => (await (0, node_dns_promises.lookup)(host, { all: true })).map((entry) => entry.address);
12819
+ /** The server asked to slow down. `retryAfterMs` is its `Retry-After`, or `null` when it named none. The message keeps the `HTTP 429` wording. */
12820
+ var RateLimitedError = class extends Error {
12821
+ retryAfterMs;
12822
+ constructor(retryAfterMs) {
12823
+ super("HTTP 429");
12824
+ this.retryAfterMs = retryAfterMs;
12825
+ this.name = "RateLimitedError";
12826
+ }
12827
+ };
12828
+ /** `Retry-After` as milliseconds: delta-seconds or an HTTP date; `null` when absent or unreadable. */
12829
+ function retryAfterMsOf(value, now = Date.now()) {
12830
+ if (value === null || value.trim() === "") return null;
12831
+ const seconds = Number(value);
12832
+ if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds * 1e3));
12833
+ const at = Date.parse(value);
12834
+ return Number.isNaN(at) ? null : Math.max(0, at - now);
12835
+ }
12836
+ /**
12837
+ * https only, at most 3 redirects each re-validated, every address the host resolves to must be
12838
+ * public, no credential, a bounded time and a streamed size cap.
12839
+ * A resolver answer can differ from the one `fetch` gets (rebinding): the host check narrows, not closes, that window.
12840
+ */
12841
+ function createRemoteFetch(deps = {}) {
12842
+ const doFetch = deps.fetchImpl ?? fetch;
12843
+ const resolve = deps.resolve ?? resolveAll;
12844
+ return async (start, init) => {
12845
+ let url = start;
12846
+ const startOrigin = isRemoteUrl(start) ? new URL(start).origin : "";
12847
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
12848
+ if (!isRemoteUrl(url)) throw new Error("only an https URL is fetched");
12849
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
12850
+ const addresses = (0, node_net.isIP)(host) === 0 ? await resolve(host) : [host];
12851
+ if (addresses.length === 0 || addresses.some(isPrivateAddress)) throw new Error("host refused: not a public address");
12852
+ const sameOrigin = new URL(url).origin === startOrigin;
12853
+ const response = await doFetch(url, {
12854
+ redirect: "manual",
12855
+ ...sameOrigin && init?.headers !== void 0 ? { headers: { ...init.headers } } : {},
12856
+ ...hop === 0 && init?.body !== void 0 ? {
12857
+ method: "POST",
12858
+ body: init.body
12859
+ } : {},
12860
+ signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
12861
+ });
12862
+ if (response.status >= 300 && response.status < 400) {
12863
+ const location = response.headers.get("location");
12864
+ if (location === null) throw new Error("redirect without a location");
12865
+ url = new URL(location, url).toString();
12866
+ continue;
12867
+ }
12868
+ if (response.status === 429) throw new RateLimitedError(retryAfterMsOf(response.headers.get("retry-after")));
12869
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
12870
+ return readCapped(response, MAX_IMAGE_BYTES);
12871
+ }
12872
+ throw new Error("too many redirects");
12873
+ };
12874
+ }
12875
+ var httpRemoteFetch = createRemoteFetch();
12876
+ //#endregion
12509
12877
  //#region src/tmdb.ts
12510
12878
  var TMDB_ID = "tmdb";
12511
12879
  var API$2 = "https://api.themoviedb.org/3";
@@ -12529,6 +12897,36 @@ var TranslationsSchema = object({ translations: array(object({
12529
12897
  overview: string().nullish()
12530
12898
  }).nullish()
12531
12899
  })) });
12900
+ var PersonSchema = object({
12901
+ id: number().int(),
12902
+ name: string().nullish(),
12903
+ profile_path: string().nullish()
12904
+ });
12905
+ /** A cast entry: a movie's `character`, a series' `roles[]` (aggregate credits), a guest star's `character`. */
12906
+ var CastEntrySchema = PersonSchema.extend({
12907
+ character: string().nullish(),
12908
+ roles: array(object({ character: string().nullish() })).nullish(),
12909
+ order: number().int().nullish()
12910
+ });
12911
+ /** A crew entry: a movie's `job`, a series' `jobs[]` (aggregate credits). */
12912
+ var CrewEntrySchema = PersonSchema.extend({
12913
+ job: string().nullish(),
12914
+ jobs: array(object({ job: string().nullish() })).nullish()
12915
+ });
12916
+ var CreditsSchema = object({
12917
+ cast: array(CastEntrySchema).nullish(),
12918
+ crew: array(CrewEntrySchema).nullish()
12919
+ });
12920
+ /** `release_dates` (movie): per country, a list of releases that may carry a certification. */
12921
+ var ReleaseDatesSchema = object({ results: array(object({
12922
+ iso_3166_1: string(),
12923
+ release_dates: array(object({ certification: string().nullish() }))
12924
+ })) });
12925
+ /** `content_ratings` (series): one rating per country. */
12926
+ var ContentRatingsSchema = object({ results: array(object({
12927
+ iso_3166_1: string(),
12928
+ rating: string().nullish()
12929
+ })) });
12532
12930
  var DetailsSchema = object({
12533
12931
  id: number().int(),
12534
12932
  title: string().nullish(),
@@ -12544,7 +12942,15 @@ var DetailsSchema = object({
12544
12942
  tvdb_id: number().int().nullish()
12545
12943
  }).nullish(),
12546
12944
  seasons: array(object({ season_number: number().int() })).nullish(),
12547
- translations: TranslationsSchema.nullish()
12945
+ translations: TranslationsSchema.nullish(),
12946
+ genres: array(object({ name: string().nullish() })).nullish(),
12947
+ runtime: number().nullish(),
12948
+ episode_run_time: array(number()).nullish(),
12949
+ created_by: array(PersonSchema).nullish(),
12950
+ credits: CreditsSchema.nullish(),
12951
+ aggregate_credits: CreditsSchema.nullish(),
12952
+ release_dates: ReleaseDatesSchema.nullish(),
12953
+ content_ratings: ContentRatingsSchema.nullish()
12548
12954
  });
12549
12955
  var FindSchema = object({
12550
12956
  movie_results: array(object({ id: number().int() })).default([]),
@@ -12555,11 +12961,18 @@ var SeasonSchema = object({ episodes: array(object({
12555
12961
  episode_number: number().int(),
12556
12962
  name: string().nullish(),
12557
12963
  overview: string().nullish(),
12558
- still_path: string().nullish()
12964
+ still_path: string().nullish(),
12965
+ runtime: number().nullish(),
12966
+ guest_stars: array(CastEntrySchema).nullish(),
12967
+ crew: array(CrewEntrySchema).nullish()
12559
12968
  })) });
12560
- /** TMDB's tag for a locale: English keeps the region it was always asked in, others are sent bare. */
12561
- function tmdbLanguageOf(locale) {
12562
- return locale === "en" ? DEFAULT_LANGUAGE : locale;
12969
+ /** Waited when TMDB says 429 and names no time. */
12970
+ var TMDB_DEFAULT_RETRY_WAIT_MS = 2e3;
12971
+ /** TMDB's tag for a content language: English keeps the region it was always asked in, Chinese is the simplified catalogue, others are sent bare. */
12972
+ function tmdbLanguageOf(language) {
12973
+ if (language === "en") return DEFAULT_LANGUAGE;
12974
+ if (language === "zh") return "zh-CN";
12975
+ return language;
12563
12976
  }
12564
12977
  function yearOf$1(date) {
12565
12978
  const match = /^(\d{4})/.exec(date ?? "");
@@ -12591,23 +13004,130 @@ function translationsOf(details) {
12591
13004
  }
12592
13005
  return out;
12593
13006
  }
13007
+ /** The region a rating is read for: the server language's own country (`it` is IT), US when unknown. */
13008
+ var REGION_OF_LANGUAGE = {
13009
+ en: "US",
13010
+ it: "IT",
13011
+ de: "DE",
13012
+ fr: "FR",
13013
+ es: "ES",
13014
+ pt: "PT",
13015
+ nl: "NL",
13016
+ ja: "JP",
13017
+ zh: "CN",
13018
+ ru: "RU",
13019
+ pl: "PL"
13020
+ };
13021
+ function tmdbRegionOf(language) {
13022
+ return (/^[A-Za-z]{2,3}[-_]([A-Za-z]{2})$/.exec(language)?.[1] ?? REGION_OF_LANGUAGE[languageKey(language) ?? ""] ?? "US").toUpperCase();
13023
+ }
13024
+ var photoOf = (path) => image("w185", path);
13025
+ var positive = (value) => value !== null && value !== void 0 && value > 0 ? Math.round(value) : null;
13026
+ function personsOf(crew, jobs) {
13027
+ const out = [];
13028
+ for (const entry of crew ?? []) {
13029
+ const held = [entry.job, ...(entry.jobs ?? []).map((job) => job.job)];
13030
+ const name = text(entry.name);
13031
+ if (name === null || !held.some((job) => job !== null && job !== void 0 && jobs.includes(job))) continue;
13032
+ if (out.some((person) => person.id === entry.id)) continue;
13033
+ out.push({
13034
+ id: entry.id,
13035
+ name,
13036
+ photo: photoOf(entry.profile_path)
13037
+ });
13038
+ }
13039
+ return out;
13040
+ }
13041
+ function castOf(cast) {
13042
+ const out = [];
13043
+ for (const [index, entry] of (cast ?? []).entries()) {
13044
+ const name = text(entry.name);
13045
+ if (name === null) continue;
13046
+ out.push({
13047
+ id: entry.id,
13048
+ name,
13049
+ photo: photoOf(entry.profile_path),
13050
+ character: text(entry.character ?? entry.roles?.[0]?.character),
13051
+ order: entry.order ?? index
13052
+ });
13053
+ }
13054
+ return out;
13055
+ }
13056
+ var DIRECTOR_JOBS = ["Director"];
13057
+ var WRITER_JOBS = [
13058
+ "Writer",
13059
+ "Screenplay",
13060
+ "Story",
13061
+ "Teleplay"
13062
+ ];
13063
+ /** Genres, runtime, rating, crew and cast of a details answer, all from the one call (`append_to_response`). */
13064
+ function itemDetailsOf(details, language, region) {
13065
+ const credits = details.credits ?? details.aggregate_credits;
13066
+ const names = (details.genres ?? []).flatMap((genre) => {
13067
+ const name = text(genre.name);
13068
+ return name === null ? [] : [name];
13069
+ });
13070
+ const key = languageKey(language);
13071
+ const certification = text(details.content_ratings?.results.find((entry) => entry.iso_3166_1 === region)?.rating) ?? details.release_dates?.results.find((entry) => entry.iso_3166_1 === region)?.release_dates.map((release) => text(release.certification)).find((value) => value !== null) ?? null;
13072
+ return {
13073
+ genres: key === void 0 || names.length === 0 ? {} : { [key]: names },
13074
+ runtimeMinutes: positive(details.runtime ?? details.episode_run_time?.[0]),
13075
+ certification,
13076
+ creators: (details.created_by ?? []).flatMap((entry) => {
13077
+ const name = text(entry.name);
13078
+ return name === null ? [] : [{
13079
+ id: entry.id,
13080
+ name,
13081
+ photo: photoOf(entry.profile_path)
13082
+ }];
13083
+ }),
13084
+ directors: personsOf(credits?.crew, DIRECTOR_JOBS),
13085
+ writers: personsOf(credits?.crew, WRITER_JOBS),
13086
+ cast: castOf(credits?.cast),
13087
+ guestStars: []
13088
+ };
13089
+ }
12594
13090
  var nameOf = (entry) => entry.title ?? entry.name ?? "";
12595
13091
  var yearIn = (entry) => yearOf$1(entry.release_date ?? entry.first_air_date);
12596
13092
  /** TMDB: movies and series, with the installation's own read token. All calls go through the shared remote fetch. */
12597
13093
  function createTmdbProvider(deps) {
12598
13094
  const language = deps.language ?? DEFAULT_LANGUAGE;
13095
+ const region = tmdbRegionOf(language);
12599
13096
  const headers = {
12600
13097
  Authorization: `Bearer ${deps.token}`,
12601
13098
  Accept: "application/json"
12602
13099
  };
12603
13100
  const segment = (kind) => kind === "movie" ? "movie" : "tv";
13101
+ const sleep = deps.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
13102
+ const clock = deps.now ?? Date.now;
13103
+ let nextSlot = 0;
13104
+ /** Reserve the next request slot, 50 ms after the previous one, and wait for it. */
13105
+ const pace = async () => {
13106
+ const slot = Math.max(clock(), nextSlot);
13107
+ nextSlot = slot + 50;
13108
+ const wait = slot - clock();
13109
+ if (wait > 0) await sleep(wait);
13110
+ };
13111
+ const get = async (url) => {
13112
+ await pace();
13113
+ try {
13114
+ return await deps.fetch(url, { headers });
13115
+ } catch (error) {
13116
+ if (!(error instanceof RateLimitedError)) throw error;
13117
+ const wait = error.retryAfterMs ?? TMDB_DEFAULT_RETRY_WAIT_MS;
13118
+ if (wait > 1e4) throw error;
13119
+ await sleep(wait);
13120
+ await pace();
13121
+ return deps.fetch(url, { headers });
13122
+ }
13123
+ };
12604
13124
  const call = async (path, query = {}) => {
12605
13125
  const params = new URLSearchParams({
12606
13126
  ...query,
12607
13127
  language
12608
13128
  });
12609
13129
  try {
12610
- const bytes = await deps.fetch(`${API$2}${path}?${params.toString()}`, { headers });
13130
+ const bytes = await get(`${API$2}${path}?${params.toString()}`);
12611
13131
  return JSON.parse(bytes.toString("utf8"));
12612
13132
  } catch (error) {
12613
13133
  if (error instanceof Error && /\b401\b/.test(error.message)) throw new ProviderAuthError(TMDB_REJECTED);
@@ -12625,11 +13145,12 @@ function createTmdbProvider(deps) {
12625
13145
  imdbId: text(details.external_ids?.imdb_id) ?? text(details.imdb_id),
12626
13146
  poster: image("w500", details.poster_path),
12627
13147
  fanart: image("w1280", details.backdrop_path),
12628
- translations: translationsOf(details)
13148
+ translations: translationsOf(details),
13149
+ details: itemDetailsOf(details, language, region)
12629
13150
  });
12630
13151
  const detailsOf = async (kind, id) => {
12631
13152
  try {
12632
- return matchOf(DetailsSchema.parse(await call(`/${segment(kind)}/${id}`, { append_to_response: "external_ids,translations" })));
13153
+ return matchOf(DetailsSchema.parse(await call(`/${segment(kind)}/${id}`, { append_to_response: kind === "movie" ? "external_ids,translations,credits,release_dates" : "external_ids,translations,aggregate_credits,content_ratings" })));
12633
13154
  } catch (error) {
12634
13155
  if (error instanceof Error && /\b404\b/.test(error.message)) return null;
12635
13156
  throw error;
@@ -12638,6 +13159,7 @@ function createTmdbProvider(deps) {
12638
13159
  return {
12639
13160
  id: TMDB_ID,
12640
13161
  translates: true,
13162
+ providesDetails: true,
12641
13163
  kinds: ["movie", "series"],
12642
13164
  lookupBy: [
12643
13165
  "tmdbId",
@@ -12678,7 +13200,17 @@ function createTmdbProvider(deps) {
12678
13200
  episode: entry.episode_number,
12679
13201
  title: text(entry.name),
12680
13202
  overview: text(entry.overview),
12681
- still: image("w300", entry.still_path)
13203
+ still: image("w300", entry.still_path),
13204
+ details: {
13205
+ genres: {},
13206
+ runtimeMinutes: positive(entry.runtime),
13207
+ certification: null,
13208
+ creators: [],
13209
+ directors: personsOf(entry.crew, DIRECTOR_JOBS),
13210
+ writers: personsOf(entry.crew, WRITER_JOBS),
13211
+ cast: [],
13212
+ guestStars: castOf(entry.guest_stars)
13213
+ }
12682
13214
  });
12683
13215
  }
12684
13216
  return out;
@@ -12986,85 +13518,6 @@ function createTvmazeProvider(deps) {
12986
13518
  };
12987
13519
  }
12988
13520
  //#endregion
12989
- //#region src/remote-fetch.ts
12990
- var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
12991
- var IMAGE_TIMEOUT_MS = 2e4;
12992
- var MAX_REDIRECTS = 3;
12993
- /** Read a response body, aborting as soon as it passes `cap`: the rest is never buffered. */
12994
- async function readCapped(response, cap) {
12995
- if (Number(response.headers.get("content-length") ?? "0") > cap) throw new Error("image too large");
12996
- if (response.body === null) return Buffer.alloc(0);
12997
- const reader = response.body.getReader();
12998
- const chunks = [];
12999
- let total = 0;
13000
- for (;;) {
13001
- const { done, value } = await reader.read();
13002
- if (done) break;
13003
- total += value.byteLength;
13004
- if (total > cap) {
13005
- await reader.cancel();
13006
- throw new Error("image too large");
13007
- }
13008
- chunks.push(Buffer.from(value));
13009
- }
13010
- return Buffer.concat(chunks, total);
13011
- }
13012
- function v4Private(address) {
13013
- const [a = 0, b = 0] = address.split(".").map(Number);
13014
- return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a >= 224;
13015
- }
13016
- /** Loopback, private, link-local, ULA, CGNAT, multicast and unspecified addresses, v4 and v6. */
13017
- function isPrivateAddress(address) {
13018
- const kind = (0, node_net.isIP)(address);
13019
- if (kind === 4) return v4Private(address);
13020
- if (kind !== 6) return true;
13021
- const lower = address.toLowerCase();
13022
- const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
13023
- if (mapped?.[1] !== void 0) return v4Private(mapped[1]);
13024
- if (lower === "::" || lower === "::1") return true;
13025
- return /^(fe[89ab]|f[cd]|ff)/.test(lower);
13026
- }
13027
- var resolveAll = async (host) => (await (0, node_dns_promises.lookup)(host, { all: true })).map((entry) => entry.address);
13028
- /**
13029
- * https only, at most 3 redirects each re-validated, every address the host resolves to must be
13030
- * public, no credential, a bounded time and a streamed size cap.
13031
- * A resolver answer can differ from the one `fetch` gets (rebinding): the host check narrows, not closes, that window.
13032
- */
13033
- function createRemoteFetch(deps = {}) {
13034
- const doFetch = deps.fetchImpl ?? fetch;
13035
- const resolve = deps.resolve ?? resolveAll;
13036
- return async (start, init) => {
13037
- let url = start;
13038
- const startOrigin = isRemoteUrl(start) ? new URL(start).origin : "";
13039
- for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
13040
- if (!isRemoteUrl(url)) throw new Error("only an https URL is fetched");
13041
- const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
13042
- const addresses = (0, node_net.isIP)(host) === 0 ? await resolve(host) : [host];
13043
- if (addresses.length === 0 || addresses.some(isPrivateAddress)) throw new Error("host refused: not a public address");
13044
- const sameOrigin = new URL(url).origin === startOrigin;
13045
- const response = await doFetch(url, {
13046
- redirect: "manual",
13047
- ...sameOrigin && init?.headers !== void 0 ? { headers: { ...init.headers } } : {},
13048
- ...hop === 0 && init?.body !== void 0 ? {
13049
- method: "POST",
13050
- body: init.body
13051
- } : {},
13052
- signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
13053
- });
13054
- if (response.status >= 300 && response.status < 400) {
13055
- const location = response.headers.get("location");
13056
- if (location === null) throw new Error("redirect without a location");
13057
- url = new URL(location, url).toString();
13058
- continue;
13059
- }
13060
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
13061
- return readCapped(response, MAX_IMAGE_BYTES);
13062
- }
13063
- throw new Error("too many redirects");
13064
- };
13065
- }
13066
- var httpRemoteFetch = createRemoteFetch();
13067
- //#endregion
13068
13521
  //#region src/img-plane.ts
13069
13522
  var FAILED_GRAB_TTL_MS = 30 * 6e4;
13070
13523
  var FAILED_GRAB_MAX = 500;
@@ -13085,8 +13538,17 @@ function typeOf(bytes) {
13085
13538
  if (bytes.length > 12 && bytes.subarray(8, 12).toString("latin1") === "WEBP") return "image/webp";
13086
13539
  return null;
13087
13540
  }
13088
- /** The remote URL of an arr cover: only a path on the arr's own origin, never another host. */
13541
+ /**
13542
+ * The remote URL of an arr cover: a path on the arr's own origin, or an absolute URL that already
13543
+ * IS on that origin (the arr app answers plain http on a LAN). Never another host, port or scheme,
13544
+ * and never a URL that carries credentials.
13545
+ */
13089
13546
  function coverUrl(source, path) {
13547
+ if (/^https?:\/\//i.test(path)) {
13548
+ const absolute = URL.canParse(path) ? new URL(path) : null;
13549
+ const own = new URL(source.baseUrl);
13550
+ return absolute !== null && absolute.origin === own.origin && absolute.username === "" && absolute.password === "" ? absolute.toString() : null;
13551
+ }
13090
13552
  if (!path.startsWith("/") || path.startsWith("//")) return null;
13091
13553
  const base = new URL(source.baseUrl);
13092
13554
  const url = new URL(`${source.baseUrl}${path}`);
@@ -13217,7 +13679,7 @@ function createImagePlaneHandler(deps) {
13217
13679
  } catch {
13218
13680
  return end(res, 404);
13219
13681
  }
13220
- if (parts.length !== 2 || !isItemId(itemId) || which !== "poster" && which !== "fanart") {
13682
+ if (parts.length !== 2 || !isItemId(itemId) || !isImageKind(which)) {
13221
13683
  deps.logger.warn("image request refused", { meta: { reason: "bad-request" } });
13222
13684
  return end(res, 404);
13223
13685
  }
@@ -13372,6 +13834,9 @@ function createMediaLibraryProvider(store, scans) {
13372
13834
  getItem: ({ itemId, language, caller }) => store.getItem(caller.userId, itemId, language),
13373
13835
  search: ({ query, limit, language, caller }) => store.search(caller.userId, query, limit, language),
13374
13836
  listRecentlyAdded: ({ limit, language, caller }) => store.listRecentlyAdded(caller.userId, limit, language),
13837
+ listWatchlist: ({ limit, offset, language, caller }) => store.listWatchlist(caller.userId, limit, offset, language),
13838
+ setWatchlisted: ({ itemId, on, caller }) => store.setWatchlisted(caller.userId, itemId, on),
13839
+ getItemDetails: ({ itemId, language }) => store.getItemDetails(itemId, language),
13375
13840
  getProgress: ({ itemId, caller }) => store.getProgress(caller.userId, itemId),
13376
13841
  setProgress: ({ caller, ...input }) => store.setProgress(caller.userId, input),
13377
13842
  markWatched: ({ caller, ...input }) => store.markWatched(caller.userId, input),
@@ -13392,6 +13857,7 @@ function fill(into, from) {
13392
13857
  year: into.year ?? from.year,
13393
13858
  overview: into.overview ?? from.overview,
13394
13859
  translations: into.translations ?? from.translations,
13860
+ details: into.details ?? from.details,
13395
13861
  tvdbId: into.tvdbId ?? from.tvdbId,
13396
13862
  tmdbId: into.tmdbId ?? from.tmdbId,
13397
13863
  imdbId: into.imdbId ?? from.imdbId,
@@ -13553,7 +14019,10 @@ var Enricher = class {
13553
14019
  cachedMatch(provider, key) {
13554
14020
  const known = this.deps.cache.getMatch(key);
13555
14021
  if (known === null) return null;
13556
- return known.found && provider.translates === true && known.match.translations === void 0 ? null : known;
14022
+ if (!known.found) return known;
14023
+ const predatesTranslations = provider.translates === true && known.match.translations === void 0;
14024
+ const predatesDetails = provider.providesDetails === true && known.match.details === void 0;
14025
+ return predatesTranslations || predatesDetails ? null : known;
13557
14026
  }
13558
14027
  /** A pinned id is asked for directly: an answer of "nothing" is final, never turned into a title guess. */
13559
14028
  async lookup(provider, ask, item, kind, pin) {
@@ -13633,14 +14102,15 @@ var Enricher = class {
13633
14102
  async episodesOf(provider, item, match) {
13634
14103
  const key = `${this.keyOf(provider)}:eps:${match.remoteId}`;
13635
14104
  const known = this.deps.cache.getEpisodes(key);
13636
- if (known !== null) return known.episodes;
14105
+ const predatesDetails = provider.providesDetails === true && known !== null && known.episodes.some((entry) => entry.details === void 0);
14106
+ if (known !== null && !predatesDetails) return known.episodes;
13637
14107
  try {
13638
14108
  const episodes = await provider.episodes(match);
13639
14109
  this.deps.cache.putEpisodes(key, { episodes: [...episodes] });
13640
14110
  return episodes;
13641
14111
  } catch (error) {
13642
14112
  this.failed(provider.id, item.id, error);
13643
- return [];
14113
+ return known?.episodes ?? [];
13644
14114
  }
13645
14115
  }
13646
14116
  async onlineLayer(provider, item, acc, resolved, held) {
@@ -13654,6 +14124,7 @@ var Enricher = class {
13654
14124
  year: match.year,
13655
14125
  overview: match.overview,
13656
14126
  translations: match.translations ?? null,
14127
+ details: match.details ?? null,
13657
14128
  tvdbId: match.tvdbId,
13658
14129
  tmdbId: match.tmdbId,
13659
14130
  imdbId: match.imdbId,
@@ -13676,15 +14147,16 @@ var Enricher = class {
13676
14147
  ...NO_LOCAL,
13677
14148
  title: found.title,
13678
14149
  overview: found.overview,
13679
- poster: found.still
14150
+ poster: found.still,
14151
+ details: found.details ?? null
13680
14152
  };
13681
14153
  }
13682
14154
  canAsk(provider, item) {
13683
14155
  return provider.kinds.includes(item.kind === "movie" ? "movie" : "series");
13684
14156
  }
13685
14157
  needsOnline(provider, item, acc) {
13686
- if (item.kind === "episode") return acc.overview === null || acc.poster === null || item.titlePlaceholder && acc.title === null;
13687
- return acc.overview === null || acc.poster === null || provider.translates === true && acc.translations === null;
14158
+ if (item.kind === "episode") return acc.overview === null || acc.poster === null || provider.providesDetails === true && acc.details === null || item.titlePlaceholder && acc.title === null;
14159
+ return acc.overview === null || acc.poster === null || provider.translates === true && acc.translations === null || provider.providesDetails === true && acc.details === null;
13688
14160
  }
13689
14161
  async localLayer(item, firstEpisodeFile) {
13690
14162
  const { reader } = this.deps;
@@ -13733,6 +14205,7 @@ var Enricher = class {
13733
14205
  year: acc.year,
13734
14206
  overview: acc.overview,
13735
14207
  translations: acc.translations,
14208
+ details: acc.details,
13736
14209
  tvdbId: acc.tvdbId,
13737
14210
  tmdbId: acc.tmdbId,
13738
14211
  imdbId: acc.imdbId,
@@ -13774,6 +14247,7 @@ function newItem(base) {
13774
14247
  episodeNumber: null,
13775
14248
  overview: null,
13776
14249
  translations: null,
14250
+ details: null,
13777
14251
  tvdbId: null,
13778
14252
  tmdbId: null,
13779
14253
  imdbId: null,
@@ -14125,6 +14599,7 @@ async function scanLibrary(deps, sources) {
14125
14599
  const { addedHint, titlePlaceholder: _placeholder, ...fields } = item;
14126
14600
  writes.push({
14127
14601
  ...fields,
14602
+ details: fields.details ?? previous?.details ?? null,
14128
14603
  addedAt: previous?.addedAt ?? addedHint ?? startedAt,
14129
14604
  seenAt: startedAt
14130
14605
  });
@@ -14201,6 +14676,7 @@ async function scanLibrary(deps, sources) {
14201
14676
  const stale = [...existingItems.values()].filter((item) => item.sourceId === entry.sourceId && !seenIds.has(item.id));
14202
14677
  if (stale.length === 0) continue;
14203
14678
  await db.deleteWhere(ITEMS, { whereIn: { id: stale.map((item) => item.id) } });
14679
+ await db.deleteWhere(WATCHLIST, { whereIn: { itemId: stale.map((item) => item.id) } });
14204
14680
  logger.info("items no longer in their source were removed", { meta: {
14205
14681
  sourceId: entry.sourceId,
14206
14682
  removed: stale.length