| 1 | import { api, native, uploadFile } from "./api"; |
| 2 | |
| 3 | export const shellFilePaths = (paths) => paths.map(path => `'${path.replaceAll("'", /^[A-Za-z]:\\/.test(path) ? "''" : "'\\''")}'`).join(" ") + " "; |
| 4 | |
| 5 | |
| 6 | |
| 7 | export async function sendFiles(content, target, id, { valid = () => true, onProgress, windowTarget } = {}) { |
| 8 | const check = () => { if (!valid()) throw new Error("文件接收目标已切换,请返回原位置重试"); }; |
| 9 | check(); |
| 10 | const files = content.files || []; |
| 11 | if (!content.fileSelection && (!files.length || files.length > 100 || files.some(file => file.size > 2 * 1024 ** 3))) |
| 12 | throw new Error("每个文件不能超过 2 GB;一次最多 100 个文件。"); |
| 13 | const request = await api("/input/files/start", { target, id, kind: content.kind || "paste", x: content.x, y: content.y, pid: windowTarget?.pid, window: windowTarget?.window }); |
| 14 | const paths = []; |
| 15 | try { |
| 16 | check(); |
| 17 | if (content.fileSelection) { |
| 18 | const result = await native("uploadHostFiles", { target, id: request.id, selection: content.fileSelection }); |
| 19 | paths.push(...(result.paths || [])); |
| 20 | } else { |
| 21 | for (const file of files) { |
| 22 | check(); |
| 23 | const result = await uploadFile(`/input/files/${target}/${request.id}?${new URLSearchParams({ name: file.name })}`, file, { onProgress }); |
| 24 | if (result.path) paths.push(result.path); |
| 25 | } |
| 26 | } |
| 27 | check(); |
| 28 | await api("/input/files/finish", { target, id: request.id }); |
| 29 | return { paths }; |
| 30 | } catch (error) { |
| 31 | await api("/input/files/cancel", { target, id: request.id }).catch(() => {}); |
| 32 | throw error; |
| 33 | } |
| 34 | } |