| 1 | // Automatizaciones entre carpetas: «pones un fichero en una carpeta y Elffuss |
| 2 | // lo coge, lo procesa y te lo deja en otra» 😉 |
| 3 | // |
| 4 | // fs.watch registra una vigilancia persistente (IndexedDB). Un poller (cada |
| 5 | // POLL_MS, mientras la pestaña esté abierta) re-lista la carpeta de origen y |
| 6 | // procesa lo nuevo: .xlsx/.xls → .csv (SheetJS); el resto se copia tal cual. |
| 7 | // Los ya procesados se recuerdan por nombre+mtime (re-dejar un archivo |
| 8 | // modificado lo reprocesa). |
| 9 | import * as db from '../db.js'; |
| 10 | import { require as requirePerm } from '../permissions.js'; |
| 11 | import { t } from '../i18n.js'; |
| 12 | import { root, xlsxToCsv, globToRegex } from './fs.js'; |
| 13 | |
| 14 | const KEY = 'automations'; |
| 15 | const POLL_MS = 8000; |
| 16 | |
| 17 | const getAll = async () => (await db.get('kv', KEY)) || []; |
| 18 | // Toda escritura de la lista es leer-modificar-escribir en UNA transacción |
| 19 | // (db.update): añadir, quitar y apuntar lo procesado ya no pueden pisarse. |
| 20 | const cambiar = fn => db.update('kv', KEY, list => fn(Array.isArray(list) ? list : [])); |
| 21 | |
| 22 | export async function add({ from, to, pattern = '*' } = {}) { |
| 23 | if (!from || !to) throw new Error(t('fsMissingFromTo')); |
| 24 | await requirePerm('fs', t('pdWatch', { from, to })); |
| 25 | await root(from); await root(to); // valida que existen y hay acceso |
| 26 | const id = 'w' + Math.random().toString(36).slice(2, 8); |
| 27 | await cambiar(list => [...list, { id, from, to, pattern, seen: {} }]); |
| 28 | return t('watchActive', { id, from, to, pattern }); |
| 29 | } |
| 30 | |
| 31 | export async function listWatches() { |
| 32 | const list = await getAll(); |
| 33 | return list.length |
| 34 | ? list.map(w => `👁 ${w.id} · ${w.from} → ${w.to} (${w.pattern}) · ` + t('watchSeen', { n: Object.keys(w.seen).length })).join('\n') |
| 35 | : t('watchNone'); |
| 36 | } |
| 37 | |
| 38 | export async function removeWatch({ id } = {}) { |
| 39 | await cambiar(list => list.filter(w => w.id !== id)); |
| 40 | return t('watchRemovedTool', { id }); |
| 41 | } |
| 42 | |
| 43 | export async function allWatches() { return getAll(); } |
| 44 | |
| 45 | async function processFile(entry, dstDir) { |
| 46 | const file = await entry.getFile(); |
| 47 | if (/\.xlsx?$/i.test(entry.name)) { |
| 48 | const { csv } = await xlsxToCsv(file); |
| 49 | const outName = entry.name.replace(/\.xlsx?$/i, '.csv'); |
| 50 | const fh = await dstDir.getFileHandle(outName, { create: true }); |
| 51 | const w = await fh.createWritable(); |
| 52 | await w.write(csv); |
| 53 | await w.close(); |
| 54 | return outName; |
| 55 | } |
| 56 | const fh = await dstDir.getFileHandle(entry.name, { create: true }); |
| 57 | const w = await fh.createWritable(); |
| 58 | await w.write(await file.arrayBuffer()); |
| 59 | await w.close(); |
| 60 | return entry.name; |
| 61 | } |
| 62 | |
| 63 | // El kernel lo arranca con un notificador (toast + mensaje en el chat). El |
| 64 | // segundo argumento lleva los datos (id, carpetas, fichero) para enlazarlos. |
| 65 | // |
| 66 | // Una pasada a la vez: si una tarda más que el intervalo (un Excel grande, una |
| 67 | // carpeta con muchos ficheros), la siguiente NO arranca encima. Antes podían |
| 68 | // solaparse dos: las dos procesaban el mismo fichero y las dos guardaban. |
| 69 | let pasando = false; |
| 70 | export function startWatcher(notify = () => {}) { |
| 71 | setInterval(async () => { |
| 72 | if (pasando) return; |
| 73 | pasando = true; |
| 74 | try { await pasada(notify); } finally { pasando = false; } |
| 75 | }, POLL_MS); |
| 76 | } |
| 77 | |
| 78 | async function pasada(notify) { |
| 79 | let list; |
| 80 | try { list = await getAll(); } catch { return; } |
| 81 | if (!list.length) return; |
| 82 | const procesados = new Map(); // id de la vigilancia → { fichero: mtime } de ESTA pasada |
| 83 | for (const w of list) { |
| 84 | try { |
| 85 | const src = await root(w.from); |
| 86 | const dst = await root(w.to); |
| 87 | const rx = globToRegex(w.pattern); |
| 88 | for await (const entry of src.values()) { |
| 89 | if (entry.kind !== 'file' || !rx.test(entry.name)) continue; |
| 90 | const mtime = (await entry.getFile()).lastModified; |
| 91 | if (w.seen[entry.name] === mtime) continue; |
| 92 | const outName = await processFile(entry, dst); |
| 93 | w.seen[entry.name] = mtime; |
| 94 | if (!procesados.has(w.id)) procesados.set(w.id, {}); |
| 95 | procesados.get(w.id)[entry.name] = mtime; |
| 96 | notify(`✨ He cogido «${entry.name}» de ${w.from}, lo he procesado y te lo he dejado en ${w.to}/${outName}`, |
| 97 | { id: w.id, from: w.from, to: w.to, fichero: entry.name, salida: outName }); |
| 98 | } |
| 99 | } catch (e) { |
| 100 | console.warn('[elffuss] automatización', w.id, e.message); |
| 101 | } |
| 102 | } |
| 103 | if (!procesados.size) return; |
| 104 | // Se guarda sobre la lista RELEÍDA, no sobre la del principio de la pasada. |
| 105 | // Procesar puede tardar, y si mientras tanto quitabas una automatización, |
| 106 | // guardar la lista vieja entera la RESUCITABA: volvía a aparecer y a vigilar. |
| 107 | // Así solo se funden los ficheros vistos, y solo en las vigilancias que |
| 108 | // siguen existiendo; las que se añadieron mientras tanto se quedan como están. |
| 109 | // Releer y escribir van en la misma transacción: un borrado a medio camino |
| 110 | // no puede colarse entre las dos. |
| 111 | try { |
| 112 | await cambiar(ahora => ahora.map(w => procesados.has(w.id) |
| 113 | ? { ...w, seen: { ...(w.seen || {}), ...procesados.get(w.id) } } : w)); |
| 114 | } catch { /* sin guardar: la próxima pasada los vuelve a ver */ } |
| 115 | } |