| 1 | import { randomUUID } from "node:crypto"; |
| 2 | import { mkdir, open, rm } from "node:fs/promises"; |
| 3 | import { basename, join } from "node:path"; |
| 4 | |
| 5 | export const uploadLimit = 2 * 1024 * 1024 * 1024; |
| 6 | export const validFileName = (name) => |
| 7 | typeof name === "string" && |
| 8 | name.length > 0 && |
| 9 | Buffer.byteLength(name) <= 255 && |
| 10 | basename(name) === name && |
| 11 | !/[\\\x00-\x1f]/.test(name) && |
| 12 | ![".", ".."].includes(name); |
| 13 | |
| 14 | export class UploadManager { |
| 15 | constructor({ directory, cdp, changed = () => {} }) { |
| 16 | this.directory = directory; |
| 17 | this.cdp = cdp; |
| 18 | this.changed = changed; |
| 19 | this.requests = new Map(); |
| 20 | this.retained = new Map(); |
| 21 | } |
| 22 | |
| 23 | async opened(tabId, sessionId, event) { |
| 24 | if (!event.backendNodeId) return; |
| 25 | this.cancelTab(tabId, false); |
| 26 | const id = randomUUID(); |
| 27 | this.requests.set(id, { |
| 28 | id, |
| 29 | tabId, |
| 30 | sessionId, |
| 31 | node: event.backendNodeId, |
| 32 | multiple: event.mode === "selectMultiple", |
| 33 | files: [], |
| 34 | busy: false, |
| 35 | kind: "chooser", |
| 36 | }); |
| 37 | this.changed(); |
| 38 | } |
| 39 | |
| 40 | snapshot() { |
| 41 | return [...this.requests.values()].map(({ id, tabId, multiple, kind }) => ({ |
| 42 | id, |
| 43 | tabId, |
| 44 | multiple, |
| 45 | kind, |
| 46 | })); |
| 47 | } |
| 48 | |
| 49 | start(tabId, sessionId, { kind, x, y }) { |
| 50 | if (!["drop", "paste"].includes(kind)) throw new Error("文件传递方式无效"); |
| 51 | if (kind === "drop" && ![x, y].every(v => Number.isFinite(v) && v >= 0 && v <= 1)) |
| 52 | throw new Error("拖入位置无效"); |
| 53 | this.cancelTab(tabId, false); |
| 54 | const id = randomUUID(); |
| 55 | this.requests.set(id, { id, tabId, sessionId, kind, x, y, multiple: true, files: [], busy: false }); |
| 56 | this.changed(); |
| 57 | return { id }; |
| 58 | } |
| 59 | |
| 60 | request(id) { |
| 61 | const request = this.requests.get(id); |
| 62 | if (!request) |
| 63 | throw new Error("上传窗口已关闭或网页已刷新,请重新点击网页的上传按钮"); |
| 64 | return request; |
| 65 | } |
| 66 | |
| 67 | async receive(id, name, stream) { |
| 68 | const request = this.request(id); |
| 69 | if (!validFileName(name)) throw new Error("文件名无效"); |
| 70 | if (request.busy || request.files.length >= (request.multiple ? 100 : 1)) |
| 71 | throw new Error("请选择允许数量的文件"); |
| 72 | request.busy = true; |
| 73 | const directory = join(this.directory, id, randomUUID()); |
| 74 | const path = join(directory, name); |
| 75 | let file, |
| 76 | size = 0, |
| 77 | accepted = false; |
| 78 | try { |
| 79 | await mkdir(directory, { recursive: true, mode: 0o700 }); |
| 80 | file = await open(path, "wx", 0o600); |
| 81 | for await (const chunk of stream) { |
| 82 | size += chunk.length; |
| 83 | if (size > uploadLimit) throw new Error("每个文件不能超过 2 GB"); |
| 84 | if (this.requests.get(id) !== request) throw new Error("上传已取消"); |
| 85 | await file.writeFile(chunk); |
| 86 | } |
| 87 | await file.close(); |
| 88 | file = null; |
| 89 | if (this.requests.get(id) !== request) throw new Error("上传已取消"); |
| 90 | request.files.push(path); |
| 91 | accepted = true; |
| 92 | return { ok: true, name, size }; |
| 93 | } finally { |
| 94 | await file?.close(); |
| 95 | if (!accepted) await rm(directory, { recursive: true, force: true }); |
| 96 | request.busy = false; |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | async finish(id) { |
| 101 | const request = this.request(id); |
| 102 | if (request.busy || !request.files.length) |
| 103 | throw new Error("请先选择并传递文件"); |
| 104 | request.busy = true; |
| 105 | try { |
| 106 | if (request.kind === "chooser") { |
| 107 | await this.cdp("DOM.setFileInputFiles", { backendNodeId: request.node, files: request.files }, request.sessionId); |
| 108 | } else { |
| 109 | const { result, exceptionDetails } = await this.cdp("Runtime.evaluate", { |
| 110 | expression: `(() => { |
| 111 | const e = document.activeElement, r = e?.getBoundingClientRect(); |
| 112 | return { width: innerWidth, height: innerHeight, |
| 113 | x: r?.width ? Math.max(0, Math.min(innerWidth - 1, r.left + r.width / 2)) : innerWidth / 2, |
| 114 | y: r?.height ? Math.max(0, Math.min(innerHeight - 1, r.top + r.height / 2)) : innerHeight / 2 }; |
| 115 | })()`, returnByValue: true, |
| 116 | }, request.sessionId); |
| 117 | if (exceptionDetails || !result?.value) throw new Error("无法确定文件接收位置"); |
| 118 | const viewport = result.value; |
| 119 | const x = request.kind === "drop" ? Math.min(viewport.width - 1, request.x * viewport.width) : viewport.x; |
| 120 | const y = request.kind === "drop" ? Math.min(viewport.height - 1, request.y * viewport.height) : viewport.y; |
| 121 | for (const type of ["dragEnter", "dragOver", "drop"]) { |
| 122 | if (this.requests.get(id) !== request) throw new Error("上传已取消"); |
| 123 | await this.cdp("Input.dispatchDragEvent", { type, x, y, data: { items: [], files: request.files, dragOperationsMask: 1 } }, request.sessionId); |
| 124 | } |
| 125 | } |
| 126 | if (this.requests.get(id) !== request) throw new Error("上传已取消"); |
| 127 | this.requests.delete(id); |
| 128 | |
| 129 | |
| 130 | const retained = this.retained.get(request.tabId) || []; |
| 131 | retained.push(id); |
| 132 | this.retained.set(request.tabId, retained); |
| 133 | this.changed(); |
| 134 | return { ok: true }; |
| 135 | } catch (error) { |
| 136 | this.cancel(id); |
| 137 | throw error; |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | cancel(id) { |
| 142 | if (!this.requests.delete(id)) return; |
| 143 | void rm(join(this.directory, id), { recursive: true, force: true }).catch( |
| 144 | () => {}, |
| 145 | ); |
| 146 | this.changed(); |
| 147 | } |
| 148 | |
| 149 | cancelTab(tabId, removeRetained = true) { |
| 150 | for (const request of this.requests.values()) |
| 151 | if (request.tabId === tabId) this.cancel(request.id); |
| 152 | if (removeRetained) { |
| 153 | for (const id of this.retained.get(tabId) || []) |
| 154 | void rm(join(this.directory, id), { |
| 155 | recursive: true, |
| 156 | force: true, |
| 157 | }).catch(() => {}); |
| 158 | this.retained.delete(tabId); |
| 159 | } |
| 160 | } |
| 161 | } |