@dominevo/addon-media-library 0.1.7 → 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.
@@ -8807,7 +8807,12 @@ var MediaItemSummarySchema = /* @__PURE__ */ object({
8807
8807
  /** False when the catalogue lists it but no playable file is on disk. */
8808
8808
  playable: /* @__PURE__ */ boolean(),
8809
8809
  /** The caller's progress; `null` when they have none. Absent on a catalogue-only row (series). */
8810
- progress: /* @__PURE__ */ MediaProgressSchema.nullable()
8810
+ progress: /* @__PURE__ */ MediaProgressSchema.nullable(),
8811
+ /**
8812
+ * The caller's watchlist state, on series and movie rows (list, get and search). Absent on an
8813
+ * episode, which cannot be watchlisted.
8814
+ */
8815
+ watchlisted: /* @__PURE__ */ boolean().optional()
8811
8816
  });
8812
8817
  /** An episode of a season list: the summary plus its plot, read in the same query. */
8813
8818
  var MediaEpisodeSummarySchema = /* @__PURE__ */ MediaItemSummarySchema.extend({ overview: /* @__PURE__ */ string().nullable() });
@@ -8837,6 +8842,41 @@ var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8837
8842
  playPath: /* @__PURE__ */ string().nullable(),
8838
8843
  file: /* @__PURE__ */ LibraryFileInfoSchema.nullable()
8839
8844
  });
8845
+ /**
8846
+ * A person of an item's credits. `photoPath` is an image-plane handle relative to the hub origin
8847
+ * (the same plane that serves posters), `null` when the source has no photo: a provider's own URL
8848
+ * never leaves the addon.
8849
+ */
8850
+ var MediaPersonSchema = /* @__PURE__ */ object({
8851
+ /** The metadata source's id of the person. */
8852
+ id: /* @__PURE__ */ number().int(),
8853
+ name: /* @__PURE__ */ string(),
8854
+ photoPath: /* @__PURE__ */ string().nullable()
8855
+ });
8856
+ var MediaCastMemberSchema = /* @__PURE__ */ MediaPersonSchema.extend({
8857
+ /** The role played; `null` when the source names none. */
8858
+ character: /* @__PURE__ */ string().nullable(),
8859
+ /** Billing order, 0 first. */
8860
+ order: /* @__PURE__ */ number().int().nonnegative()
8861
+ });
8862
+ /**
8863
+ * What the metadata source holds about an item beyond its plot. Nothing fetched yet answers empty
8864
+ * arrays and `null`s; a failed re-fetch never replaces what is stored.
8865
+ */
8866
+ var MediaItemDetailsSchema = /* @__PURE__ */ object({
8867
+ itemId: /* @__PURE__ */ string(),
8868
+ genres: /* @__PURE__ */ array(/* @__PURE__ */ string()).readonly(),
8869
+ /** `null` when the source does not know it. */
8870
+ runtimeMinutes: /* @__PURE__ */ number().int().positive().nullable(),
8871
+ /** The age rating for the server's region (`PG-13`, `TV-MA`, `12`), or `null`. */
8872
+ certification: /* @__PURE__ */ string().nullable(),
8873
+ creators: /* @__PURE__ */ array(MediaPersonSchema).readonly(),
8874
+ directors: /* @__PURE__ */ array(MediaPersonSchema).readonly(),
8875
+ writers: /* @__PURE__ */ array(MediaPersonSchema).readonly(),
8876
+ cast: /* @__PURE__ */ array(MediaCastMemberSchema).readonly(),
8877
+ /** Episodes only; empty on a series or a movie. */
8878
+ guestStars: /* @__PURE__ */ array(MediaCastMemberSchema).readonly()
8879
+ });
8840
8880
  var MediaSeasonSchema = /* @__PURE__ */ object({
8841
8881
  seasonNumber: /* @__PURE__ */ number().int(),
8842
8882
  episodeCount: /* @__PURE__ */ number().int().nonnegative(),
@@ -8904,6 +8944,24 @@ var mediaLibraryCapability = {
8904
8944
  limit: /* @__PURE__ */ number().int().positive().max(100).optional(),
8905
8945
  language: LanguageInputSchema
8906
8946
  }), /* @__PURE__ */ array(MediaItemSummarySchema).readonly(), { caller: "required" }),
8947
+ /** The caller's series and movies they watchlisted, the latest added first. */
8948
+ listWatchlist: /* @__PURE__ */ method(PageInputSchema, MediaItemPageSchema, { caller: "required" }),
8949
+ /**
8950
+ * Put a series or a movie on the caller's watchlist, or take it off. Idempotent: the answer is the
8951
+ * state now. An episode is refused (`watchlist-kind`).
8952
+ */
8953
+ setWatchlisted: /* @__PURE__ */ method(/* @__PURE__ */ object({
8954
+ itemId: /* @__PURE__ */ string().min(1),
8955
+ on: /* @__PURE__ */ boolean()
8956
+ }), /* @__PURE__ */ object({ on: /* @__PURE__ */ boolean() }), {
8957
+ kind: "mutation",
8958
+ caller: "required"
8959
+ }),
8960
+ /** Genres, runtime, rating, crew and cast of one item; `null` when the id is unknown. */
8961
+ getItemDetails: /* @__PURE__ */ method(/* @__PURE__ */ object({
8962
+ itemId: /* @__PURE__ */ string().min(1),
8963
+ language: LanguageInputSchema
8964
+ }), /* @__PURE__ */ MediaItemDetailsSchema.nullable(), { caller: "required" }),
8907
8965
  /** The caller's progress in one item; `null` when they have none. */
8908
8966
  getProgress: /* @__PURE__ */ method(/* @__PURE__ */ object({ itemId: /* @__PURE__ */ string().min(1) }), /* @__PURE__ */ MediaProgressSchema.nullable(), { caller: "required" }),
