Login button with show-password, skip identical photos on upload
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
This commit is contained in:
parent
ab842a1d73
commit
6240907809
6 changed files with 138 additions and 44 deletions
|
|
@ -9,8 +9,11 @@
|
|||
</head>
|
||||
<body class="page-add">
|
||||
<header class="topbar">
|
||||
<div>
|
||||
<nav class="crumbs"><a href="./">← Všechny hry</a></nav>
|
||||
<h1>Přidat hru</h1>
|
||||
</div>
|
||||
<div class="topbar-actions" id="auth"></div>
|
||||
</header>
|
||||
<main class="wrap">
|
||||
<p class="error" id="disabled" hidden></p>
|
||||
|
|
@ -25,7 +28,8 @@
|
|||
<input type="file" id="files" accept="image/*" multiple>
|
||||
<span><b>Vyberte fotky</b> nebo je sem přetáhněte. Jedna fotka = jedna strana.</span>
|
||||
</label>
|
||||
<p class="muted small">Strany se seřadí podle názvu souboru; pořadí můžete změnit šipkami. Fotky se před nahráním zmenší.</p>
|
||||
<p class="muted small">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ší.</p>
|
||||
<p class="notice" id="notice" role="status" hidden></p>
|
||||
<ol class="thumbs" id="thumbs"></ol>
|
||||
</fieldset>
|
||||
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
|
|
|
|||
|
|
@ -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 = `<form method="dialog">
|
||||
<h2>Heslo pro úpravy</h2>
|
||||
dlg.innerHTML = `<form method="dialog" novalidate>
|
||||
<h2>Přihlášení</h2>
|
||||
${reason ? `<p class="muted">${esc(reason)}</p>` : ""}
|
||||
<label class="field"><span>Heslo</span><input type="password" name="pw" autocomplete="current-password" required></label>
|
||||
<label class="radio"><input type="checkbox" name="remember"> Zapamatovat na tomto zařízení</label>
|
||||
<p class="error" hidden></p>
|
||||
<div class="actions"><button value="cancel" formnovalidate>Zrušit</button><button class="primary" value="ok">Přihlásit</button></div>
|
||||
<label class="field"><span>Heslo</span>
|
||||
<span class="pw-field">
|
||||
<input type="password" name="pw" autocomplete="current-password" autocapitalize="off" spellcheck="false" aria-describedby="login-error">
|
||||
<button type="button" class="eye" aria-label="Zobrazit heslo" aria-pressed="false" title="Zobrazit heslo">${EYE}</button>
|
||||
</span>
|
||||
</label>
|
||||
<label class="check"><input type="checkbox" name="remember"> Zůstat přihlášen v tomto prohlížeči</label>
|
||||
<p class="error" id="login-error" role="alert" hidden></p>
|
||||
<div class="actions"><button value="cancel" type="button" data-cancel>Zrušit</button><button class="primary" value="ok" type="submit">Přihlásit</button></div>
|
||||
</form>`;
|
||||
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 = `<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg>`;
|
||||
const EYE_OFF = `<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.6 5.1A10.9 10.9 0 0 1 12 5c6.5 0 10 7 10 7a17.6 17.6 0 0 1-2.9 3.8M6.6 6.6C3.6 8.4 2 12 2 12s3.5 7 10 7c1.8 0 3.4-.5 4.8-1.3"/><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2"/><path d="M3 3l18 18"/></svg>`;
|
||||
|
||||
// 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(); }
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@
|
|||
<h1>Divadelní čtečka</h1>
|
||||
<div class="topbar-actions">
|
||||
<a class="button primary" id="add" href="add.html" hidden>+ Přidat hru</a>
|
||||
<button id="logout" hidden>Odhlásit</button>
|
||||
</div>
|
||||
</header>
|
||||
<main class="wrap">
|
||||
|
|
|
|||
|
|
@ -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 = `<li class="muted">Zatím tu není žádná hra.${cfg.uploads ? " Přidejte první tlačítkem nahoře." : ""}</li>`;
|
||||
$("plays").innerHTML = `<li class="muted">Zatím tu není žádná hra.${loggedIn ? " Přidejte první tlačítkem nahoře." : ""}</li>`;
|
||||
return;
|
||||
}
|
||||
$("plays").innerHTML = plays.map((p) => {
|
||||
|
|
|
|||
36
public/photos.js
Normal file
36
public/photos.js
Normal file
|
|
@ -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)}`;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue