dsh-folia 4.20.2 → 4.21.1

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/lib/client.js CHANGED
@@ -20914,13 +20914,22 @@ window.__ModuleLoader__.load({
20914
20914
  try { if (LF_STATE.note) LF_STATE.note(text, ok !== false); } catch { /* 提示失败不影响下载 */ }
20915
20915
  }
20916
20916
 
20917
- /** 从 inventory 里找这条(`/folia/inventory` 的 items)。 */
20917
+ /** 从 inventory 里找这条。
20918
+ *
20919
+ * ⚠️ 老实现只认 `items` / `data.items`,而 `/folia/inventory` 实际把壁纸放在 **`wallpapers`** 里
20920
+ * ⇒ 永远找不到 ⇒ 静默不入队 ⇒ 代理侧也拿不到可复用的 job ⇒ 壁纸退化为"远端流式 + 被播放器背压"
20921
+ *(实测 0.6 MB/s、且缓存永远补不满)。现在按"任何一个对象数组里找 id"兜底,不依赖具体键名。
20922
+ */
20918
20923
  async function lfFindItem(id) {
20919
20924
  try {
20920
20925
  const resp = await apiJson("/inventory");
20921
- const items = (resp && resp.data && Array.isArray(resp.data.items)) ? resp.data.items
20922
- : (Array.isArray(resp && resp.items) ? resp.items : []);
20923
- return items.find((x) => x && x.id === id) || null;
20926
+ const doc = (resp && resp.data && typeof resp.data === 'object') ? resp.data : (resp || {});
20927
+ const pools = [doc.items, doc.wallpapers, doc.list, doc.entries].filter(Array.isArray);
20928
+ for (const pool of pools) {
20929
+ const hit = pool.find((x) => x && x.id === id);
20930
+ if (hit) return hit;
20931
+ }
20932
+ return null;
20924
20933
  } catch { return null; }
20925
20934
  }
20926
20935
 
@@ -288,6 +288,15 @@ export function createDownloadQueue(opts = {}) {
288
288
  load();
289
289
  pump();
290
290
 
291
+ /** 按 dest 反查 job(含 dest/状态/总大小)——代理复用同一条下载用。 */
292
+ function jobFor(dest) {
293
+ for (const j of jobs.values()) {
294
+ if (j.dest !== dest) continue;
295
+ return { id: j.id, dest: j.dest, status: j.status, total: j.total, received: j.received };
296
+ }
297
+ return null;
298
+ }
299
+
291
300
  /** 已落地文件的绝对路径(未完成 / 不存在 ⇒ null)。/folia/local-media/<id> 用它。 */
292
301
  function pathFor(id) {
293
302
  const job = jobs.get(id);
@@ -295,5 +304,5 @@ export function createDownloadQueue(opts = {}) {
295
304
  try { return existsSync(job.dest) ? job.dest : null; } catch { return null; }
296
305
  }
297
306
 
298
- return { add, cancel, snapshot, pump, statePath, pathFor };
307
+ return { add, cancel, snapshot, pump, statePath, pathFor, jobFor };
299
308
  }
@@ -44,15 +44,25 @@ function libraryDest(kind, slug, ext) {
44
44
  * 未命中 ⇒ 返回 null,调用方保持原来的远端/代理地址(用户点了会先入队下载)。
45
45
  */
46
46
  export function localCopyFor(url, kind = 'wallpaper') {
47
+ try {
48
+ const job = queueJobFor(url, kind);
49
+ if (!job || job.status !== 'done') return null;
50
+ return { id: job.id, url: `/folia/local-media/${job.id}`, bytes: job.total };
51
+ } catch { return null; }
52
+ }
53
+
54
+ /**
55
+ * 这条 URL 在下载队列里的**原始 job**(含 dest 绝对路径与状态),供 site-media 代理复用:
56
+ * 代理拿着 dest 就能"渐进读正在增长的文件",而不是再开一条上游连接。
57
+ * 返回 null = 队列里没有这条(代理照旧走远端流式)。
58
+ */
59
+ export function queueJobFor(url, kind = 'wallpaper') {
47
60
  try {
48
61
  const u = new URL(String(url));
49
62
  const ext = (u.pathname.match(/\.([a-z0-9]{2,5})$/i) || [])[1] || 'bin';
50
63
  const slug = u.pathname.split('/').filter(Boolean).pop() || 'item';
51
64
  const dest = libraryDest(kind, slug, ext);
52
- const q = getDownloadQueue();
53
- const job = q.snapshot().find((j) => j.dest === dest);
54
- if (!job || job.status !== 'done') return null;
55
- return { id: job.id, url: `/folia/local-media/${job.id}`, bytes: job.total };
65
+ return getDownloadQueue().jobFor(dest);
56
66
  } catch { return null; }
57
67
  }
58
68
 
@@ -26,7 +26,9 @@
26
26
  *
27
27
  * 注入契约(ADR-0013 D12):`DEPS` 逐键由 `lib/index.js` 给到。
28
28
  */
29
- import { createHash } from 'node:crypto';
29
+ import { createHash } from 'node:crypto';
30
+ import { openSync, readSync, closeSync } from 'node:fs';
31
+ import { queueJobFor } from './downloads.js';
30
32
  import { Readable } from 'node:stream';
31
33
  import { createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';
32
34
  import { join, extname } from 'node:path';
@@ -76,6 +78,69 @@ function keyFor(u) {
76
78
  return h + (EXT_OK.has(ext) ? ext : '.bin');
77
79
  }
78
80
 
81
+ /**
82
+ * 从"正在增长的文件"里按偏移读给客户端(**渐进读**)。
83
+ *
84
+ * 场景:下载队列正在把这条壁纸拉到本地(`<dest>.part`),播放器同时要播。
85
+ * 与其再开一条上游连接(会抢带宽、还会被播放器背压拖成 0.6 MB/s),
86
+ * 不如直接读这份正在长大的文件:队列按线路速度推进,读端有多少字节喂多少。
87
+ *
88
+ * 终止条件:读到 job 状态变成 done 且读到 total;或 job 失败/取消;或客户端断开。
89
+ * 任何异常都只是提前结束响应,不抛出(不能让一次播放把进程搞崩)。
90
+ */
91
+ async function serveGrowingFile(filePath, job, res, headOnly) {
92
+ const openAt = () => { try { return openSync(filePath, 'r'); } catch { return -1; } };
93
+ let fd = openAt();
94
+ let offset = 0;
95
+ let stalled = 0;
96
+ const sleep = (ms) => new Promise((r) => { setTimeout(r, ms); });
97
+ try {
98
+ res.statusCode = 200;
99
+ res.setHeader('content-type', 'application/octet-stream');
100
+ res.setHeader('accept-ranges', 'none');
101
+ res.setHeader('cache-control', 'no-store');
102
+ res.setHeader('x-folia-source', 'library');
103
+ if (headOnly) { res.end(); return true; }
104
+ const BUF = Buffer.alloc(256 * 1024);
105
+ for (;;) {
106
+ if (res.writableEnded) break;
107
+ if (fd < 0) fd = openAt();
108
+ let n = 0;
109
+ if (fd >= 0) {
110
+ try { n = readSync(fd, BUF, 0, BUF.length, offset); } catch { n = 0; }
111
+ }
112
+ if (n > 0) {
113
+ offset += n;
114
+ stalled = 0;
115
+ const ok = res.write(BUF.subarray(0, n));
116
+ if (!ok) await new Promise((r) => { res.once('drain', r); });
117
+ continue;
118
+ }
119
+ // 暂时没有新字节:看队列是否还在推进
120
+ const cur = typeof job.refresh === 'function' ? job.refresh() : job;
121
+ if (cur && cur.status === 'done') {
122
+ // 完成的瞬间 .part 会被 rename 掉;重新打开最终文件继续读完
123
+ try { if (fd >= 0) closeSync(fd); } catch { /* ignore */ }
124
+ fd = -1;
125
+ if (offset >= (cur.total || 0)) break;
126
+ filePath = cur.dest || filePath;
127
+ continue;
128
+ }
129
+ if (cur && (cur.status === 'failed' || cur.status === 'cancelled')) break;
130
+ stalled += 1;
131
+ if (stalled > 600) break; // ≈ 30 秒没有新字节就收尾(不无限挂着)
132
+ await sleep(50);
133
+ }
134
+ res.end();
135
+ return true;
136
+ } catch {
137
+ try { res.end(); } catch { /* ignore */ }
138
+ return false;
139
+ } finally {
140
+ try { if (fd >= 0) closeSync(fd); } catch { /* ignore */ }
141
+ }
142
+ }
143
+
79
144
  /** 目录总量与最旧条目(LRU 用;只看本目录的常规文件,跳过分片)。 */
80
145
  function scanCache(dir) {
81
146
  let total = 0;
@@ -341,6 +406,22 @@ export function registerSiteMediaRoutes(webServer, c) {
341
406
  const key = keyFor(u);
342
407
  const abs = join(dir, key);
343
408
 
409
+ // **单源复用**:如果下载队列已经在为这条 URL 拉文件(用户点它时入队的),
410
+ // 就直接读那个**正在增长的本地文件**,不再开第二条上游连接。
411
+ // 为什么重要:实测同一份字节被拉两遍(代理 0.6 MB/s + 队列 3.2 MB/s),
412
+ // 互相抢带宽,缓存补全速度还不如只跑一条。复用后带宽只花一份,速度=线路速度。
413
+ try {
414
+ const job = queueJobFor(u.toString(), 'wallpaper');
415
+ if (job && (job.status === 'done' || job.status === 'running')) {
416
+ const partPath = job.status === 'done' ? job.dest : job.dest + '.part';
417
+ if (existsSync(partPath)) {
418
+ if (job.status === 'done') { try { res.setHeader('x-folia-cache', 'hit'); } catch { /* ignore */ } }
419
+ await serveGrowingFile(partPath, job, res, headOnly);
420
+ return;
421
+ }
422
+ }
423
+ } catch { /* 复用失败就照旧走远端流式 */ }
424
+
344
425
  if (ensureCache(dir) && existsSync(abs)) {
345
426
  stats.hits += 1;
346
427
  touch(abs);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-folia",
3
- "version": "4.20.2",
3
+ "version": "4.21.1",
4
4
  "description": "Folia 壁纸引擎:把本机 Wallpaper Engine 壁纸搬进 DSH 界面(场景实时渲染 / 视频 / 网页),内置液态玻璃与 Folia 吉祥物,并可从自建站点拉取壁纸。单包形态(组件已合并)。",
5
5
  "type": "module",
6
6
  "engines": {