okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-split-int (a3024ed10) into f-split-qa1: qa2's s3237-s3238 kept, my 21 strings renumbered s3260-s32808667a3dbf

main
2.5 KiB48 linesraw
1/**
2 * Files dropped on the app window (Linux and macOS).
3 *
4 * The page cannot read a dragged file there: WebKit gives it the drag events but no files. The app shell sees the drop with the real paths and
5 * hands them to the host with its shell secret (POST /api/app/drop); the host reads the files and keeps them for a short time under
6 * unguessable ids; the page asks for each id once (GET /api/app/drop/<id>) and attaches the files as if they had been dropped in a browser.
7 * Only regular files up to MAX_BYTES, at most MAX_FILES per drop; folders and anything else are skipped.
8 */
9import { randomUUID } from 'node:crypto';
10import { readFile, stat } from 'node:fs/promises';
11import { basename, extname, isAbsolute } from 'node:path';
12
13export const MAX_FILES = 10, MAX_BYTES = 25 * 1024 * 1024, KEEP_MS = 2 * 60_000;
14
15const TYPES = {
16  png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', bmp: 'image/bmp',
17  txt: 'text/plain', md: 'text/markdown', markdown: 'text/markdown', csv: 'text/csv', json: 'application/json', log: 'text/plain',
18  html: 'text/html', htm: 'text/html', xml: 'text/xml', yaml: 'text/yaml', yml: 'text/yaml', pdf: 'application/pdf',
19};
20export const typeOfName = name => TYPES[extname(String(name)).slice(1).toLowerCase()] ?? 'application/octet-stream';
21
22export function createNativeDrops({ now = Date.now, read = readFile, info = stat } = {}) {
23  const held = new Map();   // id -> { name, type, bytes, at }
24  const sweep = () => { for (const [id, f] of held) if (now() - f.at > KEEP_MS) held.delete(id); };
25  return {
26    /** Read the dropped paths; answer what the page may ask for: [{ id, name, type, size }]. */
27    async add(paths) {
28      sweep();
29      const out = [];
30      for (const raw of (Array.isArray(paths) ? paths : []).slice(0, MAX_FILES)) {
31        const path = typeof raw === 'string' ? raw : '';
32        if (!path || path.includes('\0') || !isAbsolute(path)) continue;
33        try {
34          const st = await info(path);
35          if (!st.isFile() || st.size > MAX_BYTES) continue;
36          const bytes = await read(path);
37          const id = randomUUID();
38          const name = basename(path);
39          held.set(id, { name, type: typeOfName(name), bytes, at: now() });
40          out.push({ id, name, type: typeOfName(name), size: bytes.length });
41        } catch { /* an unreadable file is skipped, the rest still arrive */ }
42      }
43      return out;
44    },
45    /** One use per id. */
46    take(id) { sweep(); const f = held.get(id); if (f) held.delete(id); return f ?? null; },
47  };
48}