8909
8967
  /**
@@ -10046,6 +10104,71 @@ function parseRows(schema, rows, onInvalid) {
10046
10104
  return out;
10047
10105
  }
10048
10106
  //#endregion
10107
+ //#region src/item-details.ts
10108
+ /**
10109
+ * What a metadata source holds about one item beyond its plot: genres, runtime, rating, crew and
10110
+ * cast. Stored with the item (a JSON column), never handed to a client as is: a person's `photo` is
10111
+ * the SOURCE's https URL, and a client gets an image-plane handle instead (`personImageKey`).
10112
+ */
10113
+ var StoredPersonSchema = object({
10114
+ id: number().int(),
10115
+ name: string(),
10116
+ /** The source's https URL of the profile picture; `null` when it has none. Never sent to a client. */
10117
+ photo: string().nullable()
10118
+ });
10119
+ var StoredCastSchema = StoredPersonSchema.extend({
10120
+ character: string().nullable(),
10121
+ order: number().int().nonnegative()
10122
+ });
10123
+ var ItemDetailsSchema = object({
10124
+ /** Genre names by language tag (lower-case, as `translations`): a source answers them in the language it was asked. */
10125
+ genres: record(string(), array(string())),
10126
+ runtimeMinutes: number().int().positive().nullable(),
10127
+ certification: string().nullable(),
10128
+ creators: array(StoredPersonSchema),
10129
+ directors: array(StoredPersonSchema),
10130
+ writers: array(StoredPersonSchema),
10131
+ cast: array(StoredCastSchema),
10132
+ guestStars: array(StoredCastSchema)
10133
+ });
10134
+ var EMPTY_DETAILS = {
10135
+ genres: {},
10136
+ runtimeMinutes: null,
10137
+ certification: null,
10138
+ creators: [],
10139
+ directors: [],
10140
+ writers: [],
10141
+ cast: [],
10142
+ guestStars: []
10143
+ };
10144
+ var PERSON_KEY = /^person-(\d{1,12})$/;
10145
+ function personImageKey(personId) {
10146
+ return `person-${personId}`;
10147
+ }
10148
+ function isImageKind(value) {
10149
+ return value === "poster" || value === "fanart" || value !== void 0 && PERSON_KEY.test(value);
10150
+ }
10151
+ function isPersonPhotoUrl(value) {
10152
+ if (!URL.canParse(value)) return false;
10153
+ const url = new URL(value);
10154
+ return url.protocol === "https:" && url.hostname === "image.tmdb.org";
10155
+ }
10156
+ /** The person id an image key names, or `null` for a poster or a fanart. */
10157
+ function personIdOf(kind) {
10158
+ const found = PERSON_KEY.exec(kind);
10159
+ return found?.[1] === void 0 ? null : Number(found[1]);
10160
+ }
10161
+ /** The profile picture URL stored for `personId` among the credits of `details`, or `null`. */
10162
+ function personPhotoOf(details, personId) {
10163
+ return [
10164
+ ...details.cast,
10165
+ ...details.guestStars,
10166
+ ...details.creators,
10167
+ ...details.directors,
10168
+ ...details.writers
10169
+ ].find((person) => person.id === personId)?.photo ?? null;
10170
+ }
10171
+ //#endregion
10049
10172
  //#region src/metadata.ts
10050
10173
  /**
10051
10174
  * One language's text of an item: either field may be absent (a provider can translate the title and
@@ -10070,14 +10193,18 @@ var ProviderMatchSchema = object({
10070
10193
  poster: string().nullable(),
10071
10194
  fanart: string().nullable(),
10072
10195
  /** The title and overview in other languages, when the provider answered them with the match. */
10073
- translations: TranslationMapSchema.optional()
10196
+ translations: TranslationMapSchema.optional(),
10197
+ /** Genres, rating, crew and cast, answered with the match. Absent from a match cached before they were kept. */
10198
+ details: ItemDetailsSchema.optional()
10074
10199
  });
10075
10200
  var ProviderEpisodeSchema = object({
10076
10201
  season: number().int(),
10077
10202
  episode: number().int(),
10078
10203
  title: string().nullable(),
10079
10204
  overview: string().nullable(),
10080
- still: string().nullable()
10205
+ still: string().nullable(),
10206
+ /** The episode's own runtime, crew and guest stars, read from the season answer. Absent from a list cached before they were kept. */
10207
+ details: ItemDetailsSchema.optional()
10081
10208
  });
10082
10209
  /** The provider refused its credential: asking again cannot work until the operator fixes it. */
