| 1 | |
| 2 | |
| 3 | import { spawn } from "node:child_process"; |
| 4 | |
| 5 | export async function phoneDesktop(op, input) { |
| 6 | const child = spawn("/usr/bin/sudo", ["-n", "/usr/local/lib/cage-phone-desktop/control.py"], |
| 7 | { stdio: ["pipe", "pipe", "ignore"] }); |
| 8 | let size = 0; |
| 9 | const chunks = []; |
| 10 | const timeout = setTimeout(() => child.kill("SIGKILL"), 12500); |
| 11 | try { |
| 12 | const output = await new Promise((resolve, reject) => { |
| 13 | child.on("error", reject); |
| 14 | child.stdout.on("data", chunk => { |
| 15 | size += chunk.length; |
| 16 | if (size > 3600000) child.kill("SIGKILL"); |
| 17 | else chunks.push(chunk); |
| 18 | }); |
| 19 | child.stdin.on("error", () => {}); |
| 20 | child.once("close", code => { |
| 21 | if (code !== 0 || !size || size > 3600000) reject(new Error("手机 Desktop 服务不可用")); |
| 22 | else resolve(Buffer.concat(chunks)); |
| 23 | }); |
| 24 | child.stdin.end(JSON.stringify({ ...input, op }) + "\n"); |
| 25 | }); |
| 26 | const result = JSON.parse(output); |
| 27 | if (result.status) { |
| 28 | const status = [400, 403, 409, 410, 412, 501, 503].includes(result.status) ? result.status : 503; |
| 29 | throw Object.assign(new Error("手机 Desktop 操作未完成"), { status }); |
| 30 | } |
| 31 | return result; |
| 32 | } finally { clearTimeout(timeout); } |
| 33 | } |