Files
gerbeur/api/test/routes/thumbnails.test.ts
khannurien 90fc281e90 v4: every image the API serves comes scaled to the size it is shown at — a first visit to the feed loaded 4.8 MB of images out of 5.1 MB in all: an avatar shown at 32 pixels was the upload itself, a 1.4 MB GIF among them, and so were a cover, a custom thumbnail, an attachment and a proxied image, only an image dump having a preview, 960 pixels wide. Every route that answers an image now takes ?w= and sends a WebP copy at most that wide, of the widths shared/image.ts lists, 128, 320, 640 and 960, a width between two taking the one above, and never wider than the image; without it the upload goes out as before, a dump's thumbnail alone being scaled to the widest by default, the custom ones included. serveImage (lib/upload.ts) is where they all end, and the image proxy scales what it fetched the same way, keeping each width in its cache. lib/ffmpeg.ts makes the copies as it made the previews, which they replace: on first request, under uploads/scaled/ at the upload's own path, each given its upload's date and made again when the two differ, so a new avatar or cover needs nobody to delete the old ones. WebP keeps a PNG's transparency and a GIF's animation. A JPEG is turned by its EXIF orientation here, ffmpeg's own rotation of images depending on its version. An animated WebP, which ffmpeg can't read, and an image it fails on go out as they are, a failure being remembered until the upload changes. ?f=compat asks for the copy as a JPEG, or a PNG for what may be transparent: the digest's emails take their thumbnails that way, at 640 pixels, not every mail client reading WebP. On the client, imageProps (utils/shared/urls.ts) gives an image its srcset of those copies and the width it is laid out at, which config/imageSizes.ts states for each place from App.css: Avatar, Thumbnail, which scales an API image and leaves another site's as that site sends it, and the playlists' covers use it. The images of notes and comments still load as uploaded. The copies go with the dump, the custom thumbnail or the attachment they were made from, and generatedMediaSweepJob, a minute after the start then daily, takes those whose upload is gone, the previews under their former name and the temporary files a generation left unfinished.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 19:01:36 +00:00

158 lines
5.2 KiB
TypeScript

