@soffits/dsh-media-hub 0.8.0 → 0.9.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.9.0
4
+
5
+ - Points extras (`points` setting, [docs/points-protocol.md](docs/points-protocol.md)): with a points extension, the people it plays with pay points for starting a series that is new to the hub and for a binge night (starting to watch late at night, one ticket for the whole night). The page shows the price and their balance at that moment and buys on *Buy*; going on with a series, later seasons, films, single videos and rooms already playing stay free. Without an extension, or for anyone it doesn't play with, nothing changes.
6
+
3
7
  ## 0.8.0
4
8
 
5
9
  - The page no longer polls. The plugin tells open pages when something they show changes (a watch-state write, a refreshed copy of a show's details, a download landing or progressing, a room opening, closing or changing, a book on the shelf), over a Server-Sent Events stream, and the page re-reads then, and once whenever the stream connects or reconnects. Before, the library and rooms were re-read every 4 seconds and the shelf every 2 seconds while a book was fetching.
package/README.md CHANGED
@@ -60,6 +60,7 @@ The page follows DSH's language setting. It ships in English, French and Chinese
60
60
  | `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. |
61
61
  | `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`). |
62
62
  | `recommender` | none | `{ command, env }`: a command speaking [docs/recommender-protocol.md](docs/recommender-protocol.md). Empty shows no picks. |
63
+ | `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. |
63
64
  | `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. |
64
65
  | `ytDlp` | `yt-dlp` | The yt-dlp command; Link is hidden without it. |
65
66
  | `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/dist/index.js CHANGED
@@ -11989,6 +11989,15 @@ var Recommender = Schema.object({
11989
11989
  command: Schema.array(Schema.string()).default([]).description("A command speaking docs/recommender-protocol.md (program and fixed arguments, the plugin adds the verbs). Empty means no picks."),
11990
11990
  env: Schema.dict(Schema.string()).default({}).description("Extra environment variables for the command.")
11991
11991
  });
11992
+ var Clock = Schema.string().pattern(/^([01]?\d|2[0-3]):[0-5]\d$/);
11993
+ var Points = Schema.object({
11994
+ 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."),
11995
+ env: Schema.dict(Schema.string()).default({}).description("Extra environment variables for the command."),
11996
+ night: Schema.object({
11997
+ from: Clock.default("01:00").description("When late night starts, on the host's clock (HH:MM)."),
11998
+ to: Clock.default("06:00").description("When it ends; a binge night ticket lasts until then.")
11999
+ }).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.")
12000
+ });
11992
12001
  var Config = Schema.object({
11993
12002
  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."),
11994
12003
  libraryRoots: Schema.array(Schema.string()).default([]).description(`Folders whose videos and episode folders anyone signed in may start a room from in the panel. The "library" folder inside the state folder is always included. The assistant's tool can open any path.`),
@@ -12010,6 +12019,7 @@ var Config = Schema.object({
12010
12019
  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."),
12011
12020
  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."),
12012
12021
  recommender: Recommender.default({ command: [], env: {} }).description("Where picks come from: a recommender extension. The hub has no taste of its own."),
12022
+ 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."),
12013
12023
  ffmpeg: Schema.string().default("ffmpeg").description("ffmpeg command."),
12014
12024
  ffprobe: Schema.string().default("ffprobe").description("ffprobe command."),
12015
12025
  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."),
@@ -12213,8 +12223,8 @@ async function readJson(req) {
12213
12223
  throw Object.assign(new Error("request body is not JSON"), { status: 400 });
12214
12224
  }
12215
12225
  }
12216
- var STATUS = Object.freeze({ invalid: 400, empty: 400, not_found: 404, unsupported: 501, outside: 403, in_use: 409, exists: 409, no_space: 507, source_failed: 424, unavailable: 503 });
12217
- var errorBody = (error) => ({ error: { code: error?.code ?? "error", ...error?.reason ? { reason: error.reason } : {}, message: error?.message ?? String(error) } });
12226
+ var STATUS = Object.freeze({ points: 402, invalid: 400, empty: 400, not_found: 404, unsupported: 501, outside: 403, in_use: 409, exists: 409, no_space: 507, source_failed: 424, unavailable: 503 });
12227
+ var errorBody = (error) => ({ error: { code: error?.code ?? "error", ...error?.reason ? { reason: error.reason } : {}, ...error?.points ? { points: error.points } : {}, message: error?.message ?? String(error) } });
12218
12228
  function createHandler({ connection, service, settings = () => ({ label: "", presence: {} }), localeDir = LOCALE_DIR, logger }) {
12219
12229
  let locales;
12220
12230
  return async (req, res) => {
@@ -14610,6 +14620,116 @@ function createFollows({ library, source, refreshed, addSeason, record, notify,
14610
14620
  };
14611
14621
  }
14612
14622
 
14623
+ // src/points.js
14624
+ var EXTRAS = Object.freeze({
14625
+ newSeries: Object.freeze({
14626
+ key: "media:new_series",
14627
+ name: "Start a new series",
14628
+ cost: 30,
14629
+ about: "Begin watching a series that is new to the library; going on with one stays free"
14630
+ }),
14631
+ bingeNight: Object.freeze({
14632
+ key: "media:binge_night",
14633
+ name: "Binge night",
14634
+ cost: 40,
14635
+ uses: 0,
14636
+ about: "Start watching late at night, as often as you like, until morning"
14637
+ })
14638
+ });
14639
+ var CLOCK = /^([01]?\d|2[0-3]):([0-5]\d)$/;
14640
+ var minutes = (text3) => {
14641
+ const [, h, m] = CLOCK.exec(text3);
14642
+ return Number(h) * 60 + Number(m);
14643
+ };
14644
+ function inNight(night, date2) {
14645
+ const now = date2.getHours() * 60 + date2.getMinutes();
14646
+ const from2 = minutes(night.from);
14647
+ const to = minutes(night.to);
14648
+ return from2 <= to ? now >= from2 && now < to : now >= from2 || now < to;
14649
+ }
14650
+ function nightOf(night, date2) {
14651
+ const evening = new Date(date2);
14652
+ if (minutes(night.from) > minutes(night.to) && date2.getHours() * 60 + date2.getMinutes() < minutes(night.to)) evening.setDate(evening.getDate() - 1);
14653
+ const pad = (n) => String(n).padStart(2, "0");
14654
+ return `${evening.getFullYear()}-${pad(evening.getMonth() + 1)}-${pad(evening.getDate())}`;
14655
+ }
14656
+ var pointsError = (need) => Object.assign(new Error(`${need.name} costs ${need.cost} points`), { code: "points", status: 402, points: need });
14657
+ function createPoints(config, { logger, now = Date.now, run: run3 = run }) {
14658
+ const enabled = config.command.length > 0;
14659
+ const registered = /* @__PURE__ */ new Set();
14660
+ async function ask(args) {
14661
+ const { code, stdout, stderr } = await run3([...config.command, ...args, "--json"], { timeoutMs: 2e4, env: config.env });
14662
+ const line = stdout.trim().split("\n").filter(Boolean).pop() ?? "";
14663
+ if (code !== 0) throw Object.assign(new Error(`points extension failed: ${stderr.trim().split("\n").pop() ?? code}`), { code: "unavailable" });
14664
+ return JSON.parse(line);
14665
+ }
14666
+ function itemArgs(extra2) {
14667
+ const args = ["--name", extra2.name, "--cost", String(extra2.cost), "--about", extra2.about];
14668
+ if (extra2.uses !== void 0) args.push("--uses", String(extra2.uses));
14669
+ if (extra2 === EXTRAS.bingeNight) args.push("--until", config.night.to);
14670
+ return args;
14671
+ }
14672
+ async function register(person) {
14673
+ if (registered.has(person)) return true;
14674
+ for (const extra2 of Object.values(EXTRAS)) {
14675
+ const answer = await ask(["shop", person, "register", extra2.key, ...itemArgs(extra2)]);
14676
+ if (answer.recorded === false) return false;
14677
+ }
14678
+ registered.add(person);
14679
+ return true;
14680
+ }
14681
+ return {
14682
+ enabled,
14683
+ /** Which extras an action needs now: `isNew` for a new series, `starts` when it starts watching. */
14684
+ wants({ isNew = false, starts = false }) {
14685
+ if (!enabled) return [];
14686
+ return [...isNew ? [EXTRAS.newSeries] : [], ...starts && inNight(config.night, new Date(now())) ? [EXTRAS.bingeNight] : []];
14687
+ },
14688
+ /** A purchase's source, the same on a retry: one per series, one binge ticket per night. */
14689
+ sourceOf(extra2, subject) {
14690
+ return extra2 === EXTRAS.bingeNight ? `media:binge:${nightOf(config.night, new Date(now()))}` : `media:series:${subject}`;
14691
+ },
14692
+ /**
14693
+ * Make sure `person` holds a ticket for every extra in `wants`, buying the ones named in `buy`. Throws a
14694
+ * `points` error (402) with the first missing one: item, name, cost, balance, gap, affordable, pending.
14695
+ * Returns the tickets to use once the action went through.
14696
+ */
14697
+ async pay(person, wants, { buy = [], subject = "" } = {}) {
14698
+ if (!enabled || wants.length === 0 || !person) return [];
14699
+ try {
14700
+ if (!await register(person)) return [];
14701
+ const tickets = [];
14702
+ for (const extra2 of wants) {
14703
+ const source = this.sourceOf(extra2, subject);
14704
+ let answer = await ask(["check", person, extra2.key]);
14705
+ if (answer.recorded === false) return [];
14706
+ if (!answer.valid && buy.includes(extra2.key) && answer.quote.affordable) {
14707
+ await ask(["buy", person, extra2.key, "--source", source]);
14708
+ answer = await ask(["check", person, extra2.key]);
14709
+ }
14710
+ if (!answer.valid) {
14711
+ const q = answer.quote;
14712
+ throw pointsError({ item: extra2.key, name: q.name, cost: q.cost, balance: q.balance, gap: q.gap, affordable: q.affordable, pending: answer.pending });
14713
+ }
14714
+ tickets.push({ extra: extra2, ticket: answer.ticket.id });
14715
+ }
14716
+ return tickets;
14717
+ } catch (error) {
14718
+ if (error.code === "points") throw error;
14719
+ logger.warn("points: %s", error.message);
14720
+ return [];
14721
+ }
14722
+ },
14723
+ /** Record each ticket's use for the action that went through: a series once, a binge ticket per room opened. */
14724
+ async use(person, tickets, { room, subject = "" }) {
14725
+ for (const { extra: extra2, ticket } of tickets) {
14726
+ const on = extra2 === EXTRAS.bingeNight ? `media:start:${room ?? subject}` : `media:series:${subject}`;
14727
+ await ask(["use", person, ticket, "--source", on]).catch((error) => logger.warn("points: %s", error.message));
14728
+ }
14729
+ }
14730
+ };
14731
+ }
14732
+
14613
14733
  // src/changes.js
14614
14734
  function createChanges({ intervalMs = 300 } = {}) {
14615
14735
  const listeners = /* @__PURE__ */ new Set();
@@ -14694,6 +14814,7 @@ function createMediaHub(options) {
14694
14814
  const covers = createCovers({ dir: join16(stateDir, "covers"), capBytes: options.coverCacheBytes, ffmpeg: options.tools.ffmpeg, logger }, (id) => sources.get(id));
14695
14815
  const log = createWatchLog({ file: join16(stateDir, LOG_NAME), now, logger });
14696
14816
  const changes = createChanges({ intervalMs: options.changeIntervalMs });
14817
+ const points = createPoints(options.points ?? { command: [], night: { from: "01:00", to: "06:00" } }, { logger, now });
14697
14818
  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 });
14698
14819
  let rooms;
14699
14820
  let cache;
@@ -14820,18 +14941,29 @@ function createMediaHub(options) {
14820
14941
  if (found === void 0) throw hubError("not_found", `no source ${String(id)}`);
14821
14942
  return found;
14822
14943
  }
14823
- async function folderFor(sourceId, item) {
14824
- const name2 = cleanName(item.title);
14944
+ async function isNewSeries(sourceId, item) {
14945
+ if (!(item.episodes > 1)) return false;
14946
+ const works = [item, ...(item.related ?? []).filter((other) => other.relation === "season" && other.id)];
14947
+ const inLibrary = new Set((await library.list()).shows.filter((show) => show.source).map((show) => `${show.source.source}
14948
+ ${show.source.id}`));
14949
+ const logged = new Set((await log.read()).map((event) => event.show).filter(Boolean));
14950
+ return !works.some((work) => inLibrary.has(`${sourceId}
14951
+ ${work.id}`) || foldersFor(sourceId, work).some((path) => logged.has(path)));
14952
+ }
14953
+ function foldersFor(sourceId, work) {
14954
+ const name2 = cleanName(work.title ?? "");
14825
14955
  const mark = createHash6("sha256").update(`${sourceId}
14826
- ${item.id}`).digest("hex").slice(0, 8);
14827
- for (const candidate of [name2, `${name2} (${mark})`]) {
14828
- const path = join16(libraryRoots[0], candidate);
14956
+ ${work.id}`).digest("hex").slice(0, 8);
14957
+ return [name2, `${name2} (${mark})`].map((candidate) => join16(libraryRoots[0], candidate));
14958
+ }
14959
+ async function folderFor(sourceId, item) {
14960
+ for (const path of foldersFor(sourceId, item)) {
14829
14961
  const exists2 = await stat10(path).then(() => true, () => false);
14830
14962
  const shows = (await library.list()).shows;
14831
14963
  const owner = shows.find((show) => show.path === path);
14832
14964
  if (!exists2 || owner?.source?.source === sourceId && owner.source.id === item.id) return path;
14833
14965
  }
14834
- throw hubError("exists", `${name2} is already in the library`);
14966
+ throw hubError("exists", `${cleanName(item.title)} is already in the library`);
14835
14967
  }
14836
14968
  return {
14837
14969
  async load() {
@@ -14849,6 +14981,8 @@ ${item.id}`).digest("hex").slice(0, 8);
14849
14981
  * `start` says otherwise.
14850
14982
  */
14851
14983
  async createRoom(input) {
14984
+ const person = typeof input.person === "string" ? input.person : "";
14985
+ const tickets = await points.pay(person, points.wants({ starts: true }), { buy: input.buy ?? [] });
14852
14986
  let start = input.start ?? null;
14853
14987
  if (start === null && typeof input.path === "string") {
14854
14988
  const show2 = library.showPath(input.path);
@@ -14858,7 +14992,9 @@ ${item.id}`).digest("hex").slice(0, 8);
14858
14992
  const show = typeof input.path === "string" ? library.showPath(input.path) : null;
14859
14993
  const from2 = show === null ? null : library.workSource(show);
14860
14994
  if (from2 && typeof input.person === "string" && from2.person !== input.person) library.mark(show, { source: { ...from2, person: input.person } });
14861
- return rooms.createRoom({ ...input, start });
14995
+ const opened = await rooms.createRoom({ ...input, start });
14996
+ await points.use(person, tickets, { room: opened.room?.id });
14997
+ return opened;
14862
14998
  },
14863
14999
  watchTogether: (id) => rooms.watchTogether(id),
14864
15000
  waitReady: (...args) => rooms.waitReady(...args),
@@ -14954,18 +15090,22 @@ ${item.id}`).digest("hex").slice(0, 8);
14954
15090
  * whose account (`person`, the one asking) and the viewer's `language`, for the captions chosen with each episode.
14955
15091
  * @param {{ source: string, id: string, watch?: boolean, all?: boolean, quality?: string, by?: string, person?: string, language?: string }} input
14956
15092
  */
14957
- async fetch({ source: sourceId, id, watch = false, together = false, all = false, quality = "", by = "", person = "", language = "" }) {
15093
+ async fetch({ source: sourceId, id, watch = false, together = false, all = false, quality = "", by = "", person = "", language = "", buy = [] }) {
14958
15094
  const item = await source(sourceId).info(id, { person, language });
14959
15095
  if (!(item.episodes > 0)) throw hubError("empty", `${item.title || id} has no episodes`);
15096
+ const dir = await folderFor(sourceId, item);
15097
+ const subject = `${sourceId}:${item.id}`;
15098
+ const isNew = points.enabled && await isNewSeries(sourceId, item);
14960
15099
  const disk = await statfs2(libraryRoots[0]).catch(() => null);
14961
15100
  if (disk !== null && disk.bavail * disk.bsize < MIN_FREE_BYTES) throw hubError("no_space", "the library disk is almost full; delete something first");
14962
- const dir = await folderFor(sourceId, item);
15101
+ const tickets = await points.pay(person, points.wants({ isNew, starts: watch }), { buy, subject });
14963
15102
  const how = { ...isQuality(quality) ? { quality } : {}, person, language };
14964
15103
  await library.adopt(dir, { source: sourceId, id: item.id, kind: item.kind, episodes: item.episodes, title: item.title, ...how }, { pinned: all });
14965
15104
  library.setWork(dir, snapshotOf(item, now()));
14966
15105
  let room = null;
14967
15106
  if (watch) room = (await rooms.createRoom({ source: "local", path: dir, title: item.title, by, person, together, start: await library.resumeFrom(dir) })).room;
14968
15107
  else await cache.refresh(dir, { retry: true });
15108
+ await points.use(person, tickets, { room: room?.id, subject });
14969
15109
  const count = all ? item.episodes : Math.min(item.episodes, options.cache.ahead + 1);
14970
15110
  return { path: dir, title: item.title, episodes: item.episodes, estimate: count * (EPISODE_BYTES[item.kind] ?? EPISODE_BYTES.drama), room, download: downloads.state(dir) };
14971
15111
  },
@@ -15063,6 +15203,7 @@ async function body(request) {
15063
15203
  }
15064
15204
  var pick4 = (value, keys) => Object.fromEntries(keys.filter((key) => value?.[key] !== void 0).map((key) => [key, value[key]]));
15065
15205
  var text2 = (value) => typeof value === "string" ? value : "";
15206
+ var buying = (value) => Array.isArray(value) ? value.filter((key) => typeof key === "string").slice(0, 4) : [];
15066
15207
  function createPersonRoutes({ hub, identity }) {
15067
15208
  const handle = (fn) => async (request) => {
15068
15209
  const current = hub();
@@ -15087,14 +15228,17 @@ function createPersonRoutes({ hub, identity }) {
15087
15228
  requestBody: "buffered",
15088
15229
  fetch: handle(async (request, current, person) => {
15089
15230
  const input = await body(request);
15090
- return current.fetch({ ...pick4(input, ["source", "id", "watch", "together", "all", "quality", "by"]), language: text2(input.language), person: person.id });
15231
+ return current.fetch({ ...pick4(input, ["source", "id", "watch", "together", "all", "quality", "by"]), language: text2(input.language), person: person.id, buy: buying(input.buy) });
15091
15232
  })
15092
15233
  },
15093
15234
  {
15094
15235
  path: `${PERSON_PATH}/rooms`,
15095
15236
  methods: ["POST"],
15096
15237
  requestBody: "buffered",
15097
- fetch: handle(async (request, current, person) => current.createRoom({ ...pick4(await body(request), ["path", "title", "by", "start"]), fromPanel: true, person: person.id }))
15238
+ fetch: handle(async (request, current, person) => {
15239
+ const input = await body(request);
15240
+ return current.createRoom({ ...pick4(input, ["path", "title", "by", "start"]), fromPanel: true, person: person.id, buy: buying(input.buy) });
15241
+ })
15098
15242
  },
15099
15243
  {
15100
15244
  path: `${PERSON_PATH}/ratings`,
@@ -15250,6 +15394,7 @@ function apply(ctx, config) {
15250
15394
  },
15251
15395
  notifyCommand: config.notifyCommand,
15252
15396
  recommender: config.recommender,
15397
+ points: config.points,
15253
15398
  cache: { ahead: config.cacheAhead, behind: config.cacheBehind, capBytes: config.cacheLimitGb * 1e9 },
15254
15399
  logger
15255
15400
  });
package/locale/en.json CHANGED
@@ -271,6 +271,14 @@
271
271
  "continue.continueAt": "Continue at {time}",
272
272
  "continue.play": "Play",
273
273
  "library.continueAt": "continue at {time}",
274
- "library.viewerStoppedAt": "{name} stopped at {time}"
274
+ "library.viewerStoppedAt": "{name} stopped at {time}",
275
+ "points.newSeries": "Starting a new series",
276
+ "points.bingeNight": "A binge night",
277
+ "points.offer": "{name} costs {cost} points. You have {balance}.",
278
+ "points.short": "{name} costs {cost} points: {gap} more to go.",
279
+ "points.pending": "{name} is waiting for approval.",
280
+ "points.buy": "Buy",
281
+ "points.notNow": "Not now",
282
+ "points.ok": "OK"
275
283
  }
276
284
  }
package/locale/fr.json CHANGED
@@ -271,6 +271,14 @@
271
271
  "continue.continueAt": "Reprendre à {time}",
272
272
  "continue.play": "Lire",
273
273
  "library.continueAt": "reprendre à {time}",
274
- "library.viewerStoppedAt": "{name} s’est arrêté·e à {time}"
274
+ "library.viewerStoppedAt": "{name} s’est arrêté·e à {time}",
275
+ "points.newSeries": "Commencer une nouvelle série",
276
+ "points.bingeNight": "Une nuit de marathon",
277
+ "points.offer": "{name} coûte {cost} points. Vous en avez {balance}.",
278
+ "points.short": "{name} coûte {cost} points : encore {gap} à gagner.",
279
+ "points.pending": "{name} attend un accord.",
280
+ "points.buy": "Acheter",
281
+ "points.notNow": "Pas maintenant",
282
+ "points.ok": "OK"
275
283
  }
276
284
  }
package/locale/zh.json CHANGED
@@ -271,6 +271,14 @@
271
271
  "continue.continueAt": "从 {time} 继续",
272
272
  "continue.play": "播放",
273
273
  "library.continueAt": "从 {time} 继续",
274
- "library.viewerStoppedAt": "{name}看到 {time}"
274
+ "library.viewerStoppedAt": "{name}看到 {time}",
275
+ "points.newSeries": "开一部新剧",
276
+ "points.bingeNight": "通宵追剧夜",
277
+ "points.offer": "{name}要 {cost} 分,你现在有 {balance} 分。",
278
+ "points.short": "{name}要 {cost} 分,还差 {gap} 分。",
279
+ "points.pending": "{name}还在等批准。",
280
+ "points.buy": "兑换",
281
+ "points.notNow": "先不了",
282
+ "points.ok": "好"
275
283
  }
276
284
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-media-hub",
3
- "version": "0.8.0",
3
+ "version": "0.9.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",
@@ -9,7 +9,7 @@ import { AvatarStack } from './avatars.js'
9
9
  import { Picture } from './details.js'
10
10
  import { currentEpisode, episodeStrip, stripCounts } from './continue.js'
11
11
  import { hasEpisodes, resumeLabel } from './format.js'
12
- import { Btn, Icon, K, P, api, asPerson, base, canChat, chatAbout, clock, copyText, displayName, fill, h, nameOf, plural, post, React, roomLink } from './ui.js'
12
+ import { Btn, Icon, K, P, React, api, asPerson, asPersonPaying, base, canChat, chatAbout, clock, copyText, displayName, fill, h, nameOf, plural, post, roomLink } from './ui.js'
13
13
 
14
14
  const names = (t, list) => new Intl.ListFormat(t.language, { type: 'conjunction' }).format(list)
15
15
  const picture = key => (key ? new URL(key, base()).href : undefined)
@@ -64,20 +64,24 @@ export function ContinueCard({ t, subject, presence, sources, onOpen, onChanged
64
64
  setBusy(false)
65
65
  if (failure) setError(failure)
66
66
  }
67
- /** A room for this show: the shared one when there is one, else a new one for this person alone. */
67
+ /** A room for this show: the shared one when there is one, else a new one for this person alone (null: they said no to an extra). */
68
68
  const openRoom = async () => {
69
69
  if (room) return room.id
70
- const answer = await asPerson('rooms', { source: 'local', path: show.path, by: await displayName(t('guest')) })
70
+ const answer = await asPersonPaying('rooms', { source: 'local', path: show.path, by: await displayName(t('guest')) })
71
71
  if (answer.error) throw new Error(answer.error)
72
- return answer.room.id
72
+ return answer.declined ? null : answer.room.id
73
73
  }
74
74
  const go = () => run(async () => {
75
- try { onOpen(await openRoom()) } catch (failure) { return failure.message }
75
+ try {
76
+ const id = await openRoom()
77
+ if (id !== null) onOpen(id)
78
+ } catch (failure) { return failure.message }
76
79
  return null
77
80
  })
78
81
  const together = () => run(async () => {
79
82
  try {
80
83
  const id = await openRoom()
84
+ if (id === null) return null
81
85
  const answer = await post(`rooms/${encodeURIComponent(id)}/together`, {})
82
86
  if (answer.error) return answer.error
83
87
  await copyText(roomLink(id), t('room.copy'))
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { Picture, WorkDetails } from './details.js'
7
7
  import { hasEpisodes, stoppedText } from './format.js'
8
- import { Confirm, DAY_MS, EPISODE_BYTES, Icon, Menu, React, api, asPerson, bytes, clock, day, displayName, fill, h, plural, post, query, watchMark } from './ui.js'
8
+ import { Confirm, DAY_MS, EPISODE_BYTES, Icon, Menu, React, api, asPersonPaying, bytes, clock, day, displayName, fill, h, plural, post, query, watchMark } from './ui.js'
9
9
 
10
10
  const titleOf = name => name.replace(/\.[^.]+$/, '')
11
11
 
@@ -139,8 +139,9 @@ function ShowRow({ t, show, days, onOpen, onChanged, onOpenWork }) {
139
139
  const start = async (startAt) => {
140
140
  setError(null)
141
141
  const by = await displayName(t('guest'))
142
- const answer = await asPerson('rooms', { source: 'local', path: show.path, by, ...(startAt ? { start: startAt } : {}) })
142
+ const answer = await asPersonPaying('rooms', { source: 'local', path: show.path, by, ...(startAt ? { start: startAt } : {}) })
143
143
  if (answer.error) return setError(answer.error)
144
+ if (answer.declined) return undefined
144
145
  return onOpen(answer.room.id)
145
146
  }
146
147
 
package/web/page.js CHANGED
@@ -9,7 +9,7 @@ import { LibrarySection } from './library-view.js'
9
9
  import { clearNav, readNav, TABS, writeNav } from './nav.js'
10
10
  import { RoomView } from './room-view.js'
11
11
  import { WatchingTab, withNews } from './watching-view.js'
12
- import { Changes, K, Known, P, api, h, React, setWords } from './ui.js'
12
+ import { Changes, K, Known, P, api, fill, h, React, setOffer, setWords } from './ui.js'
13
13
 
14
14
  /** Marks the history entries this page added, so a back control knows going back stays on the page. */
15
15
  const PUSHED = 'vsyncPushed'
@@ -75,6 +75,33 @@ function Home({ t, nav, go, onOpen, rooms, library, load }) {
75
75
  h(DiscoverView, { t, nav, onNav: go, onOpen, onSaved: load, onBack: () => (history.state?.[PUSHED] ? history.back() : go({ work: null }, { replace: true })) }))))
76
76
  }
77
77
 
78
+ /** The page's words for the extras the hub sells (src/points.js EXTRAS), by item key; another item keeps its shop name. */
79
+ const EXTRA_WORDS = Object.freeze({ 'media:new_series': 'points.newSeries', 'media:binge_night': 'points.bingeNight' })
80
+
81
+ /**
82
+ * The offer of an extra at the moment of the action: its price and the person's balance, and Buy when they can.
83
+ * One at a time; `asPersonPaying` (ui.js) waits for the answer.
84
+ */
85
+ function PointsOffer({ t }) {
86
+ const [ask, setAsk] = React.useState(null)
87
+ React.useEffect(() => {
88
+ setOffer(points => new Promise(resolve => setAsk({ points, resolve })))
89
+ return () => setOffer(null)
90
+ }, [])
91
+ if (ask === null) return null
92
+ const { points, resolve } = ask
93
+ const done = (yes) => { setAsk(null); resolve(yes) }
94
+ const name = EXTRA_WORDS[points.item] ? t(EXTRA_WORDS[points.item]) : points.name
95
+ const key = points.pending ? 'points.pending' : points.affordable ? 'points.offer' : 'points.short'
96
+ return h('div', { className: 'vsync-pointsOffer', role: 'alertdialog', 'aria-live': 'polite' },
97
+ h('span', { className: 'vsync-pointsText' }, fill(t(key), { name, cost: points.cost, balance: points.balance, gap: points.gap })),
98
+ h('span', { className: 'vsync-actions' },
99
+ points.affordable && !points.pending
100
+ ? [h('button', { key: 'no', type: 'button', className: 'vsync-btn', onClick: () => done(false) }, t('points.notNow')),
101
+ h('button', { key: 'yes', type: 'button', className: 'vsync-btn vsync-primary', autoFocus: true, onClick: () => done(true) }, t('points.buy'))]
102
+ : h('button', { type: 'button', className: 'vsync-btn', autoFocus: true, onClick: () => done(false) }, t('points.ok'))))
103
+ }
104
+
78
105
  export function Page({ t, initialRoom }) {
79
106
  setWords(t)
80
107
  const [roomId, setRoomId] = React.useState(initialRoom)
@@ -100,7 +127,9 @@ export function Page({ t, initialRoom }) {
100
127
 
101
128
  const known = React.useMemo(() => ({ library, rooms, reload: load }), [library, rooms, load])
102
129
  const changes = React.useMemo(() => ({ shelf }), [shelf])
103
- return h(Changes.Provider, { value: changes }, h(Known.Provider, { value: known }, roomId === null
104
- ? h(Home, { t, nav, go, onOpen: setRoomId, rooms, library, load })
105
- : h(RoomView, { key: roomId, t, roomId, onLeave: () => setRoomId(null), onOpen: setRoomId })))
130
+ return h(Changes.Provider, { value: changes }, h(Known.Provider, { value: known }, h(React.Fragment, null,
131
+ roomId === null
132
+ ? h(Home, { t, nav, go, onOpen: setRoomId, rooms, library, load })
133
+ : h(RoomView, { key: roomId, t, roomId, onLeave: () => setRoomId(null), onOpen: setRoomId }),
134
+ h(PointsOffer, { t }))))
106
135
  }
package/web/panel.css CHANGED
@@ -361,3 +361,7 @@
361
361
  .vsync-pageTabs,.vsync-ccActions,.vsync-rateAnswers,.vsync-pickActions,.vsync-ccLive,.vsync-sectionMeta,.vsync-sectionHead h2,.vsync-actions,.vsync-tabCount,.vsync-ccStrip,.vsync-rateHead .uk-tile{user-select:none;-webkit-user-select:none}
362
362
  .vsync-page img{-webkit-user-drag:none;user-select:none;-webkit-user-select:none}
363
363
  .vsync-ccActions .uk-touch,.vsync-pickActions .uk-touch,.vsync-rateAnswers .uk-touch{font-size:13px}
364
+ /* Points offer: an extra's price at the moment of the action */
365
+ .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)}
366
+ .vsync-pointsText{flex:1;min-width:0;font-size:13px;line-height:19px;color:var(--dsw-alias-label-primary)}
367
+ @media (width<=767px){.vsync-pointsOffer{flex-wrap:wrap;bottom:12px}.vsync-pointsOffer>.vsync-actions{margin-left:auto}}
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { Picture } from './details.js'
8
8
  import { FollowButton } from './follow.js'
9
- import { Btn, Icon, K, P, asPerson, displayName, fillNodes, h, React } from './ui.js'
9
+ import { Btn, Icon, K, P, React, asPerson, asPersonPaying, displayName, fillNodes, h } from './ui.js'
10
10
 
11
11
  /** The answers, in order, with the icon each one shows (DSH's own where it has one). */
12
12
  const ANSWERS = [
@@ -69,9 +69,10 @@ function PickCard({ t, pick, onOpen, onOpenWork }) {
69
69
  const together = async () => {
70
70
  setBusy(true)
71
71
  setError(null)
72
- const answer = await asPerson('fetch', { source: work.source, id: work.id, watch: true, together: true, language: t.language, by: await displayName(t('guest')) })
72
+ const answer = await asPersonPaying('fetch', { source: work.source, id: work.id, watch: true, together: true, language: t.language, by: await displayName(t('guest')) })
73
73
  setBusy(false)
74
74
  if (answer.error) return setError(answer.error)
75
+ if (answer.declined) return undefined
75
76
  return onOpen(answer.room.id)
76
77
  }
77
78
  return h(K.Surface, { as: 'li', className: 'vsync-pickCard' },
@@ -9,7 +9,7 @@ import { Cover, WorkDetails, glance, infoOf } from './details.js'
9
9
  import { FollowButton } from './follow.js'
10
10
  import { hasEpisodes, resumeLabel } from './format.js'
11
11
  import { useKnownWork } from './known.js'
12
- import { Confirm, EPISODE_BYTES, Icon, React, Spinner, asPerson, bytes, chatAbout, clock, displayName, fill, h } from './ui.js'
12
+ import { Confirm, EPISODE_BYTES, Icon, React, Spinner, asPersonPaying, bytes, chatAbout, clock, displayName, fill, h } from './ui.js'
13
13
 
14
14
  /** Episodes fetched ahead of the one being watched; the Host's `cacheAhead` default, for the size hint. */
15
15
  const WINDOW_EPISODES = 6
@@ -49,9 +49,10 @@ export function Result({ t, source, result, onOpen, onSaved, onFocus, defaultOpe
49
49
  submitting.current = true
50
50
  setState({ step: watch ? 'opening' : 'saving' })
51
51
  const by = await displayName(t('guest'))
52
- const answer = await asPerson('fetch', { source: source.id, id: result.id, watch, all, quality, language: t.language, by })
52
+ const answer = await asPersonPaying('fetch', { source: source.id, id: result.id, watch, all, quality, language: t.language, by })
53
53
  submitting.current = false
54
54
  if (answer.error) return setState({ step: 'error', message: answer.error })
55
+ if (answer.declined) return setState({ step: 'idle' })
55
56
  if (watch && answer.room) return onOpen(answer.room.id)
56
57
  setState({ step: 'saved', all })
57
58
  onSaved()
package/web/room-view.js CHANGED
@@ -6,7 +6,7 @@ import { About, nextSeason } from './about-view.js'
6
6
  import { AvatarStack } from './avatars.js'
7
7
  import { Cover } from './details.js'
8
8
  import { useKnownWork } from './known.js'
9
- import { Confirm, Icon, ProgressBar, React, api, asPerson, base, captionText, clock, copyText, displayName, fill, h, post, progressFraction, progressText, roomLink, watchMark } from './ui.js'
9
+ import { Confirm, Icon, ProgressBar, React, api, asPersonPaying, base, captionText, clock, copyText, displayName, fill, h, post, progressFraction, progressText, roomLink, watchMark } from './ui.js'
10
10
 
11
11
  const TOAST_MS = 4000
12
12
  /** A wait shorter than this (a seek into what is already loaded) shows nothing. */
@@ -116,9 +116,10 @@ export function RoomView({ t, roomId, onLeave, onOpen }) {
116
116
  const watchSeason = async () => {
117
117
  if (seasonKnown.room !== null) return onOpen(seasonKnown.room.id)
118
118
  setSeasonBusy(true)
119
- const answer = await asPerson('fetch', { source: about.source, id: season.id, watch: true, all: false, language: t.language, by: await displayName(t('guest')) })
119
+ const answer = await asPersonPaying('fetch', { source: about.source, id: season.id, watch: true, all: false, language: t.language, by: await displayName(t('guest')) })
120
120
  setSeasonBusy(false)
121
121
  if (answer.error) return toast(answer.error)
122
+ if (answer.declined) return undefined
122
123
  return onOpen(answer.room.id)
123
124
  }
124
125
 
package/web/ui.js CHANGED
@@ -54,7 +54,7 @@ async function request(url, init = {}) {
54
54
  try {
55
55
  const response = await fetch(url, init.body === undefined ? init : { ...init, headers: { 'content-type': 'application/json' } })
56
56
  const data = await response.json().catch(() => ({}))
57
- if (!response.ok) return { error: failureText(data.error, response.status), code: data.error?.code, reason: data.error?.reason ?? null }
57
+ if (!response.ok) return { error: failureText(data.error, response.status), code: data.error?.code, reason: data.error?.reason ?? null, ...(data.error?.points ? { points: data.error.points } : {}) }
58
58
  return data
59
59
  } catch (error) {
60
60
  return { error: words === null ? error.message : words('error.network') }
@@ -70,6 +70,24 @@ 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 }
76
+
77
+ /**
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 }`.
80
+ */
81
+ export async function asPersonPaying(path, body) {
82
+ const buy = []
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)
88
+ }
89
+ }
90
+
73
91
  /** The shelf's routes, under the same /api (src/shelf-routes.js). */
74
92
  export const shelfUrl = (path = '') => personUrl(`shelf${path}`)
75
93
  export const shelf = (path = '', body) => request(shelfUrl(path), body === undefined ? {} : { method: 'POST', body: JSON.stringify(body) })
@@ -10,7 +10,7 @@ import { continueSubject, continueWatching } from './continue.js'
10
10
  import { Poster, showMeta } from './library-view.js'
11
11
  import { PicksSection, RatingsSection } from './presence-view.js'
12
12
  import { RoomsSection } from './rooms-view.js'
13
- import { Btn, K, api, asPerson, displayName, fill, h, plural, post, React } from './ui.js'
13
+ import { Btn, K, React, api, asPersonPaying, displayName, fill, h, plural, post } from './ui.js'
14
14
 
15
15
  /** Shows with news from a followed work: a new season added, or more episodes. */
16
16
  export const withNews = library => (library?.shows ?? []).filter(show => show.newSeason || show.newEpisodes)
@@ -30,9 +30,9 @@ function StartButton({ t, show, label, variant, onOpen, onStarted }) {
30
30
  const [busy, setBusy] = React.useState(false)
31
31
  const start = async () => {
32
32
  setBusy(true)
33
- const answer = await asPerson('rooms', { source: 'local', path: show.path, by: await displayName(t('guest')) })
33
+ const answer = await asPersonPaying('rooms', { source: 'local', path: show.path, by: await displayName(t('guest')) })
34
34
  setBusy(false)
35
- if (answer.error) return
35
+ if (answer.error || answer.declined) return
36
36
  onStarted?.()
37
37
  onOpen(answer.room.id)
38
38
  }