@soffits/dsh-media-hub 0.13.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";
@@ -10811,7 +10823,33 @@ function parseInfo(document2) {
10811
10823
  return work === null ? null : { ...work, relation: text(raw.relation) };
10812
10824
  }).filter((work) => work !== null && work.id !== id).slice(0, MAX_RELATED);
10813
10825
  const episodeTitles = Array.isArray(document2.episodes) ? document2.episodes.map((episode) => text(episode?.title)) : [];
10814
- 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 };
10815
10853
  }
10816
10854
  function sha256Of(path) {
10817
10855
  return new Promise((resolve7, reject) => {
@@ -10853,16 +10891,24 @@ function createCommandSource(definition, { logger, cwd }) {
10853
10891
  await mkdir(cwd, { recursive: true });
10854
10892
  return cwd;
10855
10893
  }
10856
- async function query(args) {
10894
+ async function answer(args) {
10857
10895
  const { code, stdout, stderr, oversized } = await run([...command, ...args], { timeoutMs: QUERY_TIMEOUT_MS, cwd: await workDir(), env });
10858
10896
  if (oversized) throw sourceError2("source_failed", `${name2()}: the answer is too large`);
10859
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);
10860
10902
  try {
10861
10903
  return JSON.parse(stdout);
10862
10904
  } catch {
10863
10905
  throw sourceError2("source_failed", `${name2()}: the answer is not JSON`);
10864
10906
  }
10865
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
+ };
10866
10912
  return {
10867
10913
  id: sourceId,
10868
10914
  label: label ?? "",
@@ -10893,7 +10939,22 @@ function createCommandSource(definition, { logger, cwd }) {
10893
10939
  const { code, stderr } = await run([...command, "cover", "--output", file, "--", String(url)], { timeoutMs: COVER_TIMEOUT_MS, cwd: await workDir(), env });
10894
10940
  if (code !== 0) throw sourceError2("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
10895
10941
  },
10896
- 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 }) {
10897
10958
  if (!ID.test(String(id))) throw sourceError2("invalid", `not a ${name2()} id`);
10898
10959
  const failed = [];
10899
10960
  let result = null;
@@ -10925,7 +10986,7 @@ function createCommandSource(definition, { logger, cwd }) {
10925
10986
  failed.push(event.name);
10926
10987
  } else if (event?.event === "result") result = event;
10927
10988
  };
10928
- 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"];
10929
10990
  const { code, stderr } = await run(argv, { signal, cwd: await workDir(), env, onStdoutLine: onLine });
10930
10991
  for (const number of [...growing.keys()]) settle2(number);
10931
10992
  await checking;
@@ -11008,6 +11069,7 @@ function snapshotOf(info, at) {
11008
11069
  meta: info.meta ?? [],
11009
11070
  related: related.map((work) => ({ ...work, tags: work.tags ?? [] })),
11010
11071
  episodeTitles: info.episodeTitles ?? [],
11072
+ qualities: info.qualities ?? [],
11011
11073
  at
11012
11074
  };
11013
11075
  }
@@ -11675,10 +11737,7 @@ var escapeTag = (tag) => `^${tag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`;
11675
11737
 
11676
11738
  // src/sources/link.js
11677
11739
  var LINK_SOURCE = "link";
11678
- var AUTO = "auto";
11679
- var AUDIO = "audio";
11680
11740
  var HEIGHTS = Object.freeze([2160, 1440, 1080, 720, 480, 360]);
11681
- var isQuality = (value) => value === AUTO || value === AUDIO || /^\d{3,4}$/.test(String(value)) && Number(value) >= 144;
11682
11741
  var INFO_TIMEOUT_MS = 12e4;
11683
11742
  var COVER_TIMEOUT_MS2 = 3e4;
11684
11743
  var MAX_BLURB = 1e3;
@@ -11972,7 +12031,9 @@ var SourceConfig = Schema.object({
11972
12031
  id: Schema.string().pattern(/^[a-z0-9][a-z0-9_-]{0,31}$/).description("What the command's search --kind takes."),
11973
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."),
11974
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)."),
11975
- 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.")
11976
12037
  })).description("What the source can search for; at least one."),
