@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.
@@ -8859,7 +8859,14 @@ var MediaScanStatusSchema = /* @__PURE__ */ object({
8859
8859
  reused: /* @__PURE__ */ number().int().nonnegative(),
8860
8860
  skipped: /* @__PURE__ */ number().int().nonnegative()
8861
8861
  });
8862
+ /**
8863
+ * The language the caller wants item text in (`title`, `overview`): a locale tag such as `it`; a
8864
+ * regional form (`it-IT`) reads as its language. Absent means the server's default language. A language
8865
+ * the item has no text in falls back to the server default, then to the text stored with the item.
8866
+ */
8867
+ var LanguageInputSchema = /* @__PURE__ */ string().min(2).max(35).optional();
8862
8868
  var PageInputSchema = /* @__PURE__ */ object({
8869
+ language: LanguageInputSchema,
8863
8870
  limit: /* @__PURE__ */ number().int().positive().max(500).optional(),
8864
8871
  offset: /* @__PURE__ */ number().int().nonnegative().optional()
8865
8872
  });
@@ -8878,17 +8885,25 @@ var mediaLibraryCapability = {
8878
8885
  /** The episodes of one season in order, each with the caller's progress. */
8879
8886
  listEpisodes: /* @__PURE__ */ method(/* @__PURE__ */ object({
8880
8887
  seriesId: /* @__PURE__ */ string().min(1),
8881
- seasonNumber: /* @__PURE__ */ number().int()
8888
+ seasonNumber: /* @__PURE__ */ number().int(),
8889
+ language: LanguageInputSchema
8882
8890
  }), /* @__PURE__ */ array(MediaEpisodeSummarySchema).readonly(), { caller: "required" }),
8883
8891
  /** One item with its streams and direct-play path; `null` when the id is unknown. */
8884
- getItem: /* @__PURE__ */ method(/* @__PURE__ */ object({ itemId: /* @__PURE__ */ string().min(1) }), /* @__PURE__ */ MediaItemDetailSchema.nullable(), { caller: "required" }),
8892
+ getItem: /* @__PURE__ */ method(/* @__PURE__ */ object({
8893
+ itemId: /* @__PURE__ */ string().min(1),
8894
+ language: LanguageInputSchema
8895
+ }), /* @__PURE__ */ MediaItemDetailSchema.nullable(), { caller: "required" }),
8885
8896
  /** Series and movies whose title contains the query, case and accents ignored. */
8886
8897
  search: /* @__PURE__ */ method(/* @__PURE__ */ object({
8887
8898
  query: /* @__PURE__ */ string().min(1),
8888
- limit: /* @__PURE__ */ number().int().positive().max(100).optional()
8899
+ limit: /* @__PURE__ */ number().int().positive().max(100).optional(),
8900
+ language: LanguageInputSchema
8889
8901
  }), /* @__PURE__ */ array(MediaItemSummarySchema).readonly(), { caller: "required" }),
8890
8902
  /** The series and movies added most recently. */
8891
- listRecentlyAdded: /* @__PURE__ */ method(/* @__PURE__ */ object({ limit: /* @__PURE__ */ number().int().positive().max(100).optional() }), /* @__PURE__ */ array(MediaItemSummarySchema).readonly(), { caller: "required" }),
8903
+ listRecentlyAdded: /* @__PURE__ */ method(/* @__PURE__ */ object({
8904
+ limit: /* @__PURE__ */ number().int().positive().max(100).optional(),
8905
+ language: LanguageInputSchema
8906
+ }), /* @__PURE__ */ array(MediaItemSummarySchema).readonly(), { caller: "required" }),
8892
8907
  /** The caller's progress in one item; `null` when they have none. */
8893
8908
  getProgress: /* @__PURE__ */ method(/* @__PURE__ */ object({ itemId: /* @__PURE__ */ string().min(1) }), /* @__PURE__ */ MediaProgressSchema.nullable(), { caller: "required" }),
8894
8909
  /**
@@ -8915,7 +8930,10 @@ var mediaLibraryCapability = {
8915
8930
  caller: "required"
8916
8931
  }),
8917
8932
  /** What the caller started and did not finish, the latest first. */
8918
- listContinue: /* @__PURE__ */ method(/* @__PURE__ */ object({ limit: /* @__PURE__ */ number().int().positive().max(100).optional() }), /* @__PURE__ */ array(MediaContinueEntrySchema).readonly(), { caller: "required" }),
8933
+ listContinue: /* @__PURE__ */ method(/* @__PURE__ */ object({
8934
+ limit: /* @__PURE__ */ number().int().positive().max(100).optional(),
8935
+ language: LanguageInputSchema
8936
+ }), /* @__PURE__ */ array(MediaContinueEntrySchema).readonly(), { caller: "required" }),
8919
8937
  /** Start a scan of every source now; answers at once, the scan runs in the background. */
8920
8938
  rescan: /* @__PURE__ */ method(/* @__PURE__ */ object({}), /* @__PURE__ */ object({ started: /* @__PURE__ */ boolean() }), {
8921
8939
  kind: "mutation",
@@ -10029,6 +10047,16 @@ function parseRows(schema, rows, onInvalid) {
10029
10047
  }
10030
10048
  //#endregion
10031
10049
  //#region src/metadata.ts
10050
+ /**
10051
+ * One language's text of an item: either field may be absent (a provider can translate the title and
10052
+ * not the overview, or the reverse). The language is the provider's own tag, lower-cased (`it`, `pt`).
10053
+ */
10054
+ var TextTranslationSchema = object({
10055
+ title: string().nullable(),
10056
+ overview: string().nullable()
10057
+ });
10058
+ /** Translations by language tag. Absent means "never asked"; `{}` means "asked, none held". */
10059
+ var TranslationMapSchema = record(string(), TextTranslationSchema);
10032
10060
  var ProviderMatchSchema = object({
10033
10061
  providerId: string(),
10034
10062
  /** The provider's own id of the match, used to ask for its episodes. */
@@ -10040,7 +10068,9 @@ var ProviderMatchSchema = object({
10040
10068
  tmdbId: number().int().nullable(),
10041
10069
  imdbId: string().nullable(),
10042
10070
  poster: string().nullable(),
10043
- fanart: string().nullable()
10071
+ fanart: string().nullable(),
10072
+ /** The title and overview in other languages, when the provider answered them with the match. */
10073
+ translations: TranslationMapSchema.optional()
10044
10074
  });
10045
10075
  var ProviderEpisodeSchema = object({
10046
10076
  season: number().int(),
@@ -10181,6 +10211,8 @@ var ItemRowSchema = object({
10181
10211
  seasonNumber: number().int().nullable(),
10182
10212
  episodeNumber: number().int().nullable(),
10183
10213
  overview: string().nullable(),
10214
+ /** The title and overview in other languages; absent on a row written before they were kept. */
10215
+ translations: TranslationMapSchema.nullish(),
10184
10216
  tvdbId: number().int().nullable(),
10185
10217
  tmdbId: number().int().nullable(),
10186
10218
  imdbId: string().nullable(),
@@ -10251,6 +10283,10 @@ var COLLECTIONS = [
10251
10283
  int("seasonNumber"),
10252
10284
  int("episodeNumber"),
10253
10285
  text$3("overview"),
10286
+ {
10287
+ name: "translations",
10288
+ type: "JSON"
10289
+ },
10254
10290
  int("tvdbId"),
10255
10291
  int("tmdbId"),
10256
10292
  text$3("imdbId"),
@@ -10616,6 +10652,7 @@ var NO_LOCAL = {
10616
10652
  title: null,
10617
10653
  year: null,
10618
10654
  overview: null,
10655
+ translations: null,
10619
10656
  tvdbId: null,
10620
10657
  tmdbId: null,
10621
10658
  imdbId: null,
@@ -10655,6 +10692,7 @@ function merge(first, second) {
10655
10692
  title: pick$1(first.title, second.title),
10656
10693
  year: pick$1(first.year, second.year),
10657
10694
  overview: pick$1(first.overview, second.overview),
10695
+ translations: pick$1(first.translations, second.translations),
10658
10696
  tvdbId: pick$1(first.tvdbId, second.tvdbId),
10659
10697
  tmdbId: pick$1(first.tmdbId, second.tmdbId),
10660
10698
  imdbId: pick$1(first.imdbId, second.imdbId),
@@ -10711,6 +10749,47 @@ async function localMovie(reader, filePath) {
10711
10749
  fanart: firstImage(dir, listing, [`${base}-fanart`, ...solo ? ["fanart"] : []])
10712
10750
  };
10713
10751
  }
10752
+ //#endregion
10753
+ //#region src/item-text.ts
10754
+ /**
10755
+ * A language tag as the translations are keyed: lower-case, region dropped (`it-IT` is `it`).
10756
+ * `undefined` for an absent or empty tag.
10757
+ */
10758
+ function languageKey(tag) {
10759
+ const primary = tag?.trim().toLowerCase().split(/[-_]/)[0] ?? "";
10760
+ return primary === "" ? void 0 : primary;
10761
+ }
10762
+ /**
10763
+ * The text of `row` for a reader: the language they asked for, else the server's default language,
10764
+ * else the base text stored with the item. Each field falls through on its own, so a language that
10765
+ * translated the title and not the overview still gives the title.
10766
+ */
10767
+ function resolveItemText(row, requested, serverDefault) {
10768
+ let title = null;
10769
+ let overview = null;
10770
+ for (const key of [languageKey(requested), languageKey(serverDefault)]) {
10771
+ const entry = key === void 0 ? void 0 : row.translations?.[key];
10772
+ title ??= entry?.title ?? null;
10773
+ overview ??= entry?.overview ?? null;
10774
+ }
10775
+ return {
10776
+ title: title ?? row.title,
10777
+ overview: overview ?? row.overview
10778
+ };
10779
+ }
10780
+ /**
10781
+ * `rows` in A–Z order of the title each reader sees (`resolveItemText`, minus a leading article), compared with the
10782
+ * collator of the reader's language (`en` when none). A stable sort: equal titles keep the order
10783
+ * the rows came in (the caller's read order: item id for `queryAllItems`), so a page cut is deterministic.
10784
+ */
10785
+ function sortByShownTitle(rows, requested, serverDefault) {
10786
+ const collator = new Intl.Collator(languageKey(requested) ?? "en", {
10787
+ sensitivity: "base",
10788
+ numeric: true
10789
+ });
10790
+ const keys = new Map(rows.map((row) => [row, sortKey(resolveItemText(row, requested, serverDefault).title)]));
10791
+ return rows.toSorted((a, b) => collator.compare(keys.get(a) ?? "", keys.get(b) ?? ""));
10792
+ }
10714
10793
  var FILE_PLANE_PREFIX = "file";
10715
10794
  var HUB_PLANE_BASE = "/addon/media-library";
10716
10795
  var SEARCH_DEFAULT_LIMIT = 50;
@@ -10731,10 +10810,12 @@ var idList = (rows) => rows.map((row) => row.id);
10731
10810
  var LibraryStore = class {
10732
10811
  db;
10733
10812
  logger;
10813
+ serverLanguage;
10734
10814
  locks = /* @__PURE__ */ new Map();
10735
- constructor(db, logger) {
10815
+ constructor(db, logger, serverLanguage = () => "en") {
10736
10816
  this.db = db;
10737
10817
  this.logger = logger;
10818
+ this.serverLanguage = serverLanguage;
10738
10819
  }
10739
10820
  async init() {
10740
10821
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -10759,7 +10840,7 @@ var LibraryStore = class {
10759
10840
  return parseRows(ProgressRowSchema, await this.db.query(PROGRESS, filter), this.invalid(PROGRESS));
10760
10841
  }
10761
10842
  /** Build the wire summaries of `rows` for one caller: file facts and the caller's progress, two reads. */
10762
- async summaries(rows, userId) {
10843
+ async summaries(rows, userId, language) {
10763
10844
  const paths = rows.flatMap((row) => row.filePath === null ? [] : [row.filePath]);
10764
10845
  const files = /* @__PURE__ */ new Map();
10765
10846
  if (paths.length > 0) for (const file of await this.queryFiles({ whereIn: { path: paths } })) files.set(file.path, file);
@@ -10769,39 +10850,30 @@ var LibraryStore = class {
10769
10850
  where: { userId },
10770
10851
  whereIn: { itemId: playableIds }
10771
10852
  })) progress.set(entry.itemId, entry);
10853
+ const fallback = this.serverLanguage();
10772
10854
  return rows.map((row) => {
10773
- return toSummary(row, row.filePath === null ? void 0 : files.get(row.filePath), progress.get(row.id));
10855
+ return toSummary(row, row.filePath === null ? void 0 : files.get(row.filePath), progress.get(row.id), resolveItemText(row, language, fallback).title);
10774
10856
  });
10775
10857
  }
10776
- pageOf = async (kind, userId, limit, offset) => {
10777
- const rows = await this.queryItems({
10778
- where: {
10779
- kind,
10780
- topLevel: true
10781
- },
10782
- orderBy: {
10783
- field: "sortTitle",
10784
- direction: "asc"
10785
- },
10786
- limit: limit ?? 100,
10787
- offset: offset ?? 0
10788
- });
10789
- const total = await this.db.count(ITEMS, { where: {
10858
+ pageOf = async (kind, userId, limit, offset, language) => {
10859
+ const all = await this.queryAllItems({ where: {
10790
10860
  kind,
10791
10861
  topLevel: true
10792
10862
  } });
10863
+ const start = offset ?? 0;
10864
+ const page = sortByShownTitle(all, language, this.serverLanguage()).slice(start, start + (limit ?? 100));
10793
10865
  return {
10794
- items: await this.summaries(rows, userId),
10795
- total
10866
+ items: await this.summaries(page, userId, language),
10867
+ total: all.length
10796
10868
  };
10797
10869
  };
10798
- listSeries(userId, limit, offset) {
10799
- return this.pageOf("series", userId, limit, offset);
10870
+ listSeries(userId, limit, offset, language) {
10871
+ return this.pageOf("series", userId, limit, offset, language);
10800
10872
  }
10801
- listMovies(userId, limit, offset) {
10802
- return this.pageOf("movie", userId, limit, offset);
10873
+ listMovies(userId, limit, offset, language) {
10874
+ return this.pageOf("movie", userId, limit, offset, language);
10803
10875
  }
10804
- async listRecentlyAdded(userId, limit) {
10876
+ async listRecentlyAdded(userId, limit, language) {
10805
10877
  const rows = await this.queryItems({
10806
10878
  where: { topLevel: true },
10807
10879
  orderBy: {
@@ -10810,19 +10882,15 @@ var LibraryStore = class {
10810
10882
  },
10811
10883
  limit: limit ?? RECENT_DEFAULT_LIMIT
10812
10884
  });
10813
- return this.summaries(rows, userId);
10885
+ return this.summaries(rows, userId, language);
10814
10886
  }
10815
- async search(userId, query, limit) {
10887
+ async search(userId, query, limit, language) {
10816
10888
  const needle = foldTitle(query);
10817
10889
  if (needle === "") return [];
10818
- const hits = (await this.queryItems({
10819
- where: { topLevel: true },
10820
- orderBy: {
10821
- field: "sortTitle",
10822
- direction: "asc"
10823
- }
10824
- })).filter((row) => row.titleFold.includes(needle)).slice(0, limit ?? SEARCH_DEFAULT_LIMIT);
10825
- return this.summaries(hits, userId);
10890
+ const rows = await this.queryAllItems({ where: { topLevel: true } });
10891
+ const fallback = this.serverLanguage();
10892
+ 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);
10893
+ return this.summaries(hits, userId, language);
10826
10894
  }
10827
10895
  episodesOf(seriesId) {
10828
10896
  return this.queryItems({
@@ -10860,7 +10928,7 @@ var LibraryStore = class {
10860
10928
  watchedCount: entry.watched
10861
10929
  }));
10862
10930
  }
10863
- async listEpisodes(userId, seriesId, seasonNumber) {
10931
+ async listEpisodes(userId, seriesId, seasonNumber, language) {
10864
10932
  const rows = await this.queryItems({
10865
10933
  where: {
10866
10934
  parentId: seriesId,
@@ -10871,18 +10939,23 @@ var LibraryStore = class {
10871
10939
  direction: "asc"
10872
10940
  }
10873
10941
  });
10874
- return (await this.summaries(rows, userId)).map((summary, index) => ({
10875
- ...summary,
10876
- overview: rows[index]?.overview ?? null
10877
- }));
10942
+ const summaries = await this.summaries(rows, userId, language);
10943
+ const fallback = this.serverLanguage();
10944
+ return summaries.map((summary, index) => {
10945
+ const row = rows[index];
10946
+ return {
10947
+ ...summary,
10948
+ overview: row === void 0 ? null : resolveItemText(row, language, fallback).overview
10949
+ };
10950
+ });
10878
10951
  }
10879
- async getItem(userId, itemId) {
10952
+ async getItem(userId, itemId, language) {
10880
10953
  const [row] = await this.queryItems({
10881
10954
  where: { id: itemId },
10882
10955
  limit: 1
10883
10956
  });
10884
10957
  if (row === void 0) return null;
10885
- const [summary] = await this.summaries([row], userId);
10958
+ const [summary] = await this.summaries([row], userId, language);
10886
10959
  if (summary === void 0) return null;
10887
10960
  const [file] = row.filePath === null ? [] : await this.queryFiles({
10888
10961
  where: { path: row.filePath },
@@ -10890,7 +10963,7 @@ var LibraryStore = class {
10890
10963
  });
10891
10964
  return {
10892
10965
  ...summary,
10893
- overview: row.overview,
10966
+ overview: resolveItemText(row, language, this.serverLanguage()).overview,
10894
10967
  ids: {
10895
10968
  tvdb: row.tvdbId,
10896
10969
  tmdb: row.tmdbId,
@@ -10936,7 +11009,7 @@ var LibraryStore = class {
10936
11009
  kind: "remote",
10937
11010
  url: cover
10938
11011
  });
10939
- else if (cover.startsWith("/")) out.push({
11012
+ else if (cover.startsWith("/") || cover.startsWith("http://")) out.push({
10940
11013
  kind: "arr",
10941
11014
  path: cover,
10942
11015
  sourceId: item.sourceId
@@ -11080,7 +11153,7 @@ var LibraryStore = class {
11080
11153
  watched
11081
11154
  };
11082
11155
  }
11083
- async listContinue(userId, limit) {
11156
+ async listContinue(userId, limit, language) {
11084
11157
  const wanted = limit ?? CONTINUE_DEFAULT_LIMIT;
11085
11158
  const rows = (await this.queryProgress({
11086
11159
  where: {
@@ -11095,7 +11168,7 @@ var LibraryStore = class {
11095
11168
  })).filter((row) => row.positionMs > 0);
11096
11169
  if (rows.length === 0) return [];
11097
11170
  const items = await this.queryItems({ whereIn: { id: rows.map((row) => row.itemId) } });
11098
- const summaries = new Map((await this.summaries(items, userId)).map((summary) => [summary.id, summary]));
11171
+ const summaries = new Map((await this.summaries(items, userId, language)).map((summary) => [summary.id, summary]));
11099
11172
  const entries = [];
11100
11173
  for (const row of rows) {
11101
11174
  const item = summaries.get(row.itemId);
@@ -11126,11 +11199,11 @@ function toFileInfo(file) {
11126
11199
  probed: file.probeOk
11127
11200
  };
11128
11201
  }
11129
- function toSummary(row, file, progress) {
11202
+ function toSummary(row, file, progress, title) {
11130
11203
  return {
11131
11204
  id: row.id,
11132
11205
  kind: row.kind,
11133
- title: row.title,
11206
+ title,
11134
11207
  year: row.year,
11135
11208
  seriesId: row.kind === "episode" ? row.parentId : null,
11136
11209
  seasonNumber: row.seasonNumber,
@@ -12380,6 +12453,51 @@ function createOmdbProvider(deps) {
12380
12453
  }
12381
12454
  };
12382
12455
  }
12456
+ /**
12457
+ * The server's default language, kept in memory so no catalogue read waits on the system call.
12458
+ * A read answers what is held; one that finds it older than {@link SERVER_LANGUAGE_REFRESH_MS}
12459
+ * starts a refresh and does not wait for it. A refresh that fails changes nothing (the last answer
12460
+ * stays, English when there never was one) and says so in the log.
12461
+ */
12462
+ var ServerLanguage = class {
12463
+ read;
12464
+ now;
12465
+ logger;
12466
+ value = "en";
12467
+ attemptedAt = null;
12468
+ inFlight = null;
12469
+ constructor(read, now, logger) {
12470
+ this.read = read;
12471
+ this.now = now;
12472
+ this.logger = logger;
12473
+ }
12474
+ /** Ask now and wait; used at boot and at the start of a scan, never on a read. */
12475
+ refresh() {
12476
+ if (this.inFlight !== null) return this.inFlight;
12477
+ const run = (async () => {
12478
+ try {
12479
+ const read = await this.read();
12480
+ if (read === null) this.logger.warn("server default language unreadable: keeping the last one", { meta: { kept: this.value } });
12481
+ else this.value = read;
12482
+ } catch (error) {
12483
+ this.logger.warn("server default language not read: keeping the last one", { meta: {
12484
+ error: errMsg(error),
12485
+ kept: this.value
12486
+ } });
12487
+ } finally {
12488
+ this.attemptedAt = this.now();
12489
+ this.inFlight = null;
12490
+ }
12491
+ })();
12492
+ this.inFlight = run;
12493
+ return run;
12494
+ }
12495
+ /** The held language; starts a background refresh when it is stale. Never throws, never waits. */
12496
+ current() {
12497
+ if (this.attemptedAt === null || this.now() - this.attemptedAt >= 6e4) this.refresh();
12498
+ return this.value;
12499
+ }
12500
+ };
12383
12501
  //#endregion
12384
12502
  //#region src/tmdb.ts
12385
12503
  var TMDB_ID = "tmdb";
@@ -12395,6 +12513,15 @@ var SearchSchema$2 = object({ results: array(object({
12395
12513
  release_date: string().nullish(),
12396
12514
  first_air_date: string().nullish()
12397
12515
  })) });
12516
+ /** `append_to_response=translations`: one entry per language TMDB holds, `data` carries the text. */
12517
+ var TranslationsSchema = object({ translations: array(object({
12518
+ iso_639_1: string(),
12519
+ data: object({
12520
+ title: string().nullish(),
12521
+ name: string().nullish(),
12522
+ overview: string().nullish()
12523
+ }).nullish()
12524
+ })) });
12398
12525
  var DetailsSchema = object({
12399
12526
  id: number().int(),
12400
12527
  title: string().nullish(),
@@ -12409,7 +12536,8 @@ var DetailsSchema = object({
12409
12536
  imdb_id: string().nullish(),
12410
12537
  tvdb_id: number().int().nullish()
12411
12538
  }).nullish(),
12412
- seasons: array(object({ season_number: number().int() })).nullish()
12539
+ seasons: array(object({ season_number: number().int() })).nullish(),
12540
+ translations: TranslationsSchema.nullish()
12413
12541
  });
12414
12542
  var FindSchema = object({
12415
12543
  movie_results: array(object({ id: number().int() })).default([]),
@@ -12422,6 +12550,12 @@ var SeasonSchema = object({ episodes: array(object({
12422
12550
  overview: string().nullish(),
12423
12551
  still_path: string().nullish()
12424
12552
  })) });
12553
+ /** 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
+ function tmdbLanguageOf(language) {
12555
+ if (language === "en") return DEFAULT_LANGUAGE;
12556
+ if (language === "zh") return "zh-CN";
12557
+ return language;
12558
+ }
12425
12559
  function yearOf$1(date) {
12426
12560
  const match = /^(\d{4})/.exec(date ?? "");
12427
12561
  return match?.[1] === void 0 ? null : Number(match[1]);
@@ -12433,6 +12567,25 @@ function text(value) {
12433
12567
  function image(size, path) {
12434
12568
  return path === null || path === void 0 || !path.startsWith("/") ? null : `${IMAGES}/${size}${path}`;
12435
12569
  }
12570
+ /**
12571
+ * The per-language text of a details answer, keyed by TMDB's language tag (`iso_639_1`, lower-cased).
12572
+ * A language that holds neither a title nor an overview is left out; a regional variant of a language
12573
+ * already seen (`pt-BR` after `pt-PT`) never replaces the first.
12574
+ */
12575
+ function translationsOf(details) {
12576
+ const out = {};
12577
+ for (const entry of details.translations?.translations ?? []) {
12578
+ const tag = entry.iso_639_1.trim().toLowerCase();
12579
+ const title = text(entry.data?.title ?? entry.data?.name);
12580
+ const overview = text(entry.data?.overview);
12581
+ if (tag === "" || out[tag] !== void 0 || title === null && overview === null) continue;
12582
+ out[tag] = {
12583
+ title,
12584
+ overview
12585
+ };
12586
+ }
12587
+ return out;
12588
+ }
12436
12589
  var nameOf = (entry) => entry.title ?? entry.name ?? "";
12437
12590
  var yearIn = (entry) => yearOf$1(entry.release_date ?? entry.first_air_date);
12438
12591
  /** TMDB: movies and series, with the installation's own read token. All calls go through the shared remote fetch. */
@@ -12466,11 +12619,12 @@ function createTmdbProvider(deps) {
12466
12619
  tmdbId: details.id,
12467
12620
  imdbId: text(details.external_ids?.imdb_id) ?? text(details.imdb_id),
12468
12621
  poster: image("w500", details.poster_path),
12469
- fanart: image("w1280", details.backdrop_path)
12622
+ fanart: image("w1280", details.backdrop_path),
12623
+ translations: translationsOf(details)
12470
12624
  });
12471
12625
  const detailsOf = async (kind, id) => {
12472
12626
  try {
12473
- return matchOf(DetailsSchema.parse(await call(`/${segment(kind)}/${id}`, { append_to_response: "external_ids" })));
12627
+ return matchOf(DetailsSchema.parse(await call(`/${segment(kind)}/${id}`, { append_to_response: "external_ids,translations" })));
12474
12628
  } catch (error) {
12475
12629
  if (error instanceof Error && /\b404\b/.test(error.message)) return null;
12476
12630
  throw error;
@@ -12478,6 +12632,7 @@ function createTmdbProvider(deps) {
12478
12632
  };
12479
12633
  return {
12480
12634
  id: TMDB_ID,
12635
+ translates: true,
12481
12636
  kinds: ["movie", "series"],
12482
12637
  lookupBy: [
12483
12638
  "tmdbId",
@@ -12925,8 +13080,17 @@ function typeOf(bytes) {
12925
13080
  if (bytes.length > 12 && bytes.subarray(8, 12).toString("latin1") === "WEBP") return "image/webp";
12926
13081
  return null;
12927
13082
  }
12928
- /** The remote URL of an arr cover: only a path on the arr's own origin, never another host. */
13083
+ /**
13084
+ * The remote URL of an arr cover: a path on the arr's own origin, or an absolute URL that already
13085
+ * IS on that origin (the arr app answers plain http on a LAN). Never another host, port or scheme,
13086
+ * and never a URL that carries credentials.
13087
+ */
12929
13088
  function coverUrl(source, path) {
13089
+ if (/^https?:\/\//i.test(path)) {
13090
+ const absolute = URL.canParse(path) ? new URL(path) : null;
13091
+ const own = new URL(source.baseUrl);
13092
+ return absolute !== null && absolute.origin === own.origin && absolute.username === "" && absolute.password === "" ? absolute.toString() : null;
13093
+ }
12930
13094
  if (!path.startsWith("/") || path.startsWith("//")) return null;
12931
13095
  const base = new URL(source.baseUrl);
12932
13096
  const url = new URL(`${source.baseUrl}${path}`);
@@ -13205,17 +13369,17 @@ function createFfmpegProber(binaryPath) {
13205
13369
  /** The `media-library` capability over the store. A caller reads and writes only their own progress. */
13206
13370
  function createMediaLibraryProvider(store, scans) {
13207
13371
  return {
13208
- listSeries: ({ limit, offset, caller }) => store.listSeries(caller.userId, limit, offset),
13209
- listMovies: ({ limit, offset, caller }) => store.listMovies(caller.userId, limit, offset),
13372
+ listSeries: ({ limit, offset, language, caller }) => store.listSeries(caller.userId, limit, offset, language),
13373
+ listMovies: ({ limit, offset, language, caller }) => store.listMovies(caller.userId, limit, offset, language),
13210
13374
  listSeasons: ({ seriesId, caller }) => store.listSeasons(caller.userId, seriesId),
13211
- listEpisodes: ({ seriesId, seasonNumber, caller }) => store.listEpisodes(caller.userId, seriesId, seasonNumber),
13212
- getItem: ({ itemId, caller }) => store.getItem(caller.userId, itemId),
13213
- search: ({ query, limit, caller }) => store.search(caller.userId, query, limit),
13214
- listRecentlyAdded: ({ limit, caller }) => store.listRecentlyAdded(caller.userId, limit),
13375
+ listEpisodes: ({ seriesId, seasonNumber, language, caller }) => store.listEpisodes(caller.userId, seriesId, seasonNumber, language),
13376
+ getItem: ({ itemId, language, caller }) => store.getItem(caller.userId, itemId, language),
13377
+ search: ({ query, limit, language, caller }) => store.search(caller.userId, query, limit, language),
13378
+ listRecentlyAdded: ({ limit, language, caller }) => store.listRecentlyAdded(caller.userId, limit, language),
13215
13379
  getProgress: ({ itemId, caller }) => store.getProgress(caller.userId, itemId),
13216
13380
  setProgress: ({ caller, ...input }) => store.setProgress(caller.userId, input),
13217
13381
  markWatched: ({ caller, ...input }) => store.markWatched(caller.userId, input),
13218
- listContinue: ({ limit, caller }) => store.listContinue(caller.userId, limit),
13382
+ listContinue: ({ limit, language, caller }) => store.listContinue(caller.userId, limit, language),
13219
13383
  rescan: async () => ({ started: scans.start("manual") }),
13220
13384
  getScanStatus: async () => scans.status()
13221
13385
  };
@@ -13231,6 +13395,7 @@ function fill(into, from) {
13231
13395
  title: into.title ?? from.title,
13232
13396
  year: into.year ?? from.year,
13233
13397
  overview: into.overview ?? from.overview,
13398
+ translations: into.translations ?? from.translations,
13234
13399
  tvdbId: into.tvdbId ?? from.tvdbId,
13235
13400
  tmdbId: into.tmdbId ?? from.tmdbId,
13236
13401
  imdbId: into.imdbId ?? from.imdbId,
@@ -13303,6 +13468,14 @@ var Enricher = class {
13303
13468
  if ((this.failures.get(id) ?? 0) >= PROVIDER_FAILURE_LIMIT) return null;
13304
13469
  return this.deps.providers.find((entry) => entry.id === id) ?? null;
13305
13470
  }
13471
+ /**
13472
+ * The cache namespace of a provider. A translating one answers its base text in the server's
13473
+ * language, so that language is part of the key: changing it asks again instead of serving the old
13474
+ * language for the cache lifetime.
13475
+ */
13476
+ keyOf(provider) {
13477
+ return provider.translates === true && this.deps.language !== void 0 ? `${provider.id}@${this.deps.language}` : provider.id;
13478
+ }
13306
13479
  imageProvider(id) {
13307
13480
  if ((this.failures.get(id) ?? 0) >= PROVIDER_FAILURE_LIMIT) return null;
13308
13481
  return this.deps.images?.find((entry) => entry.id === id) ?? null;
@@ -13377,10 +13550,19 @@ var Enricher = class {
13377
13550
  }
13378
13551
  });
13379
13552
  }
13553
+ /**
13554
+ * The cached answer for `key`, unless it predates translations: a match a translating provider
13555
+ * cached before it carried them is asked again, so a rollout does not wait out the cache lifetime.
13556
+ */
13557
+ cachedMatch(provider, key) {
13558
+ const known = this.deps.cache.getMatch(key);
13559
+ if (known === null) return null;
13560
+ return known.found && provider.translates === true && known.match.translations === void 0 ? null : known;
13561
+ }
13380
13562
  /** A pinned id is asked for directly: an answer of "nothing" is final, never turned into a title guess. */
13381
13563
  async lookup(provider, ask, item, kind, pin) {
13382
- const key = `${provider.id}:lookup:${kind}:${pin.tvdbId ?? ""}:${pin.imdbId ?? ""}:${pin.tmdbId ?? ""}`;
13383
- const known = this.deps.cache.getMatch(key);
13564
+ const key = `${this.keyOf(provider)}:lookup:${kind}:${pin.tvdbId ?? ""}:${pin.imdbId ?? ""}:${pin.tmdbId ?? ""}`;
13565
+ const known = this.cachedMatch(provider, key);
13384
13566
  if (known !== null) return known.found ? known.match : null;
13385
13567
  const pending = this.matches.get(key);
13386
13568
  if (pending !== void 0) return pending;
@@ -13431,8 +13613,8 @@ var Enricher = class {
13431
13613
  const found = await this.lookup(provider, provider.lookup.bind(provider), item, kind, ask.ids);
13432
13614
  if (found !== null || ask.fromPin) return found;
13433
13615
  }
13434
- const key = `${provider.id}:id:${kind}:${foldTitle(title)}:${year ?? 0}`;
13435
- const known = this.deps.cache.getMatch(key);
13616
+ const key = `${this.keyOf(provider)}:id:${kind}:${foldTitle(title)}:${year ?? 0}`;
13617
+ const known = this.cachedMatch(provider, key);
13436
13618
  if (known !== null) return known.found ? known.match : null;
13437
13619
  const pending = this.matches.get(key);
13438
13620
  if (pending !== void 0) return pending;
@@ -13453,7 +13635,7 @@ var Enricher = class {
13453
13635
  return run;
13454
13636
  }
13455
13637
  async episodesOf(provider, item, match) {
13456
- const key = `${provider.id}:eps:${match.remoteId}`;
13638
+ const key = `${this.keyOf(provider)}:eps:${match.remoteId}`;
13457
13639
  const known = this.deps.cache.getEpisodes(key);
13458
13640
  if (known !== null) return known.episodes;
13459
13641
  try {
@@ -13475,6 +13657,7 @@ var Enricher = class {
13475
13657
  title: match.title,
13476
13658
  year: match.year,
13477
13659
  overview: match.overview,
13660
+ translations: match.translations ?? null,
13478
13661
  tvdbId: match.tvdbId,
13479
13662
  tmdbId: match.tmdbId,
13480
13663
  imdbId: match.imdbId,
@@ -13503,9 +13686,9 @@ var Enricher = class {
13503
13686
  canAsk(provider, item) {
13504
13687
  return provider.kinds.includes(item.kind === "movie" ? "movie" : "series");
13505
13688
  }
13506
- needsOnline(item, acc) {
13689
+ needsOnline(provider, item, acc) {
13507
13690
  if (item.kind === "episode") return acc.overview === null || acc.poster === null || item.titlePlaceholder && acc.title === null;
13508
- return acc.overview === null || acc.poster === null;
13691
+ return acc.overview === null || acc.poster === null || provider.translates === true && acc.translations === null;
13509
13692
  }
13510
13693
  async localLayer(item, firstEpisodeFile) {
13511
13694
  const { reader } = this.deps;
@@ -13541,7 +13724,7 @@ var Enricher = class {
13541
13724
  const images = this.imageProvider(step);
13542
13725
  const provider = this.provider(step);
13543
13726
  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));
13544
- else if (provider !== null && this.canAsk(provider, item) && this.needsOnline(item, acc)) acc = fill(acc, await this.onlineLayer(provider, item, acc, resolved, held));
13727
+ else if (provider !== null && this.canAsk(provider, item) && this.needsOnline(provider, item, acc)) acc = fill(acc, await this.onlineLayer(provider, item, acc, resolved, held));
13545
13728
  }
13546
13729
  applyPin();
13547
13730
  acc = fill(acc, fileLayer(item));
@@ -13553,6 +13736,7 @@ var Enricher = class {
13553
13736
  titleFold: foldTitle(title),
13554
13737
  year: acc.year,
13555
13738
  overview: acc.overview,
13739
+ translations: acc.translations,
13556
13740
  tvdbId: acc.tvdbId,
13557
13741
  tmdbId: acc.tmdbId,
13558
13742
  imdbId: acc.imdbId,
@@ -13593,6 +13777,7 @@ function newItem(base) {
13593
13777
  seasonNumber: null,
13594
13778
  episodeNumber: null,
13595
13779
  overview: null,
13780
+ translations: null,
13596
13781
  tvdbId: null,
13597
13782
  tmdbId: null,
13598
13783
  imdbId: null,
@@ -13749,13 +13934,13 @@ async function folderItems(root, paths, reader) {
13749
13934
  //#endregion
13750
13935
  //#region src/scanner.ts
13751
13936
  /** The online providers this scan may ask: the fixed ones, plus each keyed one whose key is set. */
13752
- function onlineProviders(deps, sources) {
13937
+ function onlineProviders(deps, sources, language = "en") {
13753
13938
  const keyed = (make, key) => make !== void 0 && (key ?? "") !== "" ? [make(key ?? "")] : [];
13754
13939
  const fanartKey = sources.fanartApiKey ?? "";
13755
13940
  return {
13756
13941
  providers: [
13757
13942
  ...deps.providers ?? [],
13758
- ...keyed(deps.createTmdb, sources.tmdbToken),
13943
+ ...deps.createTmdb !== void 0 && (sources.tmdbToken ?? "") !== "" ? [deps.createTmdb(sources.tmdbToken ?? "", language)] : [],
13759
13944
  ...keyed(deps.createTvdb, sources.tvdbApiKey),
13760
13945
  ...keyed(deps.createOmdb, sources.omdbApiKey),
13761
13946
  ...deps.createAnilist !== void 0 && (sources.metadataSteps ?? []).includes("anilist") ? [deps.createAnilist()] : []
@@ -13903,12 +14088,14 @@ async function scanLibrary(deps, sources) {
13903
14088
  logger.warn("metadata matches could not be saved: they are asked for again next scan", { meta: { error: error instanceof Error ? error.message : String(error) } });
13904
14089
  }
13905
14090
  };
14091
+ const language = await deps.language?.() ?? "en";
13906
14092
  for (const [index, entry] of harvests.entries()) {
13907
14093
  try {
13908
- const online = onlineProviders(deps, sources);
14094
+ const online = onlineProviders(deps, sources, language);
13909
14095
  const items = await enrichItems(entry.items, sources.metadataSteps ?? DEFAULT_STEPS, {
13910
14096
  reader,
13911
14097
  providers: online.providers,
14098
+ language,
13912
14099
  images: online.images,
13913
14100
  cache,
13914
14101
  logger,
@@ -14182,7 +14369,9 @@ var MediaLibraryAddon = class extends BaseAddon {
14182
14369
  const { ctx } = this;
14183
14370
  const logger = ctx.logger;
14184
14371
  const db = settingsStoreDb(ctx.api.settingsStore);
14185
- const store = new LibraryStore(db, logger);
14372
+ const serverLanguage = new ServerLanguage(async () => (await ctx.api.system.info.query()).defaultLanguage, () => Date.now(), logger);
14373
+ await serverLanguage.refresh();
14374
+ const store = new LibraryStore(db, logger, () => serverLanguage.current());
14186
14375
  await store.init();
14187
14376
  const ffmpeg = await ctx.deps.ensureFfmpeg();
14188
14377
  const scans = new ScanController({
@@ -14203,9 +14392,14 @@ var MediaLibraryAddon = class extends BaseAddon {
14203
14392
  },
14204
14393
  probe: createFfmpegProber(ffmpeg),
14205
14394
  providers: [createTvmazeProvider({ fetch: httpRemoteFetch })],
14206
- createTmdb: (token) => createTmdbProvider({
14395
+ language: async () => {
14396
+ await serverLanguage.refresh();
14397
+ return serverLanguage.current();
14398
+ },
14399
+ createTmdb: (token, language) => createTmdbProvider({
14207
14400
  fetch: httpRemoteFetch,
14208
- token
14401
+ token,
14402
+ language: tmdbLanguageOf(language)
14209
14403
  }),
14210
14404
  createTvdb: (apiKey) => createTvdbProvider({
14211
14405
  fetch: httpRemoteFetch,