10083
10210
  var ProviderAuthError = class extends Error {
@@ -10199,6 +10326,7 @@ var ITEMS = "media-library:items";
10199
10326
  var FILES = "media-library:files";
10200
10327
  var PROGRESS = "media-library:progress";
10201
10328
  var PINS = "media-library:pins";
10329
+ var WATCHLIST = "media-library:watchlist";
10202
10330
  /** Item row: one series, movie or episode of the catalogue. */
10203
10331
  var ItemRowSchema = object({
10204
10332
  id: string(),
@@ -10213,6 +10341,8 @@ var ItemRowSchema = object({
10213
10341
  overview: string().nullable(),
10214
10342
  /** The title and overview in other languages; absent on a row written before they were kept. */
10215
10343
  translations: TranslationMapSchema.nullish(),
10344
+ /** Genres, rating, crew and cast; absent on a row written before they were kept, `null` when no source gave any. */
10345
+ details: ItemDetailsSchema.nullish(),
10216
10346
  tvdbId: number().int().nullable(),
10217
10347
  tmdbId: number().int().nullable(),
10218
10348
  imdbId: string().nullable(),
@@ -10258,6 +10388,12 @@ var ProgressRowSchema = object({
10258
10388
  updatedAt: number().int(),
10259
10389
  watched: boolean()
10260
10390
  });
10391
+ /** One series or movie a person put on their watchlist. */
10392
+ var WatchlistRowSchema = object({
10393
+ userId: string(),
10394
+ itemId: string(),
10395
+ addedAt: number().int()
10396
+ });
10261
10397
  var text$3 = (name, notNull = false) => ({
10262
10398
  name,
10263
10399
  type: "TEXT",
@@ -10287,6 +10423,10 @@ var COLLECTIONS = [
10287
10423
  name: "translations",
10288
10424
  type: "JSON"
10289
10425
  },
10426
+ {
10427
+ name: "details",
10428
+ type: "JSON"
10429
+ },
10290
10430
  int("tvdbId"),
10291
10431
  int("tmdbId"),
10292
10432
  text$3("imdbId"),
@@ -10386,6 +10526,20 @@ var COLLECTIONS = [
10386
10526
  "updatedAt"
10387
10527
  ]
10388
10528
  }]
10529
+ },
10530
+ {
10531
+ collection: WATCHLIST,
10532
+ primaryKey: ["userId", "itemId"],
10533
+ withoutRowid: true,
10534
+ columns: [
10535
+ text$3("userId", true),
10536
+ text$3("itemId", true),
10537
+ int("addedAt", true)
10538
+ ],
10539
+ indexes: [{
10540
+ name: "idx_media_watchlist_user",
10541
+ columns: ["userId", "addedAt"]
10542
+ }]
10389
10543
  }
10390
10544
  ];
10391
10545
  //#endregion
@@ -10653,6 +10807,7 @@ var NO_LOCAL = {
10653
10807
  year: null,
10654
10808
  overview: null,
10655
10809
  translations: null,
10810
+ details: null,
10656
10811
  tvdbId: null,
10657
10812
  tmdbId: null,
10658
10813
  imdbId: null,
@@ -10693,6 +10848,7 @@ function merge(first, second) {
10693
10848
  year: pick$1(first.year, second.year),
10694
10849
  overview: pick$1(first.overview, second.overview),
10695
10850
  translations: pick$1(first.translations, second.translations),
10851
+ details: pick$1(first.details, second.details),
10696
10852
  tvdbId: pick$1(first.tvdbId, second.tvdbId),
10697
10853
  tmdbId: pick$1(first.tmdbId, second.tmdbId),
10698
10854
  imdbId: pick$1(first.imdbId, second.imdbId),
@@ -10797,6 +10953,8 @@ var RECENT_DEFAULT_LIMIT = 20;
10797
10953
  var CONTINUE_DEFAULT_LIMIT = 20;
10798
10954
  /** A rewound row is not "continue", so the read asks for a few more than it will show. */
10799
10955
  var CONTINUE_OVERFETCH = 3;
10956
+ /** Item ids resolved per read when a watchlist is larger than one query takes. */
10957
+ var WATCHLIST_RESOLVE_CHUNK = 500;
10800
10958
  function playPathOf(itemId) {
10801
10959
  return `${HUB_PLANE_BASE}/${FILE_PLANE_PREFIX}/${itemId}`;
10802
10960
  }
@@ -10806,16 +10964,26 @@ function imagePathOf(itemId, which) {
10806
10964
  function isWatched(positionMs, durationMs) {
10807
10965
  return durationMs > 0 && positionMs / durationMs >= .9;
10808
10966
  }
10967
+ /** An episode cannot be watchlisted: the series is what a person follows. */
10968
+ var WatchlistKindError = class extends Error {
10969
+ code = "watchlist-kind";
10970
+ constructor(itemId) {
10971
+ super(`watchlist-kind: ${itemId} is an episode; only a series or a movie can be watchlisted`);
10972
+ this.name = "WatchlistKindError";
10973
+ }
10974
+ };
10809
10975
  var idList = (rows) => rows.map((row) => row.id);
10810
10976
  var LibraryStore = class {
10811
10977
  db;
10812
10978
  logger;
10813
10979
  serverLanguage;
10980
+ now;
10814
10981
  locks = /* @__PURE__ */ new Map();
10815
- constructor(db, logger, serverLanguage = () => "en") {
10982
+ constructor(db, logger, serverLanguage = () => "en", now = Date.now) {
10816
10983
  this.db = db;
10817
10984
  this.logger = logger;
10818
10985
  this.serverLanguage = serverLanguage;
10986
+ this.now = now;
10819
10987
  }
10820
10988
  async init() {
10821
10989
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -10836,6 +11004,9 @@ var LibraryStore = class {
10836
11004
  async queryFiles(filter) {
10837
11005
  return parseRows(FileRowSchema, await this.db.query(FILES, filter), this.invalid(FILES));
10838
11006
  }
11007
+ async queryWatchlist(filter) {
11008
+ return parseRows(WatchlistRowSchema, await this.db.query(WATCHLIST, filter), this.invalid(WATCHLIST));
11009
+ }
10839
11010
  async queryProgress(filter) {
10840
11011
  return parseRows(ProgressRowSchema, await this.db.query(PROGRESS, filter), this.invalid(PROGRESS));
10841
11012
  }
@@ -10850,9 +11021,15 @@ var LibraryStore = class {
10850
11021
  where: { userId },
10851
11022
  whereIn: { itemId: playableIds }
10852
11023
  })) progress.set(entry.itemId, entry);
11024
+ const followable = rows.filter((row) => row.kind !== "episode").map((row) => row.id);
11025
+ const watchlisted = /* @__PURE__ */ new Set();
11026
+ if (followable.length > 0) for (const entry of await this.queryWatchlist({
11027
+ where: { userId },
11028
+ whereIn: { itemId: followable }
11029
+ })) watchlisted.add(entry.itemId);
10853
11030
  const fallback = this.serverLanguage();
10854
11031
  return rows.map((row) => {
10855
- return toSummary(row, row.filePath === null ? void 0 : files.get(row.filePath), progress.get(row.id), resolveItemText(row, language, fallback).title);
11032
+ 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));
10856
11033
  });
10857
11034
  }
10858
11035
  pageOf = async (kind, userId, limit, offset, language) => {
@@ -10997,6 +11174,14 @@ var LibraryStore = class {
10997
11174
  limit: 1
10998
11175
  });
10999
11176
  if (item === void 0) return [];
11177
+ const personId = personIdOf(which);
11178
+ if (personId !== null) {
11179
+ const photo = item.details === null || item.details === void 0 ? null : personPhotoOf(item.details, personId);
11180
+ return photo !== null && isPersonPhotoUrl(photo) ? [{
11181
+ kind: "remote",
11182
+ url: photo
11183
+ }] : [];
11184
+ }
11000
11185
  const out = [];
11001
11186
  const cover = which === "poster" ? item.posterSource : item.fanartSource;
11002
11187
  if (cover !== null) {
@@ -11032,6 +11217,86 @@ var LibraryStore = class {
11032
11217
  }
11033
11218
  return out;
11034
11219
  }
11220
+ /** The caller's series and movies on their watchlist, the latest added first. */
11221
+ async listWatchlist(userId, limit, offset, language) {
11222
+ 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));
11223
+ if (held.length === 0) return {
11224
+ items: [],
11225
+ total: 0
11226
+ };
11227
+ const rows = /* @__PURE__ */ new Map();
11228
+ for (let at = 0; at < held.length; at += WATCHLIST_RESOLVE_CHUNK) {
11229
+ const ids = held.slice(at, at + WATCHLIST_RESOLVE_CHUNK).map((entry) => entry.itemId);
11230
+ for (const row of await this.queryItems({ whereIn: { id: ids } })) rows.set(row.id, row);
11231
+ }
11232
+ const resolved = held.flatMap((entry) => {
11233
+ const row = rows.get(entry.itemId);
11234
+ return row === void 0 ? [] : [row];
11235
+ });
11236
+ const start = offset ?? 0;
11237
+ const ordered = resolved.slice(start, start + (limit ?? 100));
11238
+ const total = resolved.length;
11239
+ return {
11240
+ items: await this.summaries(ordered, userId, language),
11241
+ total
11242
+ };
11243
+ }
11244
+ /** Put a series or a movie on the caller's watchlist, or take it off. Idempotent; an episode is refused. */
11245
+ setWatchlisted(userId, itemId, on) {
11246
+ return this.locked(`watchlist\u0000${userId}\u0000${itemId}`, async () => {
11247
+ if ((await this.requirePlayable(itemId)).kind === "episode") throw new WatchlistKindError(itemId);
11248
+ if (!on) {
11249
+ await this.db.deleteWhere(WATCHLIST, { where: {
11250
+ userId,
11251
+ itemId
11252
+ } });
11253
+ return { on: false };
11254
+ }
11255
+ const [held] = await this.queryWatchlist({
11256
+ where: {
11257
+ userId,
11258
+ itemId
11259
+ },
11260
+ limit: 1
11261
+ });
11262
+ if (held === void 0) await this.db.upsertMany(WATCHLIST, ["userId", "itemId"], [{
11263
+ userId,
11264
+ itemId,
11265
+ addedAt: this.now()
11266
+ }]);
11267
+ return { on: true };
11268
+ });
11269
+ }
11270
+ /** Genres, runtime, rating, crew and cast of one item, in the reader's language; empty when nothing was fetched. */
11271
+ async getItemDetails(itemId, language) {
11272
+ const [row] = await this.queryItems({
11273
+ where: { id: itemId },
11274
+ limit: 1
11275
+ });
11276
+ if (row === void 0) return null;
11277
+ const details = row.details ?? EMPTY_DETAILS;
11278
+ const person = (entry) => ({
11279
+ id: entry.id,
11280
+ name: entry.name,
11281
+ photoPath: entry.photo === null || !isPersonPhotoUrl(entry.photo) ? null : imagePathOf(row.id, personImageKey(entry.id))
11282
+ });
11283
+ const member = (entry) => ({
11284
+ ...person(entry),
11285
+ character: entry.character,
11286
+ order: entry.order
11287
+ });
11288
+ return {
11289
+ itemId: row.id,
11290
+ genres: genresOf(details, language, this.serverLanguage()),
11291
+ runtimeMinutes: details.runtimeMinutes,
11292
+ certification: details.certification,
11293
+ creators: details.creators.map(person),
11294
+ directors: details.directors.map(person),
11295
+ writers: details.writers.map(person),
11296
+ cast: details.cast.map(member),
11297
+ guestStars: details.guestStars.map(member)
11298
+ };
11299
+ }
11035
11300
  /** Serialise the read-compare-write of one (user, item) so two writes of one person cannot interleave. */
11036
11301
  async locked(key, run) {
11037
11302
  const next = (this.locks.get(key) ?? Promise.resolve()).then(run, run);
@@ -11181,6 +11446,14 @@ var LibraryStore = class {
11181
11446
  return entries;
11182
11447
  }
11183
11448
  };
11449
+ /** Genre names: the language asked for, else the server's, else whichever language the source answered. */
11450
+ function genresOf(details, requested, serverDefault) {
11451
+ for (const key of [languageKey(requested), languageKey(serverDefault)]) {
11452
+ const found = key === void 0 ? void 0 : details.genres[key];
11453
+ if (found !== void 0) return found;
11454
+ }
11455
+ return Object.values(details.genres)[0] ?? [];
11456
+ }
11184
11457
  function toProgress(row) {
11185
11458
  return {
11186
11459
  itemId: row.itemId,
@@ -11199,7 +11472,7 @@ function toFileInfo(file) {
11199
11472
  probed: file.probeOk
11200
11473
  };
11201
11474
  }
11202
- function toSummary(row, file, progress, title) {
11475
+ function toSummary(row, file, progress, title, watchlisted) {
11203
11476
  return {
11204
11477
  id: row.id,
11205
11478
  kind: row.kind,
@@ -11212,7 +11485,8 @@ function toSummary(row, file, progress, title) {
11212
11485
  addedAt: row.addedAt,
11213
11486
  durationMs: file?.durationMs ?? null,
11214
11487
  playable: row.kind !== "series" && file !== void 0,
11215
- progress: progress === void 0 ? null : toProgress(progress)
11488
+ progress: progress === void 0 ? null : toProgress(progress),
11489
+ ...watchlisted === void 0 ? {} : { watchlisted }
11216
11490
  };
11217
11491
  }
11218
11492
  //#endregion
@@ -12499,6 +12773,103 @@ var ServerLanguage = class {
12499
12773
  }
12500
12774
  };
12501
12775
  //#endregion
12776
+ //#region src/remote-fetch.ts
12777
+ var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
12778
+ var IMAGE_TIMEOUT_MS = 2e4;
12779
+ var MAX_REDIRECTS = 3;
12780
+ /** Read a response body, aborting as soon as it passes `cap`: the rest is never buffered. */
12781
+ async function readCapped(response, cap) {
12782
+ if (Number(response.headers.get("content-length") ?? "0") > cap) throw new Error("image too large");
12783
+ if (response.body === null) return Buffer.alloc(0);
12784
+ const reader = response.body.getReader();
12785
+ const chunks = [];
12786
+ let total = 0;
12787
+ for (;;) {
12788
+ const { done, value } = await reader.read();
12789
+ if (done) break;
12790
+ total += value.byteLength;
12791
+ if (total > cap) {
12792
+ await reader.cancel();
12793
+ throw new Error("image too large");
12794
+ }
12795
+ chunks.push(Buffer.from(value));
12796
+ }
12797
+ return Buffer.concat(chunks, total);
12798
+ }
12799
+ function v4Private(address) {
12800
+ const [a = 0, b = 0] = address.split(".").map(Number);
12801
+ 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;
12802
+ }
12803
+ /** Loopback, private, link-local, ULA, CGNAT, multicast and unspecified addresses, v4 and v6. */
12804
+ function isPrivateAddress(address) {
12805
+ const kind = isIP(address);
12806
+ if (kind === 4) return v4Private(address);
12807
+ if (kind !== 6) return true;
12808
+ const lower = address.toLowerCase();
12809
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
12810
+ if (mapped?.[1] !== void 0) return v4Private(mapped[1]);
12811
+ if (lower === "::" || lower === "::1") return true;
12812
+ return /^(fe[89ab]|f[cd]|ff)/.test(lower);
12813
+ }
12814
+ var resolveAll = async (host) => (await lookup(host, { all: true })).map((entry) => entry.address);
12815
+ /** The server asked to slow down. `retryAfterMs` is its `Retry-After`, or `null` when it named none. The message keeps the `HTTP 429` wording. */
12816
+ var RateLimitedError = class extends Error {
12817
+ retryAfterMs;
12818
+ constructor(retryAfterMs) {
12819
+ super("HTTP 429");
12820
+ this.retryAfterMs = retryAfterMs;
12821
+ this.name = "RateLimitedError";
12822
+ }
12823
+ };
12824
+ /** `Retry-After` as milliseconds: delta-seconds or an HTTP date; `null` when absent or unreadable. */
12825
+ function retryAfterMsOf(value, now = Date.now()) {
12826
+ if (value === null || value.trim() === "") return null;
12827
+ const seconds = Number(value);
12828
+ if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds * 1e3));
12829
+ const at = Date.parse(value);
12830
+ return Number.isNaN(at) ? null : Math.max(0, at - now);
12831
+ }
12832
+ /**
12833
+ * https only, at most 3 redirects each re-validated, every address the host resolves to must be
12834
+ * public, no credential, a bounded time and a streamed size cap.
12835
+ * A resolver answer can differ from the one `fetch` gets (rebinding): the host check narrows, not closes, that window.
12836
+ */
12837
+ function createRemoteFetch(deps = {}) {
12838
+ const doFetch = deps.fetchImpl ?? fetch;
12839
+ const resolve = deps.resolve ?? resolveAll;
12840
+ return async (start, init) => {
12841
+ let url = start;
12842
+ const startOrigin = isRemoteUrl(start) ? new URL(start).origin : "";
12843
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
12844
+ if (!isRemoteUrl(url)) throw new Error("only an https URL is fetched");
12845
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
12846
+ const addresses = isIP(host) === 0 ? await resolve(host) : [host];
12847
+ if (addresses.length === 0 || addresses.some(isPrivateAddress)) throw new Error("host refused: not a public address");
12848
+ const sameOrigin = new URL(url).origin === startOrigin;
12849
+ const response = await doFetch(url, {
12850
+ redirect: "manual",
12851
+ ...sameOrigin && init?.headers !== void 0 ? { headers: { ...init.headers } } : {},
12852
+ ...hop === 0 && init?.body !== void 0 ? {
12853
+ method: "POST",
12854
+ body: init.body
12855
+ } : {},
12856
+ signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
12857
+ });
12858
+ if (response.status >= 300 && response.status < 400) {
12859
+ const location = response.headers.get("location");
12860
+ if (location === null) throw new Error("redirect without a location");
12861
+ url = new URL(location, url).toString();
12862
+ continue;
12863
+ }
12864
+ if (response.status === 429) throw new RateLimitedError(retryAfterMsOf(response.headers.get("retry-after")));
12865
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
12866
+ return readCapped(response, MAX_IMAGE_BYTES);
12867
+ }
12868
+ throw new Error("too many redirects");
12869
+ };
12870
+ }
12871
+ var httpRemoteFetch = createRemoteFetch();
12872
+ //#endregion
12502
12873
  //#region src/tmdb.ts
12503
12874
  var TMDB_ID = "tmdb";
12504
12875
  var API$2 = "https://api.themoviedb.org/3";
@@ -12522,6 +12893,36 @@ var TranslationsSchema = object({ translations: array(object({
12522
12893
  overview: string().nullish()
12523
12894
  }).nullish()
12524
12895
  })) });