11977
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."),
11978
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."),
@@ -12000,7 +12061,7 @@ var CookieRule = Schema.object({
12000
12061
  var DEFAULT_SOURCES = Object.freeze([
12001
12062
  {
12002
12063
  id: "fanqie",
12003
- kinds: [{ id: "drama", media: "video", trending: true }, { id: "audio", media: "audio" }, { 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 }],
12004
12065
  filters: [],
12005
12066
  command: ["fanqie"],
12006
12067
  env: {}
@@ -12134,6 +12195,12 @@ async function readLocales(dir, logger) {
12134
12195
  return locales;
12135
12196
  }
12136
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
+
12137
12204
  // src/http.js
12138
12205
  var ROUTE = `/${PREFIX}`;
12139
12206
  var WS_PATH = `${ROUTE}/ws`;
@@ -12166,12 +12233,14 @@ var MODULES = Object.freeze({
12166
12233
  "i18n.js": resolve2(here, "../src/i18n.js"),
12167
12234
  "captions.js": resolve2(here, "../src/captions.js")
12168
12235
  });
12169
- function hlsFile() {
12170
- const built = resolve2(here, "../dist/hls.mjs");
12171
- 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);
12172
12241
  }
12173
12242
  function webFile(name2) {
12174
- if (name2 === "hls.mjs") return hlsFile();
12243
+ if (Object.hasOwn(VENDORED, name2)) return vendoredFile(name2);
12175
12244
  if (MODULES[name2] !== void 0) return MODULES[name2];
12176
12245
  return /^[a-z0-9-]+\.(js|css)$/.test(name2) ? resolve2(WEB_DIR, name2) : void 0;
12177
12246
  }
@@ -12299,6 +12368,9 @@ function createHandler({ connection, service, settings = () => ({ label: "", pre
12299
12368
  const query = (name2) => url.searchParams.get(name2) ?? "";
12300
12369
  if (route === "GET rooms") return sendJson(res, 200, { rooms: await hub.listRooms() });
12301
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 ?? "")));
12302
12374
  if (req.method === "DELETE" && parts[1] === "rooms" && parts.length === 3) return sendJson(res, 200, hub.closeRoom(parts[2]));
12303
12375
  if (req.method === "POST" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "together") return sendJson(res, 200, hub.watchTogether(parts[2]));
12304
12376
  if (route === "GET library") return sendJson(res, 200, await hub.library());
@@ -12354,7 +12426,7 @@ Content-Length: 0\r
12354
12426
  import { spawn as spawn5 } from "node:child_process";
12355
12427
  import { createHash as createHash6 } from "node:crypto";
12356
12428
  import { statfs as statfs2, stat as stat10 } from "node:fs/promises";
12357
- import { join as join16, resolve as resolve5 } from "node:path";
12429
+ import { join as join17, resolve as resolve5 } from "node:path";
12358
12430
 
12359
12431
  // src/downloads.js
12360
12432
  import { readFile as readFile6, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
@@ -12564,6 +12636,18 @@ function createDownloads({ stateDir, sources, have, hasSpace = async () => true,
12564
12636
  pump();
12565
12637
  return job;
12566
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
+ },
12567
12651
  /** Stop and forget a show's download. */
12568
12652
  async cancel(dir) {
12569
12653
  const job = jobs.get(dir);
@@ -12645,7 +12729,25 @@ function createCache({ library, downloads, rooms, window: size, logger }) {
12645
12729
  }
12646
12730
  await enforceCap();
12647
12731
  }),
12648
- 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
+ })
12649
12751
  };
12650
12752
  }
12651
12753
 
@@ -13808,6 +13910,8 @@ function createRoomService(options) {
13808
13910
  * (`growing` settles when they are complete): rooms waiting on it play it once enough is there.
13809
13911
  */
13810
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,
13811
13915
  /** The prepared file of a ready local item. */
13812
13916
  mediaFile(roomId, index) {
13813
13917
  const item = rooms.get(roomId)?.items[index];
@@ -14421,6 +14525,13 @@ function createLibrary(options) {
14421
14525
  update(path, { source: { ...entry.source, episodes } });
14422
14526
  changed(path);
14423
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
+ },
14424
14535
  /** The saved (offline fallback) copy of a show's work, or null. */
14425
14536
  workOf: (path) => record(path).work ?? null,
14426
14537
  /** Which source and work id a show came from (`{ source, id, ... }`), or null. */
@@ -14546,11 +14657,76 @@ function createLibrary(options) {
14546
14657
  };
14547
14658
  }
14548
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
+
14549
14725
  // src/follow.js
14550
- var DAY_MS2 = 864e5;
14726
+ var DAY_MS3 = 864e5;
14551
14727
  var OPEN_RECHECK_MS = 36e5;
14552
14728
  var JITTER = 0.1;
14553
- 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));
14554
14730
  function dueFollows(follows, now) {
14555
14731
  return follows.filter(({ follow: follow2 }) => (follow2.nextAt ?? 0) <= now).sort((a, b) => (a.follow.nextAt ?? 0) - (b.follow.nextAt ?? 0));
14556
14732
  }
@@ -14769,27 +14945,27 @@ function createChanges({ intervalMs = 300 } = {}) {
14769
14945
  }
14770
14946
 
14771
14947
  // src/copies.js
14772
- 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";
14773
14949
  import { dirname as dirname6 } from "node:path";
14774
- var DAY_MS3 = 864e5;
14775
- var HOUR_MS = 36e5;
14776
- function createCopies({ file, changed, logger, maxAgeMs = DAY_MS3, retryMs = HOUR_MS, parallel = 4, 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 }) {
14777
14953
  const copies = /* @__PURE__ */ new Map();
14778
14954
  const flying = /* @__PURE__ */ new Map();
14779
14955
  const failedAt = /* @__PURE__ */ new Map();
14780
14956
  const waiting = [];
14781
14957
  let running = 0;
14782
14958
  let saving = Promise.resolve();
14783
- const loaded = readFile11(file, "utf8").then((text3) => {
14959
+ const loaded = readFile12(file, "utf8").then((text3) => {
14784
14960
  for (const [key, copy] of Object.entries(JSON.parse(text3))) copies.set(key, copy);
14785
14961
  }).catch((error) => {
14786
14962
  if (error.code !== "ENOENT") logger.warn("the saved copies of Discover could not be read: %s", error.message);
14787
14963
  });
14788
14964
  function save() {
14789
14965
  saving = saving.then(async () => {
14790
- await mkdir10(dirname6(file), { recursive: true });
14791
- await writeFile7(`${file}.part`, JSON.stringify(Object.fromEntries(copies)));
14792
- 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);
14793
14969
  }).catch((error) => logger.warn("the copies of Discover could not be saved: %s", error.message));
14794
14970
  return saving;
14795
14971
  }
@@ -14907,9 +15083,9 @@ function createDiscover({ copies, sources, covers, recommender }) {
14907
15083
  }
14908
15084
 
14909
15085
  // src/work-refresh.js
14910
- var DAY_MS4 = 864e5;
14911
- var HOUR_MS2 = 36e5;
14912
- 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 }) {
14913
15089
  const flying = /* @__PURE__ */ new Set();
14914
15090
  const failedAt = /* @__PURE__ */ new Map();
14915
15091
  const waiting = [];
@@ -14947,18 +15123,18 @@ ${entry.source.id}`;
14947
15123
  }
14948
15124
 
14949
15125
  // src/media.js
14950
- var HOUR_MS3 = 36e5;
15126
+ var HOUR_MS4 = 36e5;
14951
15127
  var MIN_FREE_BYTES = 1e9;
14952
15128
  var NO_CONVERTER = Object.freeze({ command: "", available: async () => false });
14953
15129
  var hubError = (code, message) => Object.assign(new Error(message), { code });
14954
15130
  function createMediaHub(options) {
14955
15131
  const { stateDir, libraryRoots, logger, now = Date.now } = options;
14956
15132
  const sources = new Map(options.sources.map((source2) => [source2.id, source2]));
14957
- const covers = createCovers({ dir: join16(stateDir, "covers"), capBytes: options.coverCacheBytes, ffmpeg: options.tools.ffmpeg, logger }, (id) => sources.get(id));
14958
- 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 });
14959
15135
  const changes = createChanges({ intervalMs: options.changeIntervalMs });
14960
15136
  const points = createPoints(options.points ?? { command: [], night: { from: "01:00", to: "06:00" } }, { logger, now });
14961
- 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 });
14962
15138
  let rooms;
14963
15139
  let cache;
14964
15140
  const downloads = createDownloads({
@@ -14978,6 +15154,7 @@ function createMediaHub(options) {
14978
15154
  logger,
14979
15155
  now
14980
15156
  });
15157
+ const remarks = createRemarks({ source: (id) => sources.get(id), logger, now });
14981
15158
  const refreshWork = createWorkRefresh({ source: (id) => sources.get(id), keep: (path, work) => library.keepWork(path, work), maxAgeMs: options.workMaxAgeMs, logger, now });
14982
15159
  const library = createLibrary({
14983
15160
  changed: () => changes.notify("library"),
@@ -15012,7 +15189,7 @@ function createMediaHub(options) {
15012
15189
  cache.refresh(show).catch(() => {
15013
15190
  });
15014
15191
  });
15015
- 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 });
15016
15193
  const discover = createDiscover({
15017
15194
  copies,
15018
15195
  sources,
@@ -15024,7 +15201,12 @@ function createMediaHub(options) {
15024
15201
  });
15025
15202
  cache.enforce().catch(() => {
15026
15203
  });
15027
- }, 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
+ }
15028
15210
  async function onFiles(job) {
15029
15211
  changes.notify("library");
15030
15212
  await rooms.syncShow(job.dir);
@@ -15095,7 +15277,7 @@ ${work.id}`) || foldersFor(sourceId, work).some((path) => logged.has(path)));
15095
15277
  const name2 = cleanName(work.title ?? "");
