devmandan's picture
Claude Opus 5.5
Slants and cans, what a phone sees, a test sheet, SVG files and more
378f397 verified
Raw History Blame Contribute Delete
5.14 kB
// Sending a picture to the server, for its reading (api/measure) and for its design test (api/design): the checks
// this browser makes first, the file without its details (details.js) or converted (a format the server doesn't
// open, or one whose content and type disagree; an SVG is drawn first: svg.js), and the reading's errors in the page's
// words. Moved out of app.js so that both routes send a picture under the same rules. Nothing else is sent or kept.
import { t } from './copy.js';
import { withoutRecord } from './png.js';
import { withoutDetails } from './details.js';
export const MAX_MB = 25;
export const MAX_BYTES = MAX_MB * 1024 * 1024;
export const MAX_CANVAS = 16e6; // pixels: a picture this browser converts is drawn at most this big (every browser can)
export function failure(message, retry = false) {
const err = new Error(message);
err.retry = retry;
return err;
}
export async function send(url, blob, signal) {
try {
return await fetch(url, { method: 'POST', body: blob, signal, headers: { 'Content-Type': blob.type || 'application/octet-stream' } });
} catch {
throw failure(t('errors.unreachable'), true);
}
}
/** source (an ImageBitmap, or an SVG loaded as an image: svg.js) drawn w x h on white, as on a printed page:
* as PNG, or as a high-quality JPEG when the PNG would be over 25 MB. A bitmap is closed once drawn. */
export async function drawn(source, w, h) {
const canvas = Object.assign(document.createElement('canvas'), { width: w, height: h });
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, w, h);
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(source, 0, 0, w, h);
source.close?.();
const encode = (type, quality) => new Promise((resolve) => canvas.toBlob(resolve, type, quality));
let out = await encode('image/png');
if (out && out.size > MAX_BYTES) out = await encode('image/jpeg', 0.95);
if (!out) throw failure(t('errors.prepare'));
if (out.size > MAX_BYTES) throw failure(t('errors.too_big_converted', { mb: MAX_MB }));
return out;
}
/** A picture in a format the server doesn't open (HEIC, AVIF, GIF…) as this browser shows it (drawn), then without
* details. One bigger than MAX_CANVAS pixels is drawn at that size, still well above the largest read (1920 pixels). */
export async function converted(file) {
let bitmap;
try {
bitmap = await createImageBitmap(file);
} catch {
throw failure(t('errors.format'));
}
const k = Math.min(1, Math.sqrt(MAX_CANVAS / (bitmap.width * bitmap.height)));
const out = await drawn(bitmap, Math.max(1, Math.round(bitmap.width * k)), Math.max(1, Math.round(bitmap.height * k)));
return (await withoutDetails(out)) ?? out; // without what this browser's encoder adds, such as Firefox's deBG or WebKit's eXIf chunk (details.js)
}
/** What a picture goes to the server as, checked first: an SVG not drawn yet, a file over MAX_MB or an empty file isn't
* sent (a failure in the page's words); a format the server doesn't open goes converted, and any other without its
* details. A design test makes it before asking for its slot, so a slow conversion never uses up the slot's hold. */
export async function prepare(file) {
if (file.type === 'image/svg+xml') throw failure(t('errors.svg')); // drawn before any upload (svg.js): one not drawn is never sent
if (file.size > MAX_BYTES) throw failure(t('errors.too_big', { mb: MAX_MB }));
if (!file.size) throw failure(t('rows.empty_file'));
if (!/^image\/(jpeg|png|webp)$/.test(file.type)) return converted(file); // a format the server doesn't open
return (await withoutDetails(await withoutRecord(file))) ?? converted(file); // never with a qr-made chunk (png.js) or a photo's details (details.js); a structure it can't follow, converted
}
/** Send a picture to url under the server's rules, as prepare() makes it (or made it already: blob), and give back
* the server's response; the file sent as it is and refused as of the wrong type (415) goes once more, converted.
* Throws failure(errors.unreachable, true) when the server can't be reached. */
export async function upload(url, file, signal, blob = null) {
const sent = blob || (await prepare(file));
const res = await send(url, sent, signal);
if (res.status === 415 && sent === file) return send(url, await converted(file), signal); // type and content disagree
return res;
}
/** The reading of one picture: its reads, place, level and checks, or a failure in the page's words (retry: a busy,
* slow or unreachable server, which Try again can help). */
export async function measure(file, signal) {
const res = await upload('api/measure', file, signal);
if (!res.ok) {
let message = '';
try { message = (await res.json()).error; } catch { /* not JSON */ }
const retry = res.status === 408 || res.status >= 500; // slow to arrive, busy, or a server fault
throw failure(message || t(retry ? 'errors.busy' : 'errors.unreadable'), retry);
}
try {
return await res.json();
} catch {
throw failure(t('errors.busy'), true); // cut off on the way, or not the server's answer
}
}