| 1 | import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; |
| 2 | import { randomUUID } from "node:crypto"; |
| 3 | import { basename, join } from "node:path"; |
| 4 | |
| 5 | const historyLimit = 50; |
| 6 | const activeLimit = 50; |
| 7 | const guidPattern = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i; |
| 8 | const terminalStates = new Set(["saved", "failed", "canceled"]); |
| 9 | |
| 10 | export class DownloadManager { |
| 11 | constructor({ directory, save, changed = () => {}, cancel = () => {} }) { |
| 12 | this.directory = directory; |
| 13 | this.manifest = join(directory, "download-state.json"); |
| 14 | this.save = save; |
| 15 | this.changed = changed; |
| 16 | this.cancel = cancel; |
| 17 | this.records = new Map(); |
| 18 | this.queue = Promise.resolve(); |
| 19 | this.lastProgress = 0; |
| 20 | mkdirSync(join(directory, "Downloads"), { recursive: true }); |
| 21 | this.restore(); |
| 22 | } |
| 23 | |
| 24 | sourceExists(id) { |
| 25 | try { |
| 26 | return guidPattern.test(id) && lstatSync(join(this.directory, "Downloads", id)).isFile(); |
| 27 | } catch { return false; } |
| 28 | } |
| 29 | |
| 30 | restore() { |
| 31 | try { |
| 32 | if (!existsSync(this.manifest)) return; |
| 33 | const fd = openSync(this.manifest, "r"); |
| 34 | let data; |
| 35 | try { |
| 36 | const buffer = Buffer.alloc((1 << 20) + 1); |
| 37 | let size = 0, n; |
| 38 | while (size < buffer.length && (n = readSync(fd, buffer, size, buffer.length - size, null)) > 0) size += n; |
| 39 | if (size > 1 << 20) throw new Error("Download manifest too large"); |
| 40 | data = buffer.subarray(0, size); |
| 41 | } finally { closeSync(fd); } |
| 42 | const records = JSON.parse(data); |
| 43 | if (!Array.isArray(records) || records.length > activeLimit + historyLimit) throw new Error("Invalid download manifest"); |
| 44 | for (const item of records) { |
| 45 | if (!guidPattern.test(item.id) || typeof item.name !== "string" || item.name.length > 1024 || basename(item.name) !== item.name) continue; |
| 46 | const record = { id: item.id, name: item.name, state: item.state, |
| 47 | receivedBytes: Number(item.receivedBytes) || 0, totalBytes: Number(item.totalBytes) || 0, |
| 48 | updatedAt: item.updatedAt, sourceReady: item.sourceReady === true, |
| 49 | ...(typeof item.path === "string" && item.path.length < 8192 ? { path: item.path } : {}), |
| 50 | ...(typeof item.error === "string" ? { error: item.error.slice(0, 300) } : {}) }; |
| 51 | if (record.state === "downloading") { |
| 52 | record.state = "failed"; |
| 53 | record.sourceReady = false; |
| 54 | record.error = "下载被中断,请从原网页重新下载。"; |
| 55 | } else if (record.state === "saving") { |
| 56 | record.state = "failed"; |
| 57 | record.error = "保存过程被中断。源文件仍在时可以重试;否则请检查 Downloads 中的文件。"; |
| 58 | } |
| 59 | if (!terminalStates.has(record.state)) continue; |
| 60 | record.retryable = record.state === "failed" && record.sourceReady && this.sourceExists(record.id); |
| 61 | this.records.set(record.id, record); |
| 62 | } |
| 63 | this.persist(); |
| 64 | } catch { |
| 65 | |
| 66 | this.records.clear(); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | prune() { |
| 71 | const finished = [...this.records.values()].filter(r => terminalStates.has(r.state)); |
| 72 | for (const record of finished.slice(0, Math.max(0, finished.length - historyLimit))) this.records.delete(record.id); |
| 73 | } |
| 74 | |
| 75 | persist() { |
| 76 | this.prune(); |
| 77 | const temporary = this.manifest + "." + randomUUID() + ".tmp"; |
| 78 | let fd; |
| 79 | try { |
| 80 | fd = openSync(temporary, "wx", 0o600); |
| 81 | writeFileSync(fd, JSON.stringify([...this.records.values()])); |
| 82 | fsyncSync(fd); |
| 83 | closeSync(fd); |
| 84 | fd = undefined; |
| 85 | renameSync(temporary, this.manifest); |
| 86 | return true; |
| 87 | } catch { |
| 88 | if (fd !== undefined) closeSync(fd); |
| 89 | try { unlinkSync(temporary); } catch {} |
| 90 | return false; |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | publish(record, persist = true) { |
| 95 | record.updatedAt = new Date().toISOString(); |
| 96 | const saved = !persist || this.persist(); |
| 97 | if (!saved) { |
| 98 | record.error = "无法保存下载记录,请检查客机可用空间。"; |
| 99 | } |
| 100 | this.changed(); |
| 101 | return saved; |
| 102 | } |
| 103 | |
| 104 | begin(id, name) { |
| 105 | if (!guidPattern.test(id) || typeof name !== "string" || !name || name.length > 1024 || basename(name) !== name) return; |
| 106 | const active = [...this.records.values()].filter(r => !terminalStates.has(r.state)).length; |
| 107 | const record = { id, name, state: "downloading", receivedBytes: 0, totalBytes: 0, retryable: false, sourceReady: false }; |
| 108 | if (active >= activeLimit) { |
| 109 | record.state = "canceled"; |
| 110 | record.error = "同时下载的文件过多,请等待部分下载完成后重试。"; |
| 111 | void Promise.resolve(this.cancel(id)).catch(() => {}); |
| 112 | } |
| 113 | this.records.set(id, record); |
| 114 | this.publish(record); |
| 115 | } |
| 116 | |
| 117 | progress({ guid, state, receivedBytes, totalBytes }) { |
| 118 | const record = this.records.get(guid); |
| 119 | if (!record || record.state !== "downloading") return; |
| 120 | record.receivedBytes = Number(receivedBytes) || 0; |
| 121 | record.totalBytes = Number(totalBytes) || 0; |
| 122 | if (state === "completed") { |
| 123 | record.sourceReady = true; |
| 124 | this.enqueue(record); |
| 125 | } else if (state === "canceled") { |
| 126 | record.state = "canceled"; |
| 127 | record.error = "下载已取消,请从原网页重新下载。"; |
| 128 | this.publish(record); |
| 129 | } else if (Date.now() - this.lastProgress >= 500) { |
| 130 | this.lastProgress = Date.now(); |
| 131 | this.publish(record, false); |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | retry(id) { |
| 136 | const record = this.records.get(id); |
| 137 | if (record?.state === "saving") return { ok: true }; |
| 138 | if (!record || record.state !== "failed" || !record.sourceReady || !this.sourceExists(id)) { |
| 139 | if (record) { |
| 140 | record.retryable = false; |
| 141 | record.error = "下载源文件已不可用,请从原网页重新下载。"; |
| 142 | this.publish(record); |
| 143 | } |
| 144 | throw new Error("下载源文件已不可用,请从原网页重新下载。"); |
| 145 | } |
| 146 | this.enqueue(record); |
| 147 | return { ok: true }; |
| 148 | } |
| 149 | |
| 150 | enqueue(record) { |
| 151 | if (!this.sourceExists(record.id)) { |
| 152 | record.state = "failed"; |
| 153 | record.retryable = false; |
| 154 | record.error = "下载源文件不可用,请从原网页重新下载。"; |
| 155 | this.publish(record); |
| 156 | return; |
| 157 | } |
| 158 | record.state = "saving"; |
| 159 | record.retryable = false; |
| 160 | delete record.error; |
| 161 | if (!this.publish(record)) { |
| 162 | record.state = "failed"; |
| 163 | record.retryable = true; |
| 164 | this.changed(); |
| 165 | return; |
| 166 | } |
| 167 | this.queue = this.queue.then(async () => { |
| 168 | try { |
| 169 | const result = await this.save(record.id, record.name); |
| 170 | if (!result?.ok || typeof result.path !== "string") throw new Error(result?.error || "保存结果无效,请检查共享目录后重试。"); |
| 171 | record.state = "saved"; |
| 172 | record.path = result.path; |
| 173 | record.name = result.name || record.name; |
| 174 | record.receivedBytes = result.bytes ?? record.receivedBytes; |
| 175 | if (result.warning) record.error = result.warning; |
| 176 | } catch (error) { |
| 177 | record.state = "failed"; |
| 178 | record.error = String(error.message || "保存失败,请检查共享目录后重试。").slice(0, 300); |
| 179 | record.retryable = this.sourceExists(record.id); |
| 180 | } |
| 181 | this.publish(record); |
| 182 | }); |
| 183 | } |
| 184 | |
| 185 | snapshot() { |
| 186 | return [...this.records.values()].reverse().map(({ sourceReady, ...record }) => record); |
| 187 | } |
| 188 | |
| 189 | sourceFile(id) { |
| 190 | const record = this.records.get(id); |
| 191 | if (!record?.sourceReady || record.state === "downloading" || record.state === "saving" || !this.sourceExists(id)) |
| 192 | throw new Error("下载源文件不可用或尚未完成"); |
| 193 | return join(this.directory, "Downloads", id); |
| 194 | } |
| 195 | } |