@soffits/dsh-media-hub 0.13.0 → 0.15.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
@@ -8271,11 +8271,11 @@ var require_socksclient = __commonJS({
8271
8271
  "use strict";
8272
8272
  var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
8273
8273
  function adopt(value) {
8274
- return value instanceof P ? value : new P(function(resolve7) {
8275
- resolve7(value);
8274
+ return value instanceof P ? value : new P(function(resolve8) {
8275
+ resolve8(value);
8276
8276
  });
8277
8277
  }
8278
- return new (P || (P = Promise))(function(resolve7, reject) {
8278
+ return new (P || (P = Promise))(function(resolve8, reject) {
8279
8279
  function fulfilled(value) {
8280
8280
  try {
8281
8281
  step(generator.next(value));
@@ -8291,7 +8291,7 @@ var require_socksclient = __commonJS({
8291
8291
  }
8292
8292
  }
8293
8293
  function step(result) {
8294
- result.done ? resolve7(result.value) : adopt(result.value).then(fulfilled, rejected);
8294
+ result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected);
8295
8295
  }
8296
8296
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8297
8297
  });
@@ -8325,13 +8325,13 @@ var require_socksclient = __commonJS({
8325
8325
  * @returns { Promise }
8326
8326
  */
8327
8327
  static createConnection(options, callback) {
8328
- return new Promise((resolve7, reject) => {
8328
+ return new Promise((resolve8, reject) => {
8329
8329
  try {
8330
8330
  (0, helpers_1.validateSocksClientOptions)(options, ["connect"]);
8331
8331
  } catch (err) {
8332
8332
  if (typeof callback === "function") {
8333
8333
  callback(err);
8334
- return resolve7(err);
8334
+ return resolve8(err);
8335
8335
  } else {
8336
8336
  return reject(err);
8337
8337
  }
@@ -8342,16 +8342,16 @@ var require_socksclient = __commonJS({
8342
8342
  client.removeAllListeners();
8343
8343
  if (typeof callback === "function") {
8344
8344
  callback(null, info);
8345
- resolve7(info);
8345
+ resolve8(info);
8346
8346
  } else {
8347
- resolve7(info);
8347
+ resolve8(info);
8348
8348
  }
8349
8349
  });
8350
8350
  client.once("error", (err) => {
8351
8351
  client.removeAllListeners();
8352
8352
  if (typeof callback === "function") {
8353
8353
  callback(err);
8354
- resolve7(err);
8354
+ resolve8(err);
8355
8355
  } else {
8356
8356
  reject(err);
8357
8357
  }
@@ -8368,13 +8368,13 @@ var require_socksclient = __commonJS({
8368
8368
  * @returns { Promise }
8369
8369
  */
8370
8370
  static createConnectionChain(options, callback) {
8371
- return new Promise((resolve7, reject) => __awaiter(this, void 0, void 0, function* () {
8371
+ return new Promise((resolve8, reject) => __awaiter(this, void 0, void 0, function* () {
8372
8372
  try {
8373
8373
  (0, helpers_1.validateSocksClientChainOptions)(options);
8374
8374
  } catch (err) {
8375
8375
  if (typeof callback === "function") {
8376
8376
  callback(err);
8377
- return resolve7(err);
8377
+ return resolve8(err);
8378
8378
  } else {
8379
8379
  return reject(err);
8380
8380
  }
@@ -8400,14 +8400,14 @@ var require_socksclient = __commonJS({
8400
8400
  }
8401
8401
  if (typeof callback === "function") {
8402
8402
  callback(null, { socket: sock });
8403
- resolve7({ socket: sock });
8403
+ resolve8({ socket: sock });
8404
8404
  } else {
8405
- resolve7({ socket: sock });
8405
+ resolve8({ socket: sock });
8406
8406
  }
8407
8407
  } catch (err) {
8408
8408
  if (typeof callback === "function") {
8409
8409
  callback(err);
8410
- resolve7(err);
8410
+ resolve8(err);
8411
8411
  } else {
8412
8412
  reject(err);
8413
8413
  }
@@ -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 resolve7 } from "node:path";
8974
8974
 
8975
8975
  // node_modules/ws/wrapper.mjs
8976
8976
  var import_stream = __toESM(require_stream(), 1);
@@ -9465,8 +9465,8 @@ function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @_
9465
9465
  if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
9466
9466
  if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
9467
9467
  }
9468
- Schema.extend = function extend(type, resolve7) {
9469
- resolvers[type] = resolve7;
9468
+ Schema.extend = function extend(type, resolve8) {
9469
+ resolvers[type] = resolve8;
9470
9470
  };
9471
9471
  Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
9472
9472
  if (!schema) return [data];
@@ -10013,7 +10013,7 @@ import { URL as URL2 } from "url";
10013
10013
  var import_debug = __toESM(require_src(), 1);
10014
10014
  var debug = (0, import_debug.default)("https-proxy-agent:parse-proxy-response");
10015
10015
  function parseProxyResponse(socket) {
10016
- return new Promise((resolve7, reject) => {
10016
+ return new Promise((resolve8, reject) => {
10017
10017
  let buffersLength = 0;
10018
10018
  const buffers = [];
10019
10019
  function read() {
@@ -10079,7 +10079,7 @@ function parseProxyResponse(socket) {
10079
10079
  }
10080
10080
  debug("got proxy server response: %o %o", firstLine, headers);
10081
10081
  cleanup();
10082
- resolve7({
10082
+ resolve8({
10083
10083
  connect: {
10084
10084
  statusCode,
10085
10085
  statusText,
@@ -10383,12 +10383,12 @@ var SocksProxyAgent = class extends Agent2 {
10383
10383
  let { host } = opts;
10384
10384
  const { port, lookup: lookupFn = dns.lookup } = opts;
10385
10385
  if (shouldLookup) {
10386
- host = await new Promise((resolve7, reject) => {
10386
+ host = await new Promise((resolve8, reject) => {
10387
10387
  lookupFn(host, {}, (err, address) => {
10388
10388
  if (err) {
10389
10389
  reject(err);
10390
10390
  } else {
10391
- resolve7(typeof address === "string" ? address : address[0].address);
10391
+ resolve8(typeof address === "string" ? address : address[0].address);
10392
10392
  }
10393
10393
  });
10394
10394
  });
@@ -10511,11 +10511,11 @@ var proxyError = (code, message) => Object.assign(new Error(message), { code });
10511
10511
  function proxyAnswers(proxy, timeoutMs = PROBE_TIMEOUT_MS) {
10512
10512
  const { hostname, port, protocol } = new URL(proxy);
10513
10513
  const defaultPort = protocol.startsWith("socks") ? 1080 : protocol === "https:" ? 443 : 80;
10514
- return new Promise((resolve7) => {
10514
+ return new Promise((resolve8) => {
10515
10515
  const socket = connect4({ host: hostname.replace(/^\[|\]$/g, ""), port: Number(port) || defaultPort });
10516
10516
  const done = (up) => {
10517
10517
  socket.destroy();
10518
- resolve7(up);
10518
+ resolve8(up);
10519
10519
  };
10520
10520
  socket.setTimeout(timeoutMs, () => done(false));
10521
10521
  socket.once("connect", () => done(true));
@@ -10541,9 +10541,9 @@ function createProxies(rules = [], io = {}) {
10541
10541
  const protocol = new URL(url).protocol;
10542
10542
  if (protocol !== "https:" && protocol !== "http:") throw proxyError("invalid", `not a web address: ${url}`);
10543
10543
  const agent = agentFor(await route(url, page));
10544
- return new Promise((resolve7, reject) => {
10544
+ return new Promise((resolve8, reject) => {
10545
10545
  const send = protocol === "https:" ? httpsRequest : httpRequest;
10546
- const req = send(url, { agent, headers: { "user-agent": USER_AGENT, accept: "image/*,*/*;q=0.5" }, timeout: timeoutMs }, resolve7);
10546
+ const req = send(url, { agent, headers: { "user-agent": USER_AGENT, accept: "image/*,*/*;q=0.5" }, timeout: timeoutMs }, resolve8);
10547
10547
  req.on("timeout", () => req.destroy(proxyError("timeout", `no answer from ${hostOf(url)} in ${timeoutMs / 1e3} s`)));
10548
10548
  req.on("error", reject);
10549
10549
  req.end();
@@ -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";
@@ -10648,7 +10660,7 @@ async function commandExists(command, path = process.env.PATH ?? "") {
10648
10660
  return false;
10649
10661
  }
10650
10662
  function run(argv, { signal, timeoutMs, onStdoutLine, cwd, env, input } = {}) {
10651
- return new Promise((resolve7, reject) => {
10663
+ return new Promise((resolve8, reject) => {
10652
10664
  const [command, ...args] = argv;
10653
10665
  const child = spawn(command, args, { stdio: [input === void 0 ? "ignore" : "pipe", "pipe", "pipe"], detached: true, cwd, env: { ...process.env, ...env } });
10654
10666
  if (input !== void 0) {
@@ -10693,7 +10705,7 @@ function run(argv, { signal, timeoutMs, onStdoutLine, cwd, env, input } = {}) {
10693
10705
  if (timer) clearTimeout(timer);
10694
10706
  signal?.removeEventListener("abort", stop);
10695
10707
  if (onStdoutLine !== void 0 && pending.trim() !== "") onStdoutLine(pending);
10696
- resolve7({ code, stdout, stderr, oversized });
10708
+ resolve8({ code, stdout, stderr, oversized });
10697
10709
  });
10698
10710
  });
10699
10711
  }
@@ -10811,12 +10823,38 @@ 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
- return new Promise((resolve7, reject) => {
10855
+ return new Promise((resolve8, reject) => {
10818
10856
  const hash = createHash("sha256");
10819
- createReadStream(path).on("data", (chunk) => hash.update(chunk)).on("error", reject).on("end", () => resolve7(hash.digest("hex")));
10857
+ createReadStream(path).on("data", (chunk) => hash.update(chunk)).on("error", reject).on("end", () => resolve8(hash.digest("hex")));
10820
10858
  });
10821
10859
  }
10822
10860
  async function verify(dir, event, label, logger) {
@@ -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
  }
@@ -11345,9 +11407,9 @@ async function streamEpisode({ files, growing, dir, ffmpeg = "ffmpeg", ffprobe =
11345
11407
  child.stderr.on("data", (chunk) => {
11346
11408
  errors = (errors + chunk).slice(-4e3);
11347
11409
  });
11348
- const exited = new Promise((resolve7, reject) => {
11410
+ const exited = new Promise((resolve8, reject) => {
11349
11411
  child.on("error", reject);
11350
- child.on("close", (code) => code === 0 ? resolve7() : reject(new Error(`ffmpeg exited with ${code}: ${errors.trim().split("\n").pop() ?? ""}`)));
11412
+ child.on("close", (code) => code === 0 ? resolve8() : reject(new Error(`ffmpeg exited with ${code}: ${errors.trim().split("\n").pop() ?? ""}`)));
11351
11413
  });
11352
11414
  const running = settledFlag(exited);
11353
11415
  let told = false;
@@ -11485,7 +11547,7 @@ async function dropPrepared(cacheDir, path) {
11485
11547
  if (key !== null) await rm4(join6(cacheDir, key), { recursive: true, force: true });
11486
11548
  }
11487
11549
  function runFfmpeg(args, { ffmpeg, duration, onProgress, signal }) {
11488
- return new Promise((resolve7, reject) => {
11550
+ return new Promise((resolve8, reject) => {
11489
11551
  const child = spawn3("nice", ["-n", "10", ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-progress", "pipe:1", ...args], { stdio: ["ignore", "pipe", "pipe"], signal });
11490
11552
  let errors = "";
11491
11553
  child.stderr.on("data", (chunk) => {
@@ -11496,7 +11558,7 @@ function runFfmpeg(args, { ffmpeg, duration, onProgress, signal }) {
11496
11558
  if (match && duration && onProgress) onProgress(Math.min(1, Number(match[1]) / 1e6 / duration));
11497
11559
  });
11498
11560
  child.on("error", reject);
11499
- child.on("close", (code) => code === 0 ? resolve7() : reject(new Error(`ffmpeg exited with ${code}: ${errors.trim().split("\n").pop() ?? ""}`)));
11561
+ child.on("close", (code) => code === 0 ? resolve8() : reject(new Error(`ffmpeg exited with ${code}: ${errors.trim().split("\n").pop() ?? ""}`)));
11500
11562
  });
11501
11563
  }
11502
11564
  var remuxArgs = (input, output) => ["-y", "-i", input, "-map", "0:V:0?", "-map", "0:a:0?", "-sn", "-dn", "-c", "copy", "-movflags", "+faststart", "-f", "mp4", output];
@@ -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: {}
@@ -12024,13 +12085,9 @@ var Recommender = Schema.object({
12024
12085
  env: Schema.dict(Schema.string()).default({}).description("Extra environment variables for the command.")
12025
12086
  });
12026
12087
  var Clock = Schema.string().pattern(/^([01]?\d|2[0-3]):[0-5]\d$/);
12027
- var Points = Schema.object({
12028
- command: Schema.array(Schema.string()).default([]).description("A points extension speaking docs/points-protocol.md (program and fixed arguments, the plugin adds the verbs). Empty means every extra is free."),
12029
- env: Schema.dict(Schema.string()).default({}).description("Extra environment variables for the command."),
12030
- night: Schema.object({
12031
- from: Clock.default("01:00").description("When late night starts, on the host's clock (HH:MM)."),
12032
- to: Clock.default("06:00").description("When it ends; a binge night ticket lasts until then.")
12033
- }).default({ from: "01:00", to: "06:00" }).description("Starting to watch in this window is a binge night for people the extension keeps points for.")
12088
+ var BingeNight = Schema.object({
12089
+ from: Clock.default("01:00").description("When late night starts, on the host's clock (HH:MM)."),
12090
+ to: Clock.default("06:00").description("When it ends; a binge night ticket lasts until then.")
12034
12091
  });
12035
12092
  var Config = Schema.object({
12036
12093
  label: Label.default("").description("Name of the sidebar entry: a string, or { <tag>: text } per language (the viewer's tag, then its primary subtag, then en). Empty uses the page's own name in the viewer's language."),
@@ -12053,7 +12110,7 @@ var Config = Schema.object({
12053
12110
  notifyCommand: Schema.array(Schema.string()).default([]).description("A command (program and fixed arguments) run when a followed work gets a new season or new episodes, with one line of JSON describing it on its standard input. Empty means nothing is run."),
12054
12111
  presence: Presence.default({ continue: true, recap: false, ratings: false, picks: false }).description("What the Watching tab shows besides the open rooms and the library. Each part can be switched on or off."),
12055
12112
  recommender: Recommender.default({ command: [], env: {} }).description("Where picks come from: a recommender extension. The hub has no taste of its own."),
12056
- points: Points.default({ command: [], env: {}, night: { from: "01:00", to: "06:00" } }).description("Extras a person's points pay for: starting a new series and a binge night, for the people a points extension plays with. Watching stays free; with no extension nothing changes."),
12113
+ bingeNight: BingeNight.default({ from: "01:00", to: "06:00" }).description("Starting to watch in this window is a binge night, an extra that costs points for the people the points plugin (@soffits/dsh-points) plays with, like starting a series new to the hub. Without that plugin every extra is free."),
12057
12114
  ffmpeg: Schema.string().default("ffmpeg").description("ffmpeg command."),
12058
12115
  ffprobe: Schema.string().default("ffprobe").description("ffprobe command."),
12059
12116
  ytDlp: Schema.string().default("yt-dlp").description("yt-dlp command. Link reads and downloads web videos and playlists with it; without it Link is hidden. Its own config file applies."),
@@ -12064,9 +12121,9 @@ var Config = Schema.object({
12064
12121
  // src/http.js
12065
12122
  import { createReadStream as createReadStream2, existsSync as existsSync2 } from "node:fs";
12066
12123
  import { readFile as readFile5, stat as stat6 } from "node:fs/promises";
12067
- import { dirname as dirname3, extname as extname5, isAbsolute as isAbsolute2, relative, resolve as resolve2, sep } from "node:path";
12124
+ import { dirname as dirname4, extname as extname5, isAbsolute as isAbsolute2, relative, resolve as resolve3, sep } from "node:path";
12068
12125
  import { createRequire } from "node:module";
12069
- import { fileURLToPath } from "node:url";
12126
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
12070
12127
 
12071
12128
  // src/filters.js
12072
12129
  var LANGUAGE = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{1,8})*$/;
@@ -12112,7 +12169,9 @@ function interleave(lists) {
12112
12169
 
12113
12170
  // src/locales.js
12114
12171
  import { readdir as readdir4, readFile as readFile4 } from "node:fs/promises";
12115
- import { join as join10 } from "node:path";
12172
+ import { dirname as dirname3, join as join10, resolve as resolve2 } from "node:path";
12173
+ import { fileURLToPath } from "node:url";
12174
+ var LOCALE_DIR = resolve2(dirname3(fileURLToPath(import.meta.url)), "../locale");
12116
12175
  async function readLocales(dir, logger) {
12117
12176
  const names = (await readdir4(dir).catch(() => [])).filter((name2) => name2.endsWith(".json")).sort();
12118
12177
  const locales = {};
@@ -12134,6 +12193,12 @@ async function readLocales(dir, logger) {
12134
12193
  return locales;
12135
12194
  }
12136
12195
 
12196
+ // src/vendored.js
12197
+ var VENDORED = Object.freeze({
12198
+ "hls.mjs": { pkg: "hls.js", file: "dist/hls.mjs" },
12199
+ "danmaku.mjs": { pkg: "danmaku", file: "dist/esm/danmaku.dom.js" }
12200
+ });
12201
+
12137
12202
  // src/http.js
12138
12203
  var ROUTE = `/${PREFIX}`;
12139
12204
  var WS_PATH = `${ROUTE}/ws`;
@@ -12157,23 +12222,24 @@ var MEDIA_TYPES = Object.freeze({
12157
12222
  ".jpg": "image/jpeg"
12158
12223
  });
12159
12224
  var WEB_TYPES = Object.freeze({ ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8" });
12160
- var here = fileURLToPath(new URL(".", import.meta.url));
12161
- var WEB_DIR = resolve2(here, "../web");
12162
- var LOCALE_DIR = resolve2(here, "../locale");
12225
+ var here = fileURLToPath2(new URL(".", import.meta.url));
12226
+ var WEB_DIR = resolve3(here, "../web");
12163
12227
  var MODULES = Object.freeze({
12164
- "sync.js": resolve2(here, "../src/sync.js"),
12165
- "formats.js": resolve2(here, "../src/formats.js"),
12166
- "i18n.js": resolve2(here, "../src/i18n.js"),
12167
- "captions.js": resolve2(here, "../src/captions.js")
12228
+ "sync.js": resolve3(here, "../src/sync.js"),
12229
+ "formats.js": resolve3(here, "../src/formats.js"),
12230
+ "i18n.js": resolve3(here, "../src/i18n.js"),
12231
+ "captions.js": resolve3(here, "../src/captions.js")
12168
12232
  });
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");
12233
+ function vendoredFile(name2) {
12234
+ const built = resolve3(here, "../dist", name2);
12235
+ if (existsSync2(built)) return built;
12236
+ const { pkg, file } = VENDORED[name2];
12237
+ return resolve3(dirname4(createRequire(import.meta.url).resolve(`${pkg}/package.json`)), file);
12172
12238
  }
12173
12239
  function webFile(name2) {
12174
- if (name2 === "hls.mjs") return hlsFile();
12240
+ if (Object.hasOwn(VENDORED, name2)) return vendoredFile(name2);
12175
12241
  if (MODULES[name2] !== void 0) return MODULES[name2];
12176
- return /^[a-z0-9-]+\.(js|css)$/.test(name2) ? resolve2(WEB_DIR, name2) : void 0;
12242
+ return /^[a-z0-9-]+\.(js|css)$/.test(name2) ? resolve3(WEB_DIR, name2) : void 0;
12177
12243
  }
12178
12244
  function admitOwner(connection, request) {
12179
12245
  const admission = connection.admit(request);
@@ -12235,7 +12301,7 @@ function sendJson(res, status, value) {
12235
12301
  res.writeHead(status, { ...SECURITY_HEADERS, "content-type": "application/json; charset=utf-8", "content-length": Buffer.byteLength(body2) }).end(body2);
12236
12302
  }
12237
12303
  function within(root, rel) {
12238
- const target = resolve2(root, rel);
12304
+ const target = resolve3(root, rel);
12239
12305
  const back = relative(root, target);
12240
12306
  if (back === "" || back === ".." || back.startsWith(`..${sep}`) || isAbsolute2(back)) return null;
12241
12307
  return target;
@@ -12285,7 +12351,7 @@ function createHandler({ connection, service, settings = () => ({ label: "", pre
12285
12351
  if (item === void 0) return sendText(res, 404, "Not found.");
12286
12352
  const rest = parts.slice(3).join("/");
12287
12353
  if (item.kind === "hls") {
12288
- const target = within(dirname3(item.file), rest);
12354
+ const target = within(dirname4(item.file), rest);
12289
12355
  return target === null ? sendText(res, 404, "Not found.") : sendFile(req, res, target);
12290
12356
  }
12291
12357
  return sendFile(req, res, item.file);
@@ -12299,6 +12365,9 @@ function createHandler({ connection, service, settings = () => ({ label: "", pre
12299
12365
  const query = (name2) => url.searchParams.get(name2) ?? "";
12300
12366
  if (route === "GET rooms") return sendJson(res, 200, { rooms: await hub.listRooms() });
12301
12367
  if (req.method === "GET" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "work") return sendJson(res, 200, hub.roomWork(parts[2]));
12368
+ 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])));
12369
+ if (req.method === "GET" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "comments") return sendJson(res, 200, await hub.roomComments(parts[2], query("cursor")));
12370
+ 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
12371
  if (req.method === "DELETE" && parts[1] === "rooms" && parts.length === 3) return sendJson(res, 200, hub.closeRoom(parts[2]));
12303
12372
  if (req.method === "POST" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "together") return sendJson(res, 200, hub.watchTogether(parts[2]));
12304
12373
  if (route === "GET library") return sendJson(res, 200, await hub.library());
@@ -12354,7 +12423,7 @@ Content-Length: 0\r
12354
12423
  import { spawn as spawn5 } from "node:child_process";
12355
12424
  import { createHash as createHash6 } from "node:crypto";
12356
12425
  import { statfs as statfs2, stat as stat10 } from "node:fs/promises";
12357
- import { join as join16, resolve as resolve5 } from "node:path";
12426
+ import { join as join17, resolve as resolve6 } from "node:path";
12358
12427
 
12359
12428
  // src/downloads.js
12360
12429
  import { readFile as readFile6, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
@@ -12564,6 +12633,18 @@ function createDownloads({ stateDir, sources, have, hasSpace = async () => true,
12564
12633
  pump();
12565
12634
  return job;
12566
12635
  },
12636
+ /**
12637
+ * Fetch a show's episodes another way from now on (`how`, as `howOf` gives it): a run under way stops and goes
12638
+ * 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
12639
+ * step that the run's own progress waits on (the rolling cache's).
12640
+ */
12641
+ switchHow(dir, how) {
12642
+ const job = jobs.get(dir);
12643
+ if (job === void 0) return;
12644
+ job.how = howOf(how);
12645
+ if (running === job) job.controller.abort("yield");
12646
+ save();
12647
+ },
12567
12648
  /** Stop and forget a show's download. */
12568
12649
  async cancel(dir) {
12569
12650
  const job = jobs.get(dir);
@@ -12645,7 +12726,25 @@ function createCache({ library, downloads, rooms, window: size, logger }) {
12645
12726
  }
12646
12727
  await enforceCap();
12647
12728
  }),
12648
- enforce: () => serial(enforceCap)
12729
+ enforce: () => serial(enforceCap),
12730
+ /**
12731
+ * Fetch a show in another quality from now on. What was fetched ahead of where people are goes and comes again in the
12732
+ * new quality; the episode someone is on keeps playing as it is, so nobody's picture stops.
12733
+ */
12734
+ requality: (path, quality) => serial(async () => {
12735
+ library.setQuality(path, quality);
12736
+ const info = await library.cacheInfo(path);
12737
+ downloads.switchHow(path, info.source);
12738
+ const places = rooms.focusesOf(path);
12739
+ const from2 = Math.max(...places.length > 0 ? places : [info.focus ?? 0]);
12740
+ const ahead = [...info.cached].filter((n) => n > from2);
12741
+ if (ahead.length > 0) {
12742
+ await library.dropEpisodes(path, ahead, { reason: "quality" });
12743
+ await rooms.syncShow(path);
12744
+ }
12745
+ await refreshShow(path, { retry: true });
12746
+ await enforceCap();
12747
+ })
12649
12748
  };
12650
12749
  }
12651
12750
 
@@ -12692,7 +12791,7 @@ function sha256Of2(path) {
12692
12791
  return readFile7(path).then((body2) => createHash4("sha256").update(body2).digest("hex"));
12693
12792
  }
12694
12793
  function runConverter(command, input, output) {
12695
- return new Promise((resolve7, reject) => {
12794
+ return new Promise((resolve8, reject) => {
12696
12795
  const child = spawn4(command, [input, output], { stdio: ["ignore", "ignore", "pipe"], detached: true });
12697
12796
  let stderr = "";
12698
12797
  const timer = setTimeout(() => {
@@ -12710,7 +12809,7 @@ function runConverter(command, input, output) {
12710
12809
  });
12711
12810
  child.on("close", (code) => {
12712
12811
  clearTimeout(timer);
12713
- if (code === 0) resolve7();
12812
+ if (code === 0) resolve8();
12714
12813
  else reject(booksError("convert_failed", `conversion failed: ${stderr.trim().split("\n").pop() || `exit ${code}`}`));
12715
12814
  });
12716
12815
  });
@@ -12988,8 +13087,8 @@ function createCovers({ dir, capBytes = 5e7, maxFileBytes = 2e6, concurrency = 3
12988
13087
  });
12989
13088
  }
12990
13089
  };
12991
- const queued = (job) => new Promise((resolve7, reject) => {
12992
- waiting.push(() => job().then(resolve7, reject));
13090
+ const queued = (job) => new Promise((resolve8, reject) => {
13091
+ waiting.push(() => job().then(resolve8, reject));
12993
13092
  pump();
12994
13093
  });
12995
13094
  async function trim() {
@@ -13094,7 +13193,7 @@ function createCovers({ dir, capBytes = 5e7, maxFileBytes = 2e6, concurrency = 3
13094
13193
  // src/hub.js
13095
13194
  import { randomBytes as randomBytes2 } from "node:crypto";
13096
13195
  import { mkdir as mkdir8, readFile as readFile8, rename as rename6, writeFile as writeFile5 } from "node:fs/promises";
13097
- import { dirname as dirname4, isAbsolute as isAbsolute3, join as join14, resolve as resolve3 } from "node:path";
13196
+ import { dirname as dirname5, isAbsolute as isAbsolute3, join as join14, resolve as resolve4 } from "node:path";
13098
13197
 
13099
13198
  // src/sync.js
13100
13199
  var DRIFT = Object.freeze({
@@ -13608,7 +13707,7 @@ function createRoomService(options) {
13608
13707
  return { ...room, items: room.items.map((entry, n) => n === room.index ? { ...entry, status: "preparing", error: null } : entry) };
13609
13708
  }
13610
13709
  async function reopen(room) {
13611
- const unfinished = async (item) => item.status === "ready" && item.kind === "hls" && typeof item.file === "string" && item.file.startsWith(`${cacheDir}/`) && await finishedPlaylist(dirname4(item.file)) === null;
13710
+ const unfinished = async (item) => item.status === "ready" && item.kind === "hls" && typeof item.file === "string" && item.file.startsWith(`${cacheDir}/`) && await finishedPlaylist(dirname5(item.file)) === null;
13612
13711
  const items = [];
13613
13712
  for (const item of room.items) {
13614
13713
  if (!await unfinished(item)) items.push(item);
@@ -13667,7 +13766,7 @@ function createRoomService(options) {
13667
13766
  }
13668
13767
  async function localItems(path, fromPanel) {
13669
13768
  if (typeof path !== "string" || !isAbsolute3(path)) throw serviceError("invalid", "path must be an absolute path");
13670
- const target = resolve3(path);
13769
+ const target = resolve4(path);
13671
13770
  if (fromPanel && !libraryRoots.some((root) => target === root || target.startsWith(`${root}/`))) {
13672
13771
  throw serviceError("outside", "the panel can only open files from the library folders");
13673
13772
  }
@@ -13683,7 +13782,7 @@ function createRoomService(options) {
13683
13782
  return episodes.map(localItem);
13684
13783
  }
13685
13784
  async function syncShow(path) {
13686
- const target = resolve3(path);
13785
+ const target = resolve4(path);
13687
13786
  const entries = await options.directory?.(target);
13688
13787
  if (!entries) return;
13689
13788
  for (const room of [...rooms.values()]) {
@@ -13722,7 +13821,7 @@ function createRoomService(options) {
13722
13821
  const start = input.start;
13723
13822
  const room = {
13724
13823
  ...created,
13725
- showPath: resolve3(input.path),
13824
+ showPath: resolve4(input.path),
13726
13825
  together: input.together === true,
13727
13826
  ...Number.isInteger(start?.index) && start.index >= 0 && start.index < items.length ? { index: start.index, position: Math.max(0, Number(start.position) || 0) } : {}
13728
13827
  };
@@ -13771,18 +13870,18 @@ function createRoomService(options) {
13771
13870
  },
13772
13871
  /** Whether an open room plays anything from `path` (a show folder or file). */
13773
13872
  usesPath(path) {
13774
- const target = resolve3(path);
13873
+ const target = resolve4(path);
13775
13874
  return [...rooms.values()].some((room) => room.showPath === target || room.items.some((item) => typeof item.sourcePath === "string" && (item.sourcePath === target || item.sourcePath.startsWith(`${target}/`))));
13776
13875
  },
13777
13876
  /** The episode numbers rooms on a show are on, one per room; empty when no room has it open. */
13778
13877
  focusesOf(path) {
13779
- const target = resolve3(path);
13878
+ const target = resolve4(path);
13780
13879
  return [...rooms.values()].filter((room) => room.showPath === target).map((room) => room.items[room.index]?.slot).filter((n) => n !== void 0);
13781
13880
  },
13782
13881
  syncShow,
13783
13882
  /** Episodes someone waits on that could not be fetched: show them as failed (with the reason, when known), so a click on one tries again. */
13784
13883
  failWaiting(path, message, reason = null) {
13785
- const target = resolve3(path);
13884
+ const target = resolve4(path);
13786
13885
  for (const room of [...rooms.values()]) {
13787
13886
  if (room.showPath !== target) continue;
13788
13887
  const items = room.items.map((item) => item.slot !== void 0 && item.sourcePath === null && item.status === "preparing" ? { ...item, status: "failed", progress: null, error: message, reason } : item);
@@ -13795,7 +13894,7 @@ function createRoomService(options) {
13795
13894
  * @param {{ fraction: number | null, done: number, total: number | null, speed: number | null, eta: number | null }} progress
13796
13895
  */
13797
13896
  downloadProgress(path, number, progress2) {
13798
- const target = resolve3(path);
13897
+ const target = resolve4(path);
13799
13898
  for (const room of [...rooms.values()]) {
13800
13899
  if (room.showPath !== target) continue;
13801
13900
  const item = room.items.find((entry) => entry.slot === number && entry.sourcePath === null && entry.status === "preparing");
@@ -13807,7 +13906,9 @@ function createRoomService(options) {
13807
13906
  * Episode `number` of a show while a source still fetches it, as files that play while they grow
13808
13907
  * (`growing` settles when they are complete): rooms waiting on it play it once enough is there.
13809
13908
  */
13810
- streamEpisode: (path, number, partial) => streams.offer(resolve3(path), number, partial),
13909
+ streamEpisode: (path, number, partial) => streams.offer(resolve4(path), number, partial),
13910
+ /** The episode number of a room's item in its show (undefined for a room on plain files). */
13911
+ slotOf: (roomId, index) => rooms.get(roomId)?.items[index]?.slot,
13811
13912
  /** The prepared file of a ready local item. */
13812
13913
  mediaFile(roomId, index) {
13813
13914
  const item = rooms.get(roomId)?.items[index];
@@ -13970,7 +14071,7 @@ function createJournal({ log, library, now = Date.now }) {
13970
14071
 
13971
14072
  // src/shows.js
13972
14073
  import { mkdir as mkdir9, readFile as readFile10, readdir as readdir7, rename as rename7, rm as rm8, stat as stat9, statfs, writeFile as writeFile6 } from "node:fs/promises";
13973
- import { basename as basename5, dirname as dirname5, extname as extname7, join as join15, resolve as resolve4 } from "node:path";
14074
+ import { basename as basename5, dirname as dirname6, extname as extname7, join as join15, resolve as resolve5 } from "node:path";
13974
14075
 
13975
14076
  // src/presence.js
13976
14077
  var RATINGS = Object.freeze(["loved", "fine", "not-for-me", "unfinished"]);
@@ -14128,8 +14229,8 @@ function createLibrary(options) {
14128
14229
  }
14129
14230
  function showPath(path) {
14130
14231
  if (typeof path !== "string") return null;
14131
- const target = resolve4(path);
14132
- return roots.includes(dirname5(target)) && !basename5(target).startsWith(".") ? target : null;
14232
+ const target = resolve5(path);
14233
+ return roots.includes(dirname6(target)) && !basename5(target).startsWith(".") ? target : null;
14133
14234
  }
14134
14235
  function requireShow(path) {
14135
14236
  const target = showPath(path);
@@ -14138,7 +14239,7 @@ function createLibrary(options) {
14138
14239
  }
14139
14240
  function showOf(episodePath) {
14140
14241
  if (typeof episodePath !== "string") return null;
14141
- return showPath(episodePath) ?? showPath(dirname5(episodePath));
14242
+ return showPath(episodePath) ?? showPath(dirname6(episodePath));
14142
14243
  }
14143
14244
  async function episodeFiles(path) {
14144
14245
  const info = await stat9(path).catch(() => null);
@@ -14421,6 +14522,13 @@ function createLibrary(options) {
14421
14522
  update(path, { source: { ...entry.source, episodes } });
14422
14523
  changed(path);
14423
14524
  },
14525
+ /** Fetch a sourced show's episodes in another quality (src/quality.js) from now on. */
14526
+ setQuality(path, quality) {
14527
+ const target = requireShow(path);
14528
+ const entry = record(target);
14529
+ if (!isSourced(entry)) throw libraryError("invalid", "this show has no source to fetch from");
14530
+ update(target, { source: { ...entry.source, quality } });
14531
+ },
14424
14532
  /** The saved (offline fallback) copy of a show's work, or null. */
14425
14533
  workOf: (path) => record(path).work ?? null,
14426
14534
  /** Which source and work id a show came from (`{ source, id, ... }`), or null. */
@@ -14467,7 +14575,7 @@ function createLibrary(options) {
14467
14575
  if (download(target)?.active) throw libraryError("in_use", "this show is still downloading");
14468
14576
  const isFile = (await stat9(target)).isFile();
14469
14577
  const clean = cleanName(name2);
14470
- const next = join15(dirname5(target), isFile && extname7(clean) === "" ? `${clean}${extname7(target)}` : clean);
14578
+ const next = join15(dirname6(target), isFile && extname7(clean) === "" ? `${clean}${extname7(target)}` : clean);
14471
14579
  if (next === target) return { path: target };
14472
14580
  if (await stat9(next).then(() => true, () => false)) throw libraryError("exists", "a show with that name is already in the library");
14473
14581
  await rename7(target, next);
@@ -14546,11 +14654,76 @@ function createLibrary(options) {
14546
14654
  };
14547
14655
  }
14548
14656
 
14657
+ // src/remarks.js
14658
+ import { mkdir as mkdir10, readFile as readFile11, rename as rename8, writeFile as writeFile7 } from "node:fs/promises";
14659
+ import { join as join16 } from "node:path";
14660
+ var HOUR_MS = 36e5;
14661
+ var DAY_MS2 = 24 * HOUR_MS;
14662
+ var REMARKS_DIR = ".source";
14663
+ function createRemarks({ source, logger, now = Date.now, danmakuMaxAgeMs = DAY_MS2, commentsMaxAgeMs = HOUR_MS }) {
14664
+ const flying = /* @__PURE__ */ new Map();
14665
+ async function read(file) {
14666
+ try {
14667
+ const copy = JSON.parse(await readFile11(file, "utf8"));
14668
+ return Number.isFinite(copy?.at) ? copy : null;
14669
+ } catch {
14670
+ return null;
14671
+ }
14672
+ }
14673
+ async function keep(file, value) {
14674
+ await mkdir10(join16(file, ".."), { recursive: true });
14675
+ await writeFile7(`${file}.part`, JSON.stringify(value));
14676
+ await rename8(`${file}.part`, file);
14677
+ }
14678
+ function fetchInto(file, ask) {
14679
+ if (!flying.has(file)) {
14680
+ const run3 = (async () => {
14681
+ const copy = { ...await ask(), at: now() };
14682
+ await keep(file, copy);
14683
+ return copy;
14684
+ })().finally(() => flying.delete(file));
14685
+ flying.set(file, run3);
14686
+ }
14687
+ return flying.get(file);
14688
+ }
14689
+ async function copyOf(file, maxAgeMs, ask) {
14690
+ const copy = await read(file);
14691
+ if (copy === null) return fetchInto(file, ask);
14692
+ if (now() - copy.at > maxAgeMs) fetchInto(file, ask).catch((error) => logger.warn("media hub: could not refresh %s: %s", file, error.message));
14693
+ return copy;
14694
+ }
14695
+ function offering(work, verb) {
14696
+ const found = work?.source ? source(work.source) : void 0;
14697
+ return found !== void 0 && typeof found.offers === "function" && found.offers(work.kind, verb) ? found : null;
14698
+ }
14699
+ return {
14700
+ /** Which of the verbs a show's source offers for its work: `{ danmaku, comments }`. */
14701
+ offered: (work) => ({ danmaku: offering(work, "danmaku") !== null, comments: offering(work, "comments") !== null }),
14702
+ /**
14703
+ * The danmaku of episode `number` of a show: `{ items: [{ time, text, likes }], at }`.
14704
+ * @param {string} show - the show's folder
14705
+ * @param {{ source: string, id: string, kind: string }} work - where the show came from (its notes' `source`)
14706
+ */
14707
+ async danmaku(show, work, number) {
14708
+ const found = offering(work, "danmaku");
14709
+ if (found === null) return { items: [], at: null };
14710
+ return copyOf(join16(show, REMARKS_DIR, "danmaku", `${number}.json`), danmakuMaxAgeMs, async () => ({ items: await found.danmaku(work.id, number, work.kind) }));
14711
+ },
14712
+ /** The comments on a show's work: the kept first page, or with `cursor` the page after it from the source. */
14713
+ async comments(show, work, cursor = "") {
14714
+ const found = offering(work, "comments");
14715
+ if (found === null) return { total: 0, items: [], next: null, at: null };
14716
+ if (cursor !== "") return { ...await found.comments(work.id, work.kind, { cursor }), at: now() };
14717
+ return copyOf(join16(show, REMARKS_DIR, "comments.json"), commentsMaxAgeMs, () => found.comments(work.id, work.kind));
14718
+ }
14719
+ };
14720
+ }
14721
+
14549
14722
  // src/follow.js
14550
- var DAY_MS2 = 864e5;
14723
+ var DAY_MS3 = 864e5;
14551
14724
  var OPEN_RECHECK_MS = 36e5;
14552
14725
  var JITTER = 0.1;
14553
- var nextCheckAt = (checkedAt, random) => checkedAt + Math.round(DAY_MS2 * (1 - JITTER + 2 * JITTER * random));
14726
+ var nextCheckAt = (checkedAt, random) => checkedAt + Math.round(DAY_MS3 * (1 - JITTER + 2 * JITTER * random));
14554
14727
  function dueFollows(follows, now) {
14555
14728
  return follows.filter(({ follow: follow2 }) => (follow2.nextAt ?? 0) <= now).sort((a, b) => (a.follow.nextAt ?? 0) - (b.follow.nextAt ?? 0));
14556
14729
  }
@@ -14627,19 +14800,8 @@ function createFollows({ library, source, refreshed, addSeason, record, notify,
14627
14800
 
14628
14801
  // src/points.js
14629
14802
  var EXTRAS = Object.freeze({
14630
- newSeries: Object.freeze({
14631
- key: "media:new_series",
14632
- name: "Start a new series",
14633
- cost: 30,
14634
- about: "Begin watching a series that is new to the library; going on with one stays free"
14635
- }),
14636
- bingeNight: Object.freeze({
14637
- key: "media:binge_night",
14638
- name: "Binge night",
14639
- cost: 40,
14640
- uses: 0,
14641
- about: "Start watching late at night, as often as you like, until morning"
14642
- })
14803
+ newSeries: Object.freeze({ key: "media:new_series", cost: 30, words: "points.newSeries" }),
14804
+ bingeNight: Object.freeze({ key: "media:binge_night", cost: 40, uses: 0, words: "points.bingeNight" })
14643
14805
  });
14644
14806
  var CLOCK = /^([01]?\d|2[0-3]):([0-5]\d)$/;
14645
14807
  var minutes = (text3) => {
@@ -14658,78 +14820,53 @@ function nightOf(night, date2) {
14658
14820
  const pad = (n) => String(n).padStart(2, "0");
14659
14821
  return `${evening.getFullYear()}-${pad(evening.getMonth() + 1)}-${pad(evening.getDate())}`;
14660
14822
  }
14661
- var pointsError = (need) => Object.assign(new Error(`${need.name} costs ${need.cost} points`), { code: "points", status: 402, points: need });
14662
- function createPoints(config, { logger, now = Date.now, run: run3 = run }) {
14663
- const enabled = config.command.length > 0;
14664
- const registered = /* @__PURE__ */ new Set();
14665
- async function ask(args) {
14666
- const { code, stdout, stderr } = await run3([...config.command, ...args, "--json"], { timeoutMs: 2e4, env: config.env });
14667
- const line = stdout.trim().split("\n").filter(Boolean).pop() ?? "";
14668
- if (code !== 0) throw Object.assign(new Error(`points extension failed: ${stderr.trim().split("\n").pop() ?? code}`), { code: "unavailable" });
14669
- return JSON.parse(line);
14670
- }
14671
- function itemArgs(extra2) {
14672
- const args = ["--name", extra2.name, "--cost", String(extra2.cost), "--about", extra2.about];
14673
- if (extra2.uses !== void 0) args.push("--uses", String(extra2.uses));
14674
- if (extra2 === EXTRAS.bingeNight) args.push("--until", config.night.to);
14675
- return args;
14676
- }
14677
- async function register(person) {
14678
- if (registered.has(person)) return true;
14679
- for (const extra2 of Object.values(EXTRAS)) {
14680
- const answer = await ask(["shop", person, "register", extra2.key, ...itemArgs(extra2)]);
14681
- if (answer.recorded === false) return false;
14682
- }
14683
- registered.add(person);
14684
- return true;
14823
+ var wordsOf = (locales, key) => Object.fromEntries(Object.entries(locales).filter(([, ui]) => typeof ui[key] === "string").map(([tag, ui]) => [tag, ui[key]]));
14824
+ function createExtras({ points, night, locales, now = Date.now }) {
14825
+ async function itemOf(extra2) {
14826
+ const words = await locales();
14827
+ return {
14828
+ key: extra2.key,
14829
+ cost: extra2.cost,
14830
+ name: wordsOf(words, extra2.words),
14831
+ about: wordsOf(words, `${extra2.words}About`),
14832
+ ...extra2.uses === void 0 ? {} : { uses: extra2.uses },
14833
+ ...extra2 === EXTRAS.bingeNight ? { until: night.to } : {}
14834
+ };
14685
14835
  }
14686
14836
  return {
14687
- enabled,
14837
+ /** Whether any extra can cost points now: the points plugin is installed and has a ledger. */
14838
+ get enabled() {
14839
+ return points()?.enabled === true;
14840
+ },
14688
14841
  /** Which extras an action needs now: `isNew` for a new series, `starts` when it starts watching. */
14689
14842
  wants({ isNew = false, starts = false }) {
14690
- if (!enabled) return [];
14691
- return [...isNew ? [EXTRAS.newSeries] : [], ...starts && inNight(config.night, new Date(now())) ? [EXTRAS.bingeNight] : []];
14843
+ if (!this.enabled) return [];
14844
+ return [...isNew ? [EXTRAS.newSeries] : [], ...starts && inNight(night, new Date(now())) ? [EXTRAS.bingeNight] : []];
14692
14845
  },
14693
14846
  /** A purchase's source, the same on a retry: one per series, one binge ticket per night. */
14694
14847
  sourceOf(extra2, subject) {
14695
- return extra2 === EXTRAS.bingeNight ? `media:binge:${nightOf(config.night, new Date(now()))}` : `media:series:${subject}`;
14848
+ return extra2 === EXTRAS.bingeNight ? `media:binge:${nightOf(night, new Date(now()))}` : `media:series:${subject}`;
14696
14849
  },
14697
14850
  /**
14698
- * Make sure `person` holds a ticket for every extra in `wants`, buying the ones named in `buy`. Throws a
14699
- * `points` error (402) with the first missing one: item, name, cost, balance, gap, affordable, pending.
14700
- * Returns the tickets to use once the action went through.
14851
+ * The tickets `person` holds for every extra in `wants`, asked of the points plugin. Throws its `points` error
14852
+ * (402, `points: { item, source }`) for the first one missing; the page offers it and asks again.
14701
14853
  */
14702
- async pay(person, wants, { buy = [], subject = "" } = {}) {
14703
- if (!enabled || wants.length === 0 || !person) return [];
14704
- try {
14705
- if (!await register(person)) return [];
14706
- const tickets = [];
14707
- for (const extra2 of wants) {
14708
- const source = this.sourceOf(extra2, subject);
14709
- let answer = await ask(["check", person, extra2.key]);
14710
- if (answer.recorded === false) return [];
14711
- if (!answer.valid && buy.includes(extra2.key) && answer.quote.affordable) {
14712
- await ask(["buy", person, extra2.key, "--source", source]);
14713
- answer = await ask(["check", person, extra2.key]);
14714
- }
14715
- if (!answer.valid) {
14716
- const q = answer.quote;
14717
- throw pointsError({ item: extra2.key, name: q.name, cost: q.cost, balance: q.balance, gap: q.gap, affordable: q.affordable, pending: answer.pending });
14718
- }
14719
- tickets.push({ extra: extra2, ticket: answer.ticket.id });
14720
- }
14721
- return tickets;
14722
- } catch (error) {
14723
- if (error.code === "points") throw error;
14724
- logger.warn("points: %s", error.message);
14725
- return [];
14726
- }
14854
+ async pay(person, wants, { subject = "" } = {}) {
14855
+ const service = points();
14856
+ if (service === void 0 || wants.length === 0) return [];
14857
+ const tickets = [];
14858
+ for (const extra2 of wants) {
14859
+ const ticket = await service.ticketFor(person, await itemOf(extra2), { source: this.sourceOf(extra2, subject) });
14860
+ if (ticket !== null) tickets.push({ extra: extra2, ticket });
14861
+ }
14862
+ return tickets;
14727
14863
  },
14728
14864
  /** Record each ticket's use for the action that went through: a series once, a binge ticket per room opened. */
14729
14865
  async use(person, tickets, { room, subject = "" }) {
14866
+ const service = points();
14867
+ if (service === void 0) return;
14730
14868
  for (const { extra: extra2, ticket } of tickets) {
14731
- const on = extra2 === EXTRAS.bingeNight ? `media:start:${room ?? subject}` : `media:series:${subject}`;
14732
- await ask(["use", person, ticket, "--source", on]).catch((error) => logger.warn("points: %s", error.message));
14869
+ await service.use(person, ticket, extra2 === EXTRAS.bingeNight ? `media:start:${room ?? subject}` : `media:series:${subject}`);
14733
14870
  }
14734
14871
  }
14735
14872
  };
@@ -14769,27 +14906,27 @@ function createChanges({ intervalMs = 300 } = {}) {
14769
14906
  }
14770
14907
 
14771
14908
  // src/copies.js
14772
- import { mkdir as mkdir10, readFile as readFile11, rename as rename8, writeFile as writeFile7 } from "node:fs/promises";
14773
- 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 }) {
14909
+ import { mkdir as mkdir11, readFile as readFile12, rename as rename9, writeFile as writeFile8 } from "node:fs/promises";
14910
+ import { dirname as dirname7 } from "node:path";
14911
+ var DAY_MS4 = 864e5;
14912
+ var HOUR_MS2 = 36e5;
14913
+ function createCopies({ file, changed, logger, maxAgeMs = DAY_MS4, retryMs = HOUR_MS2, parallel = 4, now = Date.now }) {
14777
14914
  const copies = /* @__PURE__ */ new Map();
14778
14915
  const flying = /* @__PURE__ */ new Map();
14779
14916
  const failedAt = /* @__PURE__ */ new Map();
14780
14917
  const waiting = [];
14781
14918
  let running = 0;
14782
14919
  let saving = Promise.resolve();
14783
- const loaded = readFile11(file, "utf8").then((text3) => {
14920
+ const loaded = readFile12(file, "utf8").then((text3) => {
14784
14921
  for (const [key, copy] of Object.entries(JSON.parse(text3))) copies.set(key, copy);
14785
14922
  }).catch((error) => {
14786
14923
  if (error.code !== "ENOENT") logger.warn("the saved copies of Discover could not be read: %s", error.message);
14787
14924
  });
14788
14925
  function save() {
14789
14926
  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);
14927
+ await mkdir11(dirname7(file), { recursive: true });
14928
+ await writeFile8(`${file}.part`, JSON.stringify(Object.fromEntries(copies)));
14929
+ await rename9(`${file}.part`, file);
14793
14930
  }).catch((error) => logger.warn("the copies of Discover could not be saved: %s", error.message));
14794
14931
  return saving;
14795
14932
  }
@@ -14804,8 +14941,8 @@ function createCopies({ file, changed, logger, maxAgeMs = DAY_MS3, retryMs = HOU
14804
14941
  }
14805
14942
  function ask(key, produce) {
14806
14943
  let settled;
14807
- flying.set(key, new Promise((resolve7) => {
14808
- settled = resolve7;
14944
+ flying.set(key, new Promise((resolve8) => {
14945
+ settled = resolve8;
14809
14946
  }));
14810
14947
  waiting.push(async () => {
14811
14948
  try {
@@ -14907,9 +15044,9 @@ function createDiscover({ copies, sources, covers, recommender }) {
14907
15044
  }
14908
15045
 
14909
15046
  // 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 }) {
15047
+ var DAY_MS5 = 864e5;
15048
+ var HOUR_MS3 = 36e5;
15049
+ function createWorkRefresh({ source, keep, maxAgeMs = DAY_MS5, retryMs = HOUR_MS3, parallel = 2, now = Date.now, logger }) {
14913
15050
  const flying = /* @__PURE__ */ new Set();
14914
15051
  const failedAt = /* @__PURE__ */ new Map();
14915
15052
  const waiting = [];
@@ -14947,18 +15084,18 @@ ${entry.source.id}`;
14947
15084
  }
14948
15085
 
14949
15086
  // src/media.js
14950
- var HOUR_MS3 = 36e5;
15087
+ var HOUR_MS4 = 36e5;
14951
15088
  var MIN_FREE_BYTES = 1e9;
14952
15089
  var NO_CONVERTER = Object.freeze({ command: "", available: async () => false });
14953
15090
  var hubError = (code, message) => Object.assign(new Error(message), { code });
14954
15091
  function createMediaHub(options) {
14955
15092
  const { stateDir, libraryRoots, logger, now = Date.now } = options;
14956
15093
  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 });
15094
+ const covers = createCovers({ dir: join17(stateDir, "covers"), capBytes: options.coverCacheBytes, ffmpeg: options.tools.ffmpeg, logger }, (id) => sources.get(id));
15095
+ const log = createWatchLog({ file: join17(stateDir, LOG_NAME), now, logger });
14959
15096
  const changes = createChanges({ intervalMs: options.changeIntervalMs });
14960
- 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 });
15097
+ const points = createExtras({ points: options.points ?? (() => void 0), night: options.bingeNight ?? { from: "01:00", to: "06:00" }, locales: () => readLocales(LOCALE_DIR, logger), now });
15098
+ 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
15099
  let rooms;
14963
15100
  let cache;
14964
15101
  const downloads = createDownloads({
@@ -14978,6 +15115,7 @@ function createMediaHub(options) {
14978
15115
  logger,
14979
15116
  now
14980
15117
  });
15118
+ const remarks = createRemarks({ source: (id) => sources.get(id), logger, now });
14981
15119
  const refreshWork = createWorkRefresh({ source: (id) => sources.get(id), keep: (path, work) => library.keepWork(path, work), maxAgeMs: options.workMaxAgeMs, logger, now });
14982
15120
  const library = createLibrary({
14983
15121
  changed: () => changes.notify("library"),
@@ -15012,7 +15150,7 @@ function createMediaHub(options) {
15012
15150
  cache.refresh(show).catch(() => {
15013
15151
  });
15014
15152
  });
15015
- const copies = createCopies({ file: join16(stateDir, "discover.json"), changed: () => changes.notify("discover"), maxAgeMs: options.discoverMaxAgeMs, logger, now });
15153
+ const copies = createCopies({ file: join17(stateDir, "discover.json"), changed: () => changes.notify("discover"), maxAgeMs: options.discoverMaxAgeMs, logger, now });
15016
15154
  const discover = createDiscover({
15017
15155
  copies,
15018
15156
  sources,
@@ -15024,7 +15162,12 @@ function createMediaHub(options) {
15024
15162
  });
15025
15163
  cache.enforce().catch(() => {
15026
15164
  });
15027
- }, HOUR_MS3);
15165
+ }, HOUR_MS4);
15166
+ function roomShow(id) {
15167
+ const room = rooms.listRooms().find((entry) => entry.id === id);
15168
+ if (room === void 0) throw hubError("not_found", "no such room");
15169
+ return room.show;
15170
+ }
15028
15171
  async function onFiles(job) {
15029
15172
  changes.notify("library");
15030
15173
  await rooms.syncShow(job.dir);
@@ -15095,7 +15238,7 @@ ${work.id}`) || foldersFor(sourceId, work).some((path) => logged.has(path)));
15095
15238
  const name2 = cleanName(work.title ?? "");
15096
15239
  const mark = createHash6("sha256").update(`${sourceId}
15097
15240
  ${work.id}`).digest("hex").slice(0, 8);
15098
- return [name2, `${name2} (${mark})`].map((candidate) => join16(libraryRoots[0], candidate));
15241
+ return [name2, `${name2} (${mark})`].map((candidate) => join17(libraryRoots[0], candidate));
15099
15242
  }
15100
15243
  async function folderFor(sourceId, item) {
15101
15244
  for (const path of foldersFor(sourceId, item)) {
@@ -15123,7 +15266,7 @@ ${work.id}`).digest("hex").slice(0, 8);
15123
15266
  */
15124
15267
  async createRoom(input) {
15125
15268
  const person = typeof input.person === "string" ? input.person : "";
15126
- const tickets = await points.pay(person, points.wants({ starts: true }), { buy: input.buy ?? [] });
15269
+ const tickets = await points.pay(person, points.wants({ starts: true }));
15127
15270
  let start = input.start ?? null;
15128
15271
  if (start === null && typeof input.path === "string") {
15129
15272
  const show2 = library.showPath(input.path);
@@ -15184,11 +15327,44 @@ ${work.id}`).digest("hex").slice(0, 8);
15184
15327
  for (const show of list.shows) if (show.source?.source) refreshWork(show.path, { source: show.source, work: show.work });
15185
15328
  return { ...list, shows: list.shows.map(withCovers) };
15186
15329
  },
15187
- /** The details of the work a room's show came from, or null. */
15330
+ /**
15331
+ * The details of the work a room's show came from (or null), the quality its episodes are fetched in, and which of
15332
+ * the work's danmaku and comments its source offers.
15333
+ */
15188
15334
  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 };
15335
+ const show = roomShow(id);
15336
+ const from2 = library.workSource(show);
15337
+ return {
15338
+ work: show === null ? null : withCovers(shownEntry(show)).work ?? null,
15339
+ source: from2?.source ?? null,
15340
+ id: from2?.id ?? null,
15341
+ quality: from2?.quality || AUTO,
15342
+ ...remarks.offered(from2)
15343
+ };
15344
+ },
15345
+ /** The danmaku of a room's item, from the copy kept with its show; the next episode's is made ready meanwhile. */
15346
+ async roomDanmaku(id, index) {
15347
+ const show = roomShow(id);
15348
+ const from2 = library.workSource(show);
15349
+ const number = rooms.slotOf(id, index);
15350
+ if (from2 === null || number === void 0) return { items: [], at: null };
15351
+ const answer = await remarks.danmaku(show, from2, number);
15352
+ 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));
15353
+ return answer;
15354
+ },
15355
+ /** The comments on a room's work: the kept first page, or the page after `cursor`. */
15356
+ roomComments(id, cursor = "") {
15357
+ const show = roomShow(id);
15358
+ const from2 = library.workSource(show);
15359
+ return from2 === null ? { total: 0, items: [], next: null, at: null } : remarks.comments(show, from2, cursor);
15360
+ },
15361
+ /** Fetch a room's show in one of the qualities its work offers, from the episodes after the one it is on. */
15362
+ async roomQuality(id, quality) {
15363
+ const show = roomShow(id);
15364
+ const offered = show === null ? [] : library.workOf(show)?.qualities ?? [];
15365
+ if (!isQuality(quality) || !offered.includes(quality)) throw hubError("invalid", "the show is not offered in this quality");
15366
+ await cache.requality(show, quality);
15367
+ return { quality };
15192
15368
  },
15193
15369
  episodes: (path) => library.episodes(path),
15194
15370
  removeShow: (path, by) => library.remove(path, { by }),
@@ -15232,7 +15408,7 @@ ${work.id}`).digest("hex").slice(0, 8);
15232
15408
  * whose account (`person`, the one asking) and the viewer's `language`, for the captions chosen with each episode.
15233
15409
  * @param {{ source: string, id: string, watch?: boolean, all?: boolean, quality?: string, by?: string, person?: string, language?: string }} input
15234
15410
  */
15235
- async fetch({ source: sourceId, id, watch = false, together = false, all = false, quality = "", by = "", person = "", language = "", buy = [] }) {
15411
+ async fetch({ source: sourceId, id, watch = false, together = false, all = false, quality = "", by = "", person = "", language = "" }) {
15236
15412
  const item = await source(sourceId).info(id, { person, language });
15237
15413
  if (!(item.episodes > 0)) throw hubError("empty", `${item.title || id} has no episodes`);
15238
15414
  const dir = await folderFor(sourceId, item);
@@ -15240,7 +15416,7 @@ ${work.id}`).digest("hex").slice(0, 8);
15240
15416
  const isNew = points.enabled && await isNewSeries(sourceId, item);
15241
15417
  const disk = await statfs2(libraryRoots[0]).catch(() => null);
15242
15418
  if (disk !== null && disk.bavail * disk.bsize < MIN_FREE_BYTES) throw hubError("no_space", "the library disk is almost full; delete something first");
15243
- const tickets = await points.pay(person, points.wants({ isNew, starts: watch }), { buy, subject });
15419
+ const tickets = await points.pay(person, points.wants({ isNew, starts: watch }), { subject });
15244
15420
  const how = { ...isQuality(quality) ? { quality } : {}, person, language };
15245
15421
  await library.adopt(dir, { source: sourceId, id: item.id, kind: item.kind, episodes: item.episodes, title: item.title, ...how }, { pinned: all });
15246
15422
  library.setWork(dir, snapshotOf(item, now()));
@@ -15248,8 +15424,8 @@ ${work.id}`).digest("hex").slice(0, 8);
15248
15424
  if (watch) room = (await rooms.createRoom({ source: "local", path: dir, title: item.title, by, person, together, start: await library.resumeFrom(dir) })).room;
15249
15425
  else await cache.refresh(dir, { retry: true });
15250
15426
  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) };
15427
+ const count2 = all ? item.episodes : Math.min(item.episodes, options.cache.ahead + 1);
15428
+ return { path: dir, title: item.title, episodes: item.episodes, estimate: count2 * (EPISODE_BYTES[item.kind] ?? EPISODE_BYTES.drama), room, download: downloads.state(dir) };
15253
15429
  },
15254
15430
  /**
15255
15431
  * 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
@@ -15293,7 +15469,7 @@ ${work.id}`).digest("hex").slice(0, 8);
15293
15469
  async cancelDownload(path) {
15294
15470
  const show = library.showPath(path);
15295
15471
  if (show !== null) await downloads.cancel(show);
15296
- return { cancelled: resolve5(path) };
15472
+ return { cancelled: resolve6(path) };
15297
15473
  },
15298
15474
  /** A download someone waits on to watch: its state and, once open, its room. */
15299
15475
  download: (path) => {
@@ -15345,7 +15521,6 @@ async function body(request) {
15345
15521
  }
15346
15522
  var pick4 = (value, keys) => Object.fromEntries(keys.filter((key) => value?.[key] !== void 0).map((key) => [key, value[key]]));
15347
15523
  var text2 = (value) => typeof value === "string" ? value : "";
15348
- var buying = (value) => Array.isArray(value) ? value.filter((key) => typeof key === "string").slice(0, 4) : [];
15349
15524
  function createPersonRoutes({ hub, identity }) {
15350
15525
  const handle = (fn) => async (request) => {
15351
15526
  const current = hub();
@@ -15370,7 +15545,7 @@ function createPersonRoutes({ hub, identity }) {
15370
15545
  requestBody: "buffered",
15371
15546
  fetch: handle(async (request, current, person) => {
15372
15547
  const input = await body(request);
15373
- return current.fetch({ ...pick4(input, ["source", "id", "watch", "together", "all", "quality", "by"]), language: text2(input.language), person: person.id, buy: buying(input.buy) });
15548
+ return current.fetch({ ...pick4(input, ["source", "id", "watch", "together", "all", "quality", "by"]), language: text2(input.language), person: person.id });
15374
15549
  })
15375
15550
  },
15376
15551
  {
@@ -15379,7 +15554,7 @@ function createPersonRoutes({ hub, identity }) {
15379
15554
  requestBody: "buffered",
15380
15555
  fetch: handle(async (request, current, person) => {
15381
15556
  const input = await body(request);
15382
- return current.createRoom({ ...pick4(input, ["path", "title", "by", "start"]), fromPanel: true, person: person.id, buy: buying(input.buy) });
15557
+ return current.createRoom({ ...pick4(input, ["path", "title", "by", "start"]), fromPanel: true, person: person.id });
15383
15558
  })
15384
15559
  },
15385
15560
  {
@@ -15513,16 +15688,16 @@ function createShelfRoutes({ books, identity }) {
15513
15688
  var name = "dsh-media-hub";
15514
15689
  var inject = ["webServer", "connection"];
15515
15690
  var ROOM_ID = /^[A-Za-z0-9_-]{6,32}$/;
15516
- var DAY_MS5 = 864e5;
15691
+ var DAY_MS6 = 864e5;
15517
15692
  function apply(ctx, config) {
15518
15693
  const logger = ctx.logger("media-hub");
15519
15694
  let current;
15520
15695
  ctx.provide?.("mediaHub", Object.freeze({ service: () => current }));
15521
15696
  ctx.effect(() => {
15522
- const stateDir = resolve6(config.stateDir);
15697
+ const stateDir = resolve7(config.stateDir);
15523
15698
  const service = createMediaHub({
15524
15699
  stateDir,
15525
- libraryRoots: [join17(stateDir, "library"), ...config.libraryRoots.map((root) => resolve6(root))],
15700
+ libraryRoots: [join18(stateDir, "library"), ...config.libraryRoots.map((root) => resolve7(root))],
15526
15701
  delivery: createDelivery({ mode: config.delivery }),
15527
15702
  tools: { ffmpeg: config.ffmpeg, ffprobe: config.ffprobe, maxHeight: config.maxHeight, threads: config.threads },
15528
15703
  webUrl: () => ctx.get("webApp")?.getAdvertisedUrl(),
@@ -15536,7 +15711,8 @@ function apply(ctx, config) {
15536
15711
  },
15537
15712
  notifyCommand: config.notifyCommand,
15538
15713
  recommender: config.recommender,
15539
- points: config.points,
15714
+ points: () => ctx.get("points"),
15715
+ bingeNight: config.bingeNight,
15540
15716
  cache: { ahead: config.cacheAhead, behind: config.cacheBehind, capBytes: config.cacheLimitGb * 1e9 },
15541
15717
  logger
15542
15718
  });
@@ -15549,7 +15725,7 @@ function apply(ctx, config) {
15549
15725
  const prune = setInterval(() => {
15550
15726
  service.pruneCache(config.cacheDays).catch(() => {
15551
15727
  });
15552
- }, DAY_MS5);
15728
+ }, DAY_MS6);
15553
15729
  const identity = () => ctx.get("requestIdentity");
15554
15730
  const fetchRoutes = [
15555
15731
  ...createShelfRoutes({ books: () => current?.books, identity }),