pixrick / web /backend.js
Algorick's picture
f00483f6497b
6138ad1 verified
Raw History Blame Contribute Delete
28.2 kB
/* PixRick online: le stesse API dell'app sul computer, ma la galleria vive nel browser
e la generazione passa dal motore su Hugging Face. Niente immagini restano sul server. */
(() => {
"use strict";
const DB_NAME = "pixrick";
const DRAFT_TTL_MS = 24 * 3600 * 1000;
const THUMB_SIDE = 640;
const MAX_INPUT_SIDE = 2048;
const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
const ENGINE_PATH = "/motore/";
/* ---------- archivio nel browser ---------- */
let dbPromise = null;
function db() {
dbPromise ||= new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, 1);
req.onupgradeneeded = () => {
const d = req.result;
d.createObjectStore("blobs");
const items = d.createObjectStore("items", { keyPath: "file" });
items.createIndex("scope", "scope");
d.createObjectStore("kv");
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
return dbPromise;
}
async function tx(stores, mode, work) {
const d = await db();
return new Promise((resolve, reject) => {
const t = d.transaction(stores, mode);
let out;
t.oncomplete = () => resolve(out);
t.onerror = () => reject(t.error);
t.onabort = () => reject(t.error || new Error("Archivio del browser non disponibile."));
out = work(...[].concat(stores).map((s) => t.objectStore(s)));
});
}
const req2p = (r) => new Promise((resolve, reject) => { r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error); });
// Le immagini si salvano come ArrayBuffer: Safari in navigazione privata rifiuta i Blob in IndexedDB.
const pack = async (blob) => (blob instanceof Blob ? { type: blob.type, data: await blob.arrayBuffer() } : blob);
const unpack = (value) => (value && !(value instanceof Blob) && value.data ? new Blob([value.data], { type: value.type }) : value);
async function readRaw(path) {
const d = await db();
return req2p(d.transaction("blobs").objectStore("blobs").get(path));
}
async function readBlob(path) {
return unpack(await readRaw(path));
}
async function readItem(file) {
const d = await db();
return req2p(d.transaction("items").objectStore("items").get(file));
}
async function itemsIn(scope) {
const d = await db();
return req2p(d.transaction("items").objectStore("items").index("scope").getAll(scope));
}
async function kvGet(key, fallback) {
const d = await db();
const v = await req2p(d.transaction("kv").objectStore("kv").get(key));
return v === undefined ? fallback : v;
}
const kvSet = (key, value) => tx("kv", "readwrite", (s) => { s.put(value, key); });
/* ---------- immagini ---------- */
const pad = (n) => String(n).padStart(2, "0");
const today = (d = new Date()) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
const clock = (d = new Date()) => `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
const stamp = (d = new Date()) => `${today(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
const rand = () => Math.random().toString(16).slice(2, 8);
async function bitmap(blob) {
try {
return await createImageBitmap(blob, { imageOrientation: "from-image" });
} catch {
throw new Error("Il file non è un'immagine leggibile.");
}
}
function canvasOf(w, h) {
const c = document.createElement("canvas");
c.width = w;
c.height = h;
return c;
}
const toBlob = (canvas, type, quality) => new Promise((r) => canvas.toBlob(r, type, quality));
async function thumbnail(blob) {
const bmp = await bitmap(blob);
const k = Math.min(1, THUMB_SIDE / Math.max(bmp.width, bmp.height));
const c = canvasOf(Math.round(bmp.width * k), Math.round(bmp.height * k));
c.getContext("2d").drawImage(bmp, 0, 0, c.width, c.height);
bmp.close?.();
return (await toBlob(c, "image/webp", 0.84)) || toBlob(c, "image/png");
}
/** Ruota secondo l'EXIF, rimpicciolisce e riscrive in PNG: via EXIF e posizione GPS. */
async function cleanUpload(file) {
if (file.size > MAX_UPLOAD_BYTES) throw new Error("Immagine troppo pesante (massimo 25 MB).");
const bmp = await bitmap(file);
const k = Math.min(1, MAX_INPUT_SIDE / Math.max(bmp.width, bmp.height));
const c = canvasOf(Math.round(bmp.width * k), Math.round(bmp.height * k));
const ctx = c.getContext("2d");
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, c.width, c.height);
ctx.drawImage(bmp, 0, 0, c.width, c.height);
bmp.close?.();
return { blob: await toBlob(c, "image/png"), width: c.width, height: c.height };
}
/* ---------- galleria ---------- */
// Percorsi come sul computer: bozze in _bozze/, galleria per giorno, cestino in _cestino/.
const SCOPE_PREFIX = { bozze: "_bozze/", galleria: "", cestino: "_cestino/" };
const thumbPath = (scope, day, stem) => (scope === "galleria" ? `.miniature/${day}/${stem}.webp` : `${SCOPE_PREFIX[scope]}${day}/${stem}.webp`);
function splitFile(file) {
const parts = file.split("/");
const name = parts.pop();
return { day: parts.pop(), stem: name.replace(/\.png$/, "") };
}
async function storeItem(scope, meta, png, thumb) {
const day = today();
const stem = meta._stem || `${clock()}_${meta.modalita || "crea"}_${meta.modello || "img"}_${rand()}`;
delete meta._stem;
const file = `${SCOPE_PREFIX[scope]}${day}/${stem}.png`;
const mini = thumbPath(scope, day, stem);
const item = { ...meta, file, miniatura: mini, bozza: scope === "bozze", titolo: meta.titolo || "", preferita: !!meta.preferita };
const [image, small] = await Promise.all([pack(png), pack(thumb)]);
await tx(["blobs", "items"], "readwrite", (blobs, items) => {
blobs.put(image, "outputs/" + file);
blobs.put(small, "outputs/" + mini);
items.put({ file, scope, t: Date.now(), meta: item });
});
return item;
}
async function move(file, fromScope, toScope) {
const rec = await readItem(file);
if (!rec || rec.scope !== fromScope) return null;
const { day, stem } = splitFile(file);
const newFile = `${SCOPE_PREFIX[toScope]}${day}/${stem}.png`;
const newMini = thumbPath(toScope, day, stem);
const png = await readRaw("outputs/" + file);
const thumb = await readRaw("outputs/" + rec.meta.miniatura);
const meta = { ...rec.meta, file: newFile, miniatura: newMini, bozza: toScope === "bozze" };
await tx(["blobs", "items"], "readwrite", (blobs, items) => {
blobs.delete("outputs/" + file);
blobs.delete("outputs/" + rec.meta.miniatura);
items.delete(file);
if (png) blobs.put(png, "outputs/" + newFile);
if (thumb) blobs.put(thumb, "outputs/" + newMini);
items.put({ file: newFile, scope: toScope, t: rec.t, meta });
});
return meta;
}
async function remove(file, scope) {
const rec = await readItem(file);
if (!rec || (scope && rec.scope !== scope)) return false;
await tx(["blobs", "items"], "readwrite", (blobs, items) => {
blobs.delete("outputs/" + file);
blobs.delete("outputs/" + rec.meta.miniatura);
items.delete(file);
});
return true;
}
async function history(params) {
const scope = params.get("vista") || "galleria";
const limit = Math.min(200, Number(params.get("limit") || 60));
const offset = Math.max(0, Number(params.get("offset") || 0));
const real = scope === "preferite" ? "galleria" : scope;
let list = (await itemsIn(real)).map((r) => r.meta);
if (scope === "preferite") list = list.filter((m) => m.preferita);
list.sort((a, b) => (a.file < b.file ? 1 : -1));
return { immagini: list.slice(offset, offset + limit) };
}
async function cleanOld() {
const limit = Date.now() - DRAFT_TTL_MS;
for (const rec of await itemsIn("bozze")) if (rec.t < limit) await remove(rec.file, "bozze");
const used = new Set();
for (const scope of ["galleria", "cestino", "bozze"]) {
for (const rec of await itemsIn(scope)) {
(rec.meta.riferimenti || []).forEach((r) => used.add(r));
if (rec.meta.maschera) used.add(rec.meta.maschera);
}
}
const inputs = (await kvGet("inputs", {})) || {};
let changed = false;
for (const [path, t] of Object.entries(inputs)) {
if (t < limit && !used.has(path)) {
await tx("blobs", "readwrite", (s) => s.delete(path));
delete inputs[path];
changed = true;
}
}
if (changed) await kvSet("inputs", inputs);
}
async function saveInput(blob, name) {
const path = `inputs/${today()}/${clock()}_${rand()}.png`;
const data = await pack(blob);
await tx("blobs", "readwrite", (s) => { s.put(data, path); });
const inputs = (await kvGet("inputs", {})) || {};
inputs[path] = Date.now();
await kvSet("inputs", inputs);
return path;
}
/* ---------- stili dell'utente ---------- */
const ITALIAN = /\b(il|lo|la|gli|le|un|una|uno|di|del|della|dei|delle|che|con|per|sul|sulla|nel|nella|non|più|mentre|sopra|sotto|dietro|davanti|vicino|foto|immagine|ragazza|ragazzo|uomo|donna|cielo|mare|togli|metti|aggiungi|cambia|rendi|sostituisci|fai)\b|[àèéìòù]/i;
const ENGLISH = new Set(
"the a an of with and on at is are by to from for under over into his her their its this that wearing holding standing sitting photo picture style".split(" ")
);
const looksItalian = (t) => {
const text = t.replace(/"[^"]*"/g, "");
if (ITALIAN.test(text)) return true;
const words = (text.match(/[a-z]+/gi) || []).map((w) => w.toLowerCase());
if (!words.length || words.some((w) => ENGLISH.has(w))) return false;
return words.filter((w) => "aeio".includes(w.at(-1))).length / words.length > 0.6;
};
const userStyles = () => kvGet("stili", []);
async function saveStyle(data) {
const name = String(data.nome || "").trim().slice(0, 40);
const text = String(data.testo || "").trim().slice(0, 600);
if (!name || !text) throw new Error("Servono un nome e una descrizione dello stile.");
let english = text;
if (looksItalian(text)) english = (await write("traduci", text)) || text;
const items = await userStyles();
let id = String(data.id || "");
if (!id.startsWith("u-") || !items.some((i) => i.id === id)) {
const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 24) || "stile";
id = `u-${slug}-${rand().slice(0, 4)}`;
}
const color = /^#[0-9a-f]{6}$/i.test(data.colore || "") ? data.colore : "#cbbcff";
const style = {
id,
nome: name,
descrizione: text.length < 90 ? text : text.slice(0, 87) + "…",
testo: text,
formato: data.formato || "1:1",
colore: color,
modello: ["z-image", "klein", "entrambi"].includes(data.modello) ? data.modello : "",
qualita: ["rapida", "bilanciata", "massima"].includes(data.qualita) ? data.qualita : "",
prompt: "{prompt}. " + english.trim().replace(/\.$/, "") + ".",
};
const next = items.some((i) => i.id === id) ? items.map((i) => (i.id === id ? style : i)) : [...items, style];
await kvSet("stili", next);
return { ...style, categoria: "I tuoi stili", utente: true, campi: [] };
}
async function templates() {
const res = await fetch("/api/templates");
const data = await res.json();
const mine = (await userStyles()).map((s) => ({ ...s, categoria: "I tuoi stili", utente: true, campi: [] }));
return { template: [...data.template, ...mine] };
}
/* ---------- motore ---------- */
let clientPromise = null;
function engine() {
const token = readAccount()?.token;
const connect = (Client, withToken) =>
Client.connect(location.origin + ENGINE_PATH, { events: ["data", "status"], ...(withToken ? { token } : {}) });
clientPromise ||= import("/web/vendor/gradio-client.js")
.then(({ Client }) => connect(Client, Boolean(token)).catch((e) => {
if (!token) throw e;
logout();
return connect(Client, false);
}))
.catch((e) => {
clientPromise = null;
throw e;
});
return clientPromise;
}
/* ---------- accesso facoltativo con Hugging Face ---------- */
const ACCOUNT = "pixrick.account";
function readAccount() {
try {
const a = JSON.parse(localStorage.getItem(ACCOUNT) || "null");
if (a?.token && a.scade > Date.now() + 60000) return a;
if (a) localStorage.removeItem(ACCOUNT);
} catch { /* storage non disponibile */ }
return null;
}
function captureLogin() {
const m = location.hash.match(/^#accesso=([\w-]+)$/);
if (!m) return null;
window.history.replaceState(window.history.state, "", location.pathname + location.search);
if (m[1].length < 40) return m[1];
try {
const a = JSON.parse(atob(m[1].replace(/-/g, "+").replace(/_/g, "/")));
if (!a.token) return "errore";
localStorage.setItem(ACCOUNT, JSON.stringify(a));
return "ok";
} catch {
return "errore";
}
}
const loginResult = captureLogin();
function account() {
const a = readAccount();
return a ? { utente: a.utente, nome: a.nome, foto: a.foto } : null;
}
function logout() {
try { localStorage.removeItem(ACCOUNT); } catch { /* storage non disponibile */ }
clientPromise = null;
}
let hiddenSince = 0;
document.addEventListener("visibilitychange", () => {
if (document.hidden) hiddenSince = Date.now();
else if (hiddenSince && Date.now() - hiddenSince > 20000) clientPromise = null;
});
const DAY = 24 * 3600 * 1000;
const FIRST_USE = "pixrick.gpu.inizio";
function markGpuUse() {
try {
const first = Number(localStorage.getItem(FIRST_USE));
if (!first || Date.now() - first > DAY) localStorage.setItem(FIRST_USE, String(Date.now()));
} catch { /* storage non disponibile */ }
}
function quotaReset() {
try {
const first = Number(localStorage.getItem(FIRST_USE));
return first && first + DAY > Date.now() ? first + DAY : null;
} catch {
return null;
}
}
function report(text) {
try {
navigator.sendBeacon("/api/errore", new Blob([JSON.stringify({ m: String(text).slice(0, 400) })], { type: "application/json" }));
} catch { /* solo diagnostica */ }
}
const QUOTA = /quota|runs limit|GPU (?:time|duration|limit)/i;
function engineError(raw) {
const text = String(raw?.message || (typeof raw === "object" ? JSON.stringify(raw) : raw) || "");
report(text || "errore vuoto");
if (QUOTA.test(text)) {
const wait = text.match(/Try again in (?:(\d+) days?, )?(\d+):(\d+):(\d+)/i);
const err = new Error("Per oggi hai finito le prove gratuite.");
err.code = "quota";
if (wait) err.retryIn = Number(wait[1] || 0) * 86400 + Number(wait[2]) * 3600 + Number(wait[3]) * 60 + Number(wait[4]);
window.PixOnline?.quota(err.retryIn);
return err;
}
if (/queue is full|too many/i.test(text)) {
const err = new Error("Ci sono troppe persone in coda in questo momento. Riprova tra un minuto.");
err.code = "full";
return err;
}
return new Error(text.replace(/^Error:\s*/, "") || "Il motore non risponde. Riprova tra poco.");
}
async function write(kind, text) {
const client = await engine();
try {
const res = await client.predict("/scrivi", [kind, text]);
markGpuUse();
return res.data[0];
} catch (e) {
throw engineError(e);
}
}
async function improve(text, mode) {
const client = await engine();
try {
const res = await client.predict("/migliora", [text, mode]);
markGpuUse();
return res.data[0];
} catch (e) {
throw engineError(e);
}
}
const jobs = new Map();
let lastPayload = null;
const listeners = new Set();
const emit = (event) => listeners.forEach((fn) => { try { fn(event); } catch { /* ascoltatore rotto */ } });
function placeholderJob(id, payload) {
return {
id,
status: "invio",
progress: 0,
current: 0,
current_model: "",
total: Math.max(1, Number(payload.quantita) || 1),
current_steps: 1,
model_name: "",
confronto: false,
elapsed: 0,
width: 1024,
height: 1024,
results: [],
request: { mode: payload.modalita || "crea", count: Number(payload.quantita) || 1, mask: payload.maschera || null },
created: Date.now() / 1000,
};
}
async function startJob(payload) {
const files = [];
for (const ref of payload.riferimenti || []) {
const blob = await readBlob(ref);
if (!blob) throw new Error("Un'immagine di partenza non c'è più. Ricaricala.");
files.push(new File([blob], "ref.png", { type: blob.type || "image/png" }));
}
let mask = null;
if (payload.maschera) {
const blob = await readBlob(payload.maschera);
if (blob) mask = new File([blob], "mask.png", { type: "image/png" });
}
lastPayload = payload;
const request = { ...payload, stili_utente: await userStyles() };
const client = await engine();
const { handle_file: handle } = await import("/web/vendor/gradio-client.js");
const id = "j" + Date.now().toString(36) + rand();
const started = Date.now();
const state = { job: placeholderJob(id, payload), payload };
jobs.set(id, state);
const inputs = [JSON.stringify(request), files.map((f) => handle(f)), mask ? handle(mask) : null];
async function follow(run) {
let received = false;
for await (const msg of run) {
if (msg.type === "status") {
if (msg.stage === "error") {
const err = engineError(msg.message);
err.lost = !received && !msg.message;
throw err;
}
if (msg.stage === "pending" && msg.position != null && state.job.status !== "generazione") {
state.job = { ...state.job, status: "in_coda", position: msg.position, eta: msg.eta ?? null, queue_size: msg.queue_size ?? null };
}
}
if (msg.type === "data") {
received = true;
const [pub, out] = msg.data;
if (!pub) continue;
const live = { ...pub, elapsed: Math.round((Date.now() - started) / 100) / 10 };
if (pub.status === "fatto" && out && out.length) {
state.job = { ...live, status: "salvataggio" };
const results = [];
try {
for (let i = 0; i < out.length; i++) {
const res = await fetch(out[i].url);
if (!res.ok) throw new Error(`download ${res.status}`);
const png = await res.blob();
const meta = { ...pub.results[i], riferimenti: payload.riferimenti || [], maschera: payload.maschera || null };
results.push(await storeItem("bozze", meta, png, await thumbnail(png)));
}
} catch (e) {
report(`salvataggio: ${e?.name || ""} ${e?.message || e}`);
const err = new Error("L'immagine è pronta ma il browser non è riuscito a salvarla. Riprova; se succede ancora, esci dalla navigazione privata.");
err.lost = false;
throw err;
}
markGpuUse();
state.job = { ...live, status: "fatto", results, progress: 1 };
emit({ type: "generata", count: results.length });
return;
}
state.job = { ...live, status: pub.status === "fatto" ? "salvataggio" : pub.status };
}
}
const err = new Error("Il motore non risponde. Riprova tra poco.");
err.lost = !received;
throw err;
}
(async () => {
try {
try {
await follow(client.submit("/genera", inputs));
} catch (e) {
if (e?.code || e?.lost === false) throw e;
clientPromise = null;
const fresh = await engine();
await follow(fresh.submit("/genera", inputs));
}
} catch (e) {
const err = e instanceof Error && e.code ? e : engineError(e);
state.job = { ...state.job, status: "errore", error: err.message, error_code: err.code || null, retry_in: err.retryIn || null };
emit({ type: "errore", code: err.code || null, retryIn: err.retryIn || null });
}
})();
return state.job;
}
/* ---------- router delle API ---------- */
const MODELS = {
"z-image": { nome: "Z-Image Turbo", descrizione: "Il più fedele al prompt. Foto realistiche e testo dentro l'immagine.", modalita: ["crea", "ristila"], qualita: { rapida: 6, bilanciata: 9, massima: 14 } },
klein: { nome: "FLUX.2 Klein", descrizione: "Veloce, stile pulito. L'unico che modifica le foto a comando.", modalita: ["crea", "ristila", "modifica", "continua"], qualita: { rapida: 4, bilanciata: 5, massima: 8 } },
};
const ASPECTS = { "1:1": [1024, 1024], "4:5": [896, 1120], "3:4": [864, 1152], "2:3": [832, 1248], "9:16": [768, 1344], "16:9": [1344, 768], "3:2": [1248, 832] };
function status() {
const busy = [...jobs.values()].filter((s) => !["fatto", "errore"].includes(s.job.status)).length;
return {
modello: "pronto",
modello_caricato: null,
modelli_installati: { "z-image": true, klein: true },
lavori_attivi: busy,
traduttore: true,
strumenti: { ingrandisci: true, scontorna: true, vettorizza: true },
motore_finto: false,
online: true,
formati: ASPECTS,
modelli: MODELS,
automatico: { crea: "z-image", ristila: "klein", modifica: "klein", continua: "klein", rifinisci: "z-image" },
max_riferimenti: 4,
};
}
async function posterSave(blob, info) {
const bmp = await bitmap(blob);
const meta = {
_stem: `${clock()}_locandina_${rand()}`,
modalita: "locandina",
prompt: String(info.titolo || "").slice(0, 120),
prompt_finale: "",
template: "libero",
stili: [],
campi: {},
riferimenti: info.sfondo ? [String(info.sfondo)] : [],
formato: String(info.formato || ""),
larghezza: bmp.width,
altezza: bmp.height,
qualita: "",
passi: 0,
seed: 0,
modello: "compositore",
modello_nome: "Compositore",
trasparente: false,
creata: stamp(),
titolo: String(info.titolo || "").slice(0, 120),
preferita: false,
};
bmp.close?.();
return storeItem("galleria", meta, blob, await thumbnail(blob));
}
async function vectorize(body) {
const blob = await readBlob(body.file);
if (!blob) throw new Error("Immagine non trovata.");
const form = new FormData();
form.append("file", blob, "immagine.png");
form.append("stile", body.stile || "colori");
form.append("trasparente", String(body.trasparente !== false));
const res = await fetch("/api/vectorize", { method: "POST", body: form });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || "Vettorizzazione non riuscita.");
return data;
}
async function extractStyle(body) {
const res = await fetch("/api/styles/extract", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...body, stili_utente: await userStyles() }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || "Non riuscito.");
return data;
}
const filesOf = (body) => (body.files || (body.file ? [body.file] : [])).map(String);
async function api(path, body, headers = {}) {
const url = new URL(path, location.origin);
const p = url.pathname;
if (body === undefined) {
if (p === "/api/status") return status();
if (p === "/api/templates") return templates();
if (p === "/api/history") return history(url.searchParams);
if (p.startsWith("/api/jobs/")) {
const s = jobs.get(p.split("/").pop());
if (!s) throw new Error("Lavoro non trovato.");
return s.job;
}
throw new Error("Pagina non trovata.");
}
switch (p) {
case "/api/upload": {
const { blob, width, height } = await cleanUpload(body);
const name = decodeURIComponent(headers["X-Filename"] || "").slice(0, 80);
return { file: await saveInput(blob, name), larghezza: width, altezza: height, nome: name };
}
case "/api/poster": {
const info = JSON.parse(decodeURIComponent(headers["X-Meta"] || "") || "{}");
return posterSave(body, info);
}
case "/api/generate":
return startJob(body);
case "/api/enhance":
if (!String(body.prompt || "").trim()) throw new Error("Scrivi prima un'idea da migliorare.");
return improve(String(body.prompt), body.modalita || "crea");
case "/api/translate":
return { testo: String(body.testo || "").trim() ? await write(body.verso === "it" ? "in_italiano" : "traduci", String(body.testo)) : "" };
case "/api/vectorize":
return vectorize(body);
case "/api/keep": {
const kept = [];
for (const f of filesOf(body)) { const m = await move(f, "bozze", "galleria"); if (m) kept.push(m); }
return { salvate: kept };
}
case "/api/discard": {
let n = 0;
const list = body.tutto ? (await itemsIn("bozze")).map((r) => r.file) : filesOf(body);
for (const f of list) if (await remove(f, "bozze")) n++;
return { scartate: n };
}
case "/api/trash": {
let n = 0;
for (const f of filesOf(body)) if (await move(f, "galleria", "cestino")) n++;
return { spostate: n };
}
case "/api/restore": {
let n = 0;
for (const f of filesOf(body)) if (await move(f, "cestino", "galleria")) n++;
return { ripristinate: n };
}
case "/api/purge": {
let n = 0;
const list = body.tutto ? (await itemsIn("cestino")).map((r) => r.file) : filesOf(body);
for (const f of list) if (await remove(f, "cestino")) n++;
return { eliminate: n };
}
case "/api/update": {
const rec = await readItem(String(body.file || ""));
if (!rec || rec.scope !== "galleria") throw new Error("Immagine non trovata.");
const changes = body.modifiche || {};
if ("titolo" in changes) rec.meta.titolo = String(changes.titolo || "").trim().slice(0, 120);
if ("preferita" in changes) rec.meta.preferita = !!changes.preferita;
await tx("items", "readwrite", (s) => { s.put(rec); });
return rec.meta;
}
case "/api/styles/save":
return saveStyle(body);
case "/api/styles/extract":
return extractStyle(body);
case "/api/styles/delete": {
const items = await userStyles();
const next = items.filter((i) => i.id !== String(body.id || ""));
if (next.length === items.length) throw new Error("Stile non trovato.");
await kvSet("stili", next);
return { ok: true };
}
case "/api/unload":
case "/api/shutdown":
return { ok: true };
default:
throw new Error("Azione non trovata.");
}
}
async function serviceWorker() {
if (!("serviceWorker" in navigator)) return false;
try {
await navigator.serviceWorker.register("/sw.js", { scope: "/" });
await navigator.serviceWorker.ready;
if (!navigator.serviceWorker.controller) {
await new Promise((resolve) => {
navigator.serviceWorker.addEventListener("controllerchange", resolve, { once: true });
setTimeout(resolve, 1500);
});
}
return !!navigator.serviceWorker.controller;
} catch {
return false;
}
}
const ready = (async () => {
await db();
const sw = await serviceWorker();
cleanOld().catch(() => {});
if (navigator.storage?.persist) navigator.storage.persist().catch(() => {});
return { serviceWorker: sw };
})();
window.PixBackend = { api, ready, engine, quotaReset, account, logout, loginResult, on: (fn) => listeners.add(fn), readBlob, get lastPayload() { return lastPayload; } };
})();