15096
15278
  const mark = createHash6("sha256").update(`${sourceId}
15097
15279
  ${work.id}`).digest("hex").slice(0, 8);
15098
- return [name2, `${name2} (${mark})`].map((candidate) => join16(libraryRoots[0], candidate));
15280
+ return [name2, `${name2} (${mark})`].map((candidate) => join17(libraryRoots[0], candidate));
15099
15281
  }
15100
15282
  async function folderFor(sourceId, item) {
15101
15283
  for (const path of foldersFor(sourceId, item)) {
@@ -15184,11 +15366,44 @@ ${work.id}`).digest("hex").slice(0, 8);
15184
15366
  for (const show of list.shows) if (show.source?.source) refreshWork(show.path, { source: show.source, work: show.work });
15185
15367
  return { ...list, shows: list.shows.map(withCovers) };
15186
15368
  },
15187
- /** 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
+ */
15188
15373
  roomWork(id) {
15189
- const room = rooms.listRooms().find((entry) => entry.id === id);
15190
- if (room === void 0) throw hubError("not_found", "no such room");
15191
- 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 };
15192
15407
  },
15193
15408
  episodes: (path) => library.episodes(path),
15194
15409
  removeShow: (path, by) => library.remove(path, { by }),
@@ -15248,8 +15463,8 @@ ${work.id}`).digest("hex").slice(0, 8);
15248
15463
  if (watch) room = (await rooms.createRoom({ source: "local", path: dir, title: item.title, by, person, together, start: await library.resumeFrom(dir) })).room;
15249
15464
  else await cache.refresh(dir, { retry: true });
15250
15465
  await points.use(person, tickets, { room: room?.id, subject });
15251
- const count = all ? item.episodes : Math.min(item.episodes, options.cache.ahead + 1);
15252
- 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) };
15253
15468
  },
