Public: anyone can read this; the crew can change it.

A photo's camera, lens, exposure and capture time are listed beside the image #14466

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/14451-a-photo-s-camera-lens-exposure-and-captu → main 5 commits fork 5 threads · 5 unresolved

  • Merged. scout/14451-a-photo-s-camera-lens-exposure-and-captu was merged into main as 1282269.

Review

Sign in to review this change.
15 files changed +533 −10
docs/design/areas/render.md +4
@@ -27,6 +27,10 @@ Backgrounds, 256-colour above 15 and truecolour are dropped; so are cursor moves
2727
2828 A .zip, .tar or .tar.gz is drawn by `src/web/render/archive-view.ts` as the existing `.table` alone, with no `.card` around it (path, size, modified; `data-dense`), and a `tfoot` for the count and unpacked size. No new class: `.archive-view` is only a hook on the table and has no rule. How it works: `docs/features/archive-listing.md`. A list that cannot be read falls back to the Download card with the reason as its one sentence.
2929
30 ## Photo facts (.jpg, .jpeg, .tif, .tiff)
31
32 `src/web/render/image.ts` adds the EXIF facts (`src/web/render/exif.ts`: make, model, lens, focal length, aperture, shutter, ISO, taken-at as a date, GPS labelled "GPS (latitude, longitude)") as the existing `.status-rows` `dl`, in rows below the picture's `.card`, not inside it. No new class. A TIFF has no `<img>` (most browsers do not draw it): its card holds the size and format, and the facts follow. A file with no EXIF draws as before. How it works: `docs/features/photo-facts.md`.
33
3034 ## Photoshop file (.psd)
3135
3236 `src/web/render/psd.ts` draws the facts as the existing `.status-rows` `dl`, the preview in the existing `.imgview-pane`, and the layers as a second `.status-rows` (name, Visible or Hidden). No card and no new class: `.psd-view` is only a hook and has no rule. How it works: `docs/features/psd.md`.
docs/features/file-kinds.md +1 −1
@@ -8,7 +8,7 @@ The forge draws a file on its page when its kind is below and it is within the s
88
99 <!-- file-kinds:begin (generated by scripts/kinds-guide.ts from src/web/render/kinds.ts; edit the code, then run `bun scripts/kinds-guide.ts`) -->
1010
11 - **Image**, drawn up to 50 MB: `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.avif`, `.bmp`, `.ico`
11 - **Image**, drawn up to 50 MB: `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.avif`, `.tif`, `.tiff`, `.bmp`, `.ico`
1212 - **SVG**, drawn up to 5 MB: `.svg`
1313 - **PDF**, drawn up to 100 MB: `.pdf`
1414 - **HTML page**, drawn up to 2 MB: `.html`, `.htm`
docs/features/photo-facts.md added +11
@@ -0,0 +1,11 @@
1 ---
2 topic: Files in the browser
3 row: A photo's camera, lens, exposure, capture time and GPS beside the picture
4 ---
5 # Photo facts
6
7 Open a `.jpg`, `.jpeg`, `.tif` or `.tiff` that carries camera data and the page lists, in rows under the picture: camera make and model, lens, focal length, aperture, shutter, ISO, when it was taken (the camera's own clock, as "6 May 2024, 07:08") and, if the camera recorded one, "GPS (latitude, longitude)" as plain numbers. A file with no camera data shows the picture alone.
8
9 - **Large photos.** The facts live in the first 64 KiB of the file, so a phone photo over the page's size limit still lists them; only the head is read.
10 - **In the terminal.** In the workspace, open the photo and press `v` to swap the picture for its facts, which include the same rows. A photo too large to open shows them in its note.
11 - **Nothing leaves the forge.** GPS is text; no map is fetched.
src/tui/screens/workspace.ts +5 −1
@@ -125,6 +125,7 @@ import {
125125 import { fill, len, split } from "../ui/layout.ts";
126126 import { renderMarkdown, type Line } from "../ui/markdown.ts";
127127 import { archiveNote } from "../ui/archive-note.ts";
128 import { holdsExif, readExif } from "../../web/render/exif.ts";
128129 import { psdNote } from "../ui/psd-note.ts";
129130 import { mediaNote } from "../ui/media-note.ts";
130131 import { undrawable, UNDRAWN } from "../../web/render/undrawable.ts";
@@ -1542,7 +1543,9 @@ export function workspaceScreen(
15421543 // One line a part, so the pane keeps the whole reason and the way to the download.
15431544 const said = undrawable(t.path, read.value, formatSize);
15441545 const lines = said === undefined ? [`${formatSize(read.value.size)} — over the render cap.`] : [said.name, said.size, said.reason];
1545 note = `${lines.join("\n")}\n\n${downloadAt(t.path)}`;
1546 // A photo's EXIF is in its head, so its facts are read even when the file is not.
1547 const photo = holdsExif(t.path) && read.value.head !== undefined ? readExif(read.value.head).map((f) => `${f.label}: ${f.value}`) : [];

New terminal behaviour (facts in the too-large note, and the v rows below) has no test. Add a workspace test that opens a JPEG fixture from test/helpers/exif.ts and asserts the rows, plus one for the too-large note. The tests must fail without this change.

1548 note = `${[...lines, ...photo].join("\n")}\n\n${downloadAt(t.path)}`;
15461549 } else if (read.value.kind === "binary") {
15471550 // A binary blob whose *name* says picture is the one binary we do
15481551 // something with. Everything else keeps the honest note: showing
@@ -3280,6 +3283,7 @@ export function workspaceScreen(
32803283 image.width > 0 ? `${image.width} × ${image.height}` : "unknown",
32813284 ],
32823285 ["size", humanBytes(image.byteLength)],
3286 ...readExif(image.bytes).map((f): [string, string] => [f.label.toLowerCase(), f.value]),
32833287 ["path", t.path],
32843288 ["terminal", `${ctx.caps.term ?? "unknown"} · ${ctx.caps.graphics}`],
32853289 ["cell", `${ctx.caps.cell.width}×${ctx.caps.cell.height}px${
src/view/local.ts +3 −1
@@ -47,6 +47,7 @@ import { repoDir } from "../git/repos.ts";
4747 import { err, ok, type Result } from "../kernel/result.ts";
4848 import type { Page } from "../origins/types.ts";
4949 import { tailable, TAIL_BYTES } from "../web/log_tail.ts";
50 import { EXIF_WINDOW, holdsExif } from "../web/render/exif.ts";
5051 import { CSV_PREFIX_BYTES, HEAD_BYTES, isJsonPath, isTablePath, JSON_PREFIX_BYTES, RENDER_CAP, wholeLines } from "../web/render/kinds.ts";
5152 import type {
5253 Blob,
@@ -231,7 +232,8 @@ export function localSource(
231232 return ok({ kind: "text", body: prefix, size: blob.size, partial: true });
232233 }
233234 // Too large to read, but its first bytes still say what it is.
234 const head = await blobHead(dir, ref, path, HEAD_BYTES);
235 // A photo's head is its EXIF window, so a phone JPEG over the ceiling still shows its facts.
236 const head = await blobHead(dir, ref, path, holdsExif(path) ? EXIF_WINDOW : HEAD_BYTES);

The EXIF_WINDOW head for an over-ceiling photo is only tested through capped(). Add a test on localSource.blob() that an over-ceiling .jpg returns a 64 KiB head.

235237 const tail = tailable(path) ? await blobTail(dir, ref, path, TAIL_BYTES, blob.size) : undefined;
236238 return ok({ ...blob, ...(head === undefined ? {} : { head }), ...(tail === undefined ? {} : { tail }) });
237239 },
src/web/pages/repo.ts +2 −1
@@ -106,6 +106,7 @@ import { csvJs, isCsvPath, sortColumn } from "../render/csv.ts";
106106 import { fontJs } from "../render/font.ts";
107107 import { INLINE_MAX, keepGcode, keptGcode, layerCount } from "../render/gcode.ts";
108108 import { hasTable } from "../render/sqlite.ts";
109 import { EXIF_WINDOW, holdsExif } from "../render/exif.ts";
109110 import { READ_CEILING } from "../render/psd-read.ts";
110111 import { NO_MEMBER, openMember } from "../render/json-big.ts";
111112 import { CSV_PREFIX_BYTES, fileKind, HEAD_BYTES, isJsonPath, isTablePath, JSON_PREFIX_BYTES, kindByName, needsPaths, RENDER_CAP, sniffType } from "../render/kinds.ts";
@@ -2044,7 +2045,7 @@ export function capped(blob: Blob, path = ""): Blob {
20442045 // A big JSON file's body is already its prefix; the renderer outlines it.
20452046 if (blob.kind === "text" && blob.partial === true && blob.body.length <= JSON_PREFIX_BYTES && isJsonPath(path)) return blob;
20462047 return blob.kind !== "too_large" && blob.size > MAX_RENDER_BYTES
2047 ? { kind: "too_large", size: blob.size, head: blob.body.slice(0, HEAD_BYTES) }
2048 ? { kind: "too_large", size: blob.size, head: blob.body.slice(0, holdsExif(path) ? EXIF_WINDOW : HEAD_BYTES) }
20482049 : blob;
20492050 }
20502051
src/web/render/exif.ts added +168
@@ -0,0 +1,168 @@
1 /**
2 * The EXIF facts of a JPEG or TIFF: camera, lens, exposure, capture time and GPS as text.
3 *
4 * Only the first `EXIF_WINDOW` bytes are read, and every offset is checked against that window, so
5 * a truncated block just ends the walk. An IFD offset seen twice is not followed again, and every
6 * loop is bounded (entries per IFD, IFDs in all), so a looping or hostile file cannot spin.
7 * Nothing is fetched: GPS is only the coordinates as text, never a map. Pure: bytes in, rows out.
8 */
9
10 /** How much of the file is read for EXIF. */
11 export const EXIF_WINDOW = 64 * 1024;
12 const MAX_ENTRIES = 256;
13 const MAX_IFDS = 8;
14
15 export interface ExifFact {
16 readonly label: string;
17 readonly value: string;
18 }
19
20 type Value = string | number | readonly number[];
21
22 /** Printable text only: control characters out, length bounded. The caller still escapes. */
23 const clean = (s: string, max = 100): string =>
24 s.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
25
26 /** Locate the TIFF header: at 0 for a TIFF, inside the first APP1 `Exif` segment for a JPEG. */
27 function tiffStart(b: Uint8Array): number | undefined {
28 const tiff = (at: number): boolean =>
29 b.length >= at + 8 && ((b[at] === 0x49 && b[at + 1] === 0x49 && b[at + 2] === 0x2a && b[at + 3] === 0) ||
30 (b[at] === 0x4d && b[at + 1] === 0x4d && b[at + 2] === 0 && b[at + 3] === 0x2a));
31 if (tiff(0)) return 0;
32 if (b[0] !== 0xff || b[1] !== 0xd8) return undefined;
33 let p = 2;
34 for (let n = 0; n < 64 && p + 4 <= b.length; n++) {
35 if (b[p] !== 0xff) return undefined;
36 const marker = b[p + 1]!;
37 if (marker === 0xff) { p++; continue; }
38 if (marker === 0xda || marker === 0xd9) return undefined;
39 const len = (b[p + 2]! << 8) | b[p + 3]!;
40 if (marker === 0xe1 && b[p + 4] === 0x45 && b[p + 5] === 0x78 && b[p + 6] === 0x69 && b[p + 7] === 0x66 && b[p + 8] === 0 && b[p + 9] === 0)
41 return tiff(p + 10) ? p + 10 : undefined;
42 if (len < 2) return undefined;
43 p += 2 + len;
44 }
45 return undefined;
46 }
47
48 /** Read the tags of one IFD; the pointers to further IFDs are returned by tag. */
49 function readIfd(b: Uint8Array, base: number, le: boolean, offset: number): Map<number, Value> {
50 const out = new Map<number, Value>();
51 const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
52 const at = base + offset;
53 if (offset < 8 || at + 2 > b.length) return out;
54 const count = Math.min(v.getUint16(at, le), MAX_ENTRIES);
55 for (let i = 0; i < count; i++) {
56 const e = at + 2 + i * 12;
57 if (e + 12 > b.length) break;
58 const tag = v.getUint16(e, le);
59 const type = v.getUint16(e + 2, le);
60 const n = v.getUint32(e + 4, le);
61 const size = ({ 1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1 } as Record<number, number>)[type];
62 if (size === undefined || n === 0 || n > 0xffff) continue;
63 const bytes = size * n;
64 const data = bytes <= 4 ? e + 8 : base + v.getUint32(e + 8, le);
65 if (data < 0 || data + bytes > b.length) continue;
66 if (type === 2) {
67 out.set(tag, clean(new TextDecoder("latin1").decode(b.subarray(data, data + bytes))));
68 } else if (type === 3 || type === 4) {
69 const vals: number[] = [];
70 for (let k = 0; k < Math.min(n, 8); k++)
71 vals.push(type === 3 ? v.getUint16(data + k * 2, le) : v.getUint32(data + k * 4, le));
72 out.set(tag, vals.length === 1 ? vals[0]! : vals);
73 } else if (type === 5) {
74 const vals: number[] = [];
75 for (let k = 0; k < Math.min(n, 3); k++) {
76 const den = v.getUint32(data + k * 8 + 4, le);
77 vals.push(den === 0 ? NaN : v.getUint32(data + k * 8, le) / den);
78 }
79 out.set(tag, vals.length === 1 ? vals[0]! : vals);
80 }
81 }
82 return out;
83 }
84
85 const text = (m: Map<number, Value>, tag: number): string | undefined => {
86 const v = m.get(tag);
87 return typeof v === "string" && v !== "" ? v : undefined;
88 };
89 const num = (m: Map<number, Value>, tag: number): number | undefined => {
90 const v = m.get(tag);
91 const x = typeof v === "number" ? v : Array.isArray(v) ? v[0] : undefined;
92 return x !== undefined && Number.isFinite(x) ? x : undefined;
93 };
94 const trim = (n: number, d: number): string => String(Number(n.toFixed(d)));
95
96 function coordinate(m: Map<number, Value>, ref: number, val: number, pos: string, neg: string, limit: number): string | undefined {
97 const v = m.get(val);
98 const r = text(m, ref);
99 if (!Array.isArray(v) || v.length !== 3 || v.some((x) => !Number.isFinite(x))) return undefined;
100 const deg = v[0]! + v[1]! / 60 + v[2]! / 3600;
101 if (deg > limit) return undefined;
102 const sign = r === neg ? "-" : r === pos ? "" : undefined;
103 return sign === undefined ? undefined : `${sign}${deg.toFixed(5)}`;
104 }
105
106 const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
107
108 /**
109 * `2024:05:06 07:08:09` as `6 May 2024, 07:08` (the camera's own clock, no zone); other text as it
110 * is.
111 */
112 function when(raw: string | undefined): string | undefined {
113 const m = raw === undefined ? null : /^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):\d{2}$/.exec(raw);
114 if (m === null) return raw;
115 const month = MONTHS[Number(m[2]) - 1];
116 const day = Number(m[3]);
117 return month === undefined || day < 1 || day > 31 || Number(m[4]) > 23 || Number(m[5]) > 59 ? raw : `${day} ${month} ${m[1]}, ${m[4]}:${m[5]}`;
outdated

Latitude should be capped at 90, longitude at 180; pass the limit into coordinate().

118 }
119
120 /** Only a JPEG or TIFF holds EXIF; its first `EXIF_WINDOW` bytes are all a reader needs. */
121 export const holdsExif = (path: string): boolean => /\.(jpe?g|tiff?)$/i.test(path);
122
123 /** The EXIF facts of a file's first bytes, in reading order; empty when there are none. */
124 export function readExif(body: Uint8Array): ExifFact[] {
125 try {
126 const b = body.subarray(0, EXIF_WINDOW);
127 const base = tiffStart(b);
128 if (base === undefined) return [];
129 const le = b[base] === 0x49;
130 const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
131 const seen = new Set<number>();
132 const walk = (offset: number): Map<number, Value> => {
133 if (seen.has(offset) || seen.size >= MAX_IFDS) return new Map();
134 seen.add(offset);
135 return readIfd(b, base, le, offset);
136 };
137 const ifd0 = walk(v.getUint32(base + 4, le));
138 const ptr = (m: Map<number, Value>, tag: number): Map<number, Value> => {
139 const o = num(m, tag);
140 return o === undefined ? new Map() : walk(o);
141 };
142 const exif = ptr(ifd0, 0x8769);
143 const gps = ptr(ifd0, 0x8825);
144
145 const facts: ExifFact[] = [];
146 const add = (label: string, value: string | undefined): void => {
147 if (value !== undefined && value !== "") facts.push({ label, value });
148 };
149 add("Camera make", text(ifd0, 0x010f));
150 add("Camera model", text(ifd0, 0x0110));
151 add("Lens", text(exif, 0xa434));
152 const focal = num(exif, 0x920a);
153 add("Focal length", focal === undefined ? undefined : `${trim(focal, 1)} mm`);
154 const f = num(exif, 0x829d);
155 add("Aperture", f === undefined || f <= 0 ? undefined : `f/${trim(f, 1)}`);
156 const t = num(exif, 0x829a);
157 add("Shutter", t === undefined || t <= 0 ? undefined : t < 1 ? `1/${Math.round(1 / t)} s` : `${trim(t, 1)} s`);
158 const iso = num(exif, 0x8827);
159 add("ISO", iso === undefined ? undefined : String(iso));
160 add("Taken at", when(text(exif, 0x9003) ?? text(ifd0, 0x0132)));
161 const lat = coordinate(gps, 1, 2, "N", "S", 90);
162 const lon = coordinate(gps, 3, 4, "E", "W", 180);
163 if (lat !== undefined && lon !== undefined) add("GPS (latitude, longitude)", `${lat}, ${lon}`);
164 return facts;
165 } catch {
166 return [];
167 }
168 }
src/web/render/image.ts +16 −4
@@ -8,6 +8,7 @@
88
99 import { html, when } from "../html.ts";
1010 import { btn, fileSize } from "../ui.ts";
11 import { holdsExif, readExif } from "./exif.ts";
1112 import type { Rendered, RenderInput } from "./renderers.ts";
1213
1314 /** Width and height from a PNG or GIF header, so the box exists before the bytes arrive. */
@@ -29,6 +30,12 @@ export function image(input: RenderInput): Rendered {
2930 const dot = name.lastIndexOf(".");
3031 const format = dot <= 0 ? "" : name.slice(dot + 1).toUpperCase();
3132 const known = headerSize(input.body);
33 // The body may be only the head of a large photo: EXIF sits in its first 64 KiB, and the reader
34 // never looks further.
35 const facts = holdsExif(input.path) ? readExif(input.body) : [];
outdated

The size gate hides facts for any photo over the page's read ceiling, though EXIF needs only the first 64 KiB. Feed the renderer a head for large images (fix first).

36 // Browsers other than Safari draw no TIFF: its facts stand alone, with Download on the page
37 // header.
38 const tiff = /^tiff?$/i.test(format);
3239 return {
3340 lines: 0,
3441 content: html`<div class="card imgview">
@@ -36,9 +43,9 @@ export function image(input: RenderInput): Rendered {
3643 <span class="imgview-dim" data-img-dim></span>
3744 <span>${fileSize(input.size)}</span>
3845 <span>${format}</span>
39 ${btn("Actual size", { type: "button", size: "sm", pressed: false, extra: "js-only imgview-zoom" })}
46 ${when(!tiff, () => btn("Actual size", { type: "button", size: "sm", pressed: false, extra: "js-only imgview-zoom" }))}
4047 </div>
41 <div
48 ${when(!tiff, () => html`<div
4249 class="imgview-pane"
4350 data-img-pane
4451 tabindex="0"
@@ -53,8 +60,13 @@ ${btn("Actual size", { type: "button", size: "sm", pressed: false, extra: "js-on
5360 ${when(known !== undefined, () => html`width="${String(known?.w)}" height="${String(known?.h)}"`)}
5461 data-img-view
5562 />
56 </div>
57 </div>`,
63 </div>`)}
64 </div>${when(
65 facts.length > 0,
66 () => html`<dl class="status-rows mt" aria-label="${`${name} photo facts`}">${facts.map(
outdated

Principles 6/7: the facts dl is inside the .card.imgview box. Render it as plain rows beneath the card. Also principle 8: format Taken at for a person.

67 (f) => html`<div class="status-row"><dt>${f.label}</dt><dd>${f.value}</dd></div>`,
68 )}</dl>`,
69 )}`,
5870 };
5971 }
6072
src/web/render/kinds.ts +2
@@ -216,6 +216,8 @@ const MEDIA: Readonly<Record<string, Media>> = {
216216 gif: { kind: "image", name: "GIF", type: "image/gif", magic: any(ascii("GIF87a"), ascii("GIF89a")) },
217217 webp: { kind: "image", name: "WebP", type: "image/webp", magic: riff("WEBP") },
218218 avif: { kind: "image", name: "AVIF", type: "image/avif", magic: (h) => ftyp(h) && (at(h, 8, "avif") || at(h, 8, "avis")) },
219 tif: { kind: "image", name: "TIFF", type: "image/tiff", magic: any(bytes(0x49, 0x49, 0x2a, 0x00), bytes(0x4d, 0x4d, 0x00, 0x2a)) },
220 tiff: { kind: "image", name: "TIFF", type: "image/tiff", magic: any(bytes(0x49, 0x49, 0x2a, 0x00), bytes(0x4d, 0x4d, 0x00, 0x2a)) },
219221 bmp: { kind: "image", name: "BMP", type: "image/bmp", magic: ascii("BM") },
220222 ico: { kind: "image", name: "ICO", type: "image/x-icon", magic: bytes(0x00, 0x00, 0x01, 0x00) },
221223 psd: { kind: "psd", name: "Photoshop", type: "image/vnd.adobe.photoshop", magic: (h) => at(h, 0, "8BPS") && h[4] === 0 && h[5] === 1 },
src/web/render/renderers.ts +5 −2
@@ -38,6 +38,7 @@ import { feedXml } from "./feed-xml.ts";
3838 import { vcf } from "./vcf.ts";
3939 import { htmlPreview } from "./html_preview.ts";
4040 import { image } from "./image.ts";
41 import { holdsExif } from "./exif.ts";
4142 import { fileKind, HEAD_BYTES, isJsonPath, kindByName, NO_BYTES, RENDER_CAP, type FileKind } from "./kinds.ts";
4243 import { log, drawsLog } from "./log.ts";
4344 import { makefile } from "./makefile.ts";
@@ -236,7 +237,9 @@ export function rendererFor(
236237 (kind === "package" && blob.kind !== "too_large" && readPackage(blob.body) === undefined);
237238 const render = declined ? undefined : renderers[kind];
238239 if (render === undefined) return undefined;
239 // A PSD over the read ceiling is drawn from its head: the header holds the facts.
240 const body = blob.kind === "too_large" ? (kind === "psd" ? (blob.head ?? NO_BYTES) : NO_BYTES) : blob.body;
240 // A PSD over the read ceiling is drawn from its head: the header holds the facts. So is a
241 // photo's: its EXIF is in the first 64 KiB.
242 const fromHead = kind === "psd" || (kind === "image" && holdsExif(path));
243 const body = blob.kind === "too_large" ? (fromHead ? (blob.head ?? NO_BYTES) : NO_BYTES) : blob.body;
241244 return { render, body };
242245 }
test/blob-photo-page.test.ts added +95
@@ -0,0 +1,95 @@
1 /**
2 * A photo committed to a repository, opened on its blob page over HTTP: its camera facts sit
3 * under the picture, also when the file is over the page's 1 MB render cap (a phone photo), where
4 * only its head is kept. A file over the source's 5 MB ceiling is read as its head too (`capped`
5 * and `rendererFor` are tested directly, as a commit cannot hold one that large).
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { capped } from "../src/web/pages/repo.ts";
16 import { RENDERERS, rendererFor } from "../src/web/render/renderers.ts";
17 import { EXIF_WINDOW } from "../src/web/render/exif.ts";
18 import { seedAdmin } from "./helpers/admin.ts";
19 import { jpeg, tiff } from "./helpers/exif.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21
22 quietLogs();
23
24 /** The JPEG with padding after its EXIF, as a camera file is. */
25 const padded = (bytes: number): Uint8Array => {
26 const small = jpeg(tiff());
27 const out = new Uint8Array(bytes);
28 out.set(small);
29 return out;
30 };
31
32 describe("a photo on its blob page", () => {
33 let dataDir = "";
34 let app: App;
35 let servers: Servers;
36 let base = "";
37
38 beforeAll(async () => {
39 dataDir = await mkdtemp(join(tmpdir(), "forge-blob-photo-"));
40 app = createApp({ dataDir, port: 0 });
41 servers = await serve(app);
42 base = servers.url;
43 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-long-photo-passphrase" });
44 if (!a.ok) throw new Error("signup failed");
45 const created = await createRepo(app, a.value, { name: "p", visibility: "public" });
46 if (!created.ok) throw new Error("repo failed");
47 const made = await commitToBranch(app, a.value, created.value, {
48 message: "photos",
49 files: [
50 { path: "small.jpg", content: jpeg(tiff()) },
51 { path: "phone.jpg", content: padded(1_500_000) },
52 { path: "scan.tif", content: tiff() },
53 ],
54 });
55 if (!made.ok) throw new Error("commit failed");
56 }, 60_000);
57
58 afterAll(async () => {
59 await servers?.stop();
60 app?.close();
61 await rm(dataDir, { recursive: true, force: true });
62 });
63
64 test("a small JPEG shows its facts under the picture", async () => {
65 const text = await (await fetch(`${base}/alice/p/blob/main/small.jpg`)).text();
66 expect(text).toContain("<dt>Camera make</dt><dd>ACME</dd>");
67 expect(text).toContain("<dd>6 May 2024, 07:08</dd>");
68 expect(text).toContain("<img");
69 });
70
71 test("a JPEG over the page's render cap still shows its facts", async () => {
72 const text = await (await fetch(`${base}/alice/p/blob/main/phone.jpg`)).text();
73 expect(text).toContain("<dt>Camera model</dt><dd>Cam 1</dd>");
74 expect(text).toContain("<img");
75 });
76
77 test("a TIFF shows its facts and no img", async () => {
78 const text = await (await fetch(`${base}/alice/p/blob/main/scan.tif`)).text();
79 expect(text).toContain("<dt>Lens</dt><dd>Lens 50</dd>");
80 expect(text).not.toContain("data-img-view");
81 });
82 });
83
84 describe("a photo past every read ceiling", () => {
85 test("capped keeps the EXIF window of a large photo, and the renderer reads it", () => {
86 const big = padded(1_500_000);
87 const shown = capped({ kind: "binary", body: big, size: big.length }, "phone.jpg");
88 if (shown.kind !== "too_large" || shown.head === undefined) throw new Error("expected too_large with a head");
89 expect(shown.head?.length).toBe(EXIF_WINDOW);
90 const hit = rendererFor("phone.jpg", { kind: "too_large", size: 6_000_000, head: shown.head }, RENDERERS);
91 expect(hit).toBeDefined();
92 const html = hit!.render({ path: "phone.jpg", size: 6_000_000, body: hit!.body, media: "/m", download: "/d" }).content.toString();
93 expect(html).toContain("<dd>ACME</dd>");
94 });
95 });
test/helpers/exif.ts added +38
@@ -0,0 +1,38 @@
1 /**
2 * A hand-built little-endian TIFF block for the tests: IFD0 (make, model, Exif ptr, GPS ptr), Exif
3 * IFD, GPS IFD.
4 */
5 export function tiff(opts: { make?: string; loop?: boolean; lat?: number } = {}): Uint8Array {
6 const out = new Uint8Array(512);
7 const v = new DataView(out.buffer);
8 const enc = new TextEncoder();
9 out.set([0x49, 0x49, 0x2a, 0]);
10 v.setUint32(4, 8, true);
11 let heap = 300;
12 const str = (s: string): number => { const at = heap; out.set(enc.encode(s + "\0"), at); heap += s.length + 1; return at; };
13 const rat = (list: [number, number][]): number => { const at = heap; list.forEach(([n, d], i) => { v.setUint32(at + i * 8, n, true); v.setUint32(at + i * 8 + 4, d, true); }); heap += list.length * 8; return at; };
14 const ifd = (at: number, entries: [number, number, number, number][], next = 0): void => {
15 v.setUint16(at, entries.length, true);
16 entries.forEach(([tag, type, n, val], i) => {
17 const e = at + 2 + i * 12;
18 v.setUint16(e, tag, true); v.setUint16(e + 2, type, true); v.setUint32(e + 4, n, true); v.setUint32(e + 8, val, true);
19 });
20 v.setUint32(at + 2 + entries.length * 12, next, true);
21 };
22 const make = opts.make ?? "ACME";
23 ifd(8, [[0x010f, 2, make.length + 1, str(make)], [0x0110, 2, 6, str("Cam 1")], [0x8769, 4, 1, 100], [0x8825, 4, 1, 200]], opts.loop ? 8 : 0);
24 ifd(100, [
25 [0x829a, 5, 1, rat([[1, 250]])], [0x829d, 5, 1, rat([[28, 10]])], [0x8827, 3, 1, 400],
26 [0x9003, 2, 20, str("2024:05:06 07:08:09")], [0xa434, 2, 8, str("Lens 50")], [0x920a, 5, 1, rat([[50, 1]])],
27 ], opts.loop ? 100 : 0);
28 ifd(200, [[1, 2, 2, 0x4e], [2, 5, 3, rat([[opts.lat ?? 48, 1], [30, 1], [0, 1]])], [3, 2, 2, 0x57], [4, 5, 3, rat([[2, 1], [0, 1], [0, 1]])]]);
29 return out;
30 }
31 /** Wrap a TIFF block as a JPEG with one APP1 segment. */
32 export function jpeg(t: Uint8Array): Uint8Array {
33 const out = new Uint8Array(4 + 8 + t.length + 2);
34 out.set([0xff, 0xd8, 0xff, 0xe1, (t.length + 8) >> 8, (t.length + 8) & 255, 0x45, 0x78, 0x69, 0x66, 0, 0]);
35 out.set(t, 12);
36 out.set([0xff, 0xd9], 12 + t.length);
37 return out;
38 }
test/render-exif.test.ts added +71
@@ -0,0 +1,71 @@
1 import { describe, expect, test } from "bun:test";
2 import { readExif, EXIF_WINDOW } from "../src/web/render/exif.ts";
3 import { image } from "../src/web/render/image.ts";
4 import { jpeg, tiff } from "./helpers/exif.ts";
5 import { fileKind } from "../src/web/render/kinds.ts";
6
7 const input = (path: string, body: Uint8Array) => ({ path, size: body.length, body, media: "/m", download: "/d" });
8
9 describe("exif", () => {
10 test("reads camera, lens, exposure, time and GPS text from a JPEG", () => {
11 const f = Object.fromEntries(readExif(jpeg(tiff())).map((x) => [x.label, x.value]));
12 expect(f["Camera make"]).toBe("ACME");
13 expect(f["Camera model"]).toBe("Cam 1");
14 expect(f.Lens).toBe("Lens 50");
15 expect(f.ISO).toBe("400");
16 expect(f.Aperture).toBe("f/2.8");
17 expect(f.Shutter).toBe("1/250 s");
18 expect(f["Focal length"]).toBe("50 mm");
19 expect(f["Taken at"]).toBe("6 May 2024, 07:08");
20 expect(f["GPS (latitude, longitude)"]).toBe("48.50000, -2.00000");
21 });
22 test("reads a bare TIFF", () => {
23 expect(readExif(tiff()).length).toBeGreaterThan(5);
24 });
25 test("looping IFD offsets and truncation end the walk, never throw", () => {
26 expect(readExif(jpeg(tiff({ loop: true }))).length).toBeGreaterThan(0);
27 const t = jpeg(tiff());
28 for (const n of [0, 5, 14, 40, 120, 250]) expect(() => readExif(t.subarray(0, n))).not.toThrow();
29 const junk = new Uint8Array(EXIF_WINDOW * 2).fill(0xff);
30 junk.set([0xff, 0xd8]);
31 expect(readExif(junk)).toEqual([]);
32 expect(readExif(new Uint8Array(0))).toEqual([]);
33 });
34 test("only the first 64 KiB is read", () => {
35 const big = new Uint8Array(EXIF_WINDOW + 600);
36 big.set(tiff().subarray(0, 8));
37 big.set(tiff(), EXIF_WINDOW - 100);
38 expect(readExif(big)).toEqual([]);
39 });
40 test("the page escapes values and shows the table; no EXIF means no table", () => {
41 const shown = image(input("a.jpg", jpeg(tiff({ make: "<b>x</b>" })))).content.toString();
42 expect(shown).toContain("Camera make");
43 expect(shown).toContain("&lt;b&gt;x&lt;/b&gt;");
44 expect(shown).not.toContain("<b>x</b>");
45 const none = image(input("a.jpg", new Uint8Array([0xff, 0xd8, 0xff, 0xd9]))).content.toString();
46 expect(none).not.toContain("photo facts");
47 });
48 test("latitude is capped at 90 degrees, longitude at 180", () => {
49 expect(readExif(jpeg(tiff({ lat: 90 }))).some((x) => x.label.startsWith("GPS"))).toBe(false);
50 expect(readExif(jpeg(tiff({ lat: 89 }))).some((x) => x.label.startsWith("GPS"))).toBe(true);
51 });
52 test("the head of a large photo is enough", () => {
53 const body = jpeg(tiff());
54 const shown = image({ ...input("a.jpg", body), size: 60_000_000 }).content.toString();
55 expect(shown).toContain("photo facts");
56 expect(shown).toContain("57.2 MB");
57 });
58 test("the facts sit under the card, the date reads as a date, the GPS is labelled", () => {
59 const shown = image(input("a.jpg", jpeg(tiff()))).content.toString();
60 expect(shown.indexOf("</div><dl")).toBeGreaterThan(0);
61 expect(shown).toContain("<dd>6 May 2024, 07:08</dd>");
62 expect(shown).not.toContain("2024:05:06");
63 expect(shown).toContain("<dt>GPS (latitude, longitude)</dt>");
64 });
65 test("a TIFF is an image kind and draws its facts without an img", () => {
66 expect(fileKind("a.tif", tiff().subarray(0, 16))).toBe("image");
67 const shown = image(input("a.tiff", tiff())).content.toString();
68 expect(shown).toContain("ACME");
69 expect(shown).not.toContain("<img");
70 });
71 });
test/render-kinds.test.ts +2
@@ -20,6 +20,8 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = {
2020 gif: [enc("GIF89a\0"), "image", "image/gif"],
2121 webp: [enc("RIFF\0\0\0\0WEBPVP8 "), "image", "image/webp"],
2222 avif: [box("avif"), "image", "image/avif"],
23 tif: [new Uint8Array([0x49, 0x49, 0x2a, 0]), "image", "image/tiff"],
24 tiff: [new Uint8Array([0x4d, 0x4d, 0, 0x2a]), "image", "image/tiff"],
2325 bmp: [enc("BM\0\0"), "image", "image/bmp"],
2426 ico: [of(0, 0, 1, 0, 1), "image", "image/x-icon"],
2527 svg: [enc('<?xml version="1.0"?>\n<svg xmlns="http://www.w3.org/2000/svg"/>'), "svg", "image/svg+xml"],
test/tui-workspace-photo.test.ts added +110
@@ -0,0 +1,110 @@
1 /**
2 * A photo's EXIF in the terminal workspace and the local source: `v` on a JPEG
3 * lists its camera rows, a photo over the read ceiling keeps its facts in the
4 * too-large note, and the source reads such a photo's head as its EXIF window.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
9 import type { App as Forge } from "../src/app.ts";
10 import type { Repo } from "../src/core/repos.ts";
11 import type { User } from "../src/core/users.ts";
12 import { repoDir } from "../src/git/repos.ts";
13 import type { TuiIdentity } from "../src/tui/session.ts";
14 import { localSource } from "../src/view/local.ts";
15 import { EXIF_WINDOW } from "../src/web/render/exif.ts";
16 import { HEAD_BYTES } from "../src/web/render/kinds.ts";
17 import { jpeg, tiff } from "./helpers/exif.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19 import { workspaceFixture, type Fixture } from "./helpers/tui-workspace.ts";
20
21 quietLogs();
22
23 /** A 6 MB JPEG whose APP1 sits past the first HEAD_BYTES, behind a padding APP0. */
24 function bigPhoto(): Uint8Array {
25 const small = jpeg(tiff({ make: "BIGCAM" }));
26 const pad = 20_000;
27 const out = new Uint8Array(6_000_000);
28 out.set([0xff, 0xd8, 0xff, 0xe0, pad >> 8, pad & 255]);
29 out.set(small.subarray(2), 4 + pad);
30 return out;
31 }
32
33 describe("a photo's facts in the terminal", () => {
34 let fx: Fixture;
35 let forge: Forge;
36 let alice: User;
37 let repo: Repo;
38 let boot: Fixture["boot"];
39 let open: Fixture["open"];
40 let openFile: Fixture["openFile"];
41 const asAlice = (): TuiIdentity => ({ sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice });
42
43 beforeAll(async () => {
44 fx = await workspaceFixture();
45 ({ forge, alice, boot, open, openFile } = fx);
46 const made = await createRepo(forge, alice, { name: "photos", visibility: "public", description: "pics" });
47 if (!made.ok) throw new Error("repo failed");
48 repo = made.value;
49 const seeded = await commitToBranch(forge, alice, repo, {
50 message: "start",
51 files: [{ path: "shot.jpg", content: jpeg(tiff()) }],
52 });
53 if (!seeded.ok) throw new Error("commit failed");
54 // Over the 2 MB a commit through the app takes: written with git itself, as a push would.
55 const dir = repoDir(forge.reposRoot, "alice", "photos");
56 const git = (args: string[], stdin?: Uint8Array | string): string => {
57 const run = Bun.spawnSync(["git", ...args], {
58 cwd: dir,
59 stdin: stdin === undefined ? "ignore" : typeof stdin === "string" ? new TextEncoder().encode(stdin) : stdin,
60 env: { ...process.env, GIT_AUTHOR_NAME: "a", GIT_AUTHOR_EMAIL: "[email protected]", GIT_COMMITTER_NAME: "a", GIT_COMMITTER_EMAIL: "[email protected]" },
61 });
62 if (run.exitCode !== 0) throw new Error(`git ${args[0]}: ${run.stderr.toString()}`);
63 return run.stdout.toString().trim();
64 };
65 const blob = git(["hash-object", "-w", "--stdin"], bigPhoto());
66 const tree = git(["mktree"], `${git(["ls-tree", "main"])}\n100644 blob ${blob}\tbig.jpg\n`);
67 git(["update-ref", "refs/heads/main", git(["commit-tree", tree, "-p", "main", "-m", "big"])]);
68 });
69
70 afterAll(() => fx.close());
71
72 test("the source reads an over-ceiling photo's head as its EXIF window", async () => {
73 const read = await localSource(forge, repo).blob("main", "big.jpg");
74 if (!read.ok || read.value.kind !== "too_large") throw new Error("expected too_large");
75 expect(read.value.head?.length).toBe(EXIF_WINDOW);
76 expect(EXIF_WINDOW).toBeGreaterThan(HEAD_BYTES);
77 });
78
79 test("v on a JPEG lists its camera rows", async () => {
80 const h = boot(asAlice(), 120, 40, "xterm-ghostty");
81 try {
82 await h.settle();
83 await open(h, "photos");
84 await openFile(h, "shot.jpg");
85 await h.press("v");
86 const text = h.text();
87 expect(text).toContain("dimensions");
88 expect(text).toContain("camera make");
89 expect(text).toContain("ACME");
90 expect(text).toContain("Lens 50");
91 expect(text).toContain("1/250 s");
92 } finally {
93 h.stop();
94 }
95 });
96
97 test("a photo too large to read keeps its facts in the note", async () => {
98 const h = boot(asAlice(), 120, 40);
99 try {
100 await h.settle();
101 await open(h, "photos");
102 await openFile(h, "big.jpg");
103 const text = h.text();
104 expect(text).toContain("Camera make: BIGCAM");
105 expect(text).toContain("Shutter: 1/250 s");
106 } finally {
107 h.stop();
108 }
109 });
110 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs