@soffits/dsh-media-hub 0.8.0 → 0.10.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,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.0
4
+
5
+ - Discover shows something before you search. Under the picked source and category it lists what the source itself puts forward (a source's rank lists and new arrivals, from the new optional `trending` verb of [docs/source-protocol.md](docs/source-protocol.md), asked for the kinds configured with `"trending": true`) and, when a `recommender` is set, *For you*: picks with the reason for each, narrowed to the source and category (the recommender now also gets `--source`, `--kind` and `--language`). Under *All sources* the picks are interleaved and each source's lists stay under its name. Link has neither.
6
+ - Both are dated local copies, rendered at once and asked again in the background when someone looks and the copy is about a day old (a failing source is left alone for an hour, the old copy stays), so the page never waits on a site. The Watching tab's picks use the same copies instead of waiting for the recommender.
7
+ - The default sources declare trending for Fanqie's dramas, audiobooks and novels and for bookfetch's ebooks. A source whose command lacks the verb just shows no lists.
8
+ ## 0.9.0
9
+
10
+ - 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.
11
+
3
12
  ## 0.8.0
4
13
 
5
14
  - 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
@@ -30,7 +30,7 @@ The bundle adds two rows: `media-hub` (the page, shelves, rooms, media) and `med
30
30
 
31
31
  ## Use
32
32
 
33
- - **From the page**: open **Media** in the sidebar (the `label` setting renames it). Three tabs: **Watching** (the default) lists the rooms opened to others, with who is in them and the episode, with copying a room's link or closing it, and the shows someone started, to continue; **Library** manages the shows and starts or continues one; **Discover** searches: pick a source (*All sources*, every configured one, or *Link* to paste the address of a video or playlist), then one of that source's categories, then search. The tab, source and category are in the page's URL (`?vs-tab=library`, `?vs-tab=discover&vs-source=<id>&vs-kind=<id>`), so a refresh and the back button keep them and a link can open a tab directly; the last source and category are remembered per browser.
33
+ - **From the page**: open **Media** in the sidebar (the `label` setting renames it). Three tabs: **Watching** (the default) lists the rooms opened to others, with who is in them and the episode, with copying a room's link or closing it, and the shows someone started, to continue; **Library** manages the shows and starts or continues one; **Discover** searches: pick a source (*All sources*, every configured one, or *Link* to paste the address of a video or playlist), then one of that source's categories, then search. Before any search it shows what the sources put forward for that category (their rank lists and new arrivals, from a source's `trending` verb) and, when a `recommender` is set, *For you*: picks with the reason for each. Both are kept as dated copies and refreshed in the background about daily, so the page never waits on a site; *All sources* merges the picks and lists each source's boards under its name; Link has neither. The tab, source and category are in the page's URL (`?vs-tab=library`, `?vs-tab=discover&vs-source=<id>&vs-kind=<id>`), so a refresh and the back button keep them and a link can open a tab directly; the last source and category are remembered per browser.
34
34
  - **Watching**: a card at the top for the show someone is in now, or the one you watched last, over its blurred cover: who is in the room, where it stands, a strip of its episodes (watched, now, on disk), and joining them, or continuing alone, or *Watch together* to open it to others. Optional parts, each off until switched on in `presence`: *So far*, a recap without spoilers kept with the show; *How was it?*, one tap that writes a rating into the watch log for a show finished or removed lately; and *Picks*, works a recommender extension suggests, each with its reason. Steps suggested for a show (written through the tool's `annotate`) show on the card when [@soffits/dsh-ui-actions](https://github.com/soffits/dsh-ui-actions) is installed.
35
35
  - **From the assistant**: `videosync` with `action: start` and `source: local` plus `path`, `source: link` plus `url` (and `quality`), or `source: <source id>` plus `id` (and `offline: true` to keep every episode), returns a link to send. `list` and `close` manage rooms, `library` lists the shows, `history` summarises the watch log (shows, episodes finished, where each viewer stopped, with whom, when).
36
36
 
@@ -60,13 +60,14 @@ 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. |
66
67
  | `cookies` | `[]` | Signed-in accounts for sites, by host: a list of `{ hosts, hostsFile, accounts }`, hosts written as in `proxies`. Each account is `{ person, name, file, userAgent, share }`: `file` a Netscape cookies file of a signed-in session (kept fresh by whatever holds that session; the hub only reads it and gives yt-dlp a private copy per run), `userAgent` the User-Agent that session uses, `person` the owner's sign-in id (empty for the default account everyone without their own uses), `name` what the page shows, `share` whether others without an account of their own may use it. A lookup or download uses the account of the person asking, else the default, else a shared one; a room uses the account of whoever opened it. |
67
68
  | `bookCacheGb` | `5` | Most disk (GB) downloaded books may use; past it the least recently used files go and stay on their shelves to fetch again. `0` is no limit. |
68
69
  | `converter` | `ebook-convert` | Calibre's converter; when installed, books can be downloaded in formats their source lacks. Empty turns conversion off. |
69
- | `sources` | `fanqie`, `bookfetch` | The sources: a list of `{ id, label, kinds: [{ id, label, media }], filters, command: [program, ...fixed arguments], env }`; `label` is the source's name in Discover's picker and each kind's `label` its category, each a string or `{ "<tag>": "text" }` like the sidebar's; left empty, the page uses its own words for that id (`source.name.<id>`, `kind.<id>` in `locale/`), else the id; `media` is `video`, `audio` or `book`; `filters` lists the search filters the command understands (`language`, `format`, `year`). The list replaces the default, so keep the default entries when adding one; an empty list turns sources off. See [docs/source-protocol.md](docs/source-protocol.md). |
70
+ | `sources` | `fanqie`, `bookfetch` | The sources: a list of `{ id, label, kinds: [{ id, label, media, trending }], filters, command: [program, ...fixed arguments], env }`; `label` is the source's name in Discover's picker and each kind's `label` its category, each a string or `{ "<tag>": "text" }` like the sidebar's; left empty, the page uses its own words for that id (`source.name.<id>`, `kind.<id>` in `locale/`), else the id; `media` is `video`, `audio` or `book`, `trending` (default false) says the command's `trending` verb answers for that kind; `filters` lists the search filters the command understands (`language`, `format`, `year`). The list replaces the default, so keep the default entries when adding one; an empty list turns sources off. See [docs/source-protocol.md](docs/source-protocol.md). |
70
71
 
71
72
  The tools row takes `agentName` (shown as who opened the assistant's rooms) and `waitSeconds` (how long `start` waits for the first episode to be ready).
72
73
 
package/dist/index.js CHANGED
@@ -10704,6 +10704,7 @@ var lastLine = (text3) => text3.trim().split("\n").filter(Boolean).pop() ?? "";
10704
10704
 
10705
10705
  // src/sources/command.js
10706
10706
  var SEARCH_LIMIT = 12;
10707
+ var TRENDING_LIMIT = 20;
10707
10708
  var QUERY_TIMEOUT_MS = 6e4;
10708
10709
  var COVER_TIMEOUT_MS = 3e4;
10709
10710
  var ID = /^[^\s\0]{1,200}$/;
@@ -10771,6 +10772,28 @@ function parseSearch(document2, kinds) {
10771
10772
  const kindIds = new Set(kinds.map((kind) => kind.id));
10772
10773
  return document2.results.map((raw) => resultOf(raw, kindIds)).filter((result) => result !== null);
10773
10774
  }
10775
+ var MAX_LISTS = 6;
10776
+ function labelOf(value) {
10777
+ if (typeof value === "string" && value.trim() !== "") return value.trim();
10778
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
10779
+ const entries = Object.entries(value).filter(([tag, words]) => typeof tag === "string" && typeof words === "string" && words.trim() !== "");
10780
+ if (entries.length > 0) return Object.fromEntries(entries.map(([tag, words]) => [tag, words.trim()]));
10781
+ }
10782
+ return null;
10783
+ }
10784
+ function parseTrending(document2, kinds, kind) {
10785
+ const kindIds = new Set(kinds.map((entry) => entry.id));
10786
+ const raw = Array.isArray(document2?.lists) ? document2.lists : Array.isArray(document2?.results) ? [{ id: "trending", results: document2.results }] : null;
10787
+ if (raw === null) throw sourceError2("source_failed", "the trending answer has no lists");
10788
+ const seen = /* @__PURE__ */ new Set();
10789
+ return raw.slice(0, MAX_LISTS).flatMap((list, index) => {
10790
+ const results = Array.isArray(list?.results) ? list.results.map((item) => resultOf(item, kindIds)).filter((result) => result !== null && result.kind === kind) : [];
10791
+ const id = text(list?.id) || `list-${index + 1}`;
10792
+ if (results.length === 0 || seen.has(id)) return [];
10793
+ seen.add(id);
10794
+ return [{ id, label: labelOf(list?.label), results }];
10795
+ });
10796
+ }
10774
10797
  function nextOffset(document2, offset = 0) {
10775
10798
  return Number.isInteger(document2?.next) && document2.next > offset ? document2.next : null;
10776
10799
  }
@@ -10850,6 +10873,11 @@ function createCommandSource(definition, { logger, cwd }) {
10850
10873
  const document2 = await query(["search", "--kind", kind, "--limit", String(limit), ...paging, ...filterArgs(filters, understood), "--json", "--", q]);
10851
10874
  return { results: parseSearch(document2, kinds).filter((result) => result.kind === kind), next: nextOffset(document2, offset) };
10852
10875
  },
10876
+ /** What the site itself puts forward for a kind that declares `trending`: lists of works, in the site's order. */
10877
+ async trending(kind, { limit = TRENDING_LIMIT } = {}) {
10878
+ if (!kinds.some((entry) => entry.id === kind && entry.trending === true)) throw sourceError2("invalid", `${name2()} has no trending list for ${kind}`);
10879
+ return parseTrending(await query(["trending", "--kind", kind, "--limit", String(limit), "--json"]), kinds, kind);
10880
+ },
10853
10881
  async info(id) {
10854
10882
  if (!ID.test(String(id))) throw sourceError2("invalid", `not a ${name2()} id`);
10855
10883
  return parseInfo(await query(["info", "--json", "--", String(id)]));
@@ -11938,7 +11966,8 @@ var SourceConfig = Schema.object({
11938
11966
  kinds: Schema.array(Schema.object({
11939
11967
  id: Schema.string().pattern(/^[a-z0-9][a-z0-9_-]{0,31}$/).description("What the command's search --kind takes."),
11940
11968
  label: Label.default("").description("Name of the category chip: a string, or { <tag>: text } per language. Empty uses the page's own words for this kind id (kind.<id> in locale/), else the id."),
11941
- media: Schema.union(MEDIA.map((media) => Schema.const(media))).default("video").description("What a work of this kind is: video or audio (episodes, watched or listened to together in a room) or book (one file, downloaded in a format).")
11969
+ media: Schema.union(MEDIA.map((media) => Schema.const(media))).default("video").description("What a work of this kind is: video or audio (episodes, watched or listened to together in a room) or book (one file, downloaded in a format)."),
11970
+ trending: Schema.boolean().default(false).description("Whether the command's trending verb answers for this kind (docs/source-protocol.md): its rank lists and new arrivals, shown on Discover before a search.")
11942
11971
  })).description("What the source can search for; at least one."),
11943
11972
  filters: Schema.array(Schema.union(FILTERS.map((filter) => Schema.const(filter)))).default([]).description("Search filters the command understands (docs/source-protocol.md). The hub filters the answers by language, format, year and size itself as well."),
11944
11973
  command: Schema.array(Schema.string()).min(1).description("The command and its fixed arguments, one entry per word; the plugin adds the protocol verbs after them."),
@@ -11966,14 +11995,14 @@ var CookieRule = Schema.object({
11966
11995
  var DEFAULT_SOURCES = Object.freeze([
11967
11996
  {
11968
11997
  id: "fanqie",
11969
- kinds: [{ id: "drama", media: "video" }, { id: "audio", media: "audio" }, { id: "novel", media: "book" }],
11998
+ kinds: [{ id: "drama", media: "video", trending: true }, { id: "audio", media: "audio", trending: true }, { id: "novel", media: "book", trending: true }],
11970
11999
  filters: [],
11971
12000
  command: ["fanqie"],
11972
12001
  env: {}
11973
12002
  },
11974
12003
  {
11975
12004
  id: "bookfetch",
11976
- kinds: [{ id: "ebook", media: "book" }, { id: "paper", media: "book" }],
12005
+ kinds: [{ id: "ebook", media: "book", trending: true }, { id: "paper", media: "book" }],
11977
12006
  filters: ["language", "format", "year"],
11978
12007
  command: ["bookfetch", "source"],
11979
12008
  env: {}
@@ -11989,6 +12018,15 @@ var Recommender = Schema.object({
11989
12018
  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
12019
  env: Schema.dict(Schema.string()).default({}).description("Extra environment variables for the command.")
11991
12020
  });
12021
+ var Clock = Schema.string().pattern(/^([01]?\d|2[0-3]):[0-5]\d$/);
12022
+ var Points = Schema.object({
12023
+ 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."),
12024
+ env: Schema.dict(Schema.string()).default({}).description("Extra environment variables for the command."),
12025
+ night: Schema.object({
12026
+ from: Clock.default("01:00").description("When late night starts, on the host's clock (HH:MM)."),
12027
+ to: Clock.default("06:00").description("When it ends; a binge night ticket lasts until then.")
12028
+ }).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.")
12029
+ });
11992
12030
  var Config = Schema.object({
11993
12031
  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
12032
  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 +12048,7 @@ var Config = Schema.object({
12010
12048
  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
12049
  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
12050
  recommender: Recommender.default({ command: [], env: {} }).description("Where picks come from: a recommender extension. The hub has no taste of its own."),
12051
+ 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
12052
  ffmpeg: Schema.string().default("ffmpeg").description("ffmpeg command."),
12014
12053
  ffprobe: Schema.string().default("ffprobe").description("ffprobe command."),
12015
12054
  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 +12252,8 @@ async function readJson(req) {
12213
12252
  throw Object.assign(new Error("request body is not JSON"), { status: 400 });
12214
12253
  }
12215
12254
  }
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) } });
12255
+ 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 });
12256
+ var errorBody = (error) => ({ error: { code: error?.code ?? "error", ...error?.reason ? { reason: error.reason } : {}, ...error?.points ? { points: error.points } : {}, message: error?.message ?? String(error) } });
12218
12257
  function createHandler({ connection, service, settings = () => ({ label: "", presence: {} }), localeDir = LOCALE_DIR, logger }) {
12219
12258
  let locales;
12220
12259
  return async (req, res) => {
@@ -12287,6 +12326,7 @@ function createHandler({ connection, service, settings = () => ({ label: "", pre
12287
12326
  if (route === "GET settings") return sendJson(res, 200, settings());
12288
12327
  if (route === "GET locales") return sendJson(res, 200, await (locales ??= readLocales(localeDir, logger)));
12289
12328
  if (route === "GET sources") return sendJson(res, 200, { sources: await hub.sources() });
12329
+ if (route === "GET trending") return sendJson(res, 200, await hub.trending(query("source"), query("kind")));
12290
12330
  if (route === "GET search") return sendJson(res, 200, await hub.search(query("source"), query("q"), query("kind") || void 0, Math.max(0, Number.parseInt(query("offset"), 10) || 0), parseFilters(query)));
12291
12331
  }
12292
12332
  return sendText(res, 404, "Not found.");
@@ -13998,53 +14038,34 @@ function parsePicks(document2, hasSource, limit = PICKS_LIMIT) {
13998
14038
  const out = [];
13999
14039
  const seen = /* @__PURE__ */ new Set();
14000
14040
  for (const pick5 of document2.picks) {
14001
- const work = pick5?.work;
14041
+ const raw = pick5?.work;
14002
14042
  const why = typeof pick5?.why === "string" ? pick5.why.trim().slice(0, MAX_WHY_CHARS) : "";
14003
- if (typeof work?.source !== "string" || !hasSource(work.source) || typeof work.id !== "string" || work.id === "" || typeof work.title !== "string" || why === "") continue;
14004
- const key = `${work.source}\0${work.id}`;
14043
+ if (typeof raw?.source !== "string" || !hasSource(raw.source) || why === "") continue;
14044
+ const work = resultOf(raw, null);
14045
+ if (work === null || work.title === "") continue;
14046
+ const key = `${raw.source}\0${work.id}`;
14005
14047
  if (seen.has(key)) continue;
14006
14048
  seen.add(key);
14007
- out.push({
14008
- work: {
14009
- source: work.source,
14010
- id: work.id,
14011
- title: work.title.slice(0, 200),
14012
- kind: typeof work.kind === "string" ? work.kind : null,
14013
- year: Number.isInteger(work.year) ? work.year : null,
14014
- score: Number.isFinite(work.score) ? work.score : null,
14015
- scoreLabel: typeof work.scoreLabel === "string" ? work.scoreLabel.slice(0, 40) : "",
14016
- cover: typeof work.cover === "string" ? work.cover : null,
14017
- url: typeof work.url === "string" ? work.url : null
14018
- },
14019
- why
14020
- });
14049
+ out.push({ work: { ...work, source: raw.source, scoreLabel: typeof raw.scoreLabel === "string" ? raw.scoreLabel.slice(0, 40) : "" }, why });
14021
14050
  if (out.length >= limit) break;
14022
14051
  }
14023
14052
  return out;
14024
14053
  }
14025
- function createPicks({ command, env = {}, cwd, hasSource, decorate, logger, now = Date.now, refreshMs = 6 * 36e5 }) {
14026
- const cached = /* @__PURE__ */ new Map();
14027
- async function ask(person) {
14028
- const argv = [...command, "recommend", "--json", "--limit", String(PICKS_LIMIT), ...person.id ? ["--person", person.id] : []];
14029
- const result = await run(argv, { timeoutMs: PICKS_TIMEOUT_MS, cwd, env });
14030
- if (result.code !== 0) throw new Error(`exit ${result.code}: ${result.stderr.trim().split("\n").pop() ?? ""}`);
14031
- return parsePicks(JSON.parse(result.stdout), hasSource).map(decorate);
14032
- }
14033
- return {
14034
- enabled: command.length > 0,
14035
- /** @param {{ key: string, id: string }} person */
14036
- async list(person) {
14037
- if (command.length === 0) return [];
14038
- const entry = cached.get(person.key);
14039
- if (entry && now() - entry.at < refreshMs) return entry.picks;
14040
- const picks = await ask(person).catch((error) => {
14041
- logger.warn("the recommender gave no picks: %s", error.message);
14042
- return [];
14043
- });
14044
- cached.set(person.key, { at: now(), picks });
14045
- return picks;
14046
- }
14047
- };
14054
+ async function recommend({ command, env = {}, cwd, hasSource }, { person, source, kind, language, limit = PICKS_LIMIT }) {
14055
+ const argv = [
14056
+ ...command,
14057
+ "recommend",
14058
+ "--json",
14059
+ "--limit",
14060
+ String(limit),
14061
+ ...person.id ? ["--person", person.id] : [],
14062
+ ...source ? ["--source", source] : [],
14063
+ ...kind ? ["--kind", kind] : [],
14064
+ ...language ? ["--language", language] : []
14065
+ ];
14066
+ const result = await run(argv, { timeoutMs: PICKS_TIMEOUT_MS, cwd, env });
14067
+ if (result.code !== 0) throw new Error(`exit ${result.code}: ${result.stderr.trim().split("\n").pop() ?? ""}`);
14068
+ return parsePicks(JSON.parse(result.stdout), hasSource, limit);
14048
14069
  }
14049
14070
 
14050
14071
  // src/shows.js
@@ -14610,6 +14631,116 @@ function createFollows({ library, source, refreshed, addSeason, record, notify,
14610
14631
  };
14611
14632
  }
14612
14633
 
14634
+ // src/points.js
14635
+ var EXTRAS = Object.freeze({
14636
+ newSeries: Object.freeze({
14637
+ key: "media:new_series",
14638
+ name: "Start a new series",
14639
+ cost: 30,
14640
+ about: "Begin watching a series that is new to the library; going on with one stays free"
14641
+ }),
14642
+ bingeNight: Object.freeze({
14643
+ key: "media:binge_night",
14644
+ name: "Binge night",
14645
+ cost: 40,
14646
+ uses: 0,
14647
+ about: "Start watching late at night, as often as you like, until morning"
14648
+ })
14649
+ });
14650
+ var CLOCK = /^([01]?\d|2[0-3]):([0-5]\d)$/;
14651
+ var minutes = (text3) => {
14652
+ const [, h, m] = CLOCK.exec(text3);
14653
+ return Number(h) * 60 + Number(m);
14654
+ };
14655
+ function inNight(night, date2) {
14656
+ const now = date2.getHours() * 60 + date2.getMinutes();
14657
+ const from2 = minutes(night.from);
14658
+ const to = minutes(night.to);
14659
+ return from2 <= to ? now >= from2 && now < to : now >= from2 || now < to;
14660
+ }
14661
+ function nightOf(night, date2) {
14662
+ const evening = new Date(date2);
14663
+ if (minutes(night.from) > minutes(night.to) && date2.getHours() * 60 + date2.getMinutes() < minutes(night.to)) evening.setDate(evening.getDate() - 1);
14664
+ const pad = (n) => String(n).padStart(2, "0");
14665
+ return `${evening.getFullYear()}-${pad(evening.getMonth() + 1)}-${pad(evening.getDate())}`;
14666
+ }
14667
+ var pointsError = (need) => Object.assign(new Error(`${need.name} costs ${need.cost} points`), { code: "points", status: 402, points: need });
14668
+ function createPoints(config, { logger, now = Date.now, run: run3 = run }) {
14669
+ const enabled = config.command.length > 0;
14670
+ const registered = /* @__PURE__ */ new Set();
14671
+ async function ask(args) {
14672
+ const { code, stdout, stderr } = await run3([...config.command, ...args, "--json"], { timeoutMs: 2e4, env: config.env });
14673
+ const line = stdout.trim().split("\n").filter(Boolean).pop() ?? "";
14674
+ if (code !== 0) throw Object.assign(new Error(`points extension failed: ${stderr.trim().split("\n").pop() ?? code}`), { code: "unavailable" });
14675
+ return JSON.parse(line);
14676
+ }
14677
+ function itemArgs(extra2) {
14678
+ const args = ["--name", extra2.name, "--cost", String(extra2.cost), "--about", extra2.about];
14679
+ if (extra2.uses !== void 0) args.push("--uses", String(extra2.uses));
14680
+ if (extra2 === EXTRAS.bingeNight) args.push("--until", config.night.to);
14681
+ return args;
14682
+ }
14683
+ async function register(person) {
14684
+ if (registered.has(person)) return true;
14685
+ for (const extra2 of Object.values(EXTRAS)) {
14686
+ const answer = await ask(["shop", person, "register", extra2.key, ...itemArgs(extra2)]);
14687
+ if (answer.recorded === false) return false;
14688
+ }
14689
+ registered.add(person);
14690
+ return true;
14691
+ }
14692
+ return {
14693
+ enabled,
14694
+ /** Which extras an action needs now: `isNew` for a new series, `starts` when it starts watching. */
14695
+ wants({ isNew = false, starts = false }) {
14696
+ if (!enabled) return [];
14697
+ return [...isNew ? [EXTRAS.newSeries] : [], ...starts && inNight(config.night, new Date(now())) ? [EXTRAS.bingeNight] : []];
14698
+ },
14699
+ /** A purchase's source, the same on a retry: one per series, one binge ticket per night. */
14700
+ sourceOf(extra2, subject) {
14701
+ return extra2 === EXTRAS.bingeNight ? `media:binge:${nightOf(config.night, new Date(now()))}` : `media:series:${subject}`;
14702
+ },
14703
+ /**
14704
+ * Make sure `person` holds a ticket for every extra in `wants`, buying the ones named in `buy`. Throws a
14705
+ * `points` error (402) with the first missing one: item, name, cost, balance, gap, affordable, pending.
14706
+ * Returns the tickets to use once the action went through.
14707
+ */
14708
+ async pay(person, wants, { buy = [], subject = "" } = {}) {
14709
+ if (!enabled || wants.length === 0 || !person) return [];
14710
+ try {
14711
+ if (!await register(person)) return [];
14712
+ const tickets = [];
14713
+ for (const extra2 of wants) {
14714
+ const source = this.sourceOf(extra2, subject);
14715
+ let answer = await ask(["check", person, extra2.key]);
14716
+ if (answer.recorded === false) return [];
14717
+ if (!answer.valid && buy.includes(extra2.key) && answer.quote.affordable) {
14718
+ await ask(["buy", person, extra2.key, "--source", source]);
14719
+ answer = await ask(["check", person, extra2.key]);
14720
+ }
14721
+ if (!answer.valid) {
14722
+ const q = answer.quote;
14723
+ throw pointsError({ item: extra2.key, name: q.name, cost: q.cost, balance: q.balance, gap: q.gap, affordable: q.affordable, pending: answer.pending });
14724
+ }
14725
+ tickets.push({ extra: extra2, ticket: answer.ticket.id });
14726
+ }
14727
+ return tickets;
14728
+ } catch (error) {
14729
+ if (error.code === "points") throw error;
14730
+ logger.warn("points: %s", error.message);
14731
+ return [];
14732
+ }
14733
+ },
14734
+ /** Record each ticket's use for the action that went through: a series once, a binge ticket per room opened. */
14735
+ async use(person, tickets, { room, subject = "" }) {
14736
+ for (const { extra: extra2, ticket } of tickets) {
14737
+ const on = extra2 === EXTRAS.bingeNight ? `media:start:${room ?? subject}` : `media:series:${subject}`;
14738
+ await ask(["use", person, ticket, "--source", on]).catch((error) => logger.warn("points: %s", error.message));
14739
+ }
14740
+ }
14741
+ };
14742
+ }
14743
+
14613
14744
  // src/changes.js
14614
14745
  function createChanges({ intervalMs = 300 } = {}) {
14615
14746
  const listeners = /* @__PURE__ */ new Set();
@@ -14643,10 +14774,132 @@ function createChanges({ intervalMs = 300 } = {}) {
14643
14774
  };
14644
14775
  }
14645
14776
 
14646
- // src/work-refresh.js
14777
+ // src/copies.js
14778
+ import { mkdir as mkdir10, readFile as readFile11, rename as rename8, writeFile as writeFile7 } from "node:fs/promises";
14779
+ import { dirname as dirname6 } from "node:path";
14647
14780
  var DAY_MS3 = 864e5;
14648
14781
  var HOUR_MS = 36e5;
14649
- function createWorkRefresh({ source, keep, maxAgeMs = DAY_MS3, retryMs = HOUR_MS, parallel = 2, now = Date.now, logger }) {
14782
+ function createCopies({ file, changed, logger, maxAgeMs = DAY_MS3, retryMs = HOUR_MS, parallel = 2, now = Date.now }) {
14783
+ const copies = /* @__PURE__ */ new Map();
14784
+ const flying = /* @__PURE__ */ new Set();
14785
+ const failedAt = /* @__PURE__ */ new Map();
14786
+ const waiting = [];
14787
+ let running = 0;
14788
+ let saving = Promise.resolve();
14789
+ const loaded = readFile11(file, "utf8").then((text3) => {
14790
+ for (const [key, copy] of Object.entries(JSON.parse(text3))) copies.set(key, copy);
14791
+ }).catch((error) => {
14792
+ if (error.code !== "ENOENT") logger.warn("the saved copies of Discover could not be read: %s", error.message);
14793
+ });
14794
+ function save() {
14795
+ saving = saving.then(async () => {
14796
+ await mkdir10(dirname6(file), { recursive: true });
14797
+ await writeFile7(`${file}.part`, JSON.stringify(Object.fromEntries(copies)));
14798
+ await rename8(`${file}.part`, file);
14799
+ }).catch((error) => logger.warn("the copies of Discover could not be saved: %s", error.message));
14800
+ return saving;
14801
+ }
14802
+ function pump() {
14803
+ while (running < parallel && waiting.length > 0) {
14804
+ running += 1;
14805
+ waiting.shift()().finally(() => {
14806
+ running -= 1;
14807
+ pump();
14808
+ });
14809
+ }
14810
+ }
14811
+ function ask(key, produce) {
14812
+ flying.add(key);
14813
+ waiting.push(async () => {
14814
+ try {
14815
+ copies.set(key, { at: now(), value: await produce() });
14816
+ failedAt.delete(key);
14817
+ await save();
14818
+ changed();
14819
+ } catch (error) {
14820
+ failedAt.set(key, now());
14821
+ logger.warn("no new copy of %s: %s", key, error.message);
14822
+ changed();
14823
+ } finally {
14824
+ flying.delete(key);
14825
+ }
14826
+ });
14827
+ pump();
14828
+ }
14829
+ return {
14830
+ /**
14831
+ * @param {string} key
14832
+ * @param {() => Promise<unknown>} produce - the outside answer, asked only when the copy is missing or old
14833
+ * @returns {Promise<{ at: number | null, value: unknown, loading: boolean }>} `loading`: no copy yet and one is on its way; `failed`: no copy and the last ask failed
14834
+ */
14835
+ async get(key, produce) {
14836
+ await loaded;
14837
+ const copy = copies.get(key);
14838
+ const old = copy === void 0 || now() - copy.at >= maxAgeMs;
14839
+ if (old && !flying.has(key) && now() - (failedAt.get(key) ?? -Infinity) >= retryMs) ask(key, produce);
14840
+ return { at: copy?.at ?? null, value: copy?.value ?? null, loading: copy === void 0 && flying.has(key), failed: copy === void 0 && failedAt.has(key) };
14841
+ }
14842
+ };
14843
+ }
14844
+
14845
+ // src/discover.js
14846
+ var DISCOVER_PICKS = 12;
14847
+ var notFound = (message) => Object.assign(new Error(message), { code: "not_found" });
14848
+ function createDiscover({ copies, sources, covers, recommender }) {
14849
+ async function sourcesFor(sourceId, kind, ability) {
14850
+ if (sourceId !== ALL_SOURCES) {
14851
+ const one = sources.get(sourceId);
14852
+ if (one === void 0) throw notFound(`no source ${String(sourceId)}`);
14853
+ return [one];
14854
+ }
14855
+ const found = [];
14856
+ for (const one of sources.values()) {
14857
+ if (one.kinds.some((entry) => entry.id === kind && ability(entry)) && await one.available()) found.push(one);
14858
+ }
14859
+ return found;
14860
+ }
14861
+ const withCovers = (one, work) => ({ ...covers.decorate(one.id, work), source: one.id });
14862
+ return {
14863
+ /**
14864
+ * @returns {Promise<{ trending: { source: string, at: number, lists: object[] }[], loading: boolean }>} `loading`: some source has no copy yet
14865
+ */
14866
+ async trending(sourceId, kind) {
14867
+ const wanted = (await sourcesFor(sourceId, kind, (entry) => entry.trending === true)).filter((one) => typeof one.trending === "function" && one.kinds.some((entry) => entry.id === kind && entry.trending === true));
14868
+ const copy = await Promise.all(wanted.map((one) => copies.get(`trending|${one.id}|${kind}`, () => one.trending(kind))));
14869
+ return {
14870
+ trending: wanted.flatMap((one, index) => copy[index].value === null ? [] : [{
14871
+ source: one.id,
14872
+ at: copy[index].at,
14873
+ lists: copy[index].value.map((list) => ({ ...list, results: list.results.map((work) => withCovers(one, work)) }))
14874
+ }]),
14875
+ loading: copy.some((entry) => entry.loading)
14876
+ };
14877
+ },
14878
+ /**
14879
+ * A person's picks for a source and category (merged under All sources), or without either (the Watching tab).
14880
+ * @returns {Promise<{ picks: object[], loading: boolean }>}
14881
+ */
14882
+ async picks(person, { source: sourceId = "", kind = "", language = "" } = {}) {
14883
+ if (recommender.command.length === 0) return { picks: [], loading: false };
14884
+ const narrowed = sourceId !== "";
14885
+ const targets = narrowed ? await sourcesFor(sourceId, kind, () => true) : [null];
14886
+ const copy = await Promise.all(targets.map((one) => copies.get(
14887
+ `picks|${person.key}|${one?.id ?? "*"}|${narrowed ? kind : "*"}|${language}`,
14888
+ () => recommend(recommender, { person, source: one?.id, kind: narrowed ? kind : void 0, language, limit: narrowed ? DISCOVER_PICKS : PICKS_LIMIT })
14889
+ )));
14890
+ const lists = copy.map((entry, index) => (entry.value ?? []).filter((pick5) => targets[index] === null || pick5.work.source === targets[index].id && (kind === "" || pick5.work.kind === kind)));
14891
+ return {
14892
+ picks: interleave(lists).map((pick5) => ({ ...pick5, work: withCovers(sources.get(pick5.work.source), pick5.work) })).slice(0, narrowed ? DISCOVER_PICKS : PICKS_LIMIT),
14893
+ loading: copy.some((entry) => entry.loading)
14894
+ };
14895
+ }
14896
+ };
14897
+ }
14898
+
14899
+ // src/work-refresh.js
14900
+ var DAY_MS4 = 864e5;
14901
+ var HOUR_MS2 = 36e5;
14902
+ function createWorkRefresh({ source, keep, maxAgeMs = DAY_MS4, retryMs = HOUR_MS2, parallel = 2, now = Date.now, logger }) {
14650
14903
  const flying = /* @__PURE__ */ new Set();
14651
14904
  const failedAt = /* @__PURE__ */ new Map();
14652
14905
  const waiting = [];
@@ -14684,7 +14937,7 @@ ${entry.source.id}`;
14684
14937
  }
14685
14938
 
14686
14939
  // src/media.js
14687
- var HOUR_MS2 = 36e5;
14940
+ var HOUR_MS3 = 36e5;
14688
14941
  var MIN_FREE_BYTES = 1e9;
14689
14942
  var NO_CONVERTER = Object.freeze({ command: "", available: async () => false });
14690
14943
  var hubError = (code, message) => Object.assign(new Error(message), { code });
@@ -14694,6 +14947,7 @@ function createMediaHub(options) {
14694
14947
  const covers = createCovers({ dir: join16(stateDir, "covers"), capBytes: options.coverCacheBytes, ffmpeg: options.tools.ffmpeg, logger }, (id) => sources.get(id));
14695
14948
  const log = createWatchLog({ file: join16(stateDir, LOG_NAME), now, logger });
14696
14949
  const changes = createChanges({ intervalMs: options.changeIntervalMs });
14950
+ const points = createPoints(options.points ?? { command: [], night: { from: "01:00", to: "06:00" } }, { logger, now });
14697
14951
  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
14952
  let rooms;
14699
14953
  let cache;
@@ -14748,21 +15002,19 @@ function createMediaHub(options) {
14748
15002
  cache.refresh(show).catch(() => {
14749
15003
  });
14750
15004
  });
14751
- const picks = createPicks({
14752
- command: options.recommender?.command ?? [],
14753
- env: options.recommender?.env ?? {},
14754
- cwd: stateDir,
14755
- hasSource: (id) => sources.has(id),
14756
- decorate: (pick5) => ({ ...pick5, work: covers.decorate(pick5.work.source, pick5.work) }),
14757
- logger,
14758
- now
15005
+ const copies = createCopies({ file: join16(stateDir, "discover.json"), changed: () => changes.notify("discover"), maxAgeMs: options.discoverMaxAgeMs, logger, now });
15006
+ const discover = createDiscover({
15007
+ copies,
15008
+ sources,
15009
+ covers,
15010
+ recommender: { command: options.recommender?.command ?? [], env: options.recommender?.env ?? {}, cwd: stateDir, hasSource: (id) => sources.has(id) }
14759
15011
  });
14760
15012
  const sweepTimer = setInterval(() => {
14761
15013
  library.sweep().catch(() => {
14762
15014
  });
14763
15015
  cache.enforce().catch(() => {
14764
15016
  });
14765
- }, HOUR_MS2);
15017
+ }, HOUR_MS3);
14766
15018
  async function onFiles(job) {
14767
15019
  changes.notify("library");
14768
15020
  await rooms.syncShow(job.dir);
@@ -14820,18 +15072,29 @@ function createMediaHub(options) {
14820
15072
  if (found === void 0) throw hubError("not_found", `no source ${String(id)}`);
14821
15073
  return found;
14822
15074
  }
14823
- async function folderFor(sourceId, item) {
14824
- const name2 = cleanName(item.title);
15075
+ async function isNewSeries(sourceId, item) {
15076
+ if (!(item.episodes > 1)) return false;
15077
+ const works = [item, ...(item.related ?? []).filter((other) => other.relation === "season" && other.id)];
15078
+ const inLibrary = new Set((await library.list()).shows.filter((show) => show.source).map((show) => `${show.source.source}
15079
+ ${show.source.id}`));
15080
+ const logged = new Set((await log.read()).map((event) => event.show).filter(Boolean));
15081
+ return !works.some((work) => inLibrary.has(`${sourceId}
15082
+ ${work.id}`) || foldersFor(sourceId, work).some((path) => logged.has(path)));
15083
+ }
15084
+ function foldersFor(sourceId, work) {
15085
+ const name2 = cleanName(work.title ?? "");
14825
15086
  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);
15087
+ ${work.id}`).digest("hex").slice(0, 8);
15088
+ return [name2, `${name2} (${mark})`].map((candidate) => join16(libraryRoots[0], candidate));
15089
+ }
15090
+ async function folderFor(sourceId, item) {
15091
+ for (const path of foldersFor(sourceId, item)) {
14829
15092
  const exists2 = await stat10(path).then(() => true, () => false);
14830
15093
  const shows = (await library.list()).shows;
14831
15094
  const owner = shows.find((show) => show.path === path);
14832
15095
  if (!exists2 || owner?.source?.source === sourceId && owner.source.id === item.id) return path;
14833
15096
  }
14834
- throw hubError("exists", `${name2} is already in the library`);
15097
+ throw hubError("exists", `${cleanName(item.title)} is already in the library`);
14835
15098
  }
14836
15099
  return {
14837
15100
  async load() {
@@ -14849,6 +15112,8 @@ ${item.id}`).digest("hex").slice(0, 8);
14849
15112
  * `start` says otherwise.
14850
15113
  */
14851
15114
  async createRoom(input) {
15115
+ const person = typeof input.person === "string" ? input.person : "";
15116
+ const tickets = await points.pay(person, points.wants({ starts: true }), { buy: input.buy ?? [] });
14852
15117
  let start = input.start ?? null;
14853
15118
  if (start === null && typeof input.path === "string") {
14854
15119
  const show2 = library.showPath(input.path);
@@ -14858,7 +15123,9 @@ ${item.id}`).digest("hex").slice(0, 8);
14858
15123
  const show = typeof input.path === "string" ? library.showPath(input.path) : null;
14859
15124
  const from2 = show === null ? null : library.workSource(show);
14860
15125
  if (from2 && typeof input.person === "string" && from2.person !== input.person) library.mark(show, { source: { ...from2, person: input.person } });
14861
- return rooms.createRoom({ ...input, start });
15126
+ const opened = await rooms.createRoom({ ...input, start });
15127
+ await points.use(person, tickets, { room: opened.room?.id });
15128
+ return opened;
14862
15129
  },
14863
15130
  watchTogether: (id) => rooms.watchTogether(id),
14864
15131
  waitReady: (...args) => rooms.waitReady(...args),
@@ -14888,7 +15155,8 @@ ${item.id}`).digest("hex").slice(0, 8);
14888
15155
  changes.notify("library");
14889
15156
  return { ok: true };
14890
15157
  },
14891
- picks: (person) => picks.list(person),
15158
+ trending: (sourceId, kind) => discover.trending(sourceId, kind),
15159
+ picks: (person, narrow) => discover.picks(person, narrow),
14892
15160
  /** Keep a recap or suggested steps with a show (the tool's annotate). */
14893
15161
  annotate(path, input) {
14894
15162
  const show = library.annotate(path, parseAnnotation(input));
@@ -14954,18 +15222,22 @@ ${item.id}`).digest("hex").slice(0, 8);
14954
15222
  * whose account (`person`, the one asking) and the viewer's `language`, for the captions chosen with each episode.
14955
15223
  * @param {{ source: string, id: string, watch?: boolean, all?: boolean, quality?: string, by?: string, person?: string, language?: string }} input
14956
15224
  */
14957
- async fetch({ source: sourceId, id, watch = false, together = false, all = false, quality = "", by = "", person = "", language = "" }) {
15225
+ async fetch({ source: sourceId, id, watch = false, together = false, all = false, quality = "", by = "", person = "", language = "", buy = [] }) {
14958
15226
  const item = await source(sourceId).info(id, { person, language });
14959
15227
  if (!(item.episodes > 0)) throw hubError("empty", `${item.title || id} has no episodes`);
15228
+ const dir = await folderFor(sourceId, item);
15229
+ const subject = `${sourceId}:${item.id}`;
15230
+ const isNew = points.enabled && await isNewSeries(sourceId, item);
14960
15231
  const disk = await statfs2(libraryRoots[0]).catch(() => null);
14961
15232
  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);
15233
+ const tickets = await points.pay(person, points.wants({ isNew, starts: watch }), { buy, subject });
14963
15234
  const how = { ...isQuality(quality) ? { quality } : {}, person, language };
14964
15235
  await library.adopt(dir, { source: sourceId, id: item.id, kind: item.kind, episodes: item.episodes, title: item.title, ...how }, { pinned: all });
14965
15236
  library.setWork(dir, snapshotOf(item, now()));
14966
15237
  let room = null;
14967
15238
  if (watch) room = (await rooms.createRoom({ source: "local", path: dir, title: item.title, by, person, together, start: await library.resumeFrom(dir) })).room;
14968
15239
  else await cache.refresh(dir, { retry: true });
15240
+ await points.use(person, tickets, { room: room?.id, subject });
14969
15241
  const count = all ? item.episodes : Math.min(item.episodes, options.cache.ahead + 1);
14970
15242
  return { path: dir, title: item.title, episodes: item.episodes, estimate: count * (EPISODE_BYTES[item.kind] ?? EPISODE_BYTES.drama), room, download: downloads.state(dir) };
14971
15243
  },
@@ -15063,6 +15335,7 @@ async function body(request) {
15063
15335
  }
15064
15336
  var pick4 = (value, keys) => Object.fromEntries(keys.filter((key) => value?.[key] !== void 0).map((key) => [key, value[key]]));
15065
15337
  var text2 = (value) => typeof value === "string" ? value : "";
15338
+ var buying = (value) => Array.isArray(value) ? value.filter((key) => typeof key === "string").slice(0, 4) : [];
15066
15339
  function createPersonRoutes({ hub, identity }) {
15067
15340
  const handle = (fn) => async (request) => {
15068
15341
  const current = hub();
@@ -15087,14 +15360,17 @@ function createPersonRoutes({ hub, identity }) {
15087
15360
  requestBody: "buffered",
15088
15361
  fetch: handle(async (request, current, person) => {
15089
15362
  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 });
15363
+ return current.fetch({ ...pick4(input, ["source", "id", "watch", "together", "all", "quality", "by"]), language: text2(input.language), person: person.id, buy: buying(input.buy) });
15091
15364
  })
15092
15365
  },
15093
15366
  {
15094
15367
  path: `${PERSON_PATH}/rooms`,
15095
15368
  methods: ["POST"],
15096
15369
  requestBody: "buffered",
15097
- fetch: handle(async (request, current, person) => current.createRoom({ ...pick4(await body(request), ["path", "title", "by", "start"]), fromPanel: true, person: person.id }))
15370
+ fetch: handle(async (request, current, person) => {
15371
+ const input = await body(request);
15372
+ return current.createRoom({ ...pick4(input, ["path", "title", "by", "start"]), fromPanel: true, person: person.id, buy: buying(input.buy) });
15373
+ })
15098
15374
  },
15099
15375
  {
15100
15376
  path: `${PERSON_PATH}/ratings`,
@@ -15106,7 +15382,7 @@ function createPersonRoutes({ hub, identity }) {
15106
15382
  path: `${PERSON_PATH}/picks`,
15107
15383
  methods: ["GET"],
15108
15384
  requestBody: "buffered",
15109
- fetch: handle(async (request, current, person) => ({ picks: await current.picks(person) }))
15385
+ fetch: handle((request, current, person) => current.picks(person, { source: param(request, "source"), kind: param(request, "kind"), language: param(request, "language") }))
15110
15386
  },
15111
15387
  {
15112
15388
  path: `${PERSON_PATH}/steps`,
@@ -15227,7 +15503,7 @@ function createShelfRoutes({ books, identity }) {
15227
15503
  var name = "dsh-media-hub";
15228
15504
  var inject = ["webServer", "connection"];
15229
15505
  var ROOM_ID = /^[A-Za-z0-9_-]{6,32}$/;
15230
- var DAY_MS4 = 864e5;
15506
+ var DAY_MS5 = 864e5;
15231
15507
  function apply(ctx, config) {
15232
15508
  const logger = ctx.logger("media-hub");
15233
15509
  let current;
@@ -15250,6 +15526,7 @@ function apply(ctx, config) {
15250
15526
  },
15251
15527
  notifyCommand: config.notifyCommand,
15252
15528
  recommender: config.recommender,
15529
+ points: config.points,
15253
15530
  cache: { ahead: config.cacheAhead, behind: config.cacheBehind, capBytes: config.cacheLimitGb * 1e9 },
15254
15531
  logger
15255
15532
  });
@@ -15262,7 +15539,7 @@ function apply(ctx, config) {
15262
15539
  const prune = setInterval(() => {
15263
15540
  service.pruneCache(config.cacheDays).catch(() => {
15264
15541
  });
15265
- }, DAY_MS4);
15542
+ }, DAY_MS5);
15266
15543
  const identity = () => ctx.get("requestIdentity");
15267
15544
  const fetchRoutes = [
15268
15545
  ...createShelfRoutes({ books: () => current?.books, identity }),
package/locale/en.json CHANGED
@@ -267,10 +267,25 @@
267
267
  "ratings.unfinished": "Didn't finish",
268
268
  "picks.heading": "Picks",
269
269
  "picks.hint": "Each with why it was picked",
270
+ "feed.picks": "For you",
271
+ "feed.picksHint": "Each with why it was picked",
272
+ "feed.trending": "Trending",
273
+ "feed.updated": "Updated {when}",
274
+ "feed.all": "Show all",
275
+ "feed.fewer": "Show fewer",
276
+ "feed.loading": "Fetching more from the sources…",
270
277
  "continue.joinOne": "Join {names}",
271
278
  "continue.continueAt": "Continue at {time}",
272
279
  "continue.play": "Play",
273
280
  "library.continueAt": "continue at {time}",
274
- "library.viewerStoppedAt": "{name} stopped at {time}"
281
+ "library.viewerStoppedAt": "{name} stopped at {time}",
282
+ "points.newSeries": "Starting a new series",
283
+ "points.bingeNight": "A binge night",
284
+ "points.offer": "{name} costs {cost} points. You have {balance}.",
285
+ "points.short": "{name} costs {cost} points: {gap} more to go.",
286
+ "points.pending": "{name} is waiting for approval.",
287
+ "points.buy": "Buy",
288
+ "points.notNow": "Not now",
289
+ "points.ok": "OK"
275
290
  }
276
291
  }
package/locale/fr.json CHANGED
@@ -267,10 +267,25 @@
267
267
  "ratings.unfinished": "Pas fini",
268
268
  "picks.heading": "Suggestions",
269
269
  "picks.hint": "Chacune avec la raison du choix",
270
+ "feed.picks": "Pour vous",
271
+ "feed.picksHint": "Chaque suggestion avec sa raison",
272
+ "feed.trending": "Tendances",
273
+ "feed.updated": "Mis à jour {when}",
274
+ "feed.all": "Tout afficher",
275
+ "feed.fewer": "Réduire",
276
+ "feed.loading": "Récupération d'autres résultats auprès des sources…",
270
277
  "continue.joinOne": "Rejoindre {names}",
271
278
  "continue.continueAt": "Reprendre à {time}",
272
279
  "continue.play": "Lire",
273
280
  "library.continueAt": "reprendre à {time}",
274
- "library.viewerStoppedAt": "{name} s’est arrêté·e à {time}"
281
+ "library.viewerStoppedAt": "{name} s’est arrêté·e à {time}",
282
+ "points.newSeries": "Commencer une nouvelle série",
283
+ "points.bingeNight": "Une nuit de marathon",
284
+ "points.offer": "{name} coûte {cost} points. Vous en avez {balance}.",
285
+ "points.short": "{name} coûte {cost} points : encore {gap} à gagner.",
286
+ "points.pending": "{name} attend un accord.",
287
+ "points.buy": "Acheter",
288
+ "points.notNow": "Pas maintenant",
289
+ "points.ok": "OK"
275
290
  }
276
291
  }
package/locale/zh.json CHANGED
@@ -267,10 +267,25 @@
267
267
  "ratings.unfinished": "没看完",
268
268
  "picks.heading": "推荐",
269
269
  "picks.hint": "每部都写了推荐理由",
270
+ "feed.picks": "为你推荐",
271
+ "feed.picksHint": "每个都带着推荐的理由",
272
+ "feed.trending": "热门",
273
+ "feed.updated": "{when}更新",
274
+ "feed.all": "显示全部",
275
+ "feed.fewer": "收起",
276
+ "feed.loading": "正在从来源获取更多…",
270
277
  "continue.joinOne": "加入{names}",
271
278
  "continue.continueAt": "从 {time} 继续",
272
279
  "continue.play": "播放",
273
280
  "library.continueAt": "从 {time} 继续",
274
- "library.viewerStoppedAt": "{name}看到 {time}"
281
+ "library.viewerStoppedAt": "{name}看到 {time}",
282
+ "points.newSeries": "开一部新剧",
283
+ "points.bingeNight": "通宵追剧夜",
284
+ "points.offer": "{name}要 {cost} 分,你现在有 {balance} 分。",
285
+ "points.short": "{name}要 {cost} 分,还差 {gap} 分。",
286
+ "points.pending": "{name}还在等批准。",
287
+ "points.buy": "兑换",
288
+ "points.notNow": "先不了",
289
+ "points.ok": "好"
275
290
  }
276
291
  }
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.10.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'))
@@ -3,7 +3,8 @@
3
3
  * pasting the address of a video or playlist on any site yt-dlp reads), under
4
4
  * it that source's own categories, then search; Link looks the address up
5
5
  * and shows it as one result. Book categories add a filter row (language, format, years, size).
6
- * Results are cards: a show or audiobook (web/result-card.js) is watched
6
+ * Before any search the area below shows what the sources put forward and the
7
+ * recommender's picks for the category (web/feed-view.js). Results are cards: a show or audiobook (web/result-card.js) is watched
7
8
  * together right away, saved to the library (the episodes being watched and
8
9
  * the next few are kept on disk), or downloaded whole to keep offline; a
9
10
  * book (web/books-view.js) is downloaded in a format onto the person's shelf.
@@ -15,6 +16,7 @@
15
16
  */
16
17
  import { BookCard, BookFilters } from './books-view.js'
17
18
  import { browserStorage, isWebAddress, pickKind, pickSource, readMemory, remember, takesUrl, withAll } from './nav.js'
19
+ import { DiscoverFeed } from './feed-view.js'
18
20
  import { Result } from './result-card.js'
19
21
  import { sortModes, sortResults } from './sort.js'
20
22
  import { infoOf } from './details.js'
@@ -171,6 +173,7 @@ export function DiscoverView({ t, nav, onNav, onOpen, onSaved, onBack }) {
171
173
  !isLink && isBook(kind) && h(BookFilters, { t, filters, languages: languageChoices(t.language, shown ? results.items : [], filters.language), onChange: filter }),
172
174
  error && h('p', { className: 'vsync-error', role: 'alert' }, error),
173
175
  !searching && shown && results.failed.length > 0 && h('p', { className: 'vsync-note', role: 'status' }, results.failed.map(one => fill(t('search.sourceFailed'), { source: sourceOf(one.source)?.label ?? one.source, message: one.message })).join(' ')),
176
+ !isLink && source !== null && results === null && loading === null && h(DiscoverFeed, { t, sourceId: source.id, kind, sourceOf, isBook, onOpen, onSaved, onFocus }),
174
177
  searching && h('div', { className: 'vsync-skeleton', role: 'status', 'aria-busy': 'true', 'aria-label': t('search.loading') },
175
178
  [0, 1, 2].map(n => h('span', { key: n, className: 'vsync-skeletonRow' }))),
176
179
  !searching && shown && results.items.length > 1 && modes.length > 1 && h('div', { className: 'vsync-tabs vsync-sort', role: 'group', 'aria-label': t('sort.label') },
@@ -0,0 +1,89 @@
1
+ /**
2
+ * What Discover shows before a search, for the source and category picked:
3
+ * "For you" (the recommender's picks, each with its reason) and one list per
4
+ * board the source itself puts forward (its rank lists, new arrivals). Under
5
+ * All sources the picks of every source are interleaved and each source's lists
6
+ * follow, headed by the source. Both come from dated copies the plugin keeps
7
+ * (src/copies.js), so the page never waits on a site: while a copy is first
8
+ * being made the area shows a loading state, and the plugin's change signal
9
+ * brings the answer. A source that offers neither shows nothing.
10
+ *
11
+ * The works are the same cards as search results.
12
+ */
13
+ import { BookCard } from './books-view.js'
14
+ import { pick } from './i18n.js'
15
+ import { Result } from './result-card.js'
16
+ import { Changes, K, Spinner, api, asPerson, fillNodes, h, query, React } from './ui.js'
17
+
18
+ /** Works of a list shown before "Show all". */
19
+ export const LIST_PREVIEW = 6
20
+
21
+ /** What the plugin has for one source and category: its trending lists and this person's picks. */
22
+ function useFeed(sourceId, kind, language) {
23
+ const { discover } = React.useContext(Changes)
24
+ const [feed, setFeed] = React.useState(null)
25
+ const key = `${sourceId}|${kind}|${language}`
26
+ React.useEffect(() => {
27
+ let live = true
28
+ const asked = query({ source: sourceId, kind })
29
+ Promise.all([api(`trending?${asked}`), asPerson(`picks?${asked}&${query({ language })}`)]).then(([trending, picks]) => {
30
+ if (!live) return
31
+ setFeed({
32
+ key,
33
+ trending: Array.isArray(trending.trending) ? trending.trending : [],
34
+ picks: Array.isArray(picks.picks) ? picks.picks : [],
35
+ loading: trending.loading === true || picks.loading === true,
36
+ })
37
+ })
38
+ return () => { live = false }
39
+ }, [key, discover])
40
+ return feed?.key === key ? feed : null
41
+ }
42
+
43
+ function Skeleton({ t }) {
44
+ return h('div', { className: 'vsync-skeleton', role: 'status', 'aria-busy': 'true', 'aria-label': t('search.loading') },
45
+ [0, 1, 2].map(n => h('span', { key: n, className: 'vsync-skeletonRow' })))
46
+ }
47
+
48
+ function FeedSection({ id, title, hint, children }) {
49
+ return h('section', { className: 'vsync-section vsync-feedSection', 'aria-labelledby': id },
50
+ h('div', { className: 'vsync-sectionHead vsync-sectionHeadInline' },
51
+ h('h2', { id }, title),
52
+ hint && h('span', { className: 'vsync-sectionMeta' }, hint)),
53
+ children)
54
+ }
55
+
56
+ export function DiscoverFeed({ t, sourceId, kind, sourceOf, isBook, onOpen, onSaved, onFocus }) {
57
+ const feed = useFeed(sourceId, kind ?? '', t.language)
58
+ const [expanded, setExpanded] = React.useState(() => new Set())
59
+ if (feed === null) return h(Skeleton, { t })
60
+ const { trending, picks, loading } = feed
61
+ if (trending.length === 0 && picks.length === 0) return loading ? h(Skeleton, { t }) : null
62
+
63
+ const card = (work) => {
64
+ const from = sourceOf(work.source)
65
+ if (from === undefined) return null
66
+ return isBook(work.kind, from)
67
+ ? h(BookCard, { key: `${from.id}:${work.id}`, t, source: from, result: work })
68
+ : h(Result, { key: `${from.id}:${work.id}`, t, source: from, result: work, onOpen, onSaved, onFocus })
69
+ }
70
+ const merged = sourceId === 'all'
71
+
72
+ return h('div', { className: 'vsync-feed' },
73
+ picks.length > 0 && h(FeedSection, { id: 'vsync-feed-picks', title: t('feed.picks'), hint: t('feed.picksHint') },
74
+ h('ul', { className: 'vsync-rows vsync-results' }, picks.map(entry => h('li', { key: `${entry.work.source}:${entry.work.id}`, className: 'vsync-feedPick' },
75
+ h('p', { className: 'vsync-pickWhy' }, h(K.Icon, { name: 'sparkles', size: 14, tone: 'violet' }), h('span', null, entry.why)),
76
+ h('ul', { className: 'vsync-rows' }, card(entry.work)))))),
77
+ trending.flatMap(({ source: from, at, lists }) => lists.map((list) => {
78
+ const id = `${from}:${list.id}`
79
+ const name = pick(list.label, t.language).trim() || t('feed.trending')
80
+ const title = merged ? `${sourceOf(from)?.label ?? from} · ${name}` : name
81
+ const all = expanded.has(id)
82
+ const shown = all ? list.results : list.results.slice(0, LIST_PREVIEW)
83
+ return h(FeedSection, { key: id, id: `vsync-feed-${id}`, title, hint: fillNodes(t('feed.updated'), { when: h(K.TimeAgo, { at: new Date(at).toISOString() }) }) },
84
+ h('ul', { className: 'vsync-rows vsync-results' }, shown.map(card)),
85
+ list.results.length > LIST_PREVIEW && h('button', { type: 'button', className: 'vsync-btn vsync-more', 'aria-expanded': String(all), onClick: () => setExpanded((current) => { const next = new Set(current); if (all) next.delete(id); else next.add(id); return next }) },
86
+ all ? t('feed.fewer') : t('feed.all')))
87
+ })),
88
+ loading && h('p', { className: 'vsync-note', role: 'status' }, h(Spinner), ' ', t('feed.loading')))
89
+ }
@@ -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)
@@ -91,16 +118,20 @@ export function Page({ t, initialRoom }) {
91
118
 
92
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.
93
120
  const [shelf, setShelf] = React.useState(0)
121
+ const [discover, setDiscover] = React.useState(0)
94
122
  const stream = K.useEventStream('api/media-hub/events', (message) => {
95
123
  if (message.what?.includes('shelf')) setShelf(count => count + 1)
124
+ if (message.what?.includes('discover')) setDiscover(count => count + 1)
96
125
  if (message.what?.some(kind => kind === 'library' || kind === 'rooms')) load()
97
126
  })
98
127
  React.useEffect(() => { if (stream === 'live') { load(); setShelf(count => count + 1) } }, [stream, load])
99
128
  React.useEffect(() => { load() }, [load])
100
129
 
101
130
  const known = React.useMemo(() => ({ library, rooms, reload: load }), [library, rooms, load])
102
- 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 })))
131
+ const changes = React.useMemo(() => ({ shelf, discover }), [shelf, discover])
132
+ return h(Changes.Provider, { value: changes }, h(Known.Provider, { value: known }, h(React.Fragment, null,
133
+ roomId === null
134
+ ? h(Home, { t, nav, go, onOpen: setRoomId, rooms, library, load })
135
+ : h(RoomView, { key: roomId, t, roomId, onLeave: () => setRoomId(null), onOpen: setRoomId }),
136
+ h(PointsOffer, { t }))))
106
137
  }
package/web/panel.css CHANGED
@@ -355,9 +355,18 @@
355
355
  @media (prefers-reduced-motion:reduce){.vsync-pickCard{transition:none}}
356
356
  .vsync-pickWhy{display:flex;gap:6px;font-size:13px;line-height:19px;color:var(--dsw-alias-label-secondary)}
357
357
  .vsync-pickWhy .uk-icon{margin-top:2px}
358
+ .vsync-feed{margin-top:8px}
359
+ .vsync-feedSection h2{color:var(--dsw-alias-label-primary);font-size:15px;font-weight:600;line-height:22px}
360
+ .vsync-feedPick{list-style:none;display:flex;flex-direction:column;gap:4px}
361
+ .vsync-feedPick .vsync-pickWhy{margin:0 4px}
362
+ .vsync-feedSection .vsync-more{display:flex;margin-top:0}
358
363
  .vsync-pickActions{margin-top:auto;padding-top:6px}
359
364
  @media (width<=640px){.vsync-cc{flex-direction:column;gap:14px}.vsync-ccPoster{width:112px;height:150px}.vsync-ccStrip .uk-segmentsLabelled{flex-wrap:wrap;row-gap:4px}.vsync-ccStrip .uk-segments{flex-basis:100%}}
360
365
  /* Interface chrome is not selectable and pictures don't drag; titles, recaps and reasons stay selectable. */
361
366
  .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
367
  .vsync-page img{-webkit-user-drag:none;user-select:none;-webkit-user-select:none}
363
368
  .vsync-ccActions .uk-touch,.vsync-pickActions .uk-touch,.vsync-rateAnswers .uk-touch{font-size:13px}
369
+ /* Points offer: an extra's price at the moment of the action */
370
+ .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)}
371
+ .vsync-pointsText{flex:1;min-width:0;font-size:13px;line-height:19px;color:var(--dsw-alias-label-primary)}
372
+ @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, Changes, Icon, K, P, React, asPerson, asPersonPaying, displayName, fillNodes, h, query } 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' },
@@ -88,7 +89,8 @@ function PickCard({ t, pick, onOpen, onOpenWork }) {
88
89
  }
89
90
 
90
91
  export function PicksSection({ t, on, onOpen, onOpenWork }) {
91
- const [picks] = usePersonList(on, 'picks', 'picks', 0)
92
+ const { discover } = React.useContext(Changes)
93
+ const [picks] = usePersonList(on, `picks?${query({ language: t.language })}`, 'picks', discover)
92
94
  if (!picks || picks.length === 0) return null
93
95
  return h(Section, { id: 'vsync-picks', title: t('picks.heading'), hint: t('picks.hint') },
94
96
  h('ul', { className: 'vsync-cards vsync-pickGrid' }, picks.map(pick => h(PickCard, { key: `${pick.work.source}:${pick.work.id}`, t, pick, onOpen, onOpenWork }))))
@@ -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
@@ -24,7 +24,7 @@ export function init(react, { primitives, kit }) {
24
24
  h = react.createElement
25
25
  P = primitives
26
26
  K = kit
27
- Changes = react.createContext({ shelf: 0 })
27
+ Changes = react.createContext({ shelf: 0, discover: 0 })
28
28
  Known = react.createContext({ library: null, rooms: undefined, reload: () => {} })
29
29
  }
30
30
 
@@ -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
  }