@dominevo/addon-media-library 0.1.5 → 0.1.7

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.
@@ -8863,7 +8863,14 @@ var MediaScanStatusSchema = /* @__PURE__ */ object({
8863
8863
  reused: /* @__PURE__ */ number().int().nonnegative(),
8864
8864
  skipped: /* @__PURE__ */ number().int().nonnegative()
8865
8865
  });
8866
+ /**
8867
+ * The language the caller wants item text in (`title`, `overview`): a locale tag such as `it`; a
8868
+ * regional form (`it-IT`) reads as its language. Absent means the server's default language. A language
8869
+ * the item has no text in falls back to the server default, then to the text stored with the item.
8870
+ */
8871
+ var LanguageInputSchema = /* @__PURE__ */ string().min(2).max(35).optional();
8866
8872
  var PageInputSchema = /* @__PURE__ */ object({
8873
+ language: LanguageInputSchema,
8867
8874
  limit: /* @__PURE__ */ number().int().positive().max(500).optional(),
8868
8875
  offset: /* @__PURE__ */ number().int().nonnegative().optional()
8869
8876
  });
@@ -8882,17 +8889,25 @@ var mediaLibraryCapability = {
8882
8889
  /** The episodes of one season in order, each with the caller's progress. */
8883
8890
  listEpisodes: /* @__PURE__ */ method(/* @__PURE__ */ object({
8884
8891
  seriesId: /* @__PURE__ */ string().min(1),
8885
- seasonNumber: /* @__PURE__ */ number().int()
8892
+ seasonNumber: /* @__PURE__ */ number().int(),
8893
+ language: LanguageInputSchema
8886
8894
  }), /* @__PURE__ */ array(MediaEpisodeSummarySchema).readonly(), { caller: "required" }),
8887
8895
  /** One item with its streams and direct-play path; `null` when the id is unknown. */
8888
- getItem: /* @__PURE__ */ method(/* @__PURE__ */ object({ itemId: /* @__PURE__ */ string().min(1) }), /* @__PURE__ */ MediaItemDetailSchema.nullable(), { caller: "required" }),
8896
+ getItem: /* @__PURE__ */ method(/* @__PURE__ */ object({
8897
+ itemId: /* @__PURE__ */ string().min(1),
8898
+ language: LanguageInputSchema
8899
+ }), /* @__PURE__ */ MediaItemDetailSchema.nullable(), { caller: "required" }),
8889
8900
  /** Series and movies whose title contains the query, case and accents ignored. */
8890
8901
  search: /* @__PURE__ */ method(/* @__PURE__ */ object({
8891
8902
  query: /* @__PURE__ */ string().min(1),
8892
- limit: /* @__PURE__ */ number().int().positive().max(100).optional()
8903
+ limit: /* @__PURE__ */ number().int().positive().max(100).optional(),
8904
+ language: LanguageInputSchema
8893
8905
  }), /* @__PURE__ */ array(MediaItemSummarySchema).readonly(), { caller: "required" }),
8894
8906
  /** The series and movies added most recently. */
8895
- listRecentlyAdded: /* @__PURE__ */ method(/* @__PURE__ */ object({ limit: /* @__PURE__ */ number().int().positive().max(100).optional() }), /* @__PURE__ */ array(MediaItemSummarySchema).readonly(), { caller: "required" }),
8907
+ listRecentlyAdded: /* @__PURE__ */ method(/* @__PURE__ */ object({
8908
+ limit: /* @__PURE__ */ number().int().positive().max(100).optional(),
8909
+ language: LanguageInputSchema
8910
+ }), /* @__PURE__ */ array(MediaItemSummarySchema).readonly(), { caller: "required" }),
8896
8911
  /** The caller's progress in one item; `null` when they have none. */
8897
8912
  getProgress: /* @__PURE__ */ method(/* @__PURE__ */ object({ itemId: /* @__PURE__ */ string().min(1) }), /* @__PURE__ */ MediaProgressSchema.nullable(), { caller: "required" }),
8898
8913
  /**
@@ -8919,7 +8934,10 @@ var mediaLibraryCapability = {
8919
8934
  caller: "required"
8920
8935
  }),
8921
8936
  /** What the caller started and did not finish, the latest first. */
8922
- listContinue: /* @__PURE__ */ method(/* @__PURE__ */ object({ limit: /* @__PURE__ */ number().int().positive().max(100).optional() }), /* @__PURE__ */ array(MediaContinueEntrySchema).readonly(), { caller: "required" }),
8937
+ listContinue: /* @__PURE__ */ method(/* @__PURE__ */ object({
8938
+ limit: /* @__PURE__ */ number().int().positive().max(100).optional(),
8939
+ language: LanguageInputSchema
8940
+ }), /* @__PURE__ */ array(MediaContinueEntrySchema).readonly(), { caller: "required" }),
8923
8941
  /** Start a scan of every source now; answers at once, the scan runs in the background. */
8924
8942
  rescan: /* @__PURE__ */ method(/* @__PURE__ */ object({}), /* @__PURE__ */ object({ started: /* @__PURE__ */ boolean() }), {
8925
8943
  kind: "mutation",
@@ -10033,6 +10051,16 @@ function parseRows(schema, rows, onInvalid) {
10033
10051
  }
10034
10052
  //#endregion
10035
10053
  //#region src/metadata.ts
10054
+ /**
10055
+ * One language's text of an item: either field may be absent (a provider can translate the title and
10056
+ * not the overview, or the reverse). The language is the provider's own tag, lower-cased (`it`, `pt`).
10057
+ */
10058
+ var TextTranslationSchema = object({
10059
+ title: string().nullable(),
10060
+ overview: string().nullable()
10061
+ });
10062
+ /** Translations by language tag. Absent means "never asked"; `{}` means "asked, none held". */
10063
+ var TranslationMapSchema = record(string(), TextTranslationSchema);
10036
10064
  var ProviderMatchSchema = object({
10037
10065
  providerId: string(),
10038
10066
  /** The provider's own id of the match, used to ask for its episodes. */
@@ -10044,7 +10072,9 @@ var ProviderMatchSchema = object({
10044
10072
  tmdbId: number().int().nullable(),
10045
10073
  imdbId: string().nullable(),
10046
10074
  poster: string().nullable(),
10047
- fanart: string().nullable()
10075
+ fanart: string().nullable(),
10076
+ /** The title and overview in other languages, when the provider answered them with the match. */
10077
+ translations: TranslationMapSchema.optional()
10048
10078
  });
10049
10079
  var ProviderEpisodeSchema = object({
10050
10080
  season: number().int(),
@@ -10185,6 +10215,8 @@ var ItemRowSchema = object({
10185
10215
  seasonNumber: number().int().nullable(),
10186
10216
  episodeNumber: number().int().nullable(),
10187
10217
  overview: string().nullable(),
10218
+ /** The title and overview in other languages; absent on a row written before they were kept. */
10219
+ translations: TranslationMapSchema.nullish(),
10188
10220
  tvdbId: number().int().nullable(),
10189
10221
  tmdbId: number().int().nullable(),
10190
10222
  imdbId: string().nullable(),
@@ -10255,6 +10287,10 @@ var COLLECTIONS = [
10255
10287
  int("seasonNumber"),
10256
10288
  int("episodeNumber"),
10257
10289
  text$3("overview"),
10290
+ {
10291
+ name: "translations",
10292
+ type: "JSON"
10293
+ },
10258
10294
  int("tvdbId"),
10259
10295
  int("tmdbId"),
10260
10296
  text$3("imdbId"),
@@ -10620,6 +10656,7 @@ var NO_LOCAL = {
10620
10656
  title: null,
10621
10657
  year: null,
10622
10658
  overview: null,
10659
+ translations: null,
10623
10660
  tvdbId: null,
10624
10661
  tmdbId: null,
10625
10662
  imdbId: null,
@@ -10659,6 +10696,7 @@ function merge(first, second) {
10659
10696
  title: pick$1(first.title, second.title),
10660
10697
  year: pick$1(first.year, second.year),
10661
10698
  overview: pick$1(first.overview, second.overview),
10699
+ translations: pick$1(first.translations, second.translations),
10662
10700
  tvdbId: pick$1(first.tvdbId, second.tvdbId),
10663
10701
  tmdbId: pick$1(first.tmdbId, second.tmdbId),
10664
10702
  imdbId: pick$1(first.imdbId, second.imdbId),
@@ -10715,6 +10753,47 @@ async function localMovie(reader, filePath) {
10715
10753
  fanart: firstImage(dir, listing, [`${base}-fanart`, ...solo ? ["fanart"] : []])
10716
10754
  };
10717
10755
  }
10756
+ //#endregion
10757
+ //#region src/item-text.ts
10758
+ /**
10759
+ * A language tag as the translations are keyed: lower-case, region dropped (`it-IT` is `it`).
10760
+ * `undefined` for an absent or empty tag.
10761
+ */
10762
+ function languageKey(tag) {
10763
+ const primary = tag?.trim().toLowerCase().split(/[-_]/)[0] ?? "";
10764
+ return primary === "" ? void 0 : primary;
10765
+ }
10766
+ /**
10767
+ * The text of `row` for a reader: the language they asked for, else the server's default language,
10768
+ * else the base text stored with the item. Each field falls through on its own, so a language that
10769
+ * translated the title and not the overview still gives the title.
10770
+ */
10771
+ function resolveItemText(row, requested, serverDefault) {
10772
+ let title = null;
10773
+ let overview = null;
10774
+ for (const key of [languageKey(requested), languageKey(serverDefault)]) {
10775
+ const entry = key === void 0 ? void 0 : row.translations?.[key];
10776
+ title ??= entry?.title ?? null;
10777
+ overview ??= entry?.overview ?? null;
10778
+ }
10779
+ return {
10780
+ title: title ?? row.title,
10781
+ overview: overview ?? row.overview
10782
+ };
10783
+ }
10784
+ /**
10785
+ * `rows` in A–Z order of the title each reader sees (`resolveItemText`, minus a leading article), compared with the
10786
+ * collator of the reader's language (`en` when none). A stable sort: equal titles keep the order
10787
+ * the rows came in (the caller's read order: item id for `queryAllItems`), so a page cut is deterministic.
10788
+ */
10789
+ function sortByShownTitle(rows, requested, serverDefault) {
10790
+ const collator = new Intl.Collator(languageKey(requested) ?? "en", {
10791
+ sensitivity: "base",
10792
+ numeric: true
10793
+ });
10794
+ const keys = new Map(rows.map((row) => [row, sortKey(resolveItemText(row, requested, serverDefault).title)]));
10795
+ return rows.toSorted((a, b) => collator.compare(keys.get(a) ?? "", keys.get(b) ?? ""));
10796
+ }
10718
10797
  var FILE_PLANE_PREFIX = "file";
10719
10798
  var HUB_PLANE_BASE = "/addon/media-library";
10720
10799
  var SEARCH_DEFAULT_LIMIT = 50;
@@ -10735,10 +10814,12 @@ var idList = (rows) => rows.map((row) => row.id);
10735
10814
  var LibraryStore = class {
10736
10815
  db;
10737
10816
  logger;
10817
+ serverLanguage;
10738
10818
  locks = /* @__PURE__ */ new Map();
10739
- constructor(db, logger) {
10819
+ constructor(db, logger, serverLanguage = () => "en") {
10740
10820
  this.db = db;
10741
10821
  this.logger = logger;
10822
+ this.serverLanguage = serverLanguage;
10742
10823
  }
10743
10824
  async init() {
10744
10825
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -10763,7 +10844,7 @@ var LibraryStore = class {
10763
10844
  return parseRows(ProgressRowSchema, await this.db.query(PROGRESS, filter), this.invalid(PROGRESS));
10764
10845
  }
10765
10846
  /** Build the wire summaries of `rows` for one caller: file facts and the caller's progress, two reads. */
10766
- async summaries(rows, userId) {
10847
+ async summaries(rows, userId, language) {
10767
10848
  const paths = rows.flatMap((row) => row.filePath === null ? [] : [row.filePath]);
10768
10849
  const files = /* @__PURE__ */ new Map();
10769
10850
  if (paths.length > 0) for (const file of await this.queryFiles({ whereIn: { path: paths } })) files.set(file.path, file);
@@ -10773,39 +10854,30 @@ var LibraryStore = class {
10773
10854
  where: { userId },
10774
10855
  whereIn: { itemId: playableIds }
10775
10856
  })) progress.set(entry.itemId, entry);
10857
+ const fallback = this.serverLanguage();
10776
10858
  return rows.map((row) => {
10777
- return toSummary(row, row.filePath === null ? void 0 : files.get(row.filePath), progress.get(row.id));
10859
+ return toSummary(row, row.filePath === null ? void 0 : files.get(row.filePath), progress.get(row.id), resolveItemText(row, language, fallback).title);
10778
10860
  });
10779
10861
  }
10780
- pageOf = async (kind, userId, limit, offset) => {
10781
- const rows = await this.queryItems({
10782
- where: {
10783
- kind,
10784
- topLevel: true
10785
- },
10786
- orderBy: {
10787
- field: "sortTitle",
10788
- direction: "asc"
10789
- },
10790
- limit: limit ?? 100,
10791
- offset: offset ?? 0
10792
- });
10793
- const total = await this.db.count(ITEMS, { where: {
10862
+ pageOf = async (kind, userId, limit, offset, language) => {
10863
+ const all = await this.queryAllItems({ where: {
10794
10864
  kind,
10795
10865
  topLevel: true
10796
10866
  } });
10867
+ const start = offset ?? 0;
10868
+ const page = sortByShownTitle(all, language, this.serverLanguage()).slice(start, start + (limit ?? 100));
10797
10869
  return {
10798
- items: await this.summaries(rows, userId),
10799
- total
10870
+ items: await this.summaries(page, userId, language),
10871
+ total: all.length
10800
10872
  };
10801
10873
  };
10802
- listSeries(userId, limit, offset) {
10803
- return this.pageOf("series", userId, limit, offset);
10874
+ listSeries(userId, limit, offset, language) {
10875
+ return this.pageOf("series", userId, limit, offset, language);
10804
10876
  }
10805
- listMovies(userId, limit, offset) {
10806
- return this.pageOf("movie", userId, limit, offset);
10877
+ listMovies(userId, limit, offset, language) {
10878
+ return this.pageOf("movie", userId, limit, offset, language);
10807
10879
  }
10808
- async listRecentlyAdded(userId, limit) {
10880
+ async listRecentlyAdded(userId, limit, language) {
10809
10881
  const rows = await this.queryItems({
10810
10882
  where: { topLevel: true },
10811
10883
  orderBy: {
@@ -10814,19 +10886,15 @@ var LibraryStore = class {
10814
10886
  },
10815
10887
  limit: limit ?? RECENT_DEFAULT_LIMIT
10816
10888
  });
10817
- return this.summaries(rows, userId);
10889
+ return this.summaries(rows, userId, language);
10818
10890
  }
10819
- async search(userId, query, limit) {
10891
+ async search(userId, query, limit, language) {
10820
10892
  const needle = foldTitle(query);
10821
10893
  if (needle === "") return [];
10822
- const hits = (await this.queryItems({
10823
- where: { topLevel: true },
10824
- orderBy: {
10825
- field: "sortTitle",
10826
- direction: "asc"
10827
- }
10828
- })).filter((row) => row.titleFold.includes(needle)).slice(0, limit ?? SEARCH_DEFAULT_LIMIT);
10829
- return this.summaries(hits, userId);
10894
+ const rows = await this.queryAllItems({ where: { topLevel: true } });
10895
+ const fallback = this.serverLanguage();
10896
+ 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);
10897
+ return this.summaries(hits, userId, language);
10830
10898
  }
10831
10899
  episodesOf(seriesId) {
10832
10900
  return this.queryItems({
@@ -10864,7 +10932,7 @@ var LibraryStore = class {
10864
10932
  watchedCount: entry.watched
10865
10933
  }));
10866
10934
  }
10867
- async listEpisodes(userId, seriesId, seasonNumber) {
10935
+ async listEpisodes(userId, seriesId, seasonNumber, language) {
10868
10936
  const rows = await this.queryItems({
10869
10937
  where: {
10870
10938
  parentId: seriesId,
@@ -10875,18 +10943,23 @@ var LibraryStore = class {
10875
10943
  direction: "asc"
10876
10944
  }
10877
10945
  });
10878
- return (await this.summaries(rows, userId)).map((summary, index) => ({
10879
- ...summary,
10880
- overview: rows[index]?.overview ?? null
10881
- }));
10946
+ const summaries = await this.summaries(rows, userId, language);
10947
+ const fallback = this.serverLanguage();
10948
+ return summaries.map((summary, index) => {
10949
+ const row = rows[index];
10950
+ return {
10951
+ ...summary,
10952
+ overview: row === void 0 ? null : resolveItemText(row, language, fallback).overview
10953
+ };
10954
+ });
10882
10955
  }
10883
- async getItem(userId, itemId) {
10956
+ async getItem(userId, itemId, language) {
10884
10957
  const [row] = await this.queryItems({
10885
10958
  where: { id: itemId },
10886
10959
  limit: 1
10887
10960
  });
10888
10961
  if (row === void 0) return null;
10889
- const [summary] = await this.summaries([row], userId);
10962
+ const [summary] = await this.summaries([row], userId, language);
10890
10963
  if (summary === void 0) return null;
10891
10964
  const [file] = row.filePath === null ? [] : await this.queryFiles({
10892
10965
  where: { path: row.filePath },
@@ -10894,7 +10967,7 @@ var LibraryStore = class {
10894
10967
  });
10895
10968
  return {
10896
10969
  ...summary,
10897
- overview: row.overview,
10970
+ overview: resolveItemText(row, language, this.serverLanguage()).overview,
10898
10971
  ids: {
10899
10972
  tvdb: row.tvdbId,
10900
10973
  tmdb: row.tmdbId,
@@ -10940,7 +11013,7 @@ var LibraryStore = class {
10940
11013
  kind: "remote",
10941
11014
  url: cover
10942
11015
  });
10943
- else if (cover.startsWith("/")) out.push({
11016
+ else if (cover.startsWith("/") || cover.startsWith("http://")) out.push({
10944
11017
  kind: "arr",
10945
11018
  path: cover,
10946
11019
  sourceId: item.sourceId
@@ -11084,7 +11157,7 @@ var LibraryStore = class {
11084
11157
  watched
11085
11158
  };
11086
11159
  }
11087
- async listContinue(userId, limit) {
11160
+ async listContinue(userId, limit, language) {
11088
11161
  const wanted = limit ?? CONTINUE_DEFAULT_LIMIT;
11089
11162
  const rows = (await this.queryProgress({
11090
11163
  where: {
@@ -11099,7 +11172,7 @@ var LibraryStore = class {
11099
11172
  })).filter((row) => row.positionMs > 0);
11100
11173
  if (rows.length === 0) return [];
11101
11174
  const items = await this.queryItems({ whereIn: { id: rows.map((row) => row.itemId) } });
11102
- const summaries = new Map((await this.summaries(items, userId)).map((summary) => [summary.id, summary]));
11175
+ const summaries = new Map((await this.summaries(items, userId, language)).map((summary) => [summary.id, summary]));
11103
11176
  const entries = [];
11104
11177
  for (const row of rows) {
11105
11178
  const item = summaries.get(row.itemId);
@@ -11130,11 +11203,11 @@ function toFileInfo(file) {
11130
11203
  probed: file.probeOk
11131
11204
  };
11132
11205
  }
11133
- function toSummary(row, file, progress) {
11206
+ function toSummary(row, file, progress, title) {
11134
11207
  return {
11135
11208
  id: row.id,
11136
11209
  kind: row.kind,
11137
- title: row.title,
11210
+ title,
11138
11211
  year: row.year,
11139
11212
  seriesId: row.kind === "episode" ? row.parentId : null,
11140
11213
  seasonNumber: row.seasonNumber,
@@ -12384,6 +12457,51 @@ function createOmdbProvider(deps) {
12384
12457
  }
12385
12458
  };
12386
12459
  }
12460
+ /**
12461
+ * The server's default language, kept in memory so no catalogue read waits on the system call.
12462
+ * A read answers what is held; one that finds it older than {@link SERVER_LANGUAGE_REFRESH_MS}
12463
+ * starts a refresh and does not wait for it. A refresh that fails changes nothing (the last answer
12464
+ * stays, English when there never was one) and says so in the log.
12465
+ */
12466
+ var ServerLanguage = class {
12467
+ read;
12468
+ now;
12469
+ logger;
12470
+ value = "en";
12471
+ attemptedAt = null;
12472
+ inFlight = null;
12473
+ constructor(read, now, logger) {
12474
+ this.read = read;
12475
+ this.now = now;
12476
+ this.logger = logger;
12477
+ }
12478
+ /** Ask now and wait; used at boot and at the start of a scan, never on a read. */
12479
+ refresh() {
12480
+ if (this.inFlight !== null) return this.inFlight;
12481
+ const run = (async () => {
12482
+ try {
12483
+ const read = await this.read();
12484
+ if (read === null) this.logger.warn("server default language unreadable: keeping the last one", { meta: { kept: this.value } });
12485
+ else this.value = read;
12486
+ } catch (error) {
12487
+ this.logger.warn("server default language not read: keeping the last one", { meta: {
12488
+ error: errMsg(error),
12489
+ kept: this.value
12490
+ } });
12491
+ } finally {
12492
+ this.attemptedAt = this.now();
12493
+ this.inFlight = null;
12494
+ }
12495
+ })();
12496
+ this.inFlight = run;
12497
+ return run;
12498
+ }
12499
+ /** The held language; starts a background refresh when it is stale. Never throws, never waits. */
12500
+ current() {
12501
+ if (this.attemptedAt === null || this.now() - this.attemptedAt >= 6e4) this.refresh();
12502
+ return this.value;
12503
+ }
12504
+ };
12387
12505
  //#endregion
12388
12506
  //#region src/tmdb.ts
12389
12507
  var TMDB_ID = "tmdb";
@@ -12399,6 +12517,15 @@ var SearchSchema$2 = object({ results: array(object({
12399
12517
  release_date: string().nullish(),
12400
12518
  first_air_date: string().nullish()
12401
12519
  })) });
12520
+ /** `append_to_response=translations`: one entry per language TMDB holds, `data` carries the text. */
12521
+ var TranslationsSchema = object({ translations: array(object({
12522
+ iso_639_1: string(),
12523
+ data: object({
12524
+ title: string().nullish(),
12525
+ name: string().nullish(),
12526
+ overview: string().nullish()
12527
+ }).nullish()
12528
+ })) });
12402
12529
  var DetailsSchema = object({
12403
12530
  id: number().int(),
12404
12531
  title: string().nullish(),
@@ -12413,7 +12540,8 @@ var DetailsSchema = object({
12413
12540
  imdb_id: string().nullish(),
12414
12541
  tvdb_id: number().int().nullish()
12415
12542
  }).nullish(),
12416
- seasons: array(object({ season_number: number().int() })).nullish()
12543
+ seasons: array(object({ season_number: number().int() })).nullish(),
12544
+ translations: TranslationsSchema.nullish()
12417
12545
  });
12418
12546
  var FindSchema = object({
12419
12547
  movie_results: array(object({ id: number().int() })).default([]),
@@ -12426,6 +12554,12 @@ var SeasonSchema = object({ episodes: array(object({
12426
12554
  overview: string().nullish(),
12427
12555
  still_path: string().nullish()
12428
12556
  })) });
12557
+ /** 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. */
12558
+ function tmdbLanguageOf(language) {
12559
+ if (language === "en") return DEFAULT_LANGUAGE;
12560
+ if (language === "zh") return "zh-CN";
12561
+ return language;
12562
+ }
12429
12563
  function yearOf$1(date) {
12430
12564
  const match = /^(\d{4})/.exec(date ?? "");
12431
12565
  return match?.[1] === void 0 ? null : Number(match[1]);
@@ -12437,6 +12571,25 @@ function text(value) {
12437
12571
  function image(size, path) {
12438
12572
  return path === null || path === void 0 || !path.startsWith("/") ? null : `${IMAGES}/${size}${path}`;
12439
12573
  }
12574
+ /**
12575
+ * The per-language text of a details answer, keyed by TMDB's language tag (`iso_639_1`, lower-cased).
12576
+ * A language that holds neither a title nor an overview is left out; a regional variant of a language
12577
+ * already seen (`pt-BR` after `pt-PT`) never replaces the first.
12578
+ */
12579
+ function translationsOf(details) {
12580
+ const out = {};
12581
+ for (const entry of details.translations?.translations ?? []) {
12582
+ const tag = entry.iso_639_1.trim().toLowerCase();
12583
+ const title = text(entry.data?.title ?? entry.data?.name);
12584
+ const overview = text(entry.data?.overview);
12585
+ if (tag === "" || out[tag] !== void 0 || title === null && overview === null) continue;
12586
+ out[tag] = {
12587
+ title,
12588
+ overview
12589
+ };
12590
+ }
12591
+ return out;
12592
+ }
12440
12593
  var nameOf = (entry) => entry.title ?? entry.name ?? "";
12441
12594
  var yearIn = (entry) => yearOf$1(entry.release_date ?? entry.first_air_date);
12442
12595
  /** TMDB: movies and series, with the installation's own read token. All calls go through the shared remote fetch. */
@@ -12470,11 +12623,12 @@ function createTmdbProvider(deps) {
12470
12623
  tmdbId: details.id,
12471
12624
  imdbId: text(details.external_ids?.imdb_id) ?? text(details.imdb_id),
12472
12625
  poster: image("w500", details.poster_path),
12473
- fanart: image("w1280", details.backdrop_path)
12626
+ fanart: image("w1280", details.backdrop_path),
12627
+ translations: translationsOf(details)
12474
12628
  });
12475
12629
  const detailsOf = async (kind, id) => {
12476
12630
  try {
12477
- return matchOf(DetailsSchema.parse(await call(`/${segment(kind)}/${id}`, { append_to_response: "external_ids" })));
12631
+ return matchOf(DetailsSchema.parse(await call(`/${segment(kind)}/${id}`, { append_to_response: "external_ids,translations" })));
12478
12632
  } catch (error) {
12479
12633
  if (error instanceof Error && /\b404\b/.test(error.message)) return null;
12480
12634
  throw error;
@@ -12482,6 +12636,7 @@ function createTmdbProvider(deps) {
12482
12636
  };
12483
12637
  return {
12484
12638
  id: TMDB_ID,
12639
+ translates: true,
12485
12640
  kinds: ["movie", "series"],
12486
12641
  lookupBy: [
12487
12642
  "tmdbId",
@@ -12929,8 +13084,17 @@ function typeOf(bytes) {
12929
13084
  if (bytes.length > 12 && bytes.subarray(8, 12).toString("latin1") === "WEBP") return "image/webp";
12930
13085
  return null;
12931
13086
  }
12932
- /** The remote URL of an arr cover: only a path on the arr's own origin, never another host. */
13087
+ /**
13088
+ * The remote URL of an arr cover: a path on the arr's own origin, or an absolute URL that already
13089
+ * IS on that origin (the arr app answers plain http on a LAN). Never another host, port or scheme,
13090
+ * and never a URL that carries credentials.
13091
+ */
12933
13092
  function coverUrl(source, path) {
13093
+ if (/^https?:\/\//i.test(path)) {
13094
+ const absolute = URL.canParse(path) ? new URL(path) : null;
13095
+ const own = new URL(source.baseUrl);
13096
+ return absolute !== null && absolute.origin === own.origin && absolute.username === "" && absolute.password === "" ? absolute.toString() : null;
13097
+ }
12934
13098
  if (!path.startsWith("/") || path.startsWith("//")) return null;
12935
13099
  const base = new URL(source.baseUrl);
12936
13100
  const url = new URL(`${source.baseUrl}${path}`);
@@ -13209,17 +13373,17 @@ function createFfmpegProber(binaryPath) {
13209
13373
  /** The `media-library` capability over the store. A caller reads and writes only their own progress. */
13210
13374
  function createMediaLibraryProvider(store, scans) {
13211
13375
  return {
13212
- listSeries: ({ limit, offset, caller }) => store.listSeries(caller.userId, limit, offset),
13213
- listMovies: ({ limit, offset, caller }) => store.listMovies(caller.userId, limit, offset),
13376
+ listSeries: ({ limit, offset, language, caller }) => store.listSeries(caller.userId, limit, offset, language),
13377
+ listMovies: ({ limit, offset, language, caller }) => store.listMovies(caller.userId, limit, offset, language),
13214
13378
  listSeasons: ({ seriesId, caller }) => store.listSeasons(caller.userId, seriesId),
13215
- listEpisodes: ({ seriesId, seasonNumber, caller }) => store.listEpisodes(caller.userId, seriesId, seasonNumber),
13216
- getItem: ({ itemId, caller }) => store.getItem(caller.userId, itemId),
13217
- search: ({ query, limit, caller }) => store.search(caller.userId, query, limit),
13218
- listRecentlyAdded: ({ limit, caller }) => store.listRecentlyAdded(caller.userId, limit),
13379
+ listEpisodes: ({ seriesId, seasonNumber, language, caller }) => store.listEpisodes(caller.userId, seriesId, seasonNumber, language),
13380
+ getItem: ({ itemId, language, caller }) => store.getItem(caller.userId, itemId, language),
13381
+ search: ({ query, limit, language, caller }) => store.search(caller.userId, query, limit, language),
13382
+ listRecentlyAdded: ({ limit, language, caller }) => store.listRecentlyAdded(caller.userId, limit, language),
13219
13383
  getProgress: ({ itemId, caller }) => store.getProgress(caller.userId, itemId),
13220
13384
  setProgress: ({ caller, ...input }) => store.setProgress(caller.userId, input),
13221
13385
  markWatched: ({ caller, ...input }) => store.markWatched(caller.userId, input),
13222
- listContinue: ({ limit, caller }) => store.listContinue(caller.userId, limit),
13386
+ listContinue: ({ limit, language, caller }) => store.listContinue(caller.userId, limit, language),
13223
13387
  rescan: async () => ({ started: scans.start("manual") }),
13224
13388
  getScanStatus: async () => scans.status()
13225
13389
  };
@@ -13235,6 +13399,7 @@ function fill(into, from) {
13235
13399
  title: into.title ?? from.title,
13236
13400
  year: into.year ?? from.year,
13237
13401
  overview: into.overview ?? from.overview,
13402
+ translations: into.translations ?? from.translations,
13238
13403
  tvdbId: into.tvdbId ?? from.tvdbId,
13239
13404
  tmdbId: into.tmdbId ?? from.tmdbId,
13240
13405
  imdbId: into.imdbId ?? from.imdbId,
@@ -13307,6 +13472,14 @@ var Enricher = class {
13307
13472
  if ((this.failures.get(id) ?? 0) >= PROVIDER_FAILURE_LIMIT) return null;
13308
13473
  return this.deps.providers.find((entry) => entry.id === id) ?? null;
13309
13474
  }
13475
+ /**
13476
+ * The cache namespace of a provider. A translating one answers its base text in the server's
13477
+ * language, so that language is part of the key: changing it asks again instead of serving the old
13478
+ * language for the cache lifetime.
13479
+ */
13480
+ keyOf(provider) {
13481
+ return provider.translates === true && this.deps.language !== void 0 ? `${provider.id}@${this.deps.language}` : provider.id;
13482
+ }
13310
13483
  imageProvider(id) {
13311
13484
  if ((this.failures.get(id) ?? 0) >= PROVIDER_FAILURE_LIMIT) return null;
13312
13485
  return this.deps.images?.find((entry) => entry.id === id) ?? null;
@@ -13381,10 +13554,19 @@ var Enricher = class {
13381
13554
  }
13382
13555
  });
13383
13556
  }
13557
+ /**
13558
+ * The cached answer for `key`, unless it predates translations: a match a translating provider
13559
+ * cached before it carried them is asked again, so a rollout does not wait out the cache lifetime.
13560
+ */
13561
+ cachedMatch(provider, key) {
13562
+ const known = this.deps.cache.getMatch(key);
13563
+ if (known === null) return null;
13564
+ return known.found && provider.translates === true && known.match.translations === void 0 ? null : known;
13565
+ }
13384
13566
  /** A pinned id is asked for directly: an answer of "nothing" is final, never turned into a title guess. */
13385
13567
  async lookup(provider, ask, item, kind, pin) {
13386
- const key = `${provider.id}:lookup:${kind}:${pin.tvdbId ?? ""}:${pin.imdbId ?? ""}:${pin.tmdbId ?? ""}`;
13387
- const known = this.deps.cache.getMatch(key);
13568
+ const key = `${this.keyOf(provider)}:lookup:${kind}:${pin.tvdbId ?? ""}:${pin.imdbId ?? ""}:${pin.tmdbId ?? ""}`;
13569
+ const known = this.cachedMatch(provider, key);
13388
13570
  if (known !== null) return known.found ? known.match : null;
13389
13571
  const pending = this.matches.get(key);
13390
13572
  if (pending !== void 0) return pending;
@@ -13435,8 +13617,8 @@ var Enricher = class {
13435
13617
  const found = await this.lookup(provider, provider.lookup.bind(provider), item, kind, ask.ids);
13436
13618
  if (found !== null || ask.fromPin) return found;
13437
13619
  }
13438
- const key = `${provider.id}:id:${kind}:${foldTitle(title)}:${year ?? 0}`;
13439
- const known = this.deps.cache.getMatch(key);
13620
+ const key = `${this.keyOf(provider)}:id:${kind}:${foldTitle(title)}:${year ?? 0}`;
13621
+ const known = this.cachedMatch(provider, key);
13440
13622
  if (known !== null) return known.found ? known.match : null;
13441
13623
  const pending = this.matches.get(key);
13442
13624
  if (pending !== void 0) return pending;
@@ -13457,7 +13639,7 @@ var Enricher = class {
13457
13639
  return run;
13458
13640
  }
13459
13641
  async episodesOf(provider, item, match) {
13460
- const key = `${provider.id}:eps:${match.remoteId}`;
13642
+ const key = `${this.keyOf(provider)}:eps:${match.remoteId}`;
13461
13643
  const known = this.deps.cache.getEpisodes(key);
13462
13644
  if (known !== null) return known.episodes;
13463
13645
  try {
@@ -13479,6 +13661,7 @@ var Enricher = class {
13479
13661
  title: match.title,
13480
13662
  year: match.year,
13481
13663
  overview: match.overview,
13664
+ translations: match.translations ?? null,
13482
13665
  tvdbId: match.tvdbId,
13483
13666
  tmdbId: match.tmdbId,
13484
13667
  imdbId: match.imdbId,
@@ -13507,9 +13690,9 @@ var Enricher = class {
13507
13690
  canAsk(provider, item) {
13508
13691
  return provider.kinds.includes(item.kind === "movie" ? "movie" : "series");
13509
13692
  }
13510
- needsOnline(item, acc) {
13693
+ needsOnline(provider, item, acc) {
13511
13694
  if (item.kind === "episode") return acc.overview === null || acc.poster === null || item.titlePlaceholder && acc.title === null;
13512
- return acc.overview === null || acc.poster === null;
13695
+ return acc.overview === null || acc.poster === null || provider.translates === true && acc.translations === null;
13513
13696
  }
13514
13697
  async localLayer(item, firstEpisodeFile) {
13515
13698
  const { reader } = this.deps;
@@ -13545,7 +13728,7 @@ var Enricher = class {
13545
13728
  const images = this.imageProvider(step);
13546
13729
  const provider = this.provider(step);
13547
13730
  if (images !== null && item.kind !== "episode" && images.kinds.includes(item.kind === "movie" ? "movie" : "series") && (acc.poster === null || acc.fanart === null)) acc = fill(acc, await this.imageLayer(images, item, acc));
13548
- else if (provider !== null && this.canAsk(provider, item) && this.needsOnline(item, acc)) acc = fill(acc, await this.onlineLayer(provider, item, acc, resolved, held));
13731
+ else if (provider !== null && this.canAsk(provider, item) && this.needsOnline(provider, item, acc)) acc = fill(acc, await this.onlineLayer(provider, item, acc, resolved, held));
13549
13732
  }
13550
13733
  applyPin();
13551
13734
  acc = fill(acc, fileLayer(item));
@@ -13557,6 +13740,7 @@ var Enricher = class {
13557
13740
  titleFold: foldTitle(title),
13558
13741
  year: acc.year,
13559
13742
  overview: acc.overview,
13743
+ translations: acc.translations,
13560
13744
  tvdbId: acc.tvdbId,
13561
13745
  tmdbId: acc.tmdbId,
13562
13746
  imdbId: acc.imdbId,
@@ -13597,6 +13781,7 @@ function newItem(base) {
13597
13781
  seasonNumber: null,
13598
13782
  episodeNumber: null,
13599
13783
  overview: null,
13784
+ translations: null,
13600
13785
  tvdbId: null,
13601
13786
  tmdbId: null,
13602
13787
  imdbId: null,
@@ -13753,13 +13938,13 @@ async function folderItems(root, paths, reader) {
13753
13938
  //#endregion
13754
13939
  //#region src/scanner.ts
13755
13940
  /** The online providers this scan may ask: the fixed ones, plus each keyed one whose key is set. */
13756
- function onlineProviders(deps, sources) {
13941
+ function onlineProviders(deps, sources, language = "en") {
13757
13942
  const keyed = (make, key) => make !== void 0 && (key ?? "") !== "" ? [make(key ?? "")] : [];
13758
13943
  const fanartKey = sources.fanartApiKey ?? "";
13759
13944
  return {
13760
13945
  providers: [
13761
13946
  ...deps.providers ?? [],
13762
- ...keyed(deps.createTmdb, sources.tmdbToken),
13947
+ ...deps.createTmdb !== void 0 && (sources.tmdbToken ?? "") !== "" ? [deps.createTmdb(sources.tmdbToken ?? "", language)] : [],
13763
13948
  ...keyed(deps.createTvdb, sources.tvdbApiKey),
13764
13949
  ...keyed(deps.createOmdb, sources.omdbApiKey),
13765
13950
  ...deps.createAnilist !== void 0 && (sources.metadataSteps ?? []).includes("anilist") ? [deps.createAnilist()] : []
@@ -13907,12 +14092,14 @@ async function scanLibrary(deps, sources) {
13907
14092
  logger.warn("metadata matches could not be saved: they are asked for again next scan", { meta: { error: error instanceof Error ? error.message : String(error) } });
13908
14093
  }
13909
14094
  };
14095
+ const language = await deps.language?.() ?? "en";
13910
14096
  for (const [index, entry] of harvests.entries()) {
13911
14097
  try {
13912
- const online = onlineProviders(deps, sources);
14098
+ const online = onlineProviders(deps, sources, language);
13913
14099
  const items = await enrichItems(entry.items, sources.metadataSteps ?? DEFAULT_STEPS, {
13914
14100
  reader,
13915
14101
  providers: online.providers,
14102
+ language,
13916
14103
  images: online.images,
13917
14104
  cache,
13918
14105
  logger,
@@ -14186,7 +14373,9 @@ var MediaLibraryAddon = class extends BaseAddon {
14186
14373
  const { ctx } = this;
14187
14374
  const logger = ctx.logger;
14188
14375
  const db = settingsStoreDb(ctx.api.settingsStore);
14189
- const store = new LibraryStore(db, logger);
14376
+ const serverLanguage = new ServerLanguage(async () => (await ctx.api.system.info.query()).defaultLanguage, () => Date.now(), logger);
14377
+ await serverLanguage.refresh();
14378
+ const store = new LibraryStore(db, logger, () => serverLanguage.current());
14190
14379
  await store.init();
14191
14380
  const ffmpeg = await ctx.deps.ensureFfmpeg();
14192
14381
  const scans = new ScanController({
@@ -14207,9 +14396,14 @@ var MediaLibraryAddon = class extends BaseAddon {
14207
14396
  },
14208
14397
  probe: createFfmpegProber(ffmpeg),
14209
14398
  providers: [createTvmazeProvider({ fetch: httpRemoteFetch })],
14210
- createTmdb: (token) => createTmdbProvider({
14399
+ language: async () => {
14400
+ await serverLanguage.refresh();
14401
+ return serverLanguage.current();
14402
+ },
14403
+ createTmdb: (token, language) => createTmdbProvider({
14211
14404
  fetch: httpRemoteFetch,
14212
- token
14405
+ token,
14406
+ language: tmdbLanguageOf(language)
14213
14407
  }),
14214
14408
  createTvdb: (apiKey) => createTvdbProvider({
14215
14409
  fetch: httpRemoteFetch,