@soffits/dsh-media-hub 0.7.1 → 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,13 @@
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
+
7
+ ## 0.8.0
8
+
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.
10
+
3
11
  ## 0.7.1
4
12
 
5
13
  - Opening the page no longer waits on the sources. Each show's details (title, blurb, score, related works, episode titles, cover) come from the copy saved with it, at once, as before 0.7.0. A copy that is missing (a show just added) or about a day old is refreshed from its source in the background, a couple of requests at a time and never for a source that just failed, and the new details show on the next look. A copy over a week old says when it was saved.
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) => {
@@ -12671,7 +12681,8 @@ function runConverter(command, input, output) {
12671
12681
  });
12672
12682
  });
12673
12683
  }
12674
- function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, now = Date.now }) {
12684
+ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, changed = () => {
12685
+ }, now = Date.now }) {
12675
12686
  let state = { files: {}, shelves: {} };
12676
12687
  let saving = Promise.resolve();
12677
12688
  const running = /* @__PURE__ */ new Map();
@@ -12679,6 +12690,7 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, no
12679
12690
  let active = 0;
12680
12691
  let disposed = false;
12681
12692
  const save = () => {
12693
+ changed();
12682
12694
  saving = saving.then(async () => {
12683
12695
  await mkdir6(dir, { recursive: true });
12684
12696
  const temporary = join12(dir, `.${STATE_FILE}.${process.pid}.tmp`);
@@ -14096,6 +14108,7 @@ function createLibrary(options) {
14096
14108
  }
14097
14109
  }
14098
14110
  function save() {
14111
+ options.changed?.();
14099
14112
  const body2 = JSON.stringify({ shows: meta }, null, 1);
14100
14113
  saving = saving.then(async () => {
14101
14114
  await writeFile6(`${metaFile}.part`, body2);
@@ -14139,6 +14152,7 @@ function createLibrary(options) {
14139
14152
  await rm8(join15(target, name2), { force: true });
14140
14153
  for (const sub of matchSubtitles(name2, await readdir7(target).catch(() => []))) await rm8(join15(target, sub.name), { force: true });
14141
14154
  await forgetSum(target, name2);
14155
+ options.changed?.();
14142
14156
  }
14143
14157
  async function folderBytes(path) {
14144
14158
  const info = await stat9(path).catch(() => null);
@@ -14606,6 +14620,149 @@ function createFollows({ library, source, refreshed, addSeason, record, notify,
14606
14620
  };
14607
14621
  }
14608
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
+
14733
+ // src/changes.js
14734
+ function createChanges({ intervalMs = 300 } = {}) {
14735
+ const listeners = /* @__PURE__ */ new Set();
14736
+ let pending = /* @__PURE__ */ new Set();
14737
+ let timer = null;
14738
+ let lastAt = 0;
14739
+ function flush() {
14740
+ timer = null;
14741
+ lastAt = Date.now();
14742
+ const what = [...pending];
14743
+ pending = /* @__PURE__ */ new Set();
14744
+ for (const listener of listeners) listener(what);
14745
+ }
14746
+ return {
14747
+ notify(kind) {
14748
+ pending.add(kind);
14749
+ if (timer !== null) return;
14750
+ timer = setTimeout(flush, Math.max(0, lastAt + intervalMs - Date.now()));
14751
+ timer.unref?.();
14752
+ },
14753
+ /** @returns {() => void} stop listening */
14754
+ listen(listener) {
14755
+ listeners.add(listener);
14756
+ return () => listeners.delete(listener);
14757
+ },
14758
+ close() {
14759
+ clearTimeout(timer);
14760
+ timer = null;
14761
+ listeners.clear();
14762
+ }
14763
+ };
14764
+ }
14765
+
14609
14766
  // src/work-refresh.js
14610
14767
  var DAY_MS3 = 864e5;
14611
14768
  var HOUR_MS = 36e5;
@@ -14656,7 +14813,9 @@ function createMediaHub(options) {
14656
14813
  const sources = new Map(options.sources.map((source2) => [source2.id, source2]));
14657
14814
  const covers = createCovers({ dir: join16(stateDir, "covers"), capBytes: options.coverCacheBytes, ffmpeg: options.tools.ffmpeg, logger }, (id) => sources.get(id));
14658
14815
  const log = createWatchLog({ file: join16(stateDir, LOG_NAME), now, logger });
14659
- const books = createBooks({ dir: join16(stateDir, "books"), sources, capBytes: options.books?.capBytes ?? 0, converter: options.books?.converter ?? NO_CONVERTER, covers, logger, now });
14816
+ const changes = createChanges({ intervalMs: options.changeIntervalMs });
14817
+ const points = createPoints(options.points ?? { command: [], night: { from: "01:00", to: "06:00" } }, { logger, now });
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 });
14660
14819
  let rooms;
14661
14820
  let cache;
14662
14821
  const downloads = createDownloads({
@@ -14668,13 +14827,17 @@ function createMediaHub(options) {
14668
14827
  return disk === null || disk.bavail * disk.bsize >= MIN_FREE_BYTES;
14669
14828
  },
14670
14829
  onFiles,
14671
- onProgress: (job, number, progress) => rooms.downloadProgress(job.dir, number, progress),
14830
+ onProgress: (job, number, progress) => {
14831
+ rooms.downloadProgress(job.dir, number, progress);
14832
+ changes.notify("library");
14833
+ },
14672
14834
  onPartial: (job, number, partial) => rooms.streamEpisode(job.dir, number, partial),
14673
14835
  logger,
14674
14836
  now
14675
14837
  });
14676
14838
  const refreshWork = createWorkRefresh({ source: (id) => sources.get(id), keep: (path, work) => library.keepWork(path, work), maxAgeMs: options.workMaxAgeMs, logger, now });
14677
14839
  const library = createLibrary({
14840
+ changed: () => changes.notify("library"),
14678
14841
  roots: libraryRoots,
14679
14842
  stateDir,
14680
14843
  autoDeleteDays: options.autoDeleteDays,
@@ -14686,6 +14849,7 @@ function createMediaHub(options) {
14686
14849
  logger,
14687
14850
  now
14688
14851
  });
14852
+ const journal = createJournal({ log, library, now });
14689
14853
  rooms = createRoomService({
14690
14854
  ...options,
14691
14855
  watchOf: (item, show) => library.watchOfItem(show, item),
@@ -14694,7 +14858,10 @@ function createMediaHub(options) {
14694
14858
  cache.refresh(show, change).catch(() => {
14695
14859
  });
14696
14860
  },
14697
- observe: createJournal({ log, library, now })
14861
+ observe: (type, detail) => {
14862
+ journal(type, detail);
14863
+ if (type !== "progress") changes.notify("rooms");
14864
+ }
14698
14865
  });
14699
14866
  cache = createCache({ library, downloads, rooms, window: options.cache, logger });
14700
14867
  library.onChange((show) => {
@@ -14718,6 +14885,7 @@ function createMediaHub(options) {
14718
14885
  });
14719
14886
  }, HOUR_MS2);
14720
14887
  async function onFiles(job) {
14888
+ changes.notify("library");
14721
14889
  await rooms.syncShow(job.dir);
14722
14890
  if (job.status === "failed") rooms.failWaiting(job.dir, job.error ?? "the download failed", job.reason ?? null);
14723
14891
  await cache.enforce();
@@ -14773,18 +14941,29 @@ function createMediaHub(options) {
14773
14941
  if (found === void 0) throw hubError("not_found", `no source ${String(id)}`);
14774
14942
  return found;
14775
14943
  }
14776
- async function folderFor(sourceId, item) {
14777
- 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 ?? "");
14778
14955
  const mark = createHash6("sha256").update(`${sourceId}
14779
- ${item.id}`).digest("hex").slice(0, 8);
14780
- for (const candidate of [name2, `${name2} (${mark})`]) {
14781
- 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)) {
14782
14961
  const exists2 = await stat10(path).then(() => true, () => false);
14783
14962
  const shows = (await library.list()).shows;
14784
14963
  const owner = shows.find((show) => show.path === path);
14785
14964
  if (!exists2 || owner?.source?.source === sourceId && owner.source.id === item.id) return path;
14786
14965
  }
14787
- throw hubError("exists", `${name2} is already in the library`);
14966
+ throw hubError("exists", `${cleanName(item.title)} is already in the library`);
14788
14967
  }
14789
14968
  return {
14790
14969
  async load() {
@@ -14802,6 +14981,8 @@ ${item.id}`).digest("hex").slice(0, 8);
14802
14981
  * `start` says otherwise.
14803
14982
  */
14804
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 ?? [] });
14805
14986
  let start = input.start ?? null;
14806
14987
  if (start === null && typeof input.path === "string") {
14807
14988
  const show2 = library.showPath(input.path);
@@ -14811,7 +14992,9 @@ ${item.id}`).digest("hex").slice(0, 8);
14811
14992
  const show = typeof input.path === "string" ? library.showPath(input.path) : null;
14812
14993
  const from2 = show === null ? null : library.workSource(show);
14813
14994
  if (from2 && typeof input.person === "string" && from2.person !== input.person) library.mark(show, { source: { ...from2, person: input.person } });
14814
- 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;
14815
14998
  },
14816
14999
  watchTogether: (id) => rooms.watchTogether(id),
14817
15000
  waitReady: (...args) => rooms.waitReady(...args),
@@ -14838,6 +15021,7 @@ ${item.id}`).digest("hex").slice(0, 8);
14838
15021
  },
14839
15022
  async rate(input, person) {
14840
15023
  await log.append("rating", ratingLine(input, person));
15024
+ changes.notify("library");
14841
15025
  return { ok: true };
14842
15026
  },
14843
15027
  picks: (person) => picks.list(person),
@@ -14906,18 +15090,22 @@ ${item.id}`).digest("hex").slice(0, 8);
14906
15090
  * whose account (`person`, the one asking) and the viewer's `language`, for the captions chosen with each episode.
14907
15091
  * @param {{ source: string, id: string, watch?: boolean, all?: boolean, quality?: string, by?: string, person?: string, language?: string }} input
14908
15092
  */
14909
- 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 = [] }) {
14910
15094
  const item = await source(sourceId).info(id, { person, language });
14911
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);
14912
15099
  const disk = await statfs2(libraryRoots[0]).catch(() => null);
14913
15100
  if (disk !== null && disk.bavail * disk.bsize < MIN_FREE_BYTES) throw hubError("no_space", "the library disk is almost full; delete something first");
14914
- const dir = await folderFor(sourceId, item);
15101
+ const tickets = await points.pay(person, points.wants({ isNew, starts: watch }), { buy, subject });
14915
15102
  const how = { ...isQuality(quality) ? { quality } : {}, person, language };
14916
15103
  await library.adopt(dir, { source: sourceId, id: item.id, kind: item.kind, episodes: item.episodes, title: item.title, ...how }, { pinned: all });
14917
15104
  library.setWork(dir, snapshotOf(item, now()));
14918
15105
  let room = null;
14919
15106
  if (watch) room = (await rooms.createRoom({ source: "local", path: dir, title: item.title, by, person, together, start: await library.resumeFrom(dir) })).room;
14920
15107
  else await cache.refresh(dir, { retry: true });
15108
+ await points.use(person, tickets, { room: room?.id, subject });
14921
15109
  const count = all ? item.episodes : Math.min(item.episodes, options.cache.ahead + 1);
14922
15110
  return { path: dir, title: item.title, episodes: item.episodes, estimate: count * (EPISODE_BYTES[item.kind] ?? EPISODE_BYTES.drama), room, download: downloads.state(dir) };
14923
15111
  },
@@ -14973,7 +15161,10 @@ ${item.id}`).digest("hex").slice(0, 8);
14973
15161
  // ---------------------------------------------------------- watch log
14974
15162
  history: (opts) => log.history(opts),
14975
15163
  logFile: log.file,
15164
+ /** Be told (with the kinds of what changed: `library`, `rooms`, `shelf`) when something a page shows changes; returns a way to stop. */
15165
+ listenChanges: (listener) => changes.listen(listener),
14976
15166
  async dispose() {
15167
+ changes.close();
14977
15168
  clearInterval(sweepTimer);
14978
15169
  follows.stop();
14979
15170
  await books.dispose();
@@ -15012,6 +15203,7 @@ async function body(request) {
15012
15203
  }
15013
15204
  var pick4 = (value, keys) => Object.fromEntries(keys.filter((key) => value?.[key] !== void 0).map((key) => [key, value[key]]));
15014
15205
  var text2 = (value) => typeof value === "string" ? value : "";
15206
+ var buying = (value) => Array.isArray(value) ? value.filter((key) => typeof key === "string").slice(0, 4) : [];
15015
15207
  function createPersonRoutes({ hub, identity }) {
15016
15208
  const handle = (fn) => async (request) => {
15017
15209
  const current = hub();
@@ -15036,14 +15228,17 @@ function createPersonRoutes({ hub, identity }) {
15036
15228
  requestBody: "buffered",
15037
15229
  fetch: handle(async (request, current, person) => {
15038
15230
  const input = await body(request);
15039
- 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) });
15040
15232
  })
15041
15233
  },
15042
15234
  {
15043
15235
  path: `${PERSON_PATH}/rooms`,
15044
15236
  methods: ["POST"],
15045
15237
  requestBody: "buffered",
15046
- 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
+ })
15047
15242
  },
15048
15243
  {
15049
15244
  path: `${PERSON_PATH}/ratings`,
@@ -15069,6 +15264,55 @@ function createPersonRoutes({ hub, identity }) {
15069
15264
  ];
15070
15265
  }
15071
15266
 
15267
+ // src/events-route.js
15268
+ var EVENTS_PATH = "/api/media-hub/events";
15269
+ var HEARTBEAT_MS = 25e3;
15270
+ function createEventsRoute({ hub }) {
15271
+ return {
15272
+ path: EVENTS_PATH,
15273
+ methods: ["GET"],
15274
+ requestBody: "buffered",
15275
+ fetch: async (request) => {
15276
+ const current = hub();
15277
+ if (current === void 0) return json(503, { error: { code: "unavailable", message: "The media hub is starting." } });
15278
+ const encoder = new TextEncoder();
15279
+ let stop = () => {
15280
+ };
15281
+ const stream = new ReadableStream({
15282
+ start(controller) {
15283
+ const write2 = (chunk) => {
15284
+ try {
15285
+ controller.enqueue(encoder.encode(chunk));
15286
+ } catch {
15287
+ stop();
15288
+ }
15289
+ };
15290
+ write2("retry: 5000\n: open\n\n");
15291
+ const unlisten = current.listenChanges((what) => write2(`data: ${JSON.stringify({ type: "change", what })}
15292
+
15293
+ `));
15294
+ const beat = setInterval(() => write2(": beat\n\n"), HEARTBEAT_MS);
15295
+ stop = () => {
15296
+ unlisten();
15297
+ clearInterval(beat);
15298
+ };
15299
+ request.signal?.addEventListener("abort", () => {
15300
+ stop();
15301
+ try {
15302
+ controller.close();
15303
+ } catch {
15304
+ }
15305
+ }, { once: true });
15306
+ },
15307
+ cancel() {
15308
+ stop();
15309
+ }
15310
+ });
15311
+ return new Response(stream, { status: 200, headers: { ...HEADERS, "content-type": "text/event-stream; charset=utf-8", "cache-control": "private, no-cache, no-transform", "x-accel-buffering": "no" } });
15312
+ }
15313
+ };
15314
+ }
15315
+
15072
15316
  // src/shelf-routes.js
15073
15317
  import { createReadStream as createReadStream3 } from "node:fs";
15074
15318
  import { stat as stat11 } from "node:fs/promises";
@@ -15150,6 +15394,7 @@ function apply(ctx, config) {
15150
15394
  },
15151
15395
  notifyCommand: config.notifyCommand,
15152
15396
  recommender: config.recommender,
15397
+ points: config.points,
15153
15398
  cache: { ahead: config.cacheAhead, behind: config.cacheBehind, capBytes: config.cacheLimitGb * 1e9 },
15154
15399
  logger
15155
15400
  });
@@ -15166,7 +15411,8 @@ function apply(ctx, config) {
15166
15411
  const identity = () => ctx.get("requestIdentity");
15167
15412
  const fetchRoutes = [
15168
15413
  ...createShelfRoutes({ books: () => current?.books, identity }),
15169
- ...createPersonRoutes({ hub: () => current, identity })
15414
+ ...createPersonRoutes({ hub: () => current, identity }),
15415
+ createEventsRoute({ hub: () => current })
15170
15416
  ].map((route) => ctx.connection.fetch.register(route));
15171
15417
  const sockets = new import_websocket_server.default({ noServer: true, maxPayload: 16 * 1024, perMessageDeflate: false });
15172
15418
  const disposeHttp = ctx.webServer.register({
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.7.1",
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",
package/web/books-view.js CHANGED
@@ -12,9 +12,8 @@
12
12
  */
13
13
  import { Cover } from './details.js'
14
14
  import { offeredFormats } from './formats.js'
15
- import { Confirm, Icon, Spinner, bytes, canChat, chatAbout, fill, h, languageName, React, shelf, shelfUrl } from './ui.js'
15
+ import { Changes, Confirm, Icon, Spinner, bytes, canChat, chatAbout, fill, h, languageName, React, shelf, shelfUrl } from './ui.js'
16
16
 
17
- const SHELF_POLL_MS = 2000
18
17
 
19
18
  export const FORMATS = ['', 'epub', 'pdf', 'txt', 'azw3', 'mobi']
20
19
  export const SIZES = ['', '5', '20', '50', '200']
@@ -67,22 +66,21 @@ export function ChatButton({ t, onClick }) {
67
66
 
68
67
  /** Waits until the shelf entry is no longer being fetched. */
69
68
  function useEntry(entryId) {
69
+ const changes = React.useContext(Changes)
70
70
  const [entry, setEntry] = React.useState(null)
71
71
  React.useEffect(() => {
72
72
  if (entryId === null) return undefined
73
73
  let live = true
74
- let timer
75
- const tick = async () => {
74
+ const read = async () => {
76
75
  const answer = await shelf()
77
76
  if (!live) return
78
77
  const found = answer.entries?.find(one => one.entry === entryId) ?? null
79
78
  setEntry(found)
80
- if (found?.state === 'fetching') timer = setTimeout(tick, SHELF_POLL_MS)
81
- else forgetShelf()
79
+ if (found?.state !== 'fetching') forgetShelf()
82
80
  }
83
- tick()
84
- return () => { live = false; clearTimeout(timer) }
85
- }, [entryId])
81
+ read()
82
+ return () => { live = false }
83
+ }, [entryId, changes.shelf])
86
84
  return entry
87
85
  }
88
86
 
@@ -138,6 +136,7 @@ export function BookCard({ t, source, result }) {
138
136
 
139
137
  /** My books: what the signed-in person downloaded, to save again, fetch again or delete. */
140
138
  export function ShelfSection({ t }) {
139
+ const changes = React.useContext(Changes)
141
140
  const [state, setState] = React.useState(null)
142
141
  const [confirm, setConfirm] = React.useState(null)
143
142
  const load = React.useCallback(async () => {
@@ -145,23 +144,13 @@ export function ShelfSection({ t }) {
145
144
  setState(answer)
146
145
  return answer
147
146
  }, [])
148
- React.useEffect(() => {
149
- let live = true
150
- let timer
151
- const tick = async () => {
152
- const answer = await load()
153
- if (live && answer.entries?.some(entry => entry.state === 'fetching')) timer = setTimeout(tick, SHELF_POLL_MS)
154
- }
155
- tick()
156
- return () => { live = false; clearTimeout(timer) }
157
- }, [load])
147
+ React.useEffect(() => { load() }, [load, changes.shelf])
158
148
 
159
149
  const act = async (path, entry) => {
160
150
  setConfirm(null)
161
151
  await shelf(path, { entry: entry.entry })
162
152
  forgetShelf()
163
- const answer = await load()
164
- if (answer.entries?.some(one => one.state === 'fetching')) setTimeout(load, SHELF_POLL_MS)
153
+ await load()
165
154
  }
166
155
 
167
156
  if (state === null) return null
@@ -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 { Known, P, POLL_MS, 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)
@@ -89,16 +116,20 @@ export function Page({ t, initialRoom }) {
89
116
  if (lib.shows) setLibrary(lib)
90
117
  }, [])
91
118
 
92
- React.useEffect(() => {
93
- let live = true
94
- const tick = () => { if (live) load() }
95
- tick()
96
- const timer = setInterval(tick, POLL_MS)
97
- return () => { live = false; clearInterval(timer) }
98
- }, [load])
119
+ // The plugin announces every change of what the page shows (src/changes.js); the page re-reads then, and once when the stream (re)connects. No timer.
120
+ const [shelf, setShelf] = React.useState(0)
121
+ const stream = K.useEventStream('api/media-hub/events', (message) => {
122
+ if (message.what?.includes('shelf')) setShelf(count => count + 1)
123
+ if (message.what?.some(kind => kind === 'library' || kind === 'rooms')) load()
124
+ })
125
+ React.useEffect(() => { if (stream === 'live') { load(); setShelf(count => count + 1) } }, [stream, load])
126
+ React.useEffect(() => { load() }, [load])
99
127
 
100
128
  const known = React.useMemo(() => ({ library, rooms, reload: load }), [library, rooms, load])
101
- return h(Known.Provider, { value: known }, roomId === null
102
- ? h(Home, { t, nav, go, onOpen: setRoomId, rooms, library, load })
103
- : h(RoomView, { key: roomId, t, roomId, onLeave: () => setRoomId(null), onOpen: setRoomId }))
129
+ const changes = React.useMemo(() => ({ shelf }), [shelf])
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 }))))
104
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
@@ -9,6 +9,8 @@ import { pick } from './i18n.js'
9
9
 
10
10
  export let React
11
11
  export let h
12
+ /** How many times each kind of change (`shelf`) has been announced by the plugin's change stream: a view re-reads when its count moves. */
13
+ export let Changes
12
14
  /** What the page knows of the library and the open rooms (web/known.js): set by Page, read anywhere a work is shown. */
13
15
  export let Known
14
16
  /** DSH's own components (@deepseek-ai/dsh-client-ui-primitives): Button, Tag, StateDot, SegmentedTabs, icons. */
@@ -22,6 +24,7 @@ export function init(react, { primitives, kit }) {
22
24
  h = react.createElement
23
25
  P = primitives
24
26
  K = kit
27
+ Changes = react.createContext({ shelf: 0 })
25
28
  Known = react.createContext({ library: null, rooms: undefined, reload: () => {} })
26
29
  }
27
30
 
@@ -30,7 +33,6 @@ export const Btn = ({ variant = 'outline', size = 'sm', className, ...rest }) =>
30
33
 
31
34
  export const base = () => new URL('media-hub/', document.baseURI)
32
35
  export const LINK_PARAM = 'media-room'
33
- export const POLL_MS = 4000
34
36
 
35
37
  /** The page's words for failures, set by the page whenever its language changes (`setWords`). */
36
38
  let words = null
@@ -52,7 +54,7 @@ async function request(url, init = {}) {
52
54
  try {
53
55
  const response = await fetch(url, init.body === undefined ? init : { ...init, headers: { 'content-type': 'application/json' } })
54
56
  const data = await response.json().catch(() => ({}))
55
- 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 } : {}) }
56
58
  return data
57
59
  } catch (error) {
58
60
  return { error: words === null ? error.message : words('error.network') }
@@ -68,6 +70,24 @@ export const post = (path, body) => api(path, { method: 'POST', body: JSON.strin
68
70
  const personUrl = path => new URL(`api/media-hub/${path}`, document.baseURI)
69
71
  export const asPerson = (path, body, init = {}) => request(personUrl(path), body === undefined ? init : { ...init, method: 'POST', body: JSON.stringify(body) })
70
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
+
71
91
  /** The shelf's routes, under the same /api (src/shelf-routes.js). */
72
92
  export const shelfUrl = (path = '') => personUrl(`shelf${path}`)
73
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
  }