12896
+ var PersonSchema = object({
12897
+ id: number().int(),
12898
+ name: string().nullish(),
12899
+ profile_path: string().nullish()
12900
+ });
12901
+ /** A cast entry: a movie's `character`, a series' `roles[]` (aggregate credits), a guest star's `character`. */
12902
+ var CastEntrySchema = PersonSchema.extend({
12903
+ character: string().nullish(),
12904
+ roles: array(object({ character: string().nullish() })).nullish(),
12905
+ order: number().int().nullish()
12906
+ });
12907
+ /** A crew entry: a movie's `job`, a series' `jobs[]` (aggregate credits). */
12908
+ var CrewEntrySchema = PersonSchema.extend({
12909
+ job: string().nullish(),
12910
+ jobs: array(object({ job: string().nullish() })).nullish()
12911
+ });
12912
+ var CreditsSchema = object({
12913
+ cast: array(CastEntrySchema).nullish(),
12914
+ crew: array(CrewEntrySchema).nullish()
12915
+ });
12916
+ /** `release_dates` (movie): per country, a list of releases that may carry a certification. */
12917
+ var ReleaseDatesSchema = object({ results: array(object({
12918
+ iso_3166_1: string(),
12919
+ release_dates: array(object({ certification: string().nullish() }))
12920
+ })) });
12921
+ /** `content_ratings` (series): one rating per country. */
12922
+ var ContentRatingsSchema = object({ results: array(object({
12923
+ iso_3166_1: string(),
12924
+ rating: string().nullish()
12925
+ })) });
12525
12926
  var DetailsSchema = object({
12526
12927
  id: number().int(),
12527
12928
  title: string().nullish(),
@@ -12537,7 +12938,15 @@ var DetailsSchema = object({
12537
12938
  tvdb_id: number().int().nullish()
12538
12939
  }).nullish(),
12539
12940
  seasons: array(object({ season_number: number().int() })).nullish(),
12540
- translations: TranslationsSchema.nullish()
12941
+ translations: TranslationsSchema.nullish(),
12942
+ genres: array(object({ name: string().nullish() })).nullish(),
12943
+ runtime: number().nullish(),
12944
+ episode_run_time: array(number()).nullish(),
12945
+ created_by: array(PersonSchema).nullish(),
12946
+ credits: CreditsSchema.nullish(),
12947
+ aggregate_credits: CreditsSchema.nullish(),
12948
+ release_dates: ReleaseDatesSchema.nullish(),
12949
+ content_ratings: ContentRatingsSchema.nullish()
12541
12950
  });