15254
15469
  /**
15255
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
@@ -15513,7 +15728,7 @@ function createShelfRoutes({ books, identity }) {
15513
15728
  var name = "dsh-media-hub";
15514
15729
  var inject = ["webServer", "connection"];
15515
15730
  var ROOM_ID = /^[A-Za-z0-9_-]{6,32}$/;
15516
- var DAY_MS5 = 864e5;
15731
+ var DAY_MS6 = 864e5;
15517
15732
  function apply(ctx, config) {
15518
15733
  const logger = ctx.logger("media-hub");
15519
15734
  let current;
@@ -15522,7 +15737,7 @@ function apply(ctx, config) {
15522
15737
  const stateDir = resolve6(config.stateDir);
15523
15738
  const service = createMediaHub({
15524
15739
  stateDir,
15525
- libraryRoots: [join17(stateDir, "library"), ...config.libraryRoots.map((root) => resolve6(root))],
15740
+ libraryRoots: [join18(stateDir, "library"), ...config.libraryRoots.map((root) => resolve6(root))],
15526
15741
  delivery: createDelivery({ mode: config.delivery }),
15527
15742
  tools: { ffmpeg: config.ffmpeg, ffprobe: config.ffprobe, maxHeight: config.maxHeight, threads: config.threads },
15528
15743
  webUrl: () => ctx.get("webApp")?.getAdvertisedUrl(),
@@ -15549,7 +15764,7 @@ function apply(ctx, config) {
15549
15764
  const prune = setInterval(() => {
15550
15765
  service.pruneCache(config.cacheDays).catch(() => {
15551
15766
  });
15552
- }, DAY_MS5);
15767
+ }, DAY_MS6);
15553
15768
  const identity = () => ctx.get("requestIdentity");
15554
15769
  const fetchRoutes = [
15555
15770
  ...createShelfRoutes({ books: () => current?.books, identity }),
package/locale/en.json CHANGED
@@ -109,6 +109,7 @@
109
109
  "rooms.heading": "Open rooms",
110
110
  "room.tab.episodes": "Episodes",
111
111
  "room.tab.about": "About",
112
+ "room.tab.comments": "Comments",
112
113
  "room.nextSeason": "Next season: {title}",
113
114
  "room.state.playing": "playing",
114
115
  "room.state.paused": "paused",
@@ -231,6 +232,32 @@
231
232
  "quality.auto": "Auto",
232
233
  "quality.audio": "Audio only",
233
234
  "quality.height": "{n}p",
235
+ "quality.fromNext": "From the next episode on, for everyone in the room.",
236
+ "quality.changing": "Switching…",
237
+ "danmaku.label": "Danmaku",
238
+ "danmaku.count": "Danmaku {n}",
239
+ "danmaku.opacity": "Opacity",
240
+ "danmaku.area": "Area",
241
+ "danmaku.area.quarter": "Top quarter",
242
+ "danmaku.area.half": "Top half",
243
+ "danmaku.area.full": "Whole picture",
244
+ "danmaku.size": "Text size",
245
+ "danmaku.size.small": "Small",
246
+ "danmaku.size.medium": "Medium",
247
+ "danmaku.size.large": "Large",
248
+ "player.settings": "Player settings",
249
+ "player.full": "Full screen",
250
+ "player.exitFull": "Exit full screen",
251
+ "comments.loading": "Loading comments…",
252
+ "comments.none": "No comments yet.",
253
+ "comments.more": "More comments",
254
+ "comments.someone": "Someone",
255
+ "comments.rating": "Rated {score}",
256
+ "comments.likes": "{n} likes",
257
+ "comments.replies.one": "{n} reply",
258
+ "comments.replies.other": "{n} replies",
259
+ "comments.total.one": "{n} comment on the site",
260
+ "comments.total.other": "{n} comments on the site",
234
261
  "error.blocked": "The site turned this request away. It may block the network the hub uses; try again later.",
235
262
  "error.sign_in": "The site wants a signed-in account for this video. Ask whoever runs the hub to add one.",
236
263
  "error.not_found": "There's nothing to play at this address. Check the link.",
package/locale/fr.json CHANGED
@@ -109,6 +109,7 @@
109
109
  "rooms.heading": "Salons ouverts",
110
110
  "room.tab.episodes": "Épisodes",
111
111
  "room.tab.about": "À propos",
112
+ "room.tab.comments": "Commentaires",
112
113
  "room.nextSeason": "Saison suivante : {title}",
113
114
  "room.state.playing": "en lecture",
114
115
  "room.state.paused": "en pause",
@@ -231,6 +232,32 @@
231
232
  "quality.auto": "Auto",
232
233
  "quality.audio": "Audio seul",
233
234
  "quality.height": "{n}p",
235
+ "quality.fromNext": "À partir de l’épisode suivant, pour toute la salle.",
236
+ "quality.changing": "Changement…",
237
+ "danmaku.label": "Danmaku",
238
+ "danmaku.count": "Danmaku {n}",
239
+ "danmaku.opacity": "Opacité",
240
+ "danmaku.area": "Zone",
241
+ "danmaku.area.quarter": "Quart du haut",
242
+ "danmaku.area.half": "Moitié du haut",
243
+ "danmaku.area.full": "Toute l’image",
244
+ "danmaku.size": "Taille du texte",
245
+ "danmaku.size.small": "Petite",
246
+ "danmaku.size.medium": "Moyenne",
247
+ "danmaku.size.large": "Grande",
248
+ "player.settings": "Réglages du lecteur",
249
+ "player.full": "Plein écran",
250
+ "player.exitFull": "Quitter le plein écran",
251
+ "comments.loading": "Chargement des commentaires…",
252
+ "comments.none": "Pas encore de commentaires.",
253
+ "comments.more": "Plus de commentaires",
254
+ "comments.someone": "Quelqu’un",
255
+ "comments.rating": "Note {score}",
256
+ "comments.likes": "{n} j’aime",
257
+ "comments.replies.one": "{n} réponse",
258
+ "comments.replies.other": "{n} réponses",
259
+ "comments.total.one": "{n} commentaire sur le site",
260
+ "comments.total.other": "{n} commentaires sur le site",
234
261
  "error.blocked": "Le site a refusé la demande. Il bloque peut-être le réseau du hub ; réessayez plus tard.",
235
262
  "error.sign_in": "Le site demande un compte connecté pour cette vidéo. Demandez à la personne qui gère le hub d'en ajouter un.",
236
263
  "error.not_found": "Il n'y a rien à lire à cette adresse. Vérifiez le lien.",