From 624090780962ddeb39e7e15adbb02331f09a7ff6 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 4 Nov 2026 16:15:27 +0000 Subject: [PATCH] Login button with show-password, skip identical photos on upload MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Přihlásit/Odhlásit button in the top bar replaces logging in via Přidat hru. The dialog has an eye toggle, says when it is checking, and keeps the remember box as it was after a wrong password; nothing is stored until the server accepts it. A remembered password that no longer works is dropped on load. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt --- public/add.html | 10 +++++-- public/add.js | 43 ++++++++++++--------------- public/api.js | 75 ++++++++++++++++++++++++++++++++++++++++------- public/index.html | 1 - public/library.js | 17 +++++++---- public/photos.js | 36 +++++++++++++++++++++++ 6 files changed, 138 insertions(+), 44 deletions(-) create mode 100644 public/photos.js diff --git a/public/add.html b/public/add.html index 9f54e1e..6ad7c5a 100644 --- a/public/add.html +++ b/public/add.html @@ -9,8 +9,11 @@
- -

Přidat hru

+
+ +

Přidat hru

+
+
@@ -25,7 +28,8 @@ Vyberte fotky nebo je sem přetáhněte. Jedna fotka = jedna strana. -

Strany se seřadí podle názvu souboru; pořadí můžete změnit šipkami. Fotky se před nahráním zmenší.

+

Na pořadí nezáleží: po přepisu se strany seřadí podle čísel stran na fotkách a stejná strana nafocená dvakrát se použije jen jednou. Fotky se před nahráním zmenší.