12542
12951
  var FindSchema = object({
12543
12952
  movie_results: array(object({ id: number().int() })).default([]),
@@ -12548,8 +12957,13 @@ var SeasonSchema = object({ episodes: array(object({
12548
12957
  episode_number: number().int(),
12549
12958
  name: string().nullish(),
12550
12959
  overview: string().nullish(),
12551
- still_path: string().nullish()
12960
+ still_path: string().nullish(),
12961
+ runtime: number().nullish(),
12962
+ guest_stars: array(CastEntrySchema).nullish(),
12963
+ crew: array(CrewEntrySchema).nullish()
12552
12964
  })) });
12965
+ /** Waited when TMDB says 429 and names no time. */
12966
+ var TMDB_DEFAULT_RETRY_WAIT_MS = 2e3;
12553
12967
  /** 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. */
12554
12968
  function tmdbLanguageOf(language) {
12555
12969
  if (language === "en") return DEFAULT_LANGUAGE;
@@ -12586,23 +13000,130 @@ function translationsOf(details) {
12586
13000
  }
12587
13001
  return out;
12588
13002
  }
13003
+ /** The region a rating is read for: the server language's own country (`it` is IT), US when unknown. */
13004
+ var REGION_OF_LANGUAGE = {
13005
+ en: "US",
13006
+ it: "IT",
13007
+ de: "DE",
13008
+ fr: "FR",
13009
+ es: "ES",
13010
+ pt: "PT",
13011
+ nl: "NL",
13012
+ ja: "JP",
13013
+ zh: "CN",
13014
+ ru: "RU",
13015
+ pl: "PL"
13016
+ };
13017
+ function tmdbRegionOf(language) {
13018
+ return (/^[A-Za-z]{2,3}[-_]([A-Za-z]{2})$/.exec(language)?.[1] ?? REGION_OF_LANGUAGE[languageKey(language) ?? ""] ?? "US").toUpperCase();
13019
+ }
13020
+ var photoOf = (path) => image("w185", path);
13021
+ var positive = (value) => value !== null && value !== void 0 && value > 0 ? Math.round(value) : null;
13022
+ function personsOf(crew, jobs) {
13023
+ const out = [];
13024
+ for (const entry of crew ?? []) {
13025
+ const held = [entry.job, ...(entry.jobs ?? []).map((job) => job.job)];
13026
+ const name = text(entry.name);
13027
+ if (name === null || !held.some((job) => job !== null && job !== void 0 && jobs.includes(job))) continue;
13028
+ if (out.some((person) => person.id === entry.id)) continue;
13029
+ out.push({
13030
+ id: entry.id,
13031
+ name,
13032
+ photo: photoOf(entry.profile_path)
13033
+ });
13034
+ }
13035
+ return out;
13036
+ }
13037
+ function castOf(cast) {
13038
+ const out = [];
13039
+ for (const [index, entry] of (cast ?? []).entries()) {
13040
+ const name = text(entry.name);
13041
+ if (name === null) continue;
13042
+ out.push({
13043
+ id: entry.id,
13044
+ name,
13045
+ photo: photoOf(entry.profile_path),
13046
+ character: text(entry.character ?? entry.roles?.[0]?.character),
13047
+ order: entry.order ?? index
13048
+ });
13049
+ }
13050
+ return out;
13051
+ }
13052
+ var DIRECTOR_JOBS = ["Director"];
13053
+ var WRITER_JOBS = [
13054
+ "Writer",
13055
+ "Screenplay",
13056
+ "Story",
13057
+ "Teleplay"
13058
+ ];
13059
+ /** Genres, runtime, rating, crew and cast of a details answer, all from the one call (`append_to_response`). */
13060
+ function itemDetailsOf(details, language, region) {
13061
+ const credits = details.credits ?? details.aggregate_credits;
13062
+ const names = (details.genres ?? []).flatMap((genre) => {
13063
+ const name = text(genre.name);
13064
+ return name === null ? [] : [name];
13065
+ });
13066
+ const key = languageKey(language);
13067
+ 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;
13068
+ return {
13069
+ genres: key === void 0 || names.length === 0 ? {} : { [key]: names },
13070
+ runtimeMinutes: positive(details.runtime ?? details.episode_run_time?.[0]),
13071
+ certification,
13072
+ creators: (details.created_by ?? []).flatMap((entry) => {
13073
+ const name = text(entry.name);
13074
+ return name === null ? [] : [{
13075
+ id: entry.id,
13076
+ name,
13077
+ photo: photoOf(entry.profile_path)
13078
+ }];
13079
+ }),
13080
+ directors: personsOf(credits?.crew, DIRECTOR_JOBS),
13081
+ writers: personsOf(credits?.crew, WRITER_JOBS),
13082
+ cast: castOf(credits?.cast),
13083
+ guestStars: []
13084
+ };
13085
+ }
12589
13086
  var nameOf = (entry) => entry.title ?? entry.name ?? "";
12590
13087
  var yearIn = (entry) => yearOf$1(entry.release_date ?? entry.first_air_date);
12591
13088
  /** TMDB: movies and series, with the installation's own read token. All calls go through the shared remote fetch. */
12592
13089
  function createTmdbProvider(deps) {
12593
13090
  const language = deps.language ?? DEFAULT_LANGUAGE;
13091
+ const region = tmdbRegionOf(language);
12594
13092
  const headers = {
12595
13093
  Authorization: `Bearer ${deps.token}`,
12596
13094
  Accept: "application/json"
12597
13095
  };
12598
13096
  const segment = (kind) => kind === "movie" ? "movie" : "tv";
13097
+ const sleep = deps.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
13098
+ const clock = deps.now ?? Date.now;
13099
+ let nextSlot = 0;
13100
+ /** Reserve the next request slot, 50 ms after the previous one, and wait for it. */
13101
+ const pace = async () => {
13102
+ const slot = Math.max(clock(), nextSlot);
13103
+ nextSlot = slot + 50;
13104
+ const wait = slot - clock();
13105
+ if (wait > 0) await sleep(wait);
13106
+ };
13107
+ const get = async (url) => {
13108
+ await pace();
13109
+ try {
13110
+ return await deps.fetch(url, { headers });
13111
+ } catch (error) {
13112
+ if (!(error instanceof RateLimitedError)) throw error;
13113
+ const wait = error.retryAfterMs ?? TMDB_DEFAULT_RETRY_WAIT_MS;
13114
+ if (wait > 1e4) throw error;
13115
+ await sleep(wait);
13116
+ await pace();
13117
+ return deps.fetch(url, { headers });
13118
+ }
13119
+ };
12599
13120
  const call = async (path, query = {}) => {
12600
13121
  const params = new URLSearchParams({
12601
13122
  ...query,
12602
13123
  language
12603
13124
  });
12604
13125
  try {
12605
- const bytes = await deps.fetch(`${API$2}${path}?${params.toString()}`, { headers });
13126
+ const bytes = await get(`${API$2}${path}?${params.toString()}`);
12606
13127
  return JSON.parse(bytes.toString("utf8"));
12607
13128
  } catch (error) {
12608
13129
  if (error instanceof Error && /\b401\b/.test(error.message)) throw new ProviderAuthError(TMDB_REJECTED);
@@ -12620,11 +13141,12 @@ function createTmdbProvider(deps) {
12620
13141
  imdbId: text(details.external_ids?.imdb_id) ?? text(details.imdb_id),
12621
13142
  poster: image("w500", details.poster_path),
12622
13143
  fanart: image("w1280", details.backdrop_path),
12623
- translations: translationsOf(details)
13144
+ translations: translationsOf(details),
13145
+ details: itemDetailsOf(details, language, region)
12624
13146
  });
12625
13147
  const detailsOf = async (kind, id) => {
12626
13148
  try {
12627
- return matchOf(DetailsSchema.parse(await call(`/${segment(kind)}/${id}`, { append_to_response: "external_ids,translations" })));
13149
+ 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" })));
12628
13150
  } catch (error) {
12629
13151
  if (error instanceof Error && /\b404\b/.test(error.message)) return null;
12630
13152
  throw error;
@@ -12633,6 +13155,7 @@ function createTmdbProvider(deps) {
12633
13155
  return {
12634
13156
  id: TMDB_ID,
12635
13157
  translates: true,
13158
+ providesDetails: true,
12636
13159
  kinds: ["movie", "series"],
12637
13160
  lookupBy: [
12638
13161
  "tmdbId",
@@ -12673,7 +13196,17 @@ function createTmdbProvider(deps) {
12673
13196
  episode: entry.episode_number,
12674
13197
  title: text(entry.name),
12675
13198
  overview: text(entry.overview),
12676
- still: image("w300", entry.still_path)
13199
+ still: image("w300", entry.still_path),
13200
+ details: {
13201
+ genres: {},
13202
+ runtimeMinutes: positive(entry.runtime),
13203
+ certification: null,
13204
+ creators: [],
13205
+ directors: personsOf(entry.crew, DIRECTOR_JOBS),
13206
+ writers: personsOf(entry.crew, WRITER_JOBS),
13207
+ cast: [],
13208
+ guestStars: castOf(entry.guest_stars)
13209
+ }
12677
13210
  });
12678
13211
  }
12679
13212
  return out;
@@ -12981,85 +13514,6 @@ function createTvmazeProvider(deps) {
12981
13514
  };
12982
13515
  }
12983
13516
  //#endregion
12984
- //#region src/remote-fetch.ts
12985
- var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
12986
- var IMAGE_TIMEOUT_MS = 2e4;
12987
- var MAX_REDIRECTS = 3;
12988
- /** Read a response body, aborting as soon as it passes `cap`: the rest is never buffered. */
12989
- async function readCapped(response, cap) {
12990
- if (Number(response.headers.get("content-length") ?? "0") > cap) throw new Error("image too large");
12991
- if (response.body === null) return Buffer.alloc(0);
12992
- const reader = response.body.getReader();
12993
- const chunks = [];
12994
- let total = 0;
12995
- for (;;) {
12996
- const { done, value } = await reader.read();
12997
- if (done) break;
12998
- total += value.byteLength;
12999
- if (total > cap) {
13000
- await reader.cancel();
13001
- throw new Error("image too large");
13002
- }
13003
- chunks.push(Buffer.from(value));
13004
- }
13005
- return Buffer.concat(chunks, total);
13006
- }
13007
- function v4Private(address) {
13008
- const [a = 0, b = 0] = address.split(".").map(Number);
13009
- 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;
13010
- }
13011
- /** Loopback, private, link-local, ULA, CGNAT, multicast and unspecified addresses, v4 and v6. */
13012
- function isPrivateAddress(address) {
13013
- const kind = isIP(address);
13014
- if (kind === 4) return v4Private(address);
13015
- if (kind !== 6) return true;
13016
- const lower = address.toLowerCase();
13017
- const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
13018
- if (mapped?.[1] !== void 0) return v4Private(mapped[1]);
13019
- if (lower === "::" || lower === "::1") return true;
13020
- return /^(fe[89ab]|f[cd]|ff)/.test(lower);
13021
- }
13022
- var resolveAll = async (host) => (await lookup(host, { all: true })).map((entry) => entry.address);
13023
- /**
13024
- * https only, at most 3 redirects each re-validated, every address the host resolves to must be
13025
- * public, no credential, a bounded time and a streamed size cap.
13026
- * A resolver answer can differ from the one `fetch` gets (rebinding): the host check narrows, not closes, that window.
13027
- */
13028
- function createRemoteFetch(deps = {}) {
13029
- const doFetch = deps.fetchImpl ?? fetch;
13030
- const resolve = deps.resolve ?? resolveAll;
13031
- return async (start, init) => {
13032
- let url = start;
13033
- const startOrigin = isRemoteUrl(start) ? new URL(start).origin : "";
13034
- for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
13035
- if (!isRemoteUrl(url)) throw new Error("only an https URL is fetched");
13036
- const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
13037
- const addresses = isIP(host) === 0 ? await resolve(host) : [host];
13038
- if (addresses.length === 0 || addresses.some(isPrivateAddress)) throw new Error("host refused: not a public address");
13039
- const sameOrigin = new URL(url).origin === startOrigin;
13040
- const response = await doFetch(url, {
13041
- redirect: "manual",
13042
- ...sameOrigin && init?.headers !== void 0 ? { headers: { ...init.headers } } : {},
13043
- ...hop === 0 && init?.body !== void 0 ? {
13044
- method: "POST",
13045
- body: init.body
13046
- } : {},
13047
- signal: AbortSignal.timeout(IMAGE_TIMEOUT_MS)
13048
- });
13049
- if (response.status >= 300 && response.status < 400) {
13050
- const location = response.headers.get("location");
13051
- if (location === null) throw new Error("redirect without a location");
13052
- url = new URL(location, url).toString();
13053
- continue;
13054
- }
13055
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
13056
- return readCapped(response, MAX_IMAGE_BYTES);
13057
- }
13058
- throw new Error("too many redirects");
13059
- };
13060
- }
13061
- var httpRemoteFetch = createRemoteFetch();
13062
- //#endregion
13063
13517
  //#region src/img-plane.ts
13064
13518
  var FAILED_GRAB_TTL_MS = 30 * 6e4;
13065
13519
  var FAILED_GRAB_MAX = 500;
@@ -13221,7 +13675,7 @@ function createImagePlaneHandler(deps) {
13221
13675
  } catch {
13222
13676
  return end(res, 404);
13223
13677
  }
13224
- if (parts.length !== 2 || !isItemId(itemId) || which !== "poster" && which !== "fanart") {
13678
+ if (parts.length !== 2 || !isItemId(itemId) || !isImageKind(which)) {
13225
13679
  deps.logger.warn("image request refused", { meta: { reason: "bad-request" } });
13226
13680
  return end(res, 404);
13227
13681
  }
@@ -13376,6 +13830,9 @@ function createMediaLibraryProvider(store, scans) {
13376
13830
  getItem: ({ itemId, language, caller }) => store.getItem(caller.userId, itemId, language),
13377
13831
  search: ({ query, limit, language, caller }) => store.search(caller.userId, query, limit, language),
13378
13832
  listRecentlyAdded: ({ limit, language, caller }) => store.listRecentlyAdded(caller.userId, limit, language),
13833
+ listWatchlist: ({ limit, offset, language, caller }) => store.listWatchlist(caller.userId, limit, offset, language),
13834
+ setWatchlisted: ({ itemId, on, caller }) => store.setWatchlisted(caller.userId, itemId, on),
13835
+ getItemDetails: ({ itemId, language }) => store.getItemDetails(itemId, language),
13379
13836
  getProgress: ({ itemId, caller }) => store.getProgress(caller.userId, itemId),
13380
13837
  setProgress: ({ caller, ...input }) => store.setProgress(caller.userId, input),
13381
13838
  markWatched: ({ caller, ...input }) => store.markWatched(caller.userId, input),
@@ -13396,6 +13853,7 @@ function fill(into, from) {
13396
13853
  year: into.year ?? from.year,
13397
13854
  overview: into.overview ?? from.overview,
13398
13855
  translations: into.translations ?? from.translations,
13856
+ details: into.details ?? from.details,
13399
13857
  tvdbId: into.tvdbId ?? from.tvdbId,
13400
13858
  tmdbId: into.tmdbId ?? from.tmdbId,
13401
13859
  imdbId: into.imdbId ?? from.imdbId,
@@ -13557,7 +14015,10 @@ var Enricher = class {
13557
14015
  cachedMatch(provider, key) {
13558
14016
  const known = this.deps.cache.getMatch(key);
13559
14017
  if (known === null) return null;
13560
- return known.found && provider.translates === true && known.match.translations === void 0 ? null : known;
14018
+ if (!known.found) return known;
14019
+ const predatesTranslations = provider.translates === true && known.match.translations === void 0;
14020
+ const predatesDetails = provider.providesDetails === true && known.match.details === void 0;
14021
+ return predatesTranslations || predatesDetails ? null : known;
13561
14022
  }
13562
14023
  /** A pinned id is asked for directly: an answer of "nothing" is final, never turned into a title guess. */
13563
14024
  async lookup(provider, ask, item, kind, pin) {
@@ -13637,14 +14098,15 @@ var Enricher = class {
13637
14098
  async episodesOf(provider, item, match) {
13638
14099
  const key = `${this.keyOf(provider)}:eps:${match.remoteId}`;
13639
14100
  const known = this.deps.cache.getEpisodes(key);
13640
- if (known !== null) return known.episodes;
14101
+ const predatesDetails = provider.providesDetails === true && known !== null && known.episodes.some((entry) => entry.details === void 0);
14102
+ if (known !== null && !predatesDetails) return known.episodes;
13641
14103
  try {
13642
14104
  const episodes = await provider.episodes(match);
13643
14105
  this.deps.cache.putEpisodes(key, { episodes: [...episodes] });
13644
14106
  return episodes;
13645
14107
  } catch (error) {
13646
14108
  this.failed(provider.id, item.id, error);
13647
- return [];
14109
+ return known?.episodes ?? [];
13648
14110
  }
13649
14111
  }
13650
14112
  async onlineLayer(provider, item, acc, resolved, held) {
@@ -13658,6 +14120,7 @@ var Enricher = class {
13658
14120
  year: match.year,
13659
14121
  overview: match.overview,
13660
14122
  translations: match.translations ?? null,
14123
+ details: match.details ?? null,
13661
14124
  tvdbId: match.tvdbId,
13662
14125
  tmdbId: match.tmdbId,
13663
14126
  imdbId: match.imdbId,
@@ -13680,15 +14143,16 @@ var Enricher = class {
13680
14143
  ...NO_LOCAL,
13681
14144
  title: found.title,
13682
14145
  overview: found.overview,
13683
- poster: found.still
14146
+ poster: found.still,
14147
+ details: found.details ?? null
13684
14148
  };
13685
14149
  }
13686
14150
  canAsk(provider, item) {
13687
14151
  return provider.kinds.includes(item.kind === "movie" ? "movie" : "series");
13688
14152
  }
13689
14153
  needsOnline(provider, item, acc) {
13690
- if (item.kind === "episode") return acc.overview === null || acc.poster === null || item.titlePlaceholder && acc.title === null;
13691
- return acc.overview === null || acc.poster === null || provider.translates === true && acc.translations === null;
14154
+ if (item.kind === "episode") return acc.overview === null || acc.poster === null || provider.providesDetails === true && acc.details === null || item.titlePlaceholder && acc.title === null;
14155
+ return acc.overview === null || acc.poster === null || provider.translates === true && acc.translations === null || provider.providesDetails === true && acc.details === null;
13692
14156
  }
13693
14157
  async localLayer(item, firstEpisodeFile) {
13694
14158
  const { reader } = this.deps;
@@ -13737,6 +14201,7 @@ var Enricher = class {
13737
14201
  year: acc.year,
13738
14202
  overview: acc.overview,
13739
14203
  translations: acc.translations,
14204
+ details: acc.details,
13740
14205
  tvdbId: acc.tvdbId,
13741
14206
  tmdbId: acc.tmdbId,
13742
14207
  imdbId: acc.imdbId,
@@ -13778,6 +14243,7 @@ function newItem(base) {
13778
14243
  episodeNumber: null,
13779
14244
  overview: null,
13780
14245
  translations: null,
14246
+ details: null,
13781
14247
  tvdbId: null,
13782
14248
  tmdbId: null,
13783
14249
  imdbId: null,
@@ -14129,6 +14595,7 @@ async function scanLibrary(deps, sources) {
14129
14595
  const { addedHint, titlePlaceholder: _placeholder, ...fields } = item;
14130
14596
  writes.push({
14131
14597
  ...fields,
14598
+ details: fields.details ?? previous?.details ?? null,
14132
14599
  addedAt: previous?.addedAt ?? addedHint ?? startedAt,
14133
14600
  seenAt: startedAt
14134
14601
  });
@@ -14205,6 +14672,7 @@ async function scanLibrary(deps, sources) {
14205
14672
  const stale = [...existingItems.values()].filter((item) => item.sourceId === entry.sourceId && !seenIds.has(item.id));
14206
14673
  if (stale.length === 0) continue;
14207
14674
  await db.deleteWhere(ITEMS, { whereIn: { id: stale.map((item) => item.id) } });
14675
+ await db.deleteWhere(WATCHLIST, { whereIn: { itemId: stale.map((item) => item.id) } });
14208
14676
  logger.info("items no longer in their source were removed", { meta: {
14209
14677
  sourceId: entry.sourceId,
14210
14678
  removed: stale.length