import { api, withLogin, getPassword, askPassword, esc, $ } from "./api.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 cfg;
const collator = new Intl.Collator("cs", { numeric: true, sensitivity: "base" });
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) })));
files.sort((a, b) => collator.compare(a.file.name, b.file.name));
if (files.length > cfg.maxPages) {
showError(`Najednou lze nahrát nejvýše ${cfg.maxPages} stran.`);
files.splice(cfg.maxPages).forEach((f) => URL.revokeObjectURL(f.url));
}
renderThumbs();
}
function renderThumbs() {
$("thumbs").innerHTML = files.map((f, i) => `
${i + 1}
${esc(f.file.name)}
`).join("");
$("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;
$("status").textContent = text;
if (value !== undefined) $("bar").value = value;
}
async function waitForTranscription(id) {
for (;;) {
const meta = await api(`plays/${id}`);
if (meta.progress) setStatus(`Přepisuji stranu ${Math.min(meta.progress.done + 1, meta.progress.total)} z ${meta.progress.total}…`, meta.progress.done / meta.progress.total);
if (meta.status !== "processing") return meta;
await new Promise((r) => setTimeout(r, 2000));
}
}
async function submit(e) {
e.preventDefault();
showError("");
if (!files.length) return;
$("go").disabled = true;
$("form").classList.add("busy");
try {
const meta = await withLogin(() => api("plays", { method: "POST", body: { title: $("title").value, note: $("note").value } }));
const id = encodeURIComponent(meta.id);
for (let i = 0; i < files.length; i++) {
setStatus(`Nahrávám stranu ${i + 1} z ${files.length}…`, i / files.length);
await api(`plays/${id}/images/${i + 1}`, { method: "PUT", body: await toJpeg(files[i].file), type: "image/jpeg" });
}
if (cfg.transcription) {
setStatus("Začínám přepis…", 0);
await api(`plays/${id}/transcribe`, { method: "POST" });
// leaving the page is fine: the server keeps going and the editor shows progress
window.removeEventListener("beforeunload", warn);
await waitForTranscription(id);
}
location.href = `edit.html?id=${id}`;
} catch (err) {
showError(err.message);
$("go").disabled = false;
} finally {
$("form").classList.remove("busy");
}
}
const warn = (e) => { if (files.length && !$("progress").hidden) e.preventDefault(); };
async function main() {
cfg = await api("config");
if (!cfg.uploads) {
$("disabled").textContent = "Přidávání her je na tomto serveru vypnuté (správce nenastavil UPLOAD_PASSWORD).";
$("disabled").hidden = false;
$("form").hidden = true;
return;
}
if (!cfg.transcription) {
$("ai-note").textContent = "Automatický přepis není na serveru zapnutý (chybí klíč k API). 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.");
$("files").addEventListener("change", (e) => { addFiles(e.target.files); e.target.value = ""; });
const drop = $("drop");
drop.addEventListener("dragover", (e) => { e.preventDefault(); drop.classList.add("over"); });
drop.addEventListener("dragleave", () => drop.classList.remove("over"));
drop.addEventListener("drop", (e) => { e.preventDefault(); drop.classList.remove("over"); addFiles(e.dataTransfer.files); });
$("thumbs").addEventListener("click", (e) => {
const b = e.target.closest("button");
if (!b) return;
const i = Number(b.dataset.i);
if (b.hasAttribute("data-remove")) URL.revokeObjectURL(files.splice(i, 1)[0].url);
else {
const j = i + Number(b.dataset.move);
[files[i], files[j]] = [files[j], files[i]];
}
renderThumbs();
});
$("form").addEventListener("submit", submit);
window.addEventListener("beforeunload", warn);
renderThumbs();
}
main().catch((err) => showError(err.message));