+
    diff --git a/public/add.js b/public/add.js index 94c48e1..32068c7 100644 --- a/public/add.js +++ b/public/add.js @@ -1,22 +1,30 @@ -import { api, withLogin, getPassword, askPassword, esc, $ } from "./api.js"; +import { api, withLogin, getPassword, askPassword, authButton, esc, $ } from "./api.js"; +import { toJpeg, fingerprint } from "./photos.js"; -// The API reads images at most ~1.15 megapixels, so a bigger upload only costs bandwidth. -const MAX_PIXELS = 1.15e6; -const MAX_SIDE = 1568; - -let files = []; // [{ file, url }] +let files = []; // [{ file, url, hash }] let cfg; const collator = new Intl.Collator("cs", { numeric: true, sensitivity: "base" }); -function addFiles(list) { +// Add picked photos, skipping any that are byte-for-byte the same as one already +// picked. (Two different photos of the same page are sorted out after transcription.) +async function addFiles(list) { const imgs = [...list].filter((f) => f.type.startsWith("image/") || /\.(heic|heif)$/i.test(f.name)); - files.push(...imgs.map((file) => ({ file, url: URL.createObjectURL(file) }))); + const skipped = []; + for (const file of imgs) { + const hash = await fingerprint(file); + const same = files.find((f) => f.hash === hash); + if (same) { skipped.push(`„${file.name}“ je stejná fotka jako „${same.file.name}“`); continue; } + files.push({ file, hash, url: URL.createObjectURL(file) }); + } files.sort((a, b) => collator.compare(a.file.name, b.file.name)); + const notes = skipped.length ? [`Přeskočeno ${skipped.length === 1 ? "1 opakování" : `${skipped.length} opakování`}: ${skipped.join("; ")}.`] : []; if (files.length > cfg.maxPages) { - showError(`Najednou lze nahrát nejvýše ${cfg.maxPages} stran.`); + notes.push(`Najednou lze nahrát nejvýše ${cfg.maxPages} stran.`); files.splice(cfg.maxPages).forEach((f) => URL.revokeObjectURL(f.url)); } + $("notice").textContent = notes.join(" "); + $("notice").hidden = !notes.length; renderThumbs(); } @@ -35,20 +43,6 @@ function renderThumbs() { $("go").disabled = !files.length; } -// Decode, shrink and re-encode as JPEG (also strips EXIF, e.g. location). -async function toJpeg(file) { - let bitmap; - try { bitmap = await createImageBitmap(file, { imageOrientation: "from-image" }); } - catch { throw new Error(`Obrázek „${file.name}“ se nepodařilo otevřít${/\.hei[cf]$/i.test(file.name) ? " (formát HEIC – zkuste fotku uložit jako JPEG)" : ""}.`); } - const scale = Math.min(1, MAX_SIDE / Math.max(bitmap.width, bitmap.height), Math.sqrt(MAX_PIXELS / (bitmap.width * bitmap.height))); - const canvas = document.createElement("canvas"); - canvas.width = Math.round(bitmap.width * scale); - canvas.height = Math.round(bitmap.height * scale); - canvas.getContext("2d").drawImage(bitmap, 0, 0, canvas.width, canvas.height); - bitmap.close(); - return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Převod obrázku selhal."))), "image/jpeg", 0.88)); -} - function showError(msg) { $("error").textContent = msg; $("error").hidden = !msg; } function setStatus(text, value) { $("progress").hidden = false; @@ -108,7 +102,8 @@ async function main() { $("ai-note").textContent = "Automatický přepis není na serveru zapnutý (chybí klíč OPENROUTER_API_KEY nebo ANTHROPIC_API_KEY). Fotky se nahrají a text pak napíšete v editoru ručně."; $("go").textContent = "Nahrát"; } - if (!getPassword()) askPassword("Přidávat hry může jen ten, kdo zná heslo."); + await authButton($("auth"), { uploads: true, onChange: (inn) => { if (!inn) location.replace("./"); } }); + if (!getPassword() && !(await askPassword("Přidávat hry může jen ten, kdo zná heslo."))) { location.replace("./"); return; } $("files").addEventListener("change", (e) => { addFiles(e.target.files); e.target.value = ""; }); const drop = $("drop"); diff --git a/public/api.js b/public/api.js index d710afd..4ba0382 100644 --- a/public/api.js +++ b/public/api.js @@ -10,6 +10,7 @@ export function setPassword(pw, remember) { if (remember) localStorage.setItem(PASS_KEY, pw); else localStorage.removeItem(PASS_KEY); } catch { /* storage blocked: the password just won't be remembered */ } } +const isRemembered = () => { try { return Boolean(localStorage.getItem(PASS_KEY)); } catch { return false; } }; export function clearPassword() { try { sessionStorage.removeItem(PASS_KEY); localStorage.removeItem(PASS_KEY); } catch { /* ignore */ } } @@ -52,37 +53,91 @@ export const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", export const $ = (id) => document.getElementById(id); // Ask for the upload password in a modal dialog; resolves true once logged in, false if cancelled. +// The password is stored only after the server accepted it, and only where the +// "stay logged in" box says (this tab, or this browser until "Odhlásit"). export function askPassword(reason = "") { return new Promise((resolve) => { const dlg = document.createElement("dialog"); dlg.className = "login"; - dlg.innerHTML = `
    -

    Heslo pro úpravy

    + dlg.innerHTML = ` +

    Přihlášení

    ${reason ? `

    ${esc(reason)}

    ` : ""} - - - -
    + + + +
    `; document.body.append(dlg); const form = dlg.querySelector("form"); + const pw = form.pw; const err = dlg.querySelector(".error"); + const ok = form.querySelector("button[type=submit]"); + const eye = form.querySelector(".eye"); + const showError = (msg) => { + err.textContent = msg; + err.hidden = !msg; + pw.toggleAttribute("aria-invalid", Boolean(msg)); + }; + eye.addEventListener("click", () => { + const show = pw.type === "password"; + pw.type = show ? "text" : "password"; + eye.innerHTML = show ? EYE_OFF : EYE; + eye.setAttribute("aria-pressed", String(show)); + eye.title = eye.ariaLabel = show ? "Skrýt heslo" : "Zobrazit heslo"; + pw.focus(); + }); + pw.addEventListener("input", () => showError("")); + form.querySelector("[data-cancel]").addEventListener("click", () => dlg.close("cancel")); form.addEventListener("submit", async (e) => { - if (e.submitter?.value !== "ok") return; e.preventDefault(); + if (!pw.value) { showError("Zadejte heslo."); pw.focus(); return; } + ok.disabled = true; + ok.textContent = "Ověřuji…"; try { - await login(form.pw.value, form.remember.checked); + await login(pw.value, form.remember.checked); dlg.close("ok"); } catch (ex) { - err.textContent = ex.message; - err.hidden = false; + showError(ex.status === 401 ? "Heslo nesouhlasí, zkuste to znovu." : ex.message); + pw.select(); + pw.focus(); + } finally { + ok.disabled = false; + ok.textContent = "Přihlásit"; } }); dlg.addEventListener("close", () => { dlg.remove(); resolve(dlg.returnValue === "ok"); }); dlg.showModal(); + pw.focus(); }); } +const EYE = ``; +const EYE_OFF = ``; + +// Log in/out button for a page's top bar. onChange runs after logging in or out. +export async function authButton(container, { uploads, onChange = () => location.reload() }) { + if (!uploads) return; + // a remembered password may have been changed on the server since + if (getPassword()) { + try { await login(getPassword(), isRemembered()); } + catch (err) { if (err.status === 401) clearPassword(); } + } + const btn = document.createElement("button"); + btn.className = "auth"; + const render = () => { btn.textContent = getPassword() ? "Odhlásit" : "Přihlásit"; }; + render(); + btn.addEventListener("click", async () => { + if (getPassword()) { clearPassword(); render(); onChange(false); return; } + if (await askPassword()) { render(); onChange(true); } + }); + container.append(btn); +} + // Run fn; on 401 ask for the password and retry once. export async function withLogin(fn, reason) { try { return await fn(); } diff --git a/public/index.html b/public/index.html index 5c63219..089fdc6 100644 --- a/public/index.html +++ b/public/index.html @@ -13,7 +13,6 @@

    Divadelní čtečka

    -
    diff --git a/public/library.js b/public/library.js index c3c4e3e..f9fd98a 100644 --- a/public/library.js +++ b/public/library.js @@ -1,4 +1,4 @@ -import { api, getPassword, clearPassword, esc, $ } from "./api.js"; +import { api, getPassword, authButton, esc, $ } from "./api.js"; // Old links (/?postava=Lída or /?hra=…) went straight to the reader. const q = new URLSearchParams(location.search); @@ -7,14 +7,19 @@ if (q.has("hra") || q.has("postava")) location.replace(`read.html${location.sear const fmtDate = (iso) => new Date(iso).toLocaleDateString("cs-CZ", { day: "numeric", month: "numeric", year: "numeric" }); async function main() { - const [cfg, plays] = await Promise.all([api("config"), api("plays")]); + const cfg = await api("config"); + await authButton(document.querySelector(".topbar-actions"), { uploads: cfg.uploads, onChange: render }); + await render(); +} + +// Logged in, the list also shows drafts, with buttons to add and edit plays. +async function render() { + const plays = await api("plays"); const loggedIn = Boolean(getPassword()); - $("add").hidden = !cfg.uploads; - $("logout").hidden = !loggedIn; - $("logout").addEventListener("click", () => { clearPassword(); location.reload(); }); + $("add").hidden = !loggedIn; if (!plays.length) { - $("plays").innerHTML = `
  1. Zatím tu není žádná hra.${cfg.uploads ? " Přidejte první tlačítkem nahoře." : ""}
  2. `; + $("plays").innerHTML = `
  3. Zatím tu není žádná hra.${loggedIn ? " Přidejte první tlačítkem nahoře." : ""}
  4. `; return; } $("plays").innerHTML = plays.map((p) => { diff --git a/public/photos.js b/public/photos.js new file mode 100644 index 0000000..a150cc9 --- /dev/null +++ b/public/photos.js @@ -0,0 +1,36 @@ +// Preparing page photos in the browser before upload. + +// The vision models read images at most ~1.15 megapixels, so a bigger upload only costs bandwidth. +const MAX_PIXELS = 1.15e6; +const MAX_SIDE = 1568; + +// Decode, shrink and re-encode as JPEG (also strips EXIF, e.g. location). +export async function toJpeg(file) { + let bitmap; + try { bitmap = await createImageBitmap(file, { imageOrientation: "from-image" }); } + catch { throw new Error(`Obrázek „${file.name}“ se nepodařilo otevřít${/\.hei[cf]$/i.test(file.name) ? " (formát HEIC – zkuste fotku uložit jako JPEG)" : ""}.`); } + const scale = Math.min(1, MAX_SIDE / Math.max(bitmap.width, bitmap.height), Math.sqrt(MAX_PIXELS / (bitmap.width * bitmap.height))); + const canvas = document.createElement("canvas"); + canvas.width = Math.round(bitmap.width * scale); + canvas.height = Math.round(bitmap.height * scale); + canvas.getContext("2d").drawImage(bitmap, 0, 0, canvas.width, canvas.height); + bitmap.close(); + return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Převod obrázku selhal."))), "image/jpeg", 0.88)); +} + +// Fingerprint of a file's bytes, to spot the same photo picked twice. +// crypto.subtle exists only on https/localhost, so fall back to FNV-1a there. +export async function fingerprint(file) { + const buf = await file.arrayBuffer(); + if (globalThis.crypto?.subtle) { + const h = new Uint8Array(await crypto.subtle.digest("SHA-256", buf)); + return [...h].map((b) => b.toString(16).padStart(2, "0")).join(""); + } + const bytes = new Uint8Array(buf); + let h1 = 0x811c9dc5, h2 = 0x01000193 ^ bytes.length; + for (let i = 0; i < bytes.length; i++) { + h1 = Math.imul(h1 ^ bytes[i], 0x01000193); + h2 = Math.imul(h2 ^ bytes[bytes.length - 1 - i], 0x01000193); + } + return `${bytes.length}-${(h1 >>> 0).toString(16)}-${(h2 >>> 0).toString(16)}`; +}