@soffits/dsh-media-hub 0.12.0 → 0.14.0

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.
package/dist/index.js CHANGED
@@ -8970,7 +8970,7 @@ var require_build = __commonJS({
8970
8970
  });
8971
8971
 
8972
8972
  // index.js
8973
- import { join as join17, resolve as resolve6 } from "node:path";
8973
+ import { join as join18, resolve as resolve6 } from "node:path";
8974
8974
 
8975
8975
  // node_modules/ws/wrapper.mjs
8976
8976
  var import_stream = __toESM(require_stream(), 1);
@@ -10630,6 +10630,18 @@ function bestTag(tags, wanted) {
10630
10630
  return best;
10631
10631
  }
10632
10632
 
10633
+ // src/quality.js
10634
+ var AUTO = "auto";
10635
+ var AUDIO = "audio";
10636
+ var HEIGHT = /^\d{3,4}$/;
10637
+ var MIN_HEIGHT = 144;
10638
+ var isHeight = (value) => HEIGHT.test(String(value)) && Number(value) >= MIN_HEIGHT;
10639
+ var isQuality = (value) => value === AUTO || value === AUDIO || isHeight(value);
10640
+ function heightChoices(raw) {
10641
+ const heights = [...new Set((Array.isArray(raw) ? raw : []).map(String).filter(isHeight))].sort((a, b) => Number(b) - Number(a));
10642
+ return heights.length > 1 ? [AUTO, ...heights] : [];
10643
+ }
10644
+
10633
10645
  // src/sources/process.js
10634
10646
  import { spawn } from "node:child_process";
10635
10647
  import { access, constants } from "node:fs/promises";
@@ -10647,10 +10659,15 @@ async function commandExists(command, path = process.env.PATH ?? "") {
10647
10659
  }
10648
10660
  return false;
10649
10661
  }
10650
- function run(argv, { signal, timeoutMs, onStdoutLine, cwd, env } = {}) {
10662
+ function run(argv, { signal, timeoutMs, onStdoutLine, cwd, env, input } = {}) {
10651
10663
  return new Promise((resolve7, reject) => {
10652
10664
  const [command, ...args] = argv;
10653
- const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], detached: true, cwd, env: { ...process.env, ...env } });
10665
+ const child = spawn(command, args, { stdio: [input === void 0 ? "ignore" : "pipe", "pipe", "pipe"], detached: true, cwd, env: { ...process.env, ...env } });
10666
+ if (input !== void 0) {
10667
+ child.stdin.on("error", () => {
10668
+ });
10669
+ child.stdin.end(input);
10670
+ }
10654
10671
  let stdout = "";
10655
10672
  let stderr = "";
10656
10673
  let pending = "";
@@ -10806,7 +10823,33 @@ function parseInfo(document2) {
10806
10823
  return work === null ? null : { ...work, relation: text(raw.relation) };
10807
10824
  }).filter((work) => work !== null && work.id !== id).slice(0, MAX_RELATED);
10808
10825
  const episodeTitles = Array.isArray(document2.episodes) ? document2.episodes.map((episode) => text(episode?.title)) : [];
10809
- return { ...resultOf(document2, null), id, episodes: listed2 > 0 ? listed2 : null, episodeTitles, related };
10826
+ return { ...resultOf(document2, null), id, episodes: listed2 > 0 ? listed2 : null, episodeTitles, related, qualities: heightChoices(document2.qualities) };
10827
+ }
10828
+ var MAX_DANMAKU = 5e3;
10829
+ var MAX_DANMAKU_TEXT = 100;
10830
+ var MAX_COMMENT_TEXT = 4e3;
10831
+ var MAX_CURSOR = 2e3;
10832
+ var COMMENTS_PAGE = 20;
10833
+ var count = (value) => Number.isInteger(value) && value >= 0 ? value : 0;
10834
+ function parseDanmaku(lines, number) {
10835
+ const found = lines.find((line) => line?.episode === number) ?? (lines.length === 1 ? lines[0] : null);
10836
+ if (!Array.isArray(found?.items)) throw sourceError2("source_failed", "the danmaku answer has no items");
10837
+ return found.items.map((raw) => ({ time: Number.isFinite(raw?.time) && raw.time >= 0 ? raw.time : null, text: text(raw?.text).replace(/\s+/g, " ").slice(0, MAX_DANMAKU_TEXT), likes: count(raw?.likes) })).filter((item) => item.time !== null && item.text !== "").sort((a, b) => a.time - b.time).slice(0, MAX_DANMAKU);
10838
+ }
10839
+ var ISO_TIME = (value) => typeof value === "string" && Number.isFinite(Date.parse(value)) ? new Date(value).toISOString() : null;
10840
+ function parseComments(document2) {
10841
+ if (!Array.isArray(document2?.items)) throw sourceError2("source_failed", "the comments answer has no items");
10842
+ const items = document2.items.map((raw) => ({
10843
+ id: text(raw?.id),
10844
+ name: text(raw?.user?.name ?? raw?.name),
10845
+ text: text(raw?.text).slice(0, MAX_COMMENT_TEXT),
10846
+ created: ISO_TIME(raw?.created),
10847
+ likes: count(raw?.likes),
10848
+ replies: count(raw?.replies),
10849
+ rating: Number.isFinite(raw?.rating) ? raw.rating : null
10850
+ })).filter((item) => item.id !== "" && item.text !== "");
10851
+ const next = text(document2.next_cursor ?? document2.next);
10852
+ return { total: countOrNull(document2.total), items, next: next !== "" && next.length <= MAX_CURSOR && items.length > 0 ? next : null };
10810
10853
  }
10811
10854
  function sha256Of(path) {
10812
10855
  return new Promise((resolve7, reject) => {
@@ -10848,16 +10891,24 @@ function createCommandSource(definition, { logger, cwd }) {
10848
10891
  await mkdir(cwd, { recursive: true });
10849
10892
  return cwd;
10850
10893
  }
10851
- async function query(args) {
10894
+ async function answer(args) {
10852
10895
  const { code, stdout, stderr, oversized } = await run([...command, ...args], { timeoutMs: QUERY_TIMEOUT_MS, cwd: await workDir(), env });
10853
10896
  if (oversized) throw sourceError2("source_failed", `${name2()}: the answer is too large`);
10854
10897
  if (code !== 0) throw sourceError2("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
10898
+ return stdout;
10899
+ }
10900
+ async function query(args) {
10901
+ const stdout = await answer(args);
10855
10902
  try {
10856
10903
  return JSON.parse(stdout);
10857
10904
  } catch {
10858
10905
  throw sourceError2("source_failed", `${name2()}: the answer is not JSON`);
10859
10906
  }
10860
10907
  }
10908
+ const offers = (kind, verb) => kinds.some((entry) => entry.id === kind && entry[verb] === true);
10909
+ const checkId = (id) => {
10910
+ if (!ID.test(String(id))) throw sourceError2("invalid", `not a ${name2()} id`);
10911
+ };
10861
10912
  return {
10862
10913
  id: sourceId,
10863
10914
  label: label ?? "",
@@ -10888,7 +10939,22 @@ function createCommandSource(definition, { logger, cwd }) {
10888
10939
  const { code, stderr } = await run([...command, "cover", "--output", file, "--", String(url)], { timeoutMs: COVER_TIMEOUT_MS, cwd: await workDir(), env });
10889
10940
  if (code !== 0) throw sourceError2("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
10890
10941
  },
10891
- async download({ id, dir, from: from2 = 1, to = null, signal, onEpisode, onStart, onPartial }) {
10942
+ offers,
10943
+ /** The danmaku of episode `number` of a work of a kind that declares `danmaku`: `[{ time, text, likes }]`. */
10944
+ async danmaku(id, number, kind) {
10945
+ checkId(id);
10946
+ if (!offers(kind, "danmaku") || !Number.isInteger(number) || number < 1) throw sourceError2("invalid", `${name2()} has no danmaku for this`);
10947
+ const lines = (await answer(["danmaku", "--episodes", String(number), "--json", "--", String(id)])).split("\n").map(parseLine).filter((line) => line !== null);
10948
+ return parseDanmaku(lines, number);
10949
+ },
10950
+ /** A page of the comments on a work of a kind that declares `comments`; `cursor` continues where an earlier page's `next` left off. */
10951
+ async comments(id, kind, { cursor = "", limit = COMMENTS_PAGE } = {}) {
10952
+ checkId(id);
10953
+ if (!offers(kind, "comments")) throw sourceError2("invalid", `${name2()} has no comments for this`);
10954
+ const paging = cursor === "" ? [] : ["--cursor", String(cursor).slice(0, MAX_CURSOR)];
10955
+ return parseComments(await query(["comments", "--limit", String(limit), ...paging, "--json", "--", String(id)]));
10956
+ },
10957
+ async download({ id, dir, from: from2 = 1, to = null, quality = "", signal, onEpisode, onStart, onPartial }) {
10892
10958
  if (!ID.test(String(id))) throw sourceError2("invalid", `not a ${name2()} id`);
10893
10959
  const failed = [];
10894
10960
  let result = null;
@@ -10920,7 +10986,7 @@ function createCommandSource(definition, { logger, cwd }) {
10920
10986
  failed.push(event.name);
10921
10987
  } else if (event?.event === "result") result = event;
10922
10988
  };
10923
- const argv = [...command, "download", `--id=${String(id)}`, "--episodes", episodes, "--output", dir, "--json"];
10989
+ const argv = [...command, "download", `--id=${String(id)}`, "--episodes", episodes, ...isHeight(quality) ? ["--quality", String(quality)] : [], "--output", dir, "--json"];
10924
10990
  const { code, stderr } = await run(argv, { signal, cwd: await workDir(), env, onStdoutLine: onLine });
10925
10991
  for (const number of [...growing.keys()]) settle2(number);
10926
10992
  await checking;
@@ -11003,6 +11069,7 @@ function snapshotOf(info, at) {
11003
11069
  meta: info.meta ?? [],
11004
11070
  related: related.map((work) => ({ ...work, tags: work.tags ?? [] })),
11005
11071
  episodeTitles: info.episodeTitles ?? [],
11072
+ qualities: info.qualities ?? [],
11006
11073
  at
11007
11074
  };
11008
11075
  }
@@ -11670,10 +11737,7 @@ var escapeTag = (tag) => `^${tag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`;
11670
11737
 
11671
11738
  // src/sources/link.js
11672
11739
  var LINK_SOURCE = "link";
11673
- var AUTO = "auto";
11674
- var AUDIO = "audio";
11675
11740
  var HEIGHTS = Object.freeze([2160, 1440, 1080, 720, 480, 360]);
11676
- var isQuality = (value) => value === AUTO || value === AUDIO || /^\d{3,4}$/.test(String(value)) && Number(value) >= 144;
11677
11741
  var INFO_TIMEOUT_MS = 12e4;
11678
11742
  var COVER_TIMEOUT_MS2 = 3e4;
11679
11743
  var MAX_BLURB = 1e3;
@@ -11967,7 +12031,9 @@ var SourceConfig = Schema.object({
11967
12031
  id: Schema.string().pattern(/^[a-z0-9][a-z0-9_-]{0,31}$/).description("What the command's search --kind takes."),
11968
12032
  label: Label.default("").description("Name of the category chip: a string, or { <tag>: text } per language. Empty uses the page's own words for this kind id (kind.<id> in locale/), else the id."),
11969
12033
  media: Schema.union(MEDIA.map((media) => Schema.const(media))).default("video").description("What a work of this kind is: video or audio (episodes, watched or listened to together in a room) or book (one file, downloaded in a format)."),
11970
- trending: Schema.boolean().default(false).description("Whether the command's trending verb answers for this kind (docs/source-protocol.md): its rank lists and new arrivals, shown on Discover before a search.")
12034
+ trending: Schema.boolean().default(false).description("Whether the command's trending verb answers for this kind (docs/source-protocol.md): its rank lists and new arrivals, shown on Discover before a search."),
12035
+ danmaku: Schema.boolean().default(false).description("Whether the command's danmaku verb answers for this kind: the comments people posted at a moment of an episode, drawn over the picture in a room."),
12036
+ comments: Schema.boolean().default(false).description("Whether the command's comments verb answers for this kind: what people wrote about a work, readable in its room.")
11971
12037
  })).description("What the source can search for; at least one."),
11972
12038
  filters: Schema.array(Schema.union(FILTERS.map((filter) => Schema.const(filter)))).default([]).description("Search filters the command understands (docs/source-protocol.md). The hub filters the answers by language, format, year and size itself as well."),
11973
12039
  command: Schema.array(Schema.string()).min(1).description("The command and its fixed arguments, one entry per word; the plugin adds the protocol verbs after them."),
@@ -11995,7 +12061,7 @@ var CookieRule = Schema.object({
11995
12061
  var DEFAULT_SOURCES = Object.freeze([
11996
12062
  {
11997
12063
  id: "fanqie",
11998
- kinds: [{ id: "drama", media: "video", trending: true }, { id: "audio", media: "audio", trending: true }, { id: "novel", media: "book", trending: true }],
12064
+ kinds: [{ id: "drama", media: "video", trending: true, danmaku: true, comments: true }, { id: "audio", media: "audio", comments: true }, { id: "novel", media: "book", trending: true }],
11999
12065
  filters: [],
12000
12066
  command: ["fanqie"],
12001
12067
  env: {}
@@ -12129,6 +12195,12 @@ async function readLocales(dir, logger) {
12129
12195
  return locales;
12130
12196
  }
12131
12197
 
12198
+ // src/vendored.js
12199
+ var VENDORED = Object.freeze({
12200
+ "hls.mjs": { pkg: "hls.js", file: "dist/hls.mjs" },
12201
+ "danmaku.mjs": { pkg: "danmaku", file: "dist/esm/danmaku.dom.js" }
12202
+ });
12203
+
12132
12204
  // src/http.js
12133
12205
  var ROUTE = `/${PREFIX}`;
12134
12206
  var WS_PATH = `${ROUTE}/ws`;
@@ -12161,12 +12233,14 @@ var MODULES = Object.freeze({
12161
12233
  "i18n.js": resolve2(here, "../src/i18n.js"),
12162
12234
  "captions.js": resolve2(here, "../src/captions.js")
12163
12235
  });
12164
- function hlsFile() {
12165
- const built = resolve2(here, "../dist/hls.mjs");
12166
- return existsSync2(built) ? built : resolve2(dirname3(createRequire(import.meta.url).resolve("hls.js/package.json")), "dist/hls.mjs");
12236
+ function vendoredFile(name2) {
12237
+ const built = resolve2(here, "../dist", name2);
12238
+ if (existsSync2(built)) return built;
12239
+ const { pkg, file } = VENDORED[name2];
12240
+ return resolve2(dirname3(createRequire(import.meta.url).resolve(`${pkg}/package.json`)), file);
12167
12241
  }
12168
12242
  function webFile(name2) {
12169
- if (name2 === "hls.mjs") return hlsFile();
12243
+ if (Object.hasOwn(VENDORED, name2)) return vendoredFile(name2);
12170
12244
  if (MODULES[name2] !== void 0) return MODULES[name2];
12171
12245
  return /^[a-z0-9-]+\.(js|css)$/.test(name2) ? resolve2(WEB_DIR, name2) : void 0;
12172
12246
  }
@@ -12294,6 +12368,9 @@ function createHandler({ connection, service, settings = () => ({ label: "", pre
12294
12368
  const query = (name2) => url.searchParams.get(name2) ?? "";
12295
12369
  if (route === "GET rooms") return sendJson(res, 200, { rooms: await hub.listRooms() });
12296
12370
  if (req.method === "GET" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "work") return sendJson(res, 200, hub.roomWork(parts[2]));
12371
+ if (req.method === "GET" && parts[1] === "rooms" && parts.length === 5 && parts[3] === "danmaku") return sendJson(res, 200, await hub.roomDanmaku(parts[2], Number(parts[4])));
12372
+ if (req.method === "GET" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "comments") return sendJson(res, 200, await hub.roomComments(parts[2], query("cursor")));
12373
+ if (req.method === "POST" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "quality") return sendJson(res, 200, await hub.roomQuality(parts[2], String((await readJson(req)).quality ?? "")));
12297
12374
  if (req.method === "DELETE" && parts[1] === "rooms" && parts.length === 3) return sendJson(res, 200, hub.closeRoom(parts[2]));
12298
12375
  if (req.method === "POST" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "together") return sendJson(res, 200, hub.watchTogether(parts[2]));
12299
12376
  if (route === "GET library") return sendJson(res, 200, await hub.library());
@@ -12349,7 +12426,7 @@ Content-Length: 0\r
12349
12426
  import { spawn as spawn5 } from "node:child_process";
12350
12427
  import { createHash as createHash6 } from "node:crypto";
12351
12428
  import { statfs as statfs2, stat as stat10 } from "node:fs/promises";
12352
- import { join as join16, resolve as resolve5 } from "node:path";
12429
+ import { join as join17, resolve as resolve5 } from "node:path";
12353
12430
 
12354
12431
  // src/downloads.js
12355
12432
  import { readFile as readFile6, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
@@ -12559,6 +12636,18 @@ function createDownloads({ stateDir, sources, have, hasSpace = async () => true,
12559
12636
  pump();
12560
12637
  return job;
12561
12638
  },
12639
+ /**
12640
+ * Fetch a show's episodes another way from now on (`how`, as `howOf` gives it): a run under way stops and goes
12641
+ * back in the queue, to start again that way. It does not wait for the run to end, so it is safe to call from a
12642
+ * step that the run's own progress waits on (the rolling cache's).
12643
+ */
12644
+ switchHow(dir, how) {
12645
+ const job = jobs.get(dir);
12646
+ if (job === void 0) return;
12647
+ job.how = howOf(how);
12648
+ if (running === job) job.controller.abort("yield");
12649
+ save();
12650
+ },
12562
12651
  /** Stop and forget a show's download. */
12563
12652
  async cancel(dir) {
12564
12653
  const job = jobs.get(dir);
@@ -12640,7 +12729,25 @@ function createCache({ library, downloads, rooms, window: size, logger }) {
12640
12729
  }
12641
12730
  await enforceCap();
12642
12731
  }),
12643
- enforce: () => serial(enforceCap)
12732
+ enforce: () => serial(enforceCap),
12733
+ /**
12734
+ * Fetch a show in another quality from now on. What was fetched ahead of where people are goes and comes again in the
12735
+ * new quality; the episode someone is on keeps playing as it is, so nobody's picture stops.
12736
+ */
12737
+ requality: (path, quality) => serial(async () => {
12738
+ library.setQuality(path, quality);
12739
+ const info = await library.cacheInfo(path);
12740
+ downloads.switchHow(path, info.source);
12741
+ const places = rooms.focusesOf(path);
12742
+ const from2 = Math.max(...places.length > 0 ? places : [info.focus ?? 0]);
12743
+ const ahead = [...info.cached].filter((n) => n > from2);
12744
+ if (ahead.length > 0) {
12745
+ await library.dropEpisodes(path, ahead, { reason: "quality" });
12746
+ await rooms.syncShow(path);
12747
+ }
12748
+ await refreshShow(path, { retry: true });
12749
+ await enforceCap();
12750
+ })
12644
12751
  };
12645
12752
  }
12646
12753
 
@@ -13803,6 +13910,8 @@ function createRoomService(options) {
13803
13910
  * (`growing` settles when they are complete): rooms waiting on it play it once enough is there.
13804
13911
  */
13805
13912
  streamEpisode: (path, number, partial) => streams.offer(resolve3(path), number, partial),
13913
+ /** The episode number of a room's item in its show (undefined for a room on plain files). */
13914
+ slotOf: (roomId, index) => rooms.get(roomId)?.items[index]?.slot,
13806
13915
  /** The prepared file of a ready local item. */
13807
13916
  mediaFile(roomId, index) {
13808
13917
  const item = rooms.get(roomId)?.items[index];
@@ -13976,7 +14085,7 @@ var MAX_STEPS = 3;
13976
14085
  var STEP_ID = /^[a-z0-9][a-z0-9_-]{0,31}$/;
13977
14086
  var MAX_LABEL_CHARS = 120;
13978
14087
  var MAX_PROMPT_CHARS = 2e3;
13979
- var PICKS_LIMIT = 6;
14088
+ var PICKS_LIMIT = 8;
13980
14089
  var PICKS_TIMEOUT_MS = 6e4;
13981
14090
  var MAX_WHY_CHARS = 280;
13982
14091
  var badInput = (message) => Object.assign(new Error(message), { code: "invalid_arguments" });
@@ -14050,19 +14159,9 @@ function parsePicks(document2, hasSource, limit = PICKS_LIMIT) {
14050
14159
  }
14051
14160
  return out;
14052
14161
  }
14053
- async function recommend({ command, env = {}, cwd, hasSource }, { person, source, kind, language, limit = PICKS_LIMIT }) {
14054
- const argv = [
14055
- ...command,
14056
- "recommend",
14057
- "--json",
14058
- "--limit",
14059
- String(limit),
14060
- ...person.id ? ["--person", person.id] : [],
14061
- ...source ? ["--source", source] : [],
14062
- ...kind ? ["--kind", kind] : [],
14063
- ...language ? ["--language", language] : []
14064
- ];
14065
- const result = await run(argv, { timeoutMs: PICKS_TIMEOUT_MS, cwd, env });
14162
+ async function recommend({ command, env = {}, cwd, hasSource }, { person, language, limit = PICKS_LIMIT, candidates = [] }) {
14163
+ const argv = [...command, "recommend", "--json", "--limit", String(limit), ...person.id ? ["--person", person.id] : [], ...language ? ["--language", language] : []];
14164
+ const result = await run(argv, { timeoutMs: PICKS_TIMEOUT_MS, cwd, env, input: JSON.stringify({ candidates }) });
14066
14165
  if (result.code !== 0) throw new Error(`exit ${result.code}: ${result.stderr.trim().split("\n").pop() ?? ""}`);
14067
14166
  return parsePicks(JSON.parse(result.stdout), hasSource, limit);
14068
14167
  }
@@ -14426,6 +14525,13 @@ function createLibrary(options) {
14426
14525
  update(path, { source: { ...entry.source, episodes } });
14427
14526
  changed(path);
14428
14527
  },
14528
+ /** Fetch a sourced show's episodes in another quality (src/quality.js) from now on. */
14529
+ setQuality(path, quality) {
14530
+ const target = requireShow(path);
14531
+ const entry = record(target);
14532
+ if (!isSourced(entry)) throw libraryError("invalid", "this show has no source to fetch from");
14533
+ update(target, { source: { ...entry.source, quality } });
14534
+ },
14429
14535
  /** The saved (offline fallback) copy of a show's work, or null. */
14430
14536
  workOf: (path) => record(path).work ?? null,
14431
14537
  /** Which source and work id a show came from (`{ source, id, ... }`), or null. */
@@ -14551,11 +14657,76 @@ function createLibrary(options) {
14551
14657
  };
14552
14658
  }
14553
14659
 
14660
+ // src/remarks.js
14661
+ import { mkdir as mkdir10, readFile as readFile11, rename as rename8, writeFile as writeFile7 } from "node:fs/promises";
14662
+ import { join as join16 } from "node:path";
14663
+ var HOUR_MS = 36e5;
14664
+ var DAY_MS2 = 24 * HOUR_MS;
14665
+ var REMARKS_DIR = ".source";
14666
+ function createRemarks({ source, logger, now = Date.now, danmakuMaxAgeMs = DAY_MS2, commentsMaxAgeMs = HOUR_MS }) {
14667
+ const flying = /* @__PURE__ */ new Map();
14668
+ async function read(file) {
14669
+ try {
14670
+ const copy = JSON.parse(await readFile11(file, "utf8"));
14671
+ return Number.isFinite(copy?.at) ? copy : null;
14672
+ } catch {
14673
+ return null;
14674
+ }
14675
+ }
14676
+ async function keep(file, value) {
14677
+ await mkdir10(join16(file, ".."), { recursive: true });
14678
+ await writeFile7(`${file}.part`, JSON.stringify(value));
14679
+ await rename8(`${file}.part`, file);
14680
+ }
14681
+ function fetchInto(file, ask) {
14682
+ if (!flying.has(file)) {
14683
+ const run3 = (async () => {
14684
+ const copy = { ...await ask(), at: now() };
14685
+ await keep(file, copy);
14686
+ return copy;
14687
+ })().finally(() => flying.delete(file));
14688
+ flying.set(file, run3);
14689
+ }
14690
+ return flying.get(file);
14691
+ }
14692
+ async function copyOf(file, maxAgeMs, ask) {
14693
+ const copy = await read(file);
14694
+ if (copy === null) return fetchInto(file, ask);
14695
+ if (now() - copy.at > maxAgeMs) fetchInto(file, ask).catch((error) => logger.warn("media hub: could not refresh %s: %s", file, error.message));
14696
+ return copy;
14697
+ }
14698
+ function offering(work, verb) {
14699
+ const found = work?.source ? source(work.source) : void 0;
14700
+ return found !== void 0 && typeof found.offers === "function" && found.offers(work.kind, verb) ? found : null;
14701
+ }
14702
+ return {
14703
+ /** Which of the verbs a show's source offers for its work: `{ danmaku, comments }`. */
14704
+ offered: (work) => ({ danmaku: offering(work, "danmaku") !== null, comments: offering(work, "comments") !== null }),
14705
+ /**
14706
+ * The danmaku of episode `number` of a show: `{ items: [{ time, text, likes }], at }`.
14707
+ * @param {string} show - the show's folder
14708
+ * @param {{ source: string, id: string, kind: string }} work - where the show came from (its notes' `source`)
14709
+ */
14710
+ async danmaku(show, work, number) {
14711
+ const found = offering(work, "danmaku");
14712
+ if (found === null) return { items: [], at: null };
14713
+ return copyOf(join16(show, REMARKS_DIR, "danmaku", `${number}.json`), danmakuMaxAgeMs, async () => ({ items: await found.danmaku(work.id, number, work.kind) }));
14714
+ },
14715
+ /** The comments on a show's work: the kept first page, or with `cursor` the page after it from the source. */
14716
+ async comments(show, work, cursor = "") {
14717
+ const found = offering(work, "comments");
14718
+ if (found === null) return { total: 0, items: [], next: null, at: null };
14719
+ if (cursor !== "") return { ...await found.comments(work.id, work.kind, { cursor }), at: now() };
14720
+ return copyOf(join16(show, REMARKS_DIR, "comments.json"), commentsMaxAgeMs, () => found.comments(work.id, work.kind));
14721
+ }
14722
+ };
14723
+ }
14724
+
14554
14725
  // src/follow.js
14555
- var DAY_MS2 = 864e5;
14726
+ var DAY_MS3 = 864e5;
14556
14727
  var OPEN_RECHECK_MS = 36e5;
14557
14728
  var JITTER = 0.1;
14558
- var nextCheckAt = (checkedAt, random) => checkedAt + Math.round(DAY_MS2 * (1 - JITTER + 2 * JITTER * random));
14729
+ var nextCheckAt = (checkedAt, random) => checkedAt + Math.round(DAY_MS3 * (1 - JITTER + 2 * JITTER * random));
14559
14730
  function dueFollows(follows, now) {
14560
14731
  return follows.filter(({ follow: follow2 }) => (follow2.nextAt ?? 0) <= now).sort((a, b) => (a.follow.nextAt ?? 0) - (b.follow.nextAt ?? 0));
14561
14732
  }
@@ -14774,27 +14945,27 @@ function createChanges({ intervalMs = 300 } = {}) {
14774
14945
  }
14775
14946
 
14776
14947
  // src/copies.js
14777
- import { mkdir as mkdir10, readFile as readFile11, rename as rename8, writeFile as writeFile7 } from "node:fs/promises";
14948
+ import { mkdir as mkdir11, readFile as readFile12, rename as rename9, writeFile as writeFile8 } from "node:fs/promises";
14778
14949
  import { dirname as dirname6 } from "node:path";
14779
- var DAY_MS3 = 864e5;
14780
- var HOUR_MS = 36e5;
14781
- function createCopies({ file, changed, logger, maxAgeMs = DAY_MS3, retryMs = HOUR_MS, parallel = 2, now = Date.now }) {
14950
+ var DAY_MS4 = 864e5;
14951
+ var HOUR_MS2 = 36e5;
14952
+ function createCopies({ file, changed, logger, maxAgeMs = DAY_MS4, retryMs = HOUR_MS2, parallel = 4, now = Date.now }) {
14782
14953
  const copies = /* @__PURE__ */ new Map();
14783
- const flying = /* @__PURE__ */ new Set();
14954
+ const flying = /* @__PURE__ */ new Map();
14784
14955
  const failedAt = /* @__PURE__ */ new Map();
14785
14956
  const waiting = [];
14786
14957
  let running = 0;
14787
14958
  let saving = Promise.resolve();
14788
- const loaded = readFile11(file, "utf8").then((text3) => {
14959
+ const loaded = readFile12(file, "utf8").then((text3) => {
14789
14960
  for (const [key, copy] of Object.entries(JSON.parse(text3))) copies.set(key, copy);
14790
14961
  }).catch((error) => {
14791
14962
  if (error.code !== "ENOENT") logger.warn("the saved copies of Discover could not be read: %s", error.message);
14792
14963
  });
14793
14964
  function save() {
14794
14965
  saving = saving.then(async () => {
14795
- await mkdir10(dirname6(file), { recursive: true });
14796
- await writeFile7(`${file}.part`, JSON.stringify(Object.fromEntries(copies)));
14797
- await rename8(`${file}.part`, file);
14966
+ await mkdir11(dirname6(file), { recursive: true });
14967
+ await writeFile8(`${file}.part`, JSON.stringify(Object.fromEntries(copies)));
14968
+ await rename9(`${file}.part`, file);
14798
14969
  }).catch((error) => logger.warn("the copies of Discover could not be saved: %s", error.message));
14799
14970
  return saving;
14800
14971
  }
@@ -14808,7 +14979,10 @@ function createCopies({ file, changed, logger, maxAgeMs = DAY_MS3, retryMs = HOU
14808
14979
  }
14809
14980
  }
14810
14981
  function ask(key, produce) {
14811
- flying.add(key);
14982
+ let settled;
14983
+ flying.set(key, new Promise((resolve7) => {
14984
+ settled = resolve7;
14985
+ }));
14812
14986
  waiting.push(async () => {
14813
14987
  try {
14814
14988
  copies.set(key, { at: now(), value: await produce() });
@@ -14821,11 +14995,23 @@ function createCopies({ file, changed, logger, maxAgeMs = DAY_MS3, retryMs = HOU
14821
14995
  changed();
14822
14996
  } finally {
14823
14997
  flying.delete(key);
14998
+ settled();
14824
14999
  }
14825
15000
  });
14826
15001
  pump();
14827
15002
  }
14828
15003
  return {
15004
+ /**
15005
+ * Like `get`, but a missing copy is waited for (the first ask), for what another copy is made from; an old one still answers at once.
15006
+ * @param {string} key
15007
+ * @param {() => Promise<unknown>} produce
15008
+ */
15009
+ async ensure(key, produce) {
15010
+ const first = await this.get(key, produce);
15011
+ if (first.value !== null || !flying.has(key)) return first;
15012
+ await flying.get(key);
15013
+ return this.get(key, produce);
15014
+ },
14829
15015
  /**
14830
15016
  * @param {string} key
14831
15017
  * @param {() => Promise<unknown>} produce - the outside answer, asked only when the copy is missing or old
@@ -14842,7 +15028,6 @@ function createCopies({ file, changed, logger, maxAgeMs = DAY_MS3, retryMs = HOU
14842
15028
  }
14843
15029
 
14844
15030
  // src/discover.js
14845
- var DISCOVER_PICKS = 12;
14846
15031
  var notFound = (message) => Object.assign(new Error(message), { code: "not_found" });
14847
15032
  function createDiscover({ copies, sources, covers, recommender }) {
14848
15033
  async function sourcesFor(sourceId, kind, ability) {
@@ -14875,30 +15060,32 @@ function createDiscover({ copies, sources, covers, recommender }) {
14875
15060
  };
14876
15061
  },
14877
15062
  /**
14878
- * A person's picks for a source and category (merged under All sources), or without either (the Watching tab).
15063
+ * A person's picks (the Watching tab). The recommender is given what every source's trending copy holds, so one
15064
+ * run a day serves all categories and asks the sources nothing more.
14879
15065
  * @returns {Promise<{ picks: object[], loading: boolean }>}
14880
15066
  */
14881
- async picks(person, { source: sourceId = "", kind = "", language = "" } = {}) {
15067
+ async picks(person, { language = "" } = {}) {
14882
15068
  if (recommender.command.length === 0) return { picks: [], loading: false };
14883
- const narrowed = sourceId !== "";
14884
- const targets = narrowed ? await sourcesFor(sourceId, kind, () => true) : [null];
14885
- const copy = await Promise.all(targets.map((one) => copies.get(
14886
- `picks|${person.key}|${one?.id ?? "*"}|${narrowed ? kind : "*"}|${language}`,
14887
- () => recommend(recommender, { person, source: one?.id, kind: narrowed ? kind : void 0, language, limit: narrowed ? DISCOVER_PICKS : PICKS_LIMIT })
14888
- )));
14889
- const lists = copy.map((entry, index) => (entry.value ?? []).filter((pick5) => targets[index] === null || pick5.work.source === targets[index].id && (kind === "" || pick5.work.kind === kind)));
14890
- return {
14891
- picks: interleave(lists).map((pick5) => ({ ...pick5, work: withCovers(sources.get(pick5.work.source), pick5.work) })).slice(0, narrowed ? DISCOVER_PICKS : PICKS_LIMIT),
14892
- loading: copy.some((entry) => entry.loading)
14893
- };
15069
+ const copy = await copies.get(`picks|${person.key}|${language}`, async () => {
15070
+ const candidates = [];
15071
+ for (const one of sources.values()) {
15072
+ if (typeof one.trending !== "function" || !await one.available()) continue;
15073
+ for (const entry of one.kinds.filter((kind) => kind.trending === true)) {
15074
+ const trending = await copies.ensure(`trending|${one.id}|${entry.id}`, () => one.trending(entry.id));
15075
+ if (trending.value !== null) candidates.push({ source: one.id, kind: entry.id, lists: trending.value });
15076
+ }
15077
+ }
15078
+ return recommend(recommender, { person, language, candidates });
15079
+ });
15080
+ return { picks: (copy.value ?? []).map((pick5) => ({ ...pick5, work: withCovers(sources.get(pick5.work.source), pick5.work) })), loading: copy.loading };
14894
15081
  }
14895
15082
  };
14896
15083
  }
14897
15084
 
14898
15085
  // src/work-refresh.js
14899
- var DAY_MS4 = 864e5;
14900
- var HOUR_MS2 = 36e5;
14901
- function createWorkRefresh({ source, keep, maxAgeMs = DAY_MS4, retryMs = HOUR_MS2, parallel = 2, now = Date.now, logger }) {
15086
+ var DAY_MS5 = 864e5;
15087
+ var HOUR_MS3 = 36e5;
15088
+ function createWorkRefresh({ source, keep, maxAgeMs = DAY_MS5, retryMs = HOUR_MS3, parallel = 2, now = Date.now, logger }) {
14902
15089
  const flying = /* @__PURE__ */ new Set();
14903
15090
  const failedAt = /* @__PURE__ */ new Map();
14904
15091
  const waiting = [];
@@ -14936,18 +15123,18 @@ ${entry.source.id}`;
14936
15123
  }
14937
15124
 
14938
15125
  // src/media.js
14939
- var HOUR_MS3 = 36e5;
15126
+ var HOUR_MS4 = 36e5;
14940
15127
  var MIN_FREE_BYTES = 1e9;
14941
15128
  var NO_CONVERTER = Object.freeze({ command: "", available: async () => false });
14942
15129
  var hubError = (code, message) => Object.assign(new Error(message), { code });
14943
15130
  function createMediaHub(options) {
14944
15131
  const { stateDir, libraryRoots, logger, now = Date.now } = options;
14945
15132
  const sources = new Map(options.sources.map((source2) => [source2.id, source2]));
14946
- const covers = createCovers({ dir: join16(stateDir, "covers"), capBytes: options.coverCacheBytes, ffmpeg: options.tools.ffmpeg, logger }, (id) => sources.get(id));
14947
- const log = createWatchLog({ file: join16(stateDir, LOG_NAME), now, logger });
15133
+ const covers = createCovers({ dir: join17(stateDir, "covers"), capBytes: options.coverCacheBytes, ffmpeg: options.tools.ffmpeg, logger }, (id) => sources.get(id));
15134
+ const log = createWatchLog({ file: join17(stateDir, LOG_NAME), now, logger });
14948
15135
  const changes = createChanges({ intervalMs: options.changeIntervalMs });
14949
15136
  const points = createPoints(options.points ?? { command: [], night: { from: "01:00", to: "06:00" } }, { logger, now });
14950
- const books = createBooks({ changed: () => changes.notify("shelf"), dir: join16(stateDir, "books"), sources, capBytes: options.books?.capBytes ?? 0, converter: options.books?.converter ?? NO_CONVERTER, covers, logger, now });
15137
+ const books = createBooks({ changed: () => changes.notify("shelf"), dir: join17(stateDir, "books"), sources, capBytes: options.books?.capBytes ?? 0, converter: options.books?.converter ?? NO_CONVERTER, covers, logger, now });
14951
15138
  let rooms;
14952
15139
  let cache;
14953
15140
  const downloads = createDownloads({
@@ -14967,6 +15154,7 @@ function createMediaHub(options) {
14967
15154
  logger,
14968
15155
  now
14969
15156
  });
15157
+ const remarks = createRemarks({ source: (id) => sources.get(id), logger, now });
14970
15158
  const refreshWork = createWorkRefresh({ source: (id) => sources.get(id), keep: (path, work) => library.keepWork(path, work), maxAgeMs: options.workMaxAgeMs, logger, now });
14971
15159
  const library = createLibrary({
14972
15160
  changed: () => changes.notify("library"),
@@ -15001,7 +15189,7 @@ function createMediaHub(options) {
15001
15189
  cache.refresh(show).catch(() => {
15002
15190
  });
15003
15191
  });
15004
- const copies = createCopies({ file: join16(stateDir, "discover.json"), changed: () => changes.notify("discover"), maxAgeMs: options.discoverMaxAgeMs, logger, now });
15192
+ const copies = createCopies({ file: join17(stateDir, "discover.json"), changed: () => changes.notify("discover"), maxAgeMs: options.discoverMaxAgeMs, logger, now });
15005
15193
  const discover = createDiscover({
15006
15194
  copies,
15007
15195
  sources,
@@ -15013,7 +15201,12 @@ function createMediaHub(options) {
15013
15201
  });
15014
15202
  cache.enforce().catch(() => {
15015
15203
  });
15016
- }, HOUR_MS3);
15204
+ }, HOUR_MS4);
15205
+ function roomShow(id) {
15206
+ const room = rooms.listRooms().find((entry) => entry.id === id);
15207
+ if (room === void 0) throw hubError("not_found", "no such room");
15208
+ return room.show;
15209
+ }
15017
15210
  async function onFiles(job) {
15018
15211
  changes.notify("library");
15019
15212
  await rooms.syncShow(job.dir);
@@ -15084,7 +15277,7 @@ ${work.id}`) || foldersFor(sourceId, work).some((path) => logged.has(path)));
15084
15277
  const name2 = cleanName(work.title ?? "");
15085
15278
  const mark = createHash6("sha256").update(`${sourceId}
15086
15279
  ${work.id}`).digest("hex").slice(0, 8);
15087
- return [name2, `${name2} (${mark})`].map((candidate) => join16(libraryRoots[0], candidate));
15280
+ return [name2, `${name2} (${mark})`].map((candidate) => join17(libraryRoots[0], candidate));
15088
15281
  }
15089
15282
  async function folderFor(sourceId, item) {
15090
15283
  for (const path of foldersFor(sourceId, item)) {
@@ -15173,11 +15366,44 @@ ${work.id}`).digest("hex").slice(0, 8);
15173
15366
  for (const show of list.shows) if (show.source?.source) refreshWork(show.path, { source: show.source, work: show.work });
15174
15367
  return { ...list, shows: list.shows.map(withCovers) };
15175
15368
  },
15176
- /** The details of the work a room's show came from, or null. */
15369
+ /**
15370
+ * The details of the work a room's show came from (or null), the quality its episodes are fetched in, and which of
15371
+ * the work's danmaku and comments its source offers.
15372
+ */
15177
15373
  roomWork(id) {
15178
- const room = rooms.listRooms().find((entry) => entry.id === id);
15179
- if (room === void 0) throw hubError("not_found", "no such room");
15180
- return { work: room.show === null ? null : withCovers(shownEntry(room.show)).work ?? null, source: library.workSource(room.show)?.source ?? null, id: library.workSource(room.show)?.id ?? null };
15374
+ const show = roomShow(id);
15375
+ const from2 = library.workSource(show);
15376
+ return {
15377
+ work: show === null ? null : withCovers(shownEntry(show)).work ?? null,
15378
+ source: from2?.source ?? null,
15379
+ id: from2?.id ?? null,
15380
+ quality: from2?.quality || AUTO,
15381
+ ...remarks.offered(from2)
15382
+ };
15383
+ },
15384
+ /** The danmaku of a room's item, from the copy kept with its show; the next episode's is made ready meanwhile. */
15385
+ async roomDanmaku(id, index) {
15386
+ const show = roomShow(id);
15387
+ const from2 = library.workSource(show);
15388
+ const number = rooms.slotOf(id, index);
15389
+ if (from2 === null || number === void 0) return { items: [], at: null };
15390
+ const answer = await remarks.danmaku(show, from2, number);
15391
+ if (number < (from2.episodes ?? 0)) remarks.danmaku(show, from2, number + 1).catch((error) => logger.warn("media hub: danmaku of %s episode %d: %s", show, number + 1, error.message));
15392
+ return answer;
15393
+ },
15394
+ /** The comments on a room's work: the kept first page, or the page after `cursor`. */
15395
+ roomComments(id, cursor = "") {
15396
+ const show = roomShow(id);
15397
+ const from2 = library.workSource(show);
15398
+ return from2 === null ? { total: 0, items: [], next: null, at: null } : remarks.comments(show, from2, cursor);
15399
+ },
15400
+ /** Fetch a room's show in one of the qualities its work offers, from the episodes after the one it is on. */
15401
+ async roomQuality(id, quality) {
15402
+ const show = roomShow(id);
15403
+ const offered = show === null ? [] : library.workOf(show)?.qualities ?? [];
15404
+ if (!isQuality(quality) || !offered.includes(quality)) throw hubError("invalid", "the show is not offered in this quality");
15405
+ await cache.requality(show, quality);
15406
+ return { quality };
15181
15407
  },
15182
15408
  episodes: (path) => library.episodes(path),
15183
15409
  removeShow: (path, by) => library.remove(path, { by }),
@@ -15237,8 +15463,8 @@ ${work.id}`).digest("hex").slice(0, 8);
15237
15463
  if (watch) room = (await rooms.createRoom({ source: "local", path: dir, title: item.title, by, person, together, start: await library.resumeFrom(dir) })).room;
15238
15464
  else await cache.refresh(dir, { retry: true });
15239
15465
  await points.use(person, tickets, { room: room?.id, subject });
15240
- const count = all ? item.episodes : Math.min(item.episodes, options.cache.ahead + 1);
15241
- return { path: dir, title: item.title, episodes: item.episodes, estimate: count * (EPISODE_BYTES[item.kind] ?? EPISODE_BYTES.drama), room, download: downloads.state(dir) };
15466
+ const count2 = all ? item.episodes : Math.min(item.episodes, options.cache.ahead + 1);
15467
+ return { path: dir, title: item.title, episodes: item.episodes, estimate: count2 * (EPISODE_BYTES[item.kind] ?? EPISODE_BYTES.drama), room, download: downloads.state(dir) };
15242
15468
  },
15243
15469
  /**
15244
15470
  * Follow a work, or stop following it. A work not in the library is added as an empty show; the host then looks for its
@@ -15381,7 +15607,7 @@ function createPersonRoutes({ hub, identity }) {
15381
15607
  path: `${PERSON_PATH}/picks`,
15382
15608
  methods: ["GET"],
15383
15609
  requestBody: "buffered",
15384
- fetch: handle((request, current, person) => current.picks(person, { source: param(request, "source"), kind: param(request, "kind"), language: param(request, "language") }))
15610
+ fetch: handle((request, current, person) => current.picks(person, { language: param(request, "language") }))
15385
15611
  },
15386
15612
  {
15387
15613
  path: `${PERSON_PATH}/steps`,
@@ -15502,7 +15728,7 @@ function createShelfRoutes({ books, identity }) {
15502
15728
  var name = "dsh-media-hub";
15503
15729
  var inject = ["webServer", "connection"];
15504
15730
  var ROOM_ID = /^[A-Za-z0-9_-]{6,32}$/;
15505
- var DAY_MS5 = 864e5;
15731
+ var DAY_MS6 = 864e5;
15506
15732
  function apply(ctx, config) {
15507
15733
  const logger = ctx.logger("media-hub");
15508
15734
  let current;
@@ -15511,7 +15737,7 @@ function apply(ctx, config) {
15511
15737
  const stateDir = resolve6(config.stateDir);
15512
15738
  const service = createMediaHub({
15513
15739
  stateDir,
15514
- libraryRoots: [join17(stateDir, "library"), ...config.libraryRoots.map((root) => resolve6(root))],
15740
+ libraryRoots: [join18(stateDir, "library"), ...config.libraryRoots.map((root) => resolve6(root))],
15515
15741
  delivery: createDelivery({ mode: config.delivery }),
15516
15742
  tools: { ffmpeg: config.ffmpeg, ffprobe: config.ffprobe, maxHeight: config.maxHeight, threads: config.threads },
15517
15743
  webUrl: () => ctx.get("webApp")?.getAdvertisedUrl(),
@@ -15538,7 +15764,7 @@ function apply(ctx, config) {
15538
15764
  const prune = setInterval(() => {
15539
15765
  service.pruneCache(config.cacheDays).catch(() => {
15540
15766
  });
15541
- }, DAY_MS5);
15767
+ }, DAY_MS6);
15542
15768
  const identity = () => ctx.get("requestIdentity");
15543
15769
  const fetchRoutes = [
15544
15770
  ...createShelfRoutes({ books: () => current?.books, identity }),