@soffits/dsh-media-hub 0.14.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/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.15.0
4
+
5
+ - Spending points moved to the points plugin, [@soffits/dsh-points](https://github.com/soffits/dsh-points): when an extra costs points, its dialog shows the price, your points and what's left, and buys it there. The hub's own offer bar is gone. Setup changes: install @soffits/dsh-points and move the ledger command from this plugin's `points.command` to its `command`; `points.night` is now `bingeNight`; `docs/points-protocol.md` is replaced by the points plugin's ledger protocol. The fetch and room routes no longer take `buy`.
6
+
3
7
  ## 0.14.0
4
8
 
5
9
  - Danmaku in rooms: the episode's danmaku fly over the picture in time with it, for sources that have them (Fanqie's short dramas). A *Danmaku* switch sits under the player, and its settings button sets their opacity, how much of the picture they cover and their size, kept per browser. The new full-screen button keeps them on the picture (on iPhone the player covers the page).
package/README.md CHANGED
@@ -61,7 +61,7 @@ The page follows DSH's language setting. It ships in English, French and Chinese
61
61
  | `notifyCommand` | `[]` | A command (program and fixed arguments) run with one line of JSON on stdin when a followed work gets a new season or new episodes. Empty runs nothing. |
62
62
  | `presence` | Continue card on, the rest off | Which parts of Watching show: `continue` (the Continue card), `recap` (*So far*, a recap kept with the show, only for viewers past what it covers), `ratings` (*How was it?*) and `picks` (needs `recommender`). |
63
63
  | `recommender` | none | `{ command, env }`: a command speaking [docs/recommender-protocol.md](docs/recommender-protocol.md). Empty shows no picks. |
64
- | `points` | none | `{ command, env, night: { from, to } }`: a command speaking [docs/points-protocol.md](docs/points-protocol.md). With one, people it plays with pay points for two extras: starting a series new to the hub, and starting to watch between `night.from` and `night.to` (default 01:00 to 06:00). Everything else stays free; empty changes nothing. |
64
+ | `bingeNight` | 01:00 to 06:00 | `{ from, to }` on the host's clock. With [@soffits/dsh-points](https://github.com/soffits/dsh-points) installed, the people it plays with pay points for two extras: starting a series new to the hub, and starting to watch in this window. Everything else stays free; without that plugin nothing changes. |
65
65
  | `coverCacheMb` | `50` | Most disk (MB) pictures may use (covers, posters, previews). The browser never fetches them from a site; the least recently shown are dropped past this. `0` is no limit. |
66
66
  | `ytDlp` | `yt-dlp` | The yt-dlp command; Link is hidden without it. |
67
67
  | `proxies` | `[]` | Which proxy each outbound request takes, by host: a list of `{ url, hosts, hostsFile }`. `url` is `socks5h://host:port` (names resolved by the proxy), `socks5://`, `socks4://`, `http://` or `https://`; `hosts` are patterns (`example.com` is that host and every host under it, `.example` every host ending so, `*` every host); `hostsFile` a file of more patterns, one per line, `#` for comments, read again when it changes. The first rule naming a host wins; other hosts go direct. Every yt-dlp call takes the rule of the page's host, and a thumbnail the rule of its own host or its page's, so a picture on an unlisted CDN goes the way its site does. While a hosts file can't be read, or the proxy is down, the request fails rather than go direct. Sources' commands keep their own network setup. |
package/client.js CHANGED
@@ -46,6 +46,12 @@ window.__ModuleLoader__.load({
46
46
  available: () => uiActions !== null,
47
47
  start: about => uiActions?.chat({ source: '@soffits/dsh-media-hub', sourceName: sourceName(), ...about }),
48
48
  }
49
+ /** The points plugin's offer (ctx.points from @soffits/dsh-points), when it is installed. */
50
+ let pointsService = null
51
+ const points = {
52
+ available: () => pointsService !== null,
53
+ offer: request => pointsService.offer(request),
54
+ }
49
55
  /** DSH's locale store, set in apply before anything renders, so the page renders again when the viewer switches language. */
50
56
  let localeStore
51
57
  const activeLanguage = () => localeStore.getSnapshot().active
@@ -87,6 +93,7 @@ window.__ModuleLoader__.load({
87
93
  pageModule ??= Promise.all([import(web('ui.js')), import(web('page.js'))]).then(([ui, page]) => {
88
94
  ui.init(React, { primitives, kit })
89
95
  ui.setChat(chat)
96
+ ui.setPoints(points)
90
97
  return page
91
98
  })
92
99
  return pageModule
@@ -143,6 +150,12 @@ window.__ModuleLoader__.load({
143
150
  return () => kitStore.set(null)
144
151
  }, 'media-hub: kit')
145
152
  })
153
+ ctx.inject(['points'], (scope) => {
154
+ scope.effect(() => {
155
+ pointsService = scope.points
156
+ return () => { pointsService = null }
157
+ }, 'media-hub: points')
158
+ })
146
159
  ctx.inject(['uiActions'], (scope) => {
147
160
  scope.effect(() => {
148
161
  uiActions = scope.uiActions
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 join18, 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();
@@ -10660,7 +10660,7 @@ async function commandExists(command, path = process.env.PATH ?? "") {
10660
10660
  return false;
10661
10661
  }
10662
10662
  function run(argv, { signal, timeoutMs, onStdoutLine, cwd, env, input } = {}) {
10663
- return new Promise((resolve7, reject) => {
10663
+ return new Promise((resolve8, reject) => {
10664
10664
  const [command, ...args] = argv;
10665
10665
  const child = spawn(command, args, { stdio: [input === void 0 ? "ignore" : "pipe", "pipe", "pipe"], detached: true, cwd, env: { ...process.env, ...env } });
10666
10666
  if (input !== void 0) {
@@ -10705,7 +10705,7 @@ function run(argv, { signal, timeoutMs, onStdoutLine, cwd, env, input } = {}) {
10705
10705
  if (timer) clearTimeout(timer);
10706
10706
  signal?.removeEventListener("abort", stop);
10707
10707
  if (onStdoutLine !== void 0 && pending.trim() !== "") onStdoutLine(pending);
10708
- resolve7({ code, stdout, stderr, oversized });
10708
+ resolve8({ code, stdout, stderr, oversized });
10709
10709
  });
10710
10710
  });
10711
10711
  }
@@ -10852,9 +10852,9 @@ function parseComments(document2) {
10852
10852
  return { total: countOrNull(document2.total), items, next: next !== "" && next.length <= MAX_CURSOR && items.length > 0 ? next : null };
10853
10853
  }
10854
10854
  function sha256Of(path) {
10855
- return new Promise((resolve7, reject) => {
10855
+ return new Promise((resolve8, reject) => {
10856
10856
  const hash = createHash("sha256");
10857
- 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")));
10858
10858
  });
10859
10859
  }
10860
10860
  async function verify(dir, event, label, logger) {
@@ -11407,9 +11407,9 @@ async function streamEpisode({ files, growing, dir, ffmpeg = "ffmpeg", ffprobe =
11407
11407
  child.stderr.on("data", (chunk) => {
11408
11408
  errors = (errors + chunk).slice(-4e3);
11409
11409
  });
11410
- const exited = new Promise((resolve7, reject) => {
11410
+ const exited = new Promise((resolve8, reject) => {
11411
11411
  child.on("error", reject);
11412
- 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() ?? ""}`)));
11413
11413
  });
11414
11414
  const running = settledFlag(exited);
11415
11415
  let told = false;
@@ -11547,7 +11547,7 @@ async function dropPrepared(cacheDir, path) {
11547
11547
  if (key !== null) await rm4(join6(cacheDir, key), { recursive: true, force: true });
11548
11548
  }
11549
11549
  function runFfmpeg(args, { ffmpeg, duration, onProgress, signal }) {
11550
- return new Promise((resolve7, reject) => {
11550
+ return new Promise((resolve8, reject) => {
11551
11551
  const child = spawn3("nice", ["-n", "10", ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-progress", "pipe:1", ...args], { stdio: ["ignore", "pipe", "pipe"], signal });
11552
11552
  let errors = "";
11553
11553
  child.stderr.on("data", (chunk) => {
@@ -11558,7 +11558,7 @@ function runFfmpeg(args, { ffmpeg, duration, onProgress, signal }) {
11558
11558
  if (match && duration && onProgress) onProgress(Math.min(1, Number(match[1]) / 1e6 / duration));
11559
11559
  });
11560
11560
  child.on("error", reject);
11561
- 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() ?? ""}`)));
11562
11562
  });
11563
11563
  }
11564
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];
@@ -12085,13 +12085,9 @@ var Recommender = Schema.object({
12085
12085
  env: Schema.dict(Schema.string()).default({}).description("Extra environment variables for the command.")
12086
12086
  });
12087
12087
  var Clock = Schema.string().pattern(/^([01]?\d|2[0-3]):[0-5]\d$/);
12088
- var Points = Schema.object({
12089
- 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."),
12090
- env: Schema.dict(Schema.string()).default({}).description("Extra environment variables for the command."),
12091
- night: Schema.object({
12092
- from: Clock.default("01:00").description("When late night starts, on the host's clock (HH:MM)."),
12093
- to: Clock.default("06:00").description("When it ends; a binge night ticket lasts until then.")
12094
- }).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.")
12095
12091
  });
12096
12092
  var Config = Schema.object({
12097
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."),
@@ -12114,7 +12110,7 @@ var Config = Schema.object({
12114
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."),
12115
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."),
12116
12112
  recommender: Recommender.default({ command: [], env: {} }).description("Where picks come from: a recommender extension. The hub has no taste of its own."),
12117
- 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."),
12118
12114
  ffmpeg: Schema.string().default("ffmpeg").description("ffmpeg command."),
12119
12115
  ffprobe: Schema.string().default("ffprobe").description("ffprobe command."),
12120
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."),
@@ -12125,9 +12121,9 @@ var Config = Schema.object({
12125
12121
  // src/http.js
12126
12122
  import { createReadStream as createReadStream2, existsSync as existsSync2 } from "node:fs";
12127
12123
  import { readFile as readFile5, stat as stat6 } from "node:fs/promises";
12128
- 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";
12129
12125
  import { createRequire } from "node:module";
12130
- import { fileURLToPath } from "node:url";
12126
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
12131
12127
 
12132
12128
  // src/filters.js
12133
12129
  var LANGUAGE = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{1,8})*$/;
@@ -12173,7 +12169,9 @@ function interleave(lists) {
12173
12169
 
12174
12170
  // src/locales.js
12175
12171
  import { readdir as readdir4, readFile as readFile4 } from "node:fs/promises";
12176
- 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");
12177
12175
  async function readLocales(dir, logger) {
12178
12176
  const names = (await readdir4(dir).catch(() => [])).filter((name2) => name2.endsWith(".json")).sort();
12179
12177
  const locales = {};
@@ -12224,25 +12222,24 @@ var MEDIA_TYPES = Object.freeze({
12224
12222
  ".jpg": "image/jpeg"
12225
12223
  });
12226
12224
  var WEB_TYPES = Object.freeze({ ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8" });
12227
- var here = fileURLToPath(new URL(".", import.meta.url));
12228
- var WEB_DIR = resolve2(here, "../web");
12229
- var LOCALE_DIR = resolve2(here, "../locale");
12225
+ var here = fileURLToPath2(new URL(".", import.meta.url));
12226
+ var WEB_DIR = resolve3(here, "../web");
12230
12227
  var MODULES = Object.freeze({
12231
- "sync.js": resolve2(here, "../src/sync.js"),
12232
- "formats.js": resolve2(here, "../src/formats.js"),
12233
- "i18n.js": resolve2(here, "../src/i18n.js"),
12234
- "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")
12235
12232
  });
12236
12233
  function vendoredFile(name2) {
12237
- const built = resolve2(here, "../dist", name2);
12234
+ const built = resolve3(here, "../dist", name2);
12238
12235
  if (existsSync2(built)) return built;
12239
12236
  const { pkg, file } = VENDORED[name2];
12240
- return resolve2(dirname3(createRequire(import.meta.url).resolve(`${pkg}/package.json`)), file);
12237
+ return resolve3(dirname4(createRequire(import.meta.url).resolve(`${pkg}/package.json`)), file);
12241
12238
  }
12242
12239
  function webFile(name2) {
12243
12240
  if (Object.hasOwn(VENDORED, name2)) return vendoredFile(name2);
12244
12241
  if (MODULES[name2] !== void 0) return MODULES[name2];
12245
- 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;
12246
12243
  }
12247
12244
  function admitOwner(connection, request) {
12248
12245
  const admission = connection.admit(request);
@@ -12304,7 +12301,7 @@ function sendJson(res, status, value) {
12304
12301
  res.writeHead(status, { ...SECURITY_HEADERS, "content-type": "application/json; charset=utf-8", "content-length": Buffer.byteLength(body2) }).end(body2);
12305
12302
  }
12306
12303
  function within(root, rel) {
12307
- const target = resolve2(root, rel);
12304
+ const target = resolve3(root, rel);
12308
12305
  const back = relative(root, target);
12309
12306
  if (back === "" || back === ".." || back.startsWith(`..${sep}`) || isAbsolute2(back)) return null;
12310
12307
  return target;
@@ -12354,7 +12351,7 @@ function createHandler({ connection, service, settings = () => ({ label: "", pre
12354
12351
  if (item === void 0) return sendText(res, 404, "Not found.");
12355
12352
  const rest = parts.slice(3).join("/");
12356
12353
  if (item.kind === "hls") {
12357
- const target = within(dirname3(item.file), rest);
12354
+ const target = within(dirname4(item.file), rest);
12358
12355
  return target === null ? sendText(res, 404, "Not found.") : sendFile(req, res, target);
12359
12356
  }
12360
12357
  return sendFile(req, res, item.file);
@@ -12426,7 +12423,7 @@ Content-Length: 0\r
12426
12423
  import { spawn as spawn5 } from "node:child_process";
12427
12424
  import { createHash as createHash6 } from "node:crypto";
12428
12425
  import { statfs as statfs2, stat as stat10 } from "node:fs/promises";
12429
- import { join as join17, resolve as resolve5 } from "node:path";
12426
+ import { join as join17, resolve as resolve6 } from "node:path";
12430
12427
 
12431
12428
  // src/downloads.js
12432
12429
  import { readFile as readFile6, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
@@ -12794,7 +12791,7 @@ function sha256Of2(path) {
12794
12791
  return readFile7(path).then((body2) => createHash4("sha256").update(body2).digest("hex"));
12795
12792
  }
12796
12793
  function runConverter(command, input, output) {
12797
- return new Promise((resolve7, reject) => {
12794
+ return new Promise((resolve8, reject) => {
12798
12795
  const child = spawn4(command, [input, output], { stdio: ["ignore", "ignore", "pipe"], detached: true });
12799
12796
  let stderr = "";
12800
12797
  const timer = setTimeout(() => {
@@ -12812,7 +12809,7 @@ function runConverter(command, input, output) {
12812
12809
  });
12813
12810
  child.on("close", (code) => {
12814
12811
  clearTimeout(timer);
12815
- if (code === 0) resolve7();
12812
+ if (code === 0) resolve8();
12816
12813
  else reject(booksError("convert_failed", `conversion failed: ${stderr.trim().split("\n").pop() || `exit ${code}`}`));
12817
12814
  });
12818
12815
  });
@@ -13090,8 +13087,8 @@ function createCovers({ dir, capBytes = 5e7, maxFileBytes = 2e6, concurrency = 3
13090
13087
  });
13091
13088
  }
13092
13089
  };
13093
- const queued = (job) => new Promise((resolve7, reject) => {
13094
- waiting.push(() => job().then(resolve7, reject));
13090
+ const queued = (job) => new Promise((resolve8, reject) => {
13091
+ waiting.push(() => job().then(resolve8, reject));
13095
13092
  pump();
13096
13093
  });
13097
13094
  async function trim() {
@@ -13196,7 +13193,7 @@ function createCovers({ dir, capBytes = 5e7, maxFileBytes = 2e6, concurrency = 3
13196
13193
  // src/hub.js
13197
13194
  import { randomBytes as randomBytes2 } from "node:crypto";
13198
13195
  import { mkdir as mkdir8, readFile as readFile8, rename as rename6, writeFile as writeFile5 } from "node:fs/promises";
13199
- 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";
13200
13197
 
13201
13198
  // src/sync.js
13202
13199
  var DRIFT = Object.freeze({
@@ -13710,7 +13707,7 @@ function createRoomService(options) {
13710
13707
  return { ...room, items: room.items.map((entry, n) => n === room.index ? { ...entry, status: "preparing", error: null } : entry) };
13711
13708
  }
13712
13709
  async function reopen(room) {
13713
- 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;
13714
13711
  const items = [];
13715
13712
  for (const item of room.items) {
13716
13713
  if (!await unfinished(item)) items.push(item);
@@ -13769,7 +13766,7 @@ function createRoomService(options) {
13769
13766
  }
13770
13767
  async function localItems(path, fromPanel) {
13771
13768
  if (typeof path !== "string" || !isAbsolute3(path)) throw serviceError("invalid", "path must be an absolute path");
13772
- const target = resolve3(path);
13769
+ const target = resolve4(path);
13773
13770
  if (fromPanel && !libraryRoots.some((root) => target === root || target.startsWith(`${root}/`))) {
13774
13771
  throw serviceError("outside", "the panel can only open files from the library folders");
13775
13772
  }
@@ -13785,7 +13782,7 @@ function createRoomService(options) {
13785
13782
  return episodes.map(localItem);
13786
13783
  }
13787
13784
  async function syncShow(path) {
13788
- const target = resolve3(path);
13785
+ const target = resolve4(path);
13789
13786
  const entries = await options.directory?.(target);
13790
13787
  if (!entries) return;
13791
13788
  for (const room of [...rooms.values()]) {
@@ -13824,7 +13821,7 @@ function createRoomService(options) {
13824
13821
  const start = input.start;
13825
13822
  const room = {
13826
13823
  ...created,
13827
- showPath: resolve3(input.path),
13824
+ showPath: resolve4(input.path),
13828
13825
  together: input.together === true,
13829
13826
  ...Number.isInteger(start?.index) && start.index >= 0 && start.index < items.length ? { index: start.index, position: Math.max(0, Number(start.position) || 0) } : {}
13830
13827
  };
@@ -13873,18 +13870,18 @@ function createRoomService(options) {
13873
13870
  },
13874
13871
  /** Whether an open room plays anything from `path` (a show folder or file). */
13875
13872
  usesPath(path) {
13876
- const target = resolve3(path);
13873
+ const target = resolve4(path);
13877
13874
  return [...rooms.values()].some((room) => room.showPath === target || room.items.some((item) => typeof item.sourcePath === "string" && (item.sourcePath === target || item.sourcePath.startsWith(`${target}/`))));
13878
13875
  },
13879
13876
  /** The episode numbers rooms on a show are on, one per room; empty when no room has it open. */
13880
13877
  focusesOf(path) {
13881
- const target = resolve3(path);
13878
+ const target = resolve4(path);
13882
13879
  return [...rooms.values()].filter((room) => room.showPath === target).map((room) => room.items[room.index]?.slot).filter((n) => n !== void 0);
13883
13880
  },
13884
13881
  syncShow,
13885
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. */
13886
13883
  failWaiting(path, message, reason = null) {
13887
- const target = resolve3(path);
13884
+ const target = resolve4(path);
13888
13885
  for (const room of [...rooms.values()]) {
13889
13886
  if (room.showPath !== target) continue;
13890
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);
@@ -13897,7 +13894,7 @@ function createRoomService(options) {
13897
13894
  * @param {{ fraction: number | null, done: number, total: number | null, speed: number | null, eta: number | null }} progress
13898
13895
  */
13899
13896
  downloadProgress(path, number, progress2) {
13900
- const target = resolve3(path);
13897
+ const target = resolve4(path);
13901
13898
  for (const room of [...rooms.values()]) {
13902
13899
  if (room.showPath !== target) continue;
13903
13900
  const item = room.items.find((entry) => entry.slot === number && entry.sourcePath === null && entry.status === "preparing");
@@ -13909,7 +13906,7 @@ function createRoomService(options) {
13909
13906
  * Episode `number` of a show while a source still fetches it, as files that play while they grow
13910
13907
  * (`growing` settles when they are complete): rooms waiting on it play it once enough is there.
13911
13908
  */
13912
- streamEpisode: (path, number, partial) => streams.offer(resolve3(path), number, partial),
13909
+ streamEpisode: (path, number, partial) => streams.offer(resolve4(path), number, partial),
13913
13910
  /** The episode number of a room's item in its show (undefined for a room on plain files). */
13914
13911
  slotOf: (roomId, index) => rooms.get(roomId)?.items[index]?.slot,
13915
13912
  /** The prepared file of a ready local item. */
@@ -14074,7 +14071,7 @@ function createJournal({ log, library, now = Date.now }) {
14074
14071
 
14075
14072
  // src/shows.js
14076
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";
14077
- 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";
14078
14075
 
14079
14076
  // src/presence.js
14080
14077
  var RATINGS = Object.freeze(["loved", "fine", "not-for-me", "unfinished"]);
@@ -14232,8 +14229,8 @@ function createLibrary(options) {
14232
14229
  }
14233
14230
  function showPath(path) {
14234
14231
  if (typeof path !== "string") return null;
14235
- const target = resolve4(path);
14236
- 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;
14237
14234
  }
14238
14235
  function requireShow(path) {
14239
14236
  const target = showPath(path);
@@ -14242,7 +14239,7 @@ function createLibrary(options) {
14242
14239
  }
14243
14240
  function showOf(episodePath) {
14244
14241
  if (typeof episodePath !== "string") return null;
14245
- return showPath(episodePath) ?? showPath(dirname5(episodePath));
14242
+ return showPath(episodePath) ?? showPath(dirname6(episodePath));
14246
14243
  }
14247
14244
  async function episodeFiles(path) {
14248
14245
  const info = await stat9(path).catch(() => null);
@@ -14578,7 +14575,7 @@ function createLibrary(options) {
14578
14575
  if (download(target)?.active) throw libraryError("in_use", "this show is still downloading");
14579
14576
  const isFile = (await stat9(target)).isFile();
14580
14577
  const clean = cleanName(name2);
14581
- 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);
14582
14579
  if (next === target) return { path: target };
14583
14580
  if (await stat9(next).then(() => true, () => false)) throw libraryError("exists", "a show with that name is already in the library");
14584
14581
  await rename7(target, next);
@@ -14803,19 +14800,8 @@ function createFollows({ library, source, refreshed, addSeason, record, notify,
14803
14800
 
14804
14801
  // src/points.js
14805
14802
  var EXTRAS = Object.freeze({
14806
- newSeries: Object.freeze({
14807
- key: "media:new_series",
14808
- name: "Start a new series",
14809
- cost: 30,
14810
- about: "Begin watching a series that is new to the library; going on with one stays free"
14811
- }),
14812
- bingeNight: Object.freeze({
14813
- key: "media:binge_night",
14814
- name: "Binge night",
14815
- cost: 40,
14816
- uses: 0,
14817
- about: "Start watching late at night, as often as you like, until morning"
14818
- })
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" })
14819
14805
  });
14820
14806
  var CLOCK = /^([01]?\d|2[0-3]):([0-5]\d)$/;
14821
14807
  var minutes = (text3) => {
@@ -14834,78 +14820,53 @@ function nightOf(night, date2) {
14834
14820
  const pad = (n) => String(n).padStart(2, "0");
14835
14821
  return `${evening.getFullYear()}-${pad(evening.getMonth() + 1)}-${pad(evening.getDate())}`;
14836
14822
  }
14837
- var pointsError = (need) => Object.assign(new Error(`${need.name} costs ${need.cost} points`), { code: "points", status: 402, points: need });
14838
- function createPoints(config, { logger, now = Date.now, run: run3 = run }) {
14839
- const enabled = config.command.length > 0;
14840
- const registered = /* @__PURE__ */ new Set();
14841
- async function ask(args) {
14842
- const { code, stdout, stderr } = await run3([...config.command, ...args, "--json"], { timeoutMs: 2e4, env: config.env });
14843
- const line = stdout.trim().split("\n").filter(Boolean).pop() ?? "";
14844
- if (code !== 0) throw Object.assign(new Error(`points extension failed: ${stderr.trim().split("\n").pop() ?? code}`), { code: "unavailable" });
14845
- return JSON.parse(line);
14846
- }
14847
- function itemArgs(extra2) {
14848
- const args = ["--name", extra2.name, "--cost", String(extra2.cost), "--about", extra2.about];
14849
- if (extra2.uses !== void 0) args.push("--uses", String(extra2.uses));
14850
- if (extra2 === EXTRAS.bingeNight) args.push("--until", config.night.to);
14851
- return args;
14852
- }
14853
- async function register(person) {
14854
- if (registered.has(person)) return true;
14855
- for (const extra2 of Object.values(EXTRAS)) {
14856
- const answer = await ask(["shop", person, "register", extra2.key, ...itemArgs(extra2)]);
14857
- if (answer.recorded === false) return false;
14858
- }
14859
- registered.add(person);
14860
- 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
+ };
14861
14835
  }
14862
14836
  return {
14863
- 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
+ },
14864
14841
  /** Which extras an action needs now: `isNew` for a new series, `starts` when it starts watching. */
14865
14842
  wants({ isNew = false, starts = false }) {
14866
- if (!enabled) return [];
14867
- 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] : []];
14868
14845
  },
14869
14846
  /** A purchase's source, the same on a retry: one per series, one binge ticket per night. */
14870
14847
  sourceOf(extra2, subject) {
14871
- 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}`;
14872
14849
  },
14873
14850
  /**
14874
- * Make sure `person` holds a ticket for every extra in `wants`, buying the ones named in `buy`. Throws a
14875
- * `points` error (402) with the first missing one: item, name, cost, balance, gap, affordable, pending.
14876
- * 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.
14877
14853
  */
14878
- async pay(person, wants, { buy = [], subject = "" } = {}) {
14879
- if (!enabled || wants.length === 0 || !person) return [];
14880
- try {
14881
- if (!await register(person)) return [];
14882
- const tickets = [];
14883
- for (const extra2 of wants) {
14884
- const source = this.sourceOf(extra2, subject);
14885
- let answer = await ask(["check", person, extra2.key]);
14886
- if (answer.recorded === false) return [];
14887
- if (!answer.valid && buy.includes(extra2.key) && answer.quote.affordable) {
14888
- await ask(["buy", person, extra2.key, "--source", source]);
14889
- answer = await ask(["check", person, extra2.key]);
14890
- }
14891
- if (!answer.valid) {
14892
- const q = answer.quote;
14893
- throw pointsError({ item: extra2.key, name: q.name, cost: q.cost, balance: q.balance, gap: q.gap, affordable: q.affordable, pending: answer.pending });
14894
- }
14895
- tickets.push({ extra: extra2, ticket: answer.ticket.id });
14896
- }
14897
- return tickets;
14898
- } catch (error) {
14899
- if (error.code === "points") throw error;
14900
- logger.warn("points: %s", error.message);
14901
- return [];
14902
- }
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;
14903
14863
  },
14904
14864
  /** Record each ticket's use for the action that went through: a series once, a binge ticket per room opened. */
14905
14865
  async use(person, tickets, { room, subject = "" }) {
14866
+ const service = points();
14867
+ if (service === void 0) return;
14906
14868
  for (const { extra: extra2, ticket } of tickets) {
14907
- const on = extra2 === EXTRAS.bingeNight ? `media:start:${room ?? subject}` : `media:series:${subject}`;
14908
- 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}`);
14909
14870
  }
14910
14871
  }
14911
14872
  };
@@ -14946,7 +14907,7 @@ function createChanges({ intervalMs = 300 } = {}) {
14946
14907
 
14947
14908
  // src/copies.js
14948
14909
  import { mkdir as mkdir11, readFile as readFile12, rename as rename9, writeFile as writeFile8 } from "node:fs/promises";
14949
- import { dirname as dirname6 } from "node:path";
14910
+ import { dirname as dirname7 } from "node:path";
14950
14911
  var DAY_MS4 = 864e5;
14951
14912
  var HOUR_MS2 = 36e5;
14952
14913
  function createCopies({ file, changed, logger, maxAgeMs = DAY_MS4, retryMs = HOUR_MS2, parallel = 4, now = Date.now }) {
@@ -14963,7 +14924,7 @@ function createCopies({ file, changed, logger, maxAgeMs = DAY_MS4, retryMs = HOU
14963
14924
  });
14964
14925
  function save() {
14965
14926
  saving = saving.then(async () => {
14966
- await mkdir11(dirname6(file), { recursive: true });
14927
+ await mkdir11(dirname7(file), { recursive: true });
14967
14928
  await writeFile8(`${file}.part`, JSON.stringify(Object.fromEntries(copies)));
14968
14929
  await rename9(`${file}.part`, file);
14969
14930
  }).catch((error) => logger.warn("the copies of Discover could not be saved: %s", error.message));
@@ -14980,8 +14941,8 @@ function createCopies({ file, changed, logger, maxAgeMs = DAY_MS4, retryMs = HOU
14980
14941
  }
14981
14942
  function ask(key, produce) {
14982
14943
  let settled;
14983
- flying.set(key, new Promise((resolve7) => {
14984
- settled = resolve7;
14944
+ flying.set(key, new Promise((resolve8) => {
14945
+ settled = resolve8;
14985
14946
  }));
14986
14947
  waiting.push(async () => {
14987
14948
  try {
@@ -15133,7 +15094,7 @@ function createMediaHub(options) {
15133
15094
  const covers = createCovers({ dir: join17(stateDir, "covers"), capBytes: options.coverCacheBytes, ffmpeg: options.tools.ffmpeg, logger }, (id) => sources.get(id));
15134
15095
  const log = createWatchLog({ file: join17(stateDir, LOG_NAME), now, logger });
15135
15096
  const changes = createChanges({ intervalMs: options.changeIntervalMs });
15136
- const points = createPoints(options.points ?? { command: [], night: { from: "01:00", to: "06:00" } }, { 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 });
15137
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 });
15138
15099
  let rooms;
15139
15100
  let cache;
@@ -15305,7 +15266,7 @@ ${work.id}`).digest("hex").slice(0, 8);
15305
15266
  */
15306
15267
  async createRoom(input) {
15307
15268
  const person = typeof input.person === "string" ? input.person : "";
15308
- const tickets = await points.pay(person, points.wants({ starts: true }), { buy: input.buy ?? [] });
15269
+ const tickets = await points.pay(person, points.wants({ starts: true }));
15309
15270
  let start = input.start ?? null;
15310
15271
  if (start === null && typeof input.path === "string") {
15311
15272
  const show2 = library.showPath(input.path);
@@ -15447,7 +15408,7 @@ ${work.id}`).digest("hex").slice(0, 8);
15447
15408
  * whose account (`person`, the one asking) and the viewer's `language`, for the captions chosen with each episode.
15448
15409
  * @param {{ source: string, id: string, watch?: boolean, all?: boolean, quality?: string, by?: string, person?: string, language?: string }} input
15449
15410
  */
15450
- 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 = "" }) {
15451
15412
  const item = await source(sourceId).info(id, { person, language });
15452
15413
  if (!(item.episodes > 0)) throw hubError("empty", `${item.title || id} has no episodes`);
15453
15414
  const dir = await folderFor(sourceId, item);
@@ -15455,7 +15416,7 @@ ${work.id}`).digest("hex").slice(0, 8);
15455
15416
  const isNew = points.enabled && await isNewSeries(sourceId, item);
15456
15417
  const disk = await statfs2(libraryRoots[0]).catch(() => null);
15457
15418
  if (disk !== null && disk.bavail * disk.bsize < MIN_FREE_BYTES) throw hubError("no_space", "the library disk is almost full; delete something first");
15458
- 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 });
15459
15420
  const how = { ...isQuality(quality) ? { quality } : {}, person, language };
15460
15421
  await library.adopt(dir, { source: sourceId, id: item.id, kind: item.kind, episodes: item.episodes, title: item.title, ...how }, { pinned: all });
15461
15422
  library.setWork(dir, snapshotOf(item, now()));
@@ -15508,7 +15469,7 @@ ${work.id}`).digest("hex").slice(0, 8);
15508
15469
  async cancelDownload(path) {
15509
15470
  const show = library.showPath(path);
15510
15471
  if (show !== null) await downloads.cancel(show);
15511
- return { cancelled: resolve5(path) };
15472
+ return { cancelled: resolve6(path) };
15512
15473
  },
15513
15474
  /** A download someone waits on to watch: its state and, once open, its room. */
15514
15475
  download: (path) => {
@@ -15560,7 +15521,6 @@ async function body(request) {
15560
15521
  }
15561
15522
  var pick4 = (value, keys) => Object.fromEntries(keys.filter((key) => value?.[key] !== void 0).map((key) => [key, value[key]]));
15562
15523
  var text2 = (value) => typeof value === "string" ? value : "";
15563
- var buying = (value) => Array.isArray(value) ? value.filter((key) => typeof key === "string").slice(0, 4) : [];
15564
15524
  function createPersonRoutes({ hub, identity }) {
15565
15525
  const handle = (fn) => async (request) => {
15566
15526
  const current = hub();
@@ -15585,7 +15545,7 @@ function createPersonRoutes({ hub, identity }) {
15585
15545
  requestBody: "buffered",
15586
15546
  fetch: handle(async (request, current, person) => {
15587
15547
  const input = await body(request);
15588
- 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 });
15589
15549
  })
15590
15550
  },
15591
15551
  {
@@ -15594,7 +15554,7 @@ function createPersonRoutes({ hub, identity }) {
15594
15554
  requestBody: "buffered",
15595
15555
  fetch: handle(async (request, current, person) => {
15596
15556
  const input = await body(request);
15597
- 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 });
15598
15558
  })
15599
15559
  },
15600
15560
  {
@@ -15734,10 +15694,10 @@ function apply(ctx, config) {
15734
15694
  let current;
15735
15695
  ctx.provide?.("mediaHub", Object.freeze({ service: () => current }));
15736
15696
  ctx.effect(() => {
15737
- const stateDir = resolve6(config.stateDir);
15697
+ const stateDir = resolve7(config.stateDir);
15738
15698
  const service = createMediaHub({
15739
15699
  stateDir,
15740
- libraryRoots: [join18(stateDir, "library"), ...config.libraryRoots.map((root) => resolve6(root))],
15700
+ libraryRoots: [join18(stateDir, "library"), ...config.libraryRoots.map((root) => resolve7(root))],
15741
15701
  delivery: createDelivery({ mode: config.delivery }),
15742
15702
  tools: { ffmpeg: config.ffmpeg, ffprobe: config.ffprobe, maxHeight: config.maxHeight, threads: config.threads },
15743
15703
  webUrl: () => ctx.get("webApp")?.getAdvertisedUrl(),
@@ -15751,7 +15711,8 @@ function apply(ctx, config) {
15751
15711
  },
15752
15712
  notifyCommand: config.notifyCommand,
15753
15713
  recommender: config.recommender,
15754
- points: config.points,
15714
+ points: () => ctx.get("points"),
15715
+ bingeNight: config.bingeNight,
15755
15716
  cache: { ahead: config.cacheAhead, behind: config.cacheBehind, capBytes: config.cacheLimitGb * 1e9 },
15756
15717
  logger
15757
15718
  });
package/locale/en.json CHANGED
@@ -307,13 +307,9 @@
307
307
  "continue.play": "Play",
308
308
  "library.continueAt": "continue at {time}",
309
309
  "library.viewerStoppedAt": "{name} stopped at {time}",
310
- "points.newSeries": "Starting a new series",
311
- "points.bingeNight": "A binge night",
312
- "points.offer": "{name} costs {cost} points. You have {balance}.",
313
- "points.short": "{name} costs {cost} points: {gap} more to go.",
314
- "points.pending": "{name} is waiting for approval.",
315
- "points.buy": "Buy",
316
- "points.notNow": "Not now",
317
- "points.ok": "OK"
310
+ "points.newSeries": "Start a new series",
311
+ "points.newSeriesAbout": "Begin watching a series that is new to the library. Going on with one stays free.",
312
+ "points.bingeNight": "Binge night",
313
+ "points.bingeNightAbout": "Start watching late at night, as often as you like, until morning."
318
314
  }
319
315
  }
package/locale/fr.json CHANGED
@@ -308,12 +308,8 @@
308
308
  "library.continueAt": "reprendre à {time}",
309
309
  "library.viewerStoppedAt": "{name} s’est arrêté·e à {time}",
310
310
  "points.newSeries": "Commencer une nouvelle série",
311
- "points.bingeNight": "Une nuit de marathon",
312
- "points.offer": "{name} coûte {cost} points. Vous en avez {balance}.",
313
- "points.short": "{name} coûte {cost} points : encore {gap} à gagner.",
314
- "points.pending": "{name} attend un accord.",
315
- "points.buy": "Acheter",
316
- "points.notNow": "Pas maintenant",
317
- "points.ok": "OK"
311
+ "points.newSeriesAbout": "Commencer une série qui n’est pas encore dans la bibliothèque. Continuer une série reste gratuit.",
312
+ "points.bingeNight": "Nuit de marathon",
313
+ "points.bingeNightAbout": "Lancer des épisodes tard dans la nuit, autant que vous voulez, jusqu’au matin."
318
314
  }
319
315
  }
package/locale/zh.json CHANGED
@@ -308,12 +308,8 @@
308
308
  "library.continueAt": "从 {time} 继续",
309
309
  "library.viewerStoppedAt": "{name}看到 {time}",
310
310
  "points.newSeries": "开一部新剧",
311
+ "points.newSeriesAbout": "开始看一部库里还没有的剧。接着看已有的剧不花分。",
311
312
  "points.bingeNight": "通宵追剧夜",
312
- "points.offer": "{name}要 {cost} 分,你现在有 {balance} 分。",
313
- "points.short": "{name}要 {cost} 分,还差 {gap} 分。",
314
- "points.pending": "{name}还在等批准。",
315
- "points.buy": "兑换",
316
- "points.notNow": "先不了",
317
- "points.ok": "好"
313
+ "points.bingeNightAbout": "深夜开播,想看几次都行,到早上为止。"
318
314
  }
319
315
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-media-hub",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "A media hub for DeepSeek Harness: search shows, novels, ebooks and papers across sources, watch together in sync, and download books in the format you want onto your own shelf.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -57,6 +57,7 @@
57
57
  "@deepseek-ai/dsh-client-locale",
58
58
  "@soffits/dsh-ui-actions",
59
59
  "@soffits/dsh-ui-kit",
60
+ "@soffits/dsh-points",
60
61
  "@deepseek-ai/dsh-client-ui-layout",
61
62
  "@deepseek-ai/dsh-client-ui-sidebar"
62
63
  ]
package/web/page.js CHANGED
@@ -8,7 +8,7 @@ import { LibrarySection } from './library-view.js'
8
8
  import { clearNav, readNav, TABS, writeNav } from './nav.js'
9
9
  import { RoomView } from './room-view.js'
10
10
  import { WatchingTab, withNews } from './watching-view.js'
11
- import { Changes, K, Known, P, api, fill, h, React, setOffer, setWords } from './ui.js'
11
+ import { Changes, K, Known, P, api, h, React, setWords } from './ui.js'
12
12
 
13
13
  /** Marks the history entries this page added, so a back control knows going back stays on the page. */
14
14
  const PUSHED = 'vsyncPushed'
@@ -73,33 +73,6 @@ function Home({ t, nav, go, onOpen, rooms, library, load }) {
73
73
  h(DiscoverView, { t, nav, onNav: go, onOpen, onSaved: load, onBack: () => (history.state?.[PUSHED] ? history.back() : go({ work: null }, { replace: true })) }))))
74
74
  }
75
75
 
76
- /** The page's words for the extras the hub sells (src/points.js EXTRAS), by item key; another item keeps its shop name. */
77
- const EXTRA_WORDS = Object.freeze({ 'media:new_series': 'points.newSeries', 'media:binge_night': 'points.bingeNight' })
78
-
79
- /**
80
- * The offer of an extra at the moment of the action: its price and the person's balance, and Buy when they can.
81
- * One at a time; `asPersonPaying` (ui.js) waits for the answer.
82
- */
83
- function PointsOffer({ t }) {
84
- const [ask, setAsk] = React.useState(null)
85
- React.useEffect(() => {
86
- setOffer(points => new Promise(resolve => setAsk({ points, resolve })))
87
- return () => setOffer(null)
88
- }, [])
89
- if (ask === null) return null
90
- const { points, resolve } = ask
91
- const done = (yes) => { setAsk(null); resolve(yes) }
92
- const name = EXTRA_WORDS[points.item] ? t(EXTRA_WORDS[points.item]) : points.name
93
- const key = points.pending ? 'points.pending' : points.affordable ? 'points.offer' : 'points.short'
94
- return h('div', { className: 'vsync-pointsOffer', role: 'alertdialog', 'aria-live': 'polite' },
95
- h('span', { className: 'vsync-pointsText' }, fill(t(key), { name, cost: points.cost, balance: points.balance, gap: points.gap })),
96
- h('span', { className: 'vsync-actions' },
97
- points.affordable && !points.pending
98
- ? [h('button', { key: 'no', type: 'button', className: 'vsync-btn', onClick: () => done(false) }, t('points.notNow')),
99
- h('button', { key: 'yes', type: 'button', className: 'vsync-btn vsync-primary', autoFocus: true, onClick: () => done(true) }, t('points.buy'))]
100
- : h('button', { type: 'button', className: 'vsync-btn', autoFocus: true, onClick: () => done(false) }, t('points.ok'))))
101
- }
102
-
103
76
  export function Page({ t, initialRoom }) {
104
77
  setWords(t)
105
78
  const [roomId, setRoomId] = React.useState(initialRoom)
@@ -132,6 +105,5 @@ export function Page({ t, initialRoom }) {
132
105
  return h(Changes.Provider, { value: changes }, h(Known.Provider, { value: known }, h(React.Fragment, null,
133
106
  roomId === null
134
107
  ? h(Home, { t, nav, go, onOpen: setRoomId, rooms, library, load })
135
- : h(RoomView, { key: roomId, t, roomId, onLeave: () => setRoomId(null), onOpen: setRoomId }),
136
- h(PointsOffer, { t }))))
108
+ : h(RoomView, { key: roomId, t, roomId, onLeave: () => setRoomId(null), onOpen: setRoomId }))))
137
109
  }
package/web/panel.css CHANGED
@@ -363,10 +363,6 @@
363
363
  .vsync-pageTabs,.vsync-ccActions,.vsync-rateAnswers,.vsync-ccLive,.vsync-sectionMeta,.vsync-sectionHead h2,.vsync-actions,.vsync-tabCount,.vsync-ccStrip,.vsync-rateHead .uk-tile{user-select:none;-webkit-user-select:none}
364
364
  .vsync-page img{-webkit-user-drag:none;user-select:none;-webkit-user-select:none}
365
365
  .vsync-ccActions .uk-touch .uk-touch,.vsync-rateAnswers .uk-touch{font-size:13px}
366
- /* Points offer: an extra's price at the moment of the action */
367
- .vsync-pointsOffer{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);z-index:40;display:flex;align-items:center;gap:12px;max-width:min(560px,calc(100% - 32px));padding:10px 12px 10px 16px;border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-lg);background:var(--dsw-alias-bg-layer-1,var(--dsw-alias-bg-base));box-shadow:var(--dsw-shadow-lv3)}
368
- .vsync-pointsText{flex:1;min-width:0;font-size:13px;line-height:19px;color:var(--dsw-alias-label-primary)}
369
- @media (width<=767px){.vsync-pointsOffer{flex-wrap:wrap;bottom:12px}.vsync-pointsOffer>.vsync-actions{margin-left:auto}}
370
366
  /* Player bar, danmaku, full screen */
371
367
  .vsync-playerBar{flex:none;display:flex;align-items:center;gap:8px;padding:6px 12px;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);border-bottom:.5px solid var(--dsw-alias-border-l4)}
372
368
  .vsync-grow{flex:1}
package/web/ui.js CHANGED
@@ -70,21 +70,21 @@ export const post = (path, body) => api(path, { method: 'POST', body: JSON.strin
70
70
  const personUrl = path => new URL(`api/media-hub/${path}`, document.baseURI)
71
71
  export const asPerson = (path, body, init = {}) => request(personUrl(path), body === undefined ? init : { ...init, method: 'POST', body: JSON.stringify(body) })
72
72
 
73
- /** Where the page offers an extra the person's points pay for (page.js `PointsOffer`): resolves true to buy it. */
74
- let offer = null
75
- export function setOffer(value) { offer = value }
73
+ /** The points plugin's offer (ctx.points from @soffits/dsh-points, set by client.js; `available` is false without it). */
74
+ let points = null
75
+ export function setPoints(value) { points = value }
76
76
 
77
77
  /**
78
78
  * An action that may need a ticket (a new series, a binge night; src/points.js): when the hub answers `points`, the
79
- * page offers the purchase where the person is, and on yes asks again buying it. A no answers `{ declined: true }`.
79
+ * points plugin offers it where the person is, and after a yes the action is asked again. A no answers `{ declined: true }`.
80
80
  */
81
81
  export async function asPersonPaying(path, body) {
82
- const buy = []
82
+ const offered = new Set()
83
83
  for (;;) {
84
- const answer = await asPerson(path, buy.length === 0 ? body : { ...body, buy })
85
- if (answer.code !== 'points' || !answer.points || offer === null || buy.includes(answer.points.item)) return answer
86
- if (!(await offer(answer.points))) return { declined: true }
87
- buy.push(answer.points.item)
84
+ const answer = await asPerson(path, body)
85
+ if (answer.code !== 'points' || !answer.points || points?.available() !== true || offered.has(answer.points.item)) return answer
86
+ offered.add(answer.points.item)
87
+ if (!(await points.offer(answer.points).catch(() => false))) return { declined: true }
88
88
  }
89
89
  }
90
90