@soffits/dsh-media-hub 0.7.0 → 0.8.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,9 +1,13 @@
1
1
  # Changelog
2
2
 
3
- ## 0.7.0
3
+ ## 0.8.0
4
4
 
5
- - A show's details (title, blurb, score, related works, episode titles, cover) are now read from its source every time the page shows them, so a rename or a new season on the source appears without any refresh. The copy saved with the show is only an offline fallback: when the source can't answer in a few seconds, the page shows it with a note saying when it was saved, and the next answer refreshes it. Nothing is cached between page loads.
6
- - The "Refresh info" menu item and the quiet backfill of details are gone: reading live makes both unnecessary.
5
+ - 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.
6
+
7
+ ## 0.7.1
8
+
9
+ - 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.
10
+ - The "Refresh info" menu item and the quiet backfill of details are gone; the background refresh replaces both.
7
11
 
8
12
  ## 0.6.2
9
13
 
package/README.md CHANGED
@@ -14,7 +14,7 @@ This plugin was called Video Sync (`@soffits/dsh-video-sync`) until 0.2.0; the r
14
14
  - **Sources**: one search box over *All sources* or one of them; each source is a configured command line tool that speaks a small JSON protocol ([docs/source-protocol.md](docs/source-protocol.md), the hub's public interface for extensions, see [docs/extensions.md](docs/extensions.md)) and brings its kinds. The defaults are `fanqie` (short dramas, audiobooks, novels) and `bookfetch source` (ebooks and papers); every request runs through the source's command, so any proxy its launcher enforces holds, and a wrapper for another site is one more entry. *Watch* opens it at once, for you alone (*Watch together* in the player opens that room to others where it stands and copies its link); *Save to library* adds the show; *Download all (offline)* keeps every episode on disk. Sources implement one small interface (`src/sources/index.js`).
15
15
  - **Search results as cards**: cover, title, score, how many watched it ("36.7万次播放" or "36.7K plays", by the page language), episodes, whether it is finished, tags; *Details* shows everything the source gives (cast, heat, last update…) and the other seasons and linked works.
16
16
  - **Pictures for everything**: a work's cover, a show's poster and a room's preview all come from the host and are cached under `<stateDir>/covers`: a source's cover through the source's own command (so its proxy keeps applying), a link's thumbnail through the `proxies` setting, and a still of the video for local files and shows without a cover. A browser never contacts a site's CDN, and a placeholder shows only when there is no picture at all.
17
- - **Details read live, kept only as an offline copy**: a show from a source has its work (cover, score, popularity, tags, blurb, other fields, related works, episode titles) read from the source each time the library, a room's *About* tab or an episode list shows it; the copy saved with the show is shown, with the date, only when the source doesn't answer.
17
+ - **Details kept with a show**: a show from a source keeps what the source said about its work (cover, score, popularity, tags, blurb, other fields, related works, episode titles), so the library, a room's *About* tab and the episode list show it at once; a missing or day-old copy is refreshed in the background, and a copy over a week old says when it was saved.
18
18
  - **Follow**: a followed work is checked about once a day through its source (and when someone opens it). A new season is added to the library as an empty show, grouped with the earlier ones and followed too, and shows under *New* in Watching and in the watch log; more episodes extend the show. With `notifyCommand` set, that command gets one line of JSON on its standard input for each piece of news.
19
19
  - **Rolling cache**: a show from a source lists every episode, but only a window is on disk: the episode people are on is fetched first, then the next few (`cacheAhead`, 5), and `cacheBehind` (1) watched ones stay. Watched episodes that fall out of the window are deleted (the watch log still marks them watched). Jumping to an episode that is not cached fetches it first (the room shows it as preparing), then refills the window around it. A show kept offline (*Download all (offline)*, or the library menu) is never trimmed. All cached episodes of other shows together stay under `cacheLimitGb` (5 GB): past it the least recently watched go first, never one near an open room. The library says *cached N of M* (and *offline*), and the episode list marks the ones not on disk.
20
20
  - **Watch log**: `<stateDir>/watch-log.jsonl`, one JSON object per line: rooms opened and closed, viewers joining and leaving, episodes started and finished, and where each viewer stopped (`position` lines when someone leaves, the episode changes, the room closes, and every two minutes while playing).
package/dist/index.js CHANGED
@@ -12255,7 +12255,7 @@ function createHandler({ connection, service, settings = () => ({ label: "", pre
12255
12255
  const route = `${req.method} ${parts.slice(1).join("/")}`;
12256
12256
  const query = (name2) => url.searchParams.get(name2) ?? "";
12257
12257
  if (route === "GET rooms") return sendJson(res, 200, { rooms: await hub.listRooms() });
12258
- if (req.method === "GET" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "work") return sendJson(res, 200, await hub.roomWork(parts[2]));
12258
+ if (req.method === "GET" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "work") return sendJson(res, 200, hub.roomWork(parts[2]));
12259
12259
  if (req.method === "DELETE" && parts[1] === "rooms" && parts.length === 3) return sendJson(res, 200, hub.closeRoom(parts[2]));
12260
12260
  if (req.method === "POST" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "together") return sendJson(res, 200, hub.watchTogether(parts[2]));
12261
12261
  if (route === "GET library") return sendJson(res, 200, await hub.library());
@@ -12671,7 +12671,8 @@ function runConverter(command, input, output) {
12671
12671
  });
12672
12672
  });
12673
12673
  }
12674
- function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, now = Date.now }) {
12674
+ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, changed = () => {
12675
+ }, now = Date.now }) {
12675
12676
  let state = { files: {}, shelves: {} };
12676
12677
  let saving = Promise.resolve();
12677
12678
  const running = /* @__PURE__ */ new Map();
@@ -12679,6 +12680,7 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, no
12679
12680
  let active = 0;
12680
12681
  let disposed = false;
12681
12682
  const save = () => {
12683
+ changed();
12682
12684
  saving = saving.then(async () => {
12683
12685
  await mkdir6(dir, { recursive: true });
12684
12686
  const temporary = join12(dir, `.${STATE_FILE}.${process.pid}.tmp`);
@@ -14096,6 +14098,7 @@ function createLibrary(options) {
14096
14098
  }
14097
14099
  }
14098
14100
  function save() {
14101
+ options.changed?.();
14099
14102
  const body2 = JSON.stringify({ shows: meta }, null, 1);
14100
14103
  saving = saving.then(async () => {
14101
14104
  await writeFile6(`${metaFile}.part`, body2);
@@ -14139,6 +14142,7 @@ function createLibrary(options) {
14139
14142
  await rm8(join15(target, name2), { force: true });
14140
14143
  for (const sub of matchSubtitles(name2, await readdir7(target).catch(() => []))) await rm8(join15(target, sub.name), { force: true });
14141
14144
  await forgetSum(target, name2);
14145
+ options.changed?.();
14142
14146
  }
14143
14147
  async function folderBytes(path) {
14144
14148
  const info = await stat9(path).catch(() => null);
@@ -14204,15 +14208,14 @@ function createLibrary(options) {
14204
14208
  if (isNearEnd(resume2.position, resume2.duration)) return index + 1 < slots.length ? slots[index + 1].n : null;
14205
14209
  return slots[index].n;
14206
14210
  }
14207
- const liveOr = (live, path, entry) => live && options.liveWork ? options.liveWork(path, entry) : Promise.resolve(entry.work ?? null);
14208
- async function describe(path, live = false) {
14211
+ async function describe(path) {
14209
14212
  const info = await stat9(path).catch(() => null);
14210
14213
  if (info === null) return null;
14211
14214
  const files = await episodeFiles(path);
14212
14215
  const state = download(path);
14213
14216
  if ((files === null || files.length === 0) && state === null && !isSourced(record(path))) return null;
14214
14217
  const names = (files ?? []).map((file) => file.name);
14215
- const entry = { ...record(path), work: await liveOr(live, path, record(path)) };
14218
+ const entry = record(path);
14216
14219
  const slots = slotsOf(entry, files ?? []);
14217
14220
  if (names.length === 0 && state === null && !isSourced(entry)) return null;
14218
14221
  const resume2 = resumeFrom(path, slots);
@@ -14264,13 +14267,13 @@ function createLibrary(options) {
14264
14267
  listeners.add(listener);
14265
14268
  return () => listeners.delete(listener);
14266
14269
  },
14267
- /** Every show, newest first, with totals and the free space of the download folder's disk. `live` has each sourced show's work asked of its source (see `options.liveWork`). */
14268
- async list({ live = false } = {}) {
14270
+ /** Every show, newest first, with totals and the free space of the download folder's disk. */
14271
+ async list() {
14269
14272
  const paths = [];
14270
14273
  for (const root of roots) {
14271
14274
  for (const name2 of await readdir7(root).catch(() => [])) if (!name2.startsWith(".")) paths.push(join15(root, name2));
14272
14275
  }
14273
- const shows = (await Promise.all(paths.map((path) => describe(path, live)))).filter((show) => show !== null);
14276
+ const shows = (await Promise.all(paths.map((path) => describe(path)))).filter((show) => show !== null);
14274
14277
  shows.sort((a, b) => b.addedAt - a.addedAt);
14275
14278
  groupSeasons(shows);
14276
14279
  const disk = await statfs(roots[0]).catch(() => null);
@@ -14283,8 +14286,7 @@ function createLibrary(options) {
14283
14286
  },
14284
14287
  async episodes(path) {
14285
14288
  const target = requireShow(path);
14286
- const entry = { ...record(target), work: await liveOr(true, target, record(target)) };
14287
- const slots = slotsOf(entry, await episodeFiles(target) ?? []);
14289
+ const slots = slotsOf(record(target), await episodeFiles(target) ?? []);
14288
14290
  return slots.map((slot) => ({
14289
14291
  n: slot.n,
14290
14292
  name: slot.file?.name ?? null,
@@ -14608,63 +14610,81 @@ function createFollows({ library, source, refreshed, addSeason, record, notify,
14608
14610
  };
14609
14611
  }
14610
14612
 
14611
- // src/live-work.js
14613
+ // src/changes.js
14614
+ function createChanges({ intervalMs = 300 } = {}) {
14615
+ const listeners = /* @__PURE__ */ new Set();
14616
+ let pending = /* @__PURE__ */ new Set();
14617
+ let timer = null;
14618
+ let lastAt = 0;
14619
+ function flush() {
14620
+ timer = null;
14621
+ lastAt = Date.now();
14622
+ const what = [...pending];
14623
+ pending = /* @__PURE__ */ new Set();
14624
+ for (const listener of listeners) listener(what);
14625
+ }
14626
+ return {
14627
+ notify(kind) {
14628
+ pending.add(kind);
14629
+ if (timer !== null) return;
14630
+ timer = setTimeout(flush, Math.max(0, lastAt + intervalMs - Date.now()));
14631
+ timer.unref?.();
14632
+ },
14633
+ /** @returns {() => void} stop listening */
14634
+ listen(listener) {
14635
+ listeners.add(listener);
14636
+ return () => listeners.delete(listener);
14637
+ },
14638
+ close() {
14639
+ clearTimeout(timer);
14640
+ timer = null;
14641
+ listeners.clear();
14642
+ }
14643
+ };
14644
+ }
14645
+
14646
+ // src/work-refresh.js
14612
14647
  var DAY_MS3 = 864e5;
14613
- var sameAs = (saved, work, at) => saved != null && at - saved.at < DAY_MS3 && JSON.stringify({ ...saved, at: 0 }) === JSON.stringify({ ...work, at: 0 });
14614
- function createLiveWork({ source, keep, waitMs = 8e3, parallel = 4, now = Date.now, logger }) {
14615
- const flying = /* @__PURE__ */ new Map();
14616
- const queue = [];
14648
+ var HOUR_MS = 36e5;
14649
+ function createWorkRefresh({ source, keep, maxAgeMs = DAY_MS3, retryMs = HOUR_MS, parallel = 2, now = Date.now, logger }) {
14650
+ const flying = /* @__PURE__ */ new Set();
14651
+ const failedAt = /* @__PURE__ */ new Map();
14652
+ const waiting = [];
14617
14653
  let running = 0;
14618
- function turn() {
14619
- while (running < parallel && queue.length > 0) {
14654
+ function pump() {
14655
+ while (running < parallel && waiting.length > 0) {
14620
14656
  running += 1;
14621
- queue.shift()();
14622
- }
14623
- }
14624
- const limited = (task) => new Promise((resolve7, reject) => {
14625
- queue.push(() => task().then(resolve7, reject).finally(() => {
14626
- running -= 1;
14627
- turn();
14628
- }));
14629
- turn();
14630
- });
14631
- function ask(path, entry) {
14632
- const { source: sourceId, id } = entry.source;
14633
- const key = `${sourceId}
14634
- ${id}`;
14635
- if (!flying.has(key)) {
14636
- const request = limited(() => source(sourceId).info(id, { person: entry.source.person })).then((info) => {
14637
- const work = snapshotOf(info, now());
14638
- if (!sameAs(entry.work, work, now())) keep(path, work);
14639
- return work;
14640
- }).finally(() => flying.delete(key));
14641
- request.catch(() => {
14657
+ waiting.shift()().finally(() => {
14658
+ running -= 1;
14659
+ pump();
14642
14660
  });
14643
- flying.set(key, request);
14644
14661
  }
14645
- return flying.get(key);
14646
14662
  }
14647
- const offline = (entry) => entry.work ? { ...entry.work, offline: true } : null;
14648
- return async function read(path, entry) {
14649
- const found = entry.source?.source ? source(entry.source.source) : void 0;
14650
- if (found === void 0) return entry.work ?? null;
14651
- let timer;
14652
- const late = new Promise((resolve7) => {
14653
- timer = setTimeout(() => resolve7(null), waitMs);
14663
+ return function touch(path, entry) {
14664
+ const sourceId = entry.source?.source;
14665
+ const found = sourceId ? source(sourceId) : void 0;
14666
+ if (found === void 0 || entry.work && now() - entry.work.at < maxAgeMs) return;
14667
+ const key = `${sourceId}
14668
+ ${entry.source.id}`;
14669
+ if (flying.has(key) || now() - (failedAt.get(key) ?? -Infinity) < retryMs) return;
14670
+ flying.add(key);
14671
+ waiting.push(async () => {
14672
+ try {
14673
+ keep(path, snapshotOf(await found.info(entry.source.id, { person: entry.source.person }), now()));
14674
+ failedAt.delete(key);
14675
+ } catch (error) {
14676
+ failedAt.set(key, now());
14677
+ logger.warn("no details for %s from %s: %s", path, sourceId, error.message);
14678
+ } finally {
14679
+ flying.delete(key);
14680
+ }
14654
14681
  });
14655
- try {
14656
- return await Promise.race([ask(path, entry), late]) ?? offline(entry);
14657
- } catch (error) {
14658
- logger.warn("no live details for %s from %s: %s", path, entry.source.source, error.message);
14659
- return offline(entry);
14660
- } finally {
14661
- clearTimeout(timer);
14662
- }
14682
+ pump();
14663
14683
  };
14664
14684
  }
14665
14685
 
14666
14686
  // src/media.js
14667
- var HOUR_MS = 36e5;
14687
+ var HOUR_MS2 = 36e5;
14668
14688
  var MIN_FREE_BYTES = 1e9;
14669
14689
  var NO_CONVERTER = Object.freeze({ command: "", available: async () => false });
14670
14690
  var hubError = (code, message) => Object.assign(new Error(message), { code });
@@ -14673,7 +14693,8 @@ function createMediaHub(options) {
14673
14693
  const sources = new Map(options.sources.map((source2) => [source2.id, source2]));
14674
14694
  const covers = createCovers({ dir: join16(stateDir, "covers"), capBytes: options.coverCacheBytes, ffmpeg: options.tools.ffmpeg, logger }, (id) => sources.get(id));
14675
14695
  const log = createWatchLog({ file: join16(stateDir, LOG_NAME), now, logger });
14676
- const books = createBooks({ dir: join16(stateDir, "books"), sources, capBytes: options.books?.capBytes ?? 0, converter: options.books?.converter ?? NO_CONVERTER, covers, logger, now });
14696
+ const changes = createChanges({ intervalMs: options.changeIntervalMs });
14697
+ 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 });
14677
14698
  let rooms;
14678
14699
  let cache;
14679
14700
  const downloads = createDownloads({
@@ -14685,14 +14706,17 @@ function createMediaHub(options) {
14685
14706
  return disk === null || disk.bavail * disk.bsize >= MIN_FREE_BYTES;
14686
14707
  },
14687
14708
  onFiles,
14688
- onProgress: (job, number, progress) => rooms.downloadProgress(job.dir, number, progress),
14709
+ onProgress: (job, number, progress) => {
14710
+ rooms.downloadProgress(job.dir, number, progress);
14711
+ changes.notify("library");
14712
+ },
14689
14713
  onPartial: (job, number, partial) => rooms.streamEpisode(job.dir, number, partial),
14690
14714
  logger,
14691
14715
  now
14692
14716
  });
14693
- const liveWork = createLiveWork({ source: (id) => sources.get(id), keep: (path, work) => library.keepWork(path, work), waitMs: options.liveWorkWaitMs, logger, now });
14717
+ const refreshWork = createWorkRefresh({ source: (id) => sources.get(id), keep: (path, work) => library.keepWork(path, work), maxAgeMs: options.workMaxAgeMs, logger, now });
14694
14718
  const library = createLibrary({
14695
- liveWork,
14719
+ changed: () => changes.notify("library"),
14696
14720
  roots: libraryRoots,
14697
14721
  stateDir,
14698
14722
  autoDeleteDays: options.autoDeleteDays,
@@ -14704,6 +14728,7 @@ function createMediaHub(options) {
14704
14728
  logger,
14705
14729
  now
14706
14730
  });
14731
+ const journal = createJournal({ log, library, now });
14707
14732
  rooms = createRoomService({
14708
14733
  ...options,
14709
14734
  watchOf: (item, show) => library.watchOfItem(show, item),
@@ -14712,7 +14737,10 @@ function createMediaHub(options) {
14712
14737
  cache.refresh(show, change).catch(() => {
14713
14738
  });
14714
14739
  },
14715
- observe: createJournal({ log, library, now })
14740
+ observe: (type, detail) => {
14741
+ journal(type, detail);
14742
+ if (type !== "progress") changes.notify("rooms");
14743
+ }
14716
14744
  });
14717
14745
  cache = createCache({ library, downloads, rooms, window: options.cache, logger });
14718
14746
  library.onChange((show) => {
@@ -14734,8 +14762,9 @@ function createMediaHub(options) {
14734
14762
  });
14735
14763
  cache.enforce().catch(() => {
14736
14764
  });
14737
- }, HOUR_MS);
14765
+ }, HOUR_MS2);
14738
14766
  async function onFiles(job) {
14767
+ changes.notify("library");
14739
14768
  await rooms.syncShow(job.dir);
14740
14769
  if (job.status === "failed") rooms.failWaiting(job.dir, job.error ?? "the download failed", job.reason ?? null);
14741
14770
  await cache.enforce();
@@ -14780,9 +14809,10 @@ function createMediaHub(options) {
14780
14809
  now,
14781
14810
  ...options.follow
14782
14811
  });
14783
- const liveEntry = async (show) => {
14812
+ const shownEntry = (show) => {
14784
14813
  const entry = { source: library.workSource(show), work: library.workOf(show) };
14785
- return { ...entry, work: await liveWork(show, entry) };
14814
+ refreshWork(show, entry);
14815
+ return entry;
14786
14816
  };
14787
14817
  const withCovers = (show) => show.work && show.source?.source ? { ...show, work: covers.decorate(show.source.source, show.work) } : show;
14788
14818
  function source(id) {
@@ -14836,7 +14866,7 @@ ${item.id}`).digest("hex").slice(0, 8);
14836
14866
  /** Open rooms with a preview of what plays: the show's cover and a frame of the episode now on. */
14837
14867
  async listRooms() {
14838
14868
  return Promise.all(rooms.listRooms().map(async ({ file, ...room }) => {
14839
- const show = room.show === null ? null : withCovers(await liveEntry(room.show));
14869
+ const show = room.show === null ? null : withCovers({ source: library.workSource(room.show), work: library.workOf(room.show) });
14840
14870
  return { ...room, cover: show?.work?.cover ?? null, frame: file === null ? null : await covers.ofFrame(file, room.duration > 30 ? Math.round(room.duration / 10) : 3) };
14841
14871
  }));
14842
14872
  },
@@ -14855,6 +14885,7 @@ ${item.id}`).digest("hex").slice(0, 8);
14855
14885
  },
14856
14886
  async rate(input, person) {
14857
14887
  await log.append("rating", ratingLine(input, person));
14888
+ changes.notify("library");
14858
14889
  return { ok: true };
14859
14890
  },
14860
14891
  picks: (person) => picks.list(person),
@@ -14871,14 +14902,15 @@ ${item.id}`).digest("hex").slice(0, 8);
14871
14902
  },
14872
14903
  // ---------------------------------------------------------- library
14873
14904
  async library() {
14874
- const list = await library.list({ live: true });
14905
+ const list = await library.list();
14906
+ for (const show of list.shows) if (show.source?.source) refreshWork(show.path, { source: show.source, work: show.work });
14875
14907
  return { ...list, shows: list.shows.map(withCovers) };
14876
14908
  },
14877
14909
  /** The details of the work a room's show came from, or null. */
14878
- async roomWork(id) {
14910
+ roomWork(id) {
14879
14911
  const room = rooms.listRooms().find((entry) => entry.id === id);
14880
14912
  if (room === void 0) throw hubError("not_found", "no such room");
14881
- return { work: room.show === null ? null : withCovers(await liveEntry(room.show)).work ?? null, source: library.workSource(room.show)?.source ?? null, id: library.workSource(room.show)?.id ?? null };
14913
+ return { work: room.show === null ? null : withCovers(shownEntry(room.show)).work ?? null, source: library.workSource(room.show)?.source ?? null, id: library.workSource(room.show)?.id ?? null };
14882
14914
  },
14883
14915
  episodes: (path) => library.episodes(path),
14884
14916
  removeShow: (path, by) => library.remove(path, { by }),
@@ -14989,7 +15021,10 @@ ${item.id}`).digest("hex").slice(0, 8);
14989
15021
  // ---------------------------------------------------------- watch log
14990
15022
  history: (opts) => log.history(opts),
14991
15023
  logFile: log.file,
15024
+ /** Be told (with the kinds of what changed: `library`, `rooms`, `shelf`) when something a page shows changes; returns a way to stop. */
15025
+ listenChanges: (listener) => changes.listen(listener),
14992
15026
  async dispose() {
15027
+ changes.close();
14993
15028
  clearInterval(sweepTimer);
14994
15029
  follows.stop();
14995
15030
  await books.dispose();
@@ -15085,6 +15120,55 @@ function createPersonRoutes({ hub, identity }) {
15085
15120
  ];
15086
15121
  }
15087
15122
 
15123
+ // src/events-route.js
15124
+ var EVENTS_PATH = "/api/media-hub/events";
15125
+ var HEARTBEAT_MS = 25e3;
15126
+ function createEventsRoute({ hub }) {
15127
+ return {
15128
+ path: EVENTS_PATH,
15129
+ methods: ["GET"],
15130
+ requestBody: "buffered",
15131
+ fetch: async (request) => {
15132
+ const current = hub();
15133
+ if (current === void 0) return json(503, { error: { code: "unavailable", message: "The media hub is starting." } });
15134
+ const encoder = new TextEncoder();
15135
+ let stop = () => {
15136
+ };
15137
+ const stream = new ReadableStream({
15138
+ start(controller) {
15139
+ const write2 = (chunk) => {
15140
+ try {
15141
+ controller.enqueue(encoder.encode(chunk));
15142
+ } catch {
15143
+ stop();
15144
+ }
15145
+ };
15146
+ write2("retry: 5000\n: open\n\n");
15147
+ const unlisten = current.listenChanges((what) => write2(`data: ${JSON.stringify({ type: "change", what })}
15148
+
15149
+ `));
15150
+ const beat = setInterval(() => write2(": beat\n\n"), HEARTBEAT_MS);
15151
+ stop = () => {
15152
+ unlisten();
15153
+ clearInterval(beat);
15154
+ };
15155
+ request.signal?.addEventListener("abort", () => {
15156
+ stop();
15157
+ try {
15158
+ controller.close();
15159
+ } catch {
15160
+ }
15161
+ }, { once: true });
15162
+ },
15163
+ cancel() {
15164
+ stop();
15165
+ }
15166
+ });
15167
+ 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" } });
15168
+ }
15169
+ };
15170
+ }
15171
+
15088
15172
  // src/shelf-routes.js
15089
15173
  import { createReadStream as createReadStream3 } from "node:fs";
15090
15174
  import { stat as stat11 } from "node:fs/promises";
@@ -15182,7 +15266,8 @@ function apply(ctx, config) {
15182
15266
  const identity = () => ctx.get("requestIdentity");
15183
15267
  const fetchRoutes = [
15184
15268
  ...createShelfRoutes({ books: () => current?.books, identity }),
15185
- ...createPersonRoutes({ hub: () => current, identity })
15269
+ ...createPersonRoutes({ hub: () => current, identity }),
15270
+ createEventsRoute({ hub: () => current })
15186
15271
  ].map((route) => ctx.connection.fetch.register(route));
15187
15272
  const sockets = new import_websocket_server.default({ noServer: true, maxPayload: 16 * 1024, perMessageDeflate: false });
15188
15273
  const disposeHttp = ctx.webServer.register({
package/locale/en.json CHANGED
@@ -143,7 +143,7 @@
143
143
  "library.offline": "offline",
144
144
  "library.notCached": "not cached",
145
145
  "library.episodeN": "Episode {n}",
146
- "library.offlineCopy": "The source didn't answer. Showing the copy saved on {date}.",
146
+ "library.oldCopy": "Details last updated {date}.",
147
147
  "library.playFromFetch": "Watch from this episode (it is fetched first)",
148
148
  "library.downloadAll": "Download all (offline)",
149
149
  "library.stopOffline": "Stop keeping offline",
package/locale/fr.json CHANGED
@@ -143,7 +143,7 @@
143
143
  "library.offline": "hors ligne",
144
144
  "library.notCached": "pas en cache",
145
145
  "library.episodeN": "Épisode {n}",
146
- "library.offlineCopy": "La source ne répond pas. Copie enregistrée le {date}.",
146
+ "library.oldCopy": "Infos mises à jour le {date}.",
147
147
  "library.playFromFetch": "Regarder à partir de cet épisode (il est d’abord récupéré)",
148
148
  "library.downloadAll": "Tout télécharger (hors ligne)",
149
149
  "library.stopOffline": "Ne plus garder hors ligne",
package/locale/zh.json CHANGED
@@ -143,7 +143,7 @@
143
143
  "library.offline": "离线",
144
144
  "library.notCached": "未缓存",
145
145
  "library.episodeN": "第 {n} 集",
146
- "library.offlineCopy": "来源没有回应,显示的是 {date} 保存的副本。",
146
+ "library.oldCopy": "详情更新于 {date}。",
147
147
  "library.playFromFetch": "从这一集开始看(先下载它)",
148
148
  "library.downloadAll": "全部下载(离线)",
149
149
  "library.stopOffline": "不再离线保存",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-media-hub",
3
- "version": "0.7.0",
3
+ "version": "0.8.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
package/web/details.js CHANGED
@@ -10,6 +10,8 @@ import { useKnownWork } from './known.js'
10
10
  import { Icon, Spinner, asPerson, base, clock, day, fill, h, plural, query, React } from './ui.js'
11
11
 
12
12
  const INFO_CONCURRENCY = 3
13
+ /** A saved copy of a work this old says so, quietly. */
14
+ const OLD_COPY_MS = 7 * 86_400_000
13
15
 
14
16
  /** Fetch work details a few at a time, so a page of results doesn't start ten downloads of metadata at once. */
15
17
  function createInfoQueue() {
@@ -92,7 +94,7 @@ export function WorkDetails({ t, info, source, onFocus }) {
92
94
  const rows = info.meta ?? []
93
95
  const related = info.related ?? []
94
96
  return h('div', { className: 'vsync-details' },
95
- info.offline && h('p', { className: 'vsync-note', role: 'status' }, fill(t('library.offlineCopy'), { date: info.at ? day(t, info.at) : '?' })),
97
+ info.at && Date.now() - info.at > OLD_COPY_MS && h('p', { className: 'vsync-note', role: 'status' }, fill(t('library.oldCopy'), { date: day(t, info.at) })),
96
98
  info.blurb && h('p', { className: 'vsync-fullBlurb' }, info.blurb),
97
99
  info.latest && h('p', { className: 'vsync-note' }, fill(t('search.latest'), { title: info.latest })),
98
100
  rows.length > 0 && h('dl', { className: 'vsync-facts' }, rows.flatMap(row => [h('dt', { key: `${row.key}-k` }, metaLabel(t, row)), h('dd', { key: `${row.key}-v` }, row.value)])),
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, h, React, 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'
@@ -89,16 +89,18 @@ export function Page({ t, initialRoom }) {
89
89
  if (lib.shows) setLibrary(lib)
90
90
  }, [])
91
91
 
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])
92
+ // 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
+ const [shelf, setShelf] = React.useState(0)
94
+ const stream = K.useEventStream('api/media-hub/events', (message) => {
95
+ if (message.what?.includes('shelf')) setShelf(count => count + 1)
96
+ if (message.what?.some(kind => kind === 'library' || kind === 'rooms')) load()
97
+ })
98
+ React.useEffect(() => { if (stream === 'live') { load(); setShelf(count => count + 1) } }, [stream, load])
99
+ React.useEffect(() => { load() }, [load])
99
100
 
100
101
  const known = React.useMemo(() => ({ library, rooms, reload: load }), [library, rooms, load])
101
- return h(Known.Provider, { value: known }, roomId === null
102
+ const changes = React.useMemo(() => ({ shelf }), [shelf])
103
+ return h(Changes.Provider, { value: changes }, h(Known.Provider, { value: known }, roomId === null
102
104
  ? h(Home, { t, nav, go, onOpen: setRoomId, rooms, library, load })
103
- : h(RoomView, { key: roomId, t, roomId, onLeave: () => setRoomId(null), onOpen: setRoomId }))
105
+ : h(RoomView, { key: roomId, t, roomId, onLeave: () => setRoomId(null), onOpen: setRoomId })))
104
106
  }
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