import {
createUser,
db,
del,
get,
hasFfmpeg,
insertDump,
makeImage,
PNG,
test,
TEST_DIR,
webpWidth,
} from "../helpers.ts";
import { assertEquals } from "@std/assert";
function createdAtOf(id: string): string {
return (db.prepare(`SELECT created_at FROM dumps WHERE id = ?;`).get(id) as {
created_at: string;
}).created_at;
}
function readDir(path: string): string[] {
try {
return [...Deno.readDirSync(path)].map((e) => e.name);
} catch {
return [];
}
}
test("GET /api/dumps/:id/thumbnail: serves a cached video still, with privacy", async () => {
const owner = await createUser();
const video = insertDump({
userId: owner.id,
fileName: "v.mp4",
fileMime: "video/mp4",
});
const priv = insertDump({
userId: owner.id,
fileName: "p.mp4",
fileMime: "video/mp4",
isPrivate: true,
});
Deno.mkdirSync(`${TEST_DIR}/uploads/thumbnails`, { recursive: true });
for (const { id } of [video, priv]) {
Deno.writeFileSync(`${TEST_DIR}/uploads/thumbnails/${id}.jpg`, PNG);
}
const res = await get(`/api/dumps/${video.id}/thumbnail`);
assertEquals(res.status, 200);
assertEquals(res.headers.get("content-type"), "image/jpeg");
assertEquals(res.headers.get("cache-control"), "public, no-cache");
const v = (id: string) => `5-${Date.parse(createdAtOf(id))}`;
assertEquals(
(await get(`/api/dumps/${video.id}/thumbnail?v=${v(video.id)}`)).headers
.get(
"cache-control",
),
"public, max-age=31536000, immutable",
);
assertEquals((await get(`/api/dumps/${priv.id}/thumbnail`)).status, 404);
const own = await get(
`/api/dumps/${priv.id}/thumbnail?v=${v(priv.id)}&token=${owner.mediaToken}`,
);
assertEquals(own.status, 200);
assertEquals(
own.headers.get("cache-control"),
"private, max-age=31536000, immutable",
);
const text = insertDump({ userId: owner.id, fileName: "t.txt" });
assertEquals((await get(`/api/dumps/${text.id}/thumbnail`)).status, 404);
assertEquals((await get(`/api/dumps/nope/thumbnail`)).status, 400);
});
test("GET /api/dumps/:id/thumbnail: an image dump gets a scaled copy, or itself when none can be made", async () => {
const owner = await createUser();
const scaled = (id: string) =>
readDir(`${TEST_DIR}/uploads/scaled/dumps`).filter((n) => n.startsWith(id))
.sort();
// Not an image ffmpeg can read (or no ffmpeg at all): the original goes out.
const gif = new TextEncoder().encode("GIF89a-not-really");
const broken = insertDump({
userId: owner.id,
fileName: "a.gif",
fileMime: "image/gif",
fileData: gif,
});
const fallback = await get(`/api/dumps/${broken.id}/thumbnail`);
assertEquals(fallback.status, 200);
assertEquals(fallback.headers.get("content-type"), "image/gif");
assertEquals(fallback.bytes, gif);
assertEquals(scaled(broken.id), []);
if (!await hasFfmpeg()) {
const photo = insertDump({
userId: owner.id,
fileName: "p.png",
fileMime: "image/png",
fileData: PNG,
});
const itself = await get(`/api/dumps/${photo.id}/thumbnail`);
assertEquals(itself.headers.get("content-type"), "image/png");
assertEquals(itself.bytes, PNG);
return;
}
// A real image is scaled to the widest width without `w`, and to the width
// asked for with it, each copy kept under the upload's own path.
const photo = insertDump({
userId: owner.id,
fileName: "p.png",
fileMime: "image/png",
fileData: await makeImage(1400, 300),
});
const widest = await get(`/api/dumps/${photo.id}/thumbnail`);
assertEquals(widest.status, 200);
assertEquals(widest.headers.get("content-type"), "image/webp");
assertEquals(webpWidth(widest.bytes), 960);
const small = await get(`/api/dumps/${photo.id}/thumbnail?w=128`);
assertEquals(small.headers.get("content-type"), "image/webp");
assertEquals(webpWidth(small.bytes), 128);
// A width between two of the list's takes the one above.
const between = await get(`/api/dumps/${photo.id}/thumbnail?w=200`);
assertEquals(webpWidth(between.bytes), 320);
assertEquals(scaled(photo.id), [
`${photo.id}.w128.webp`,
`${photo.id}.w320.webp`,
`${photo.id}.w960.webp`,
]);
// A reader without WebP, as a mail client, asks for a PNG or a JPEG.
const compat = await get(`/api/dumps/${photo.id}/thumbnail?w=640&f=compat`);
assertEquals(compat.status, 200);
assertEquals(compat.headers.get("content-type"), "image/png");
// Its header states the width, on four bytes from the sixteenth.
assertEquals(new DataView(compat.bytes.buffer).getUint32(16), 640);
assertEquals(scaled(photo.id).includes(`${photo.id}.w640.png`), true);
// An animation keeps its frames.
const animated = insertDump({
userId: owner.id,
fileName: "anim.gif",
fileMime: "image/gif",
fileData: await makeImage(400, 300, "blue", "gif"),
});
const moving = await get(`/api/dumps/${animated.id}/thumbnail?w=128`);
assertEquals(moving.headers.get("content-type"), "image/webp");
assertEquals(webpWidth(moving.bytes), 128);
assertEquals(new TextDecoder().decode(moving.bytes).includes("ANMF"), true);
// The copies go with the dump.
assertEquals(
(await del(`/api/dumps/${photo.id}`, { auth: owner.auth })).status,
200,
);
assertEquals(scaled(photo.id), []);
});