Files
gerbeur/api/routes/remote.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

136 lines
4.7 KiB
TypeScript

/**
* Reads other sites for the client, as `api/remote/` does for the server: the
* previews of links on the create form, the images its thumbnails can't load
* directly, and the tracks the players list. On any failure of the last two,
* the player falls back to the embed.
*
* - `GET /api/remote/preview?url=` — signed in. Answers the preview of a link,
* and whether its page could be reached.
* - `GET /api/remote/image?url=&w=` — public. Serves a remote raster image
* through this site, scaled down to `w` (`shared/image.ts`) when it names
* one; 400 when it isn't an image, 502 when its host can't be reached.
* - `GET /api/remote/bandcamp?url=&force=` — public. Answers a Bandcamp
* page's tracks and their stream URLs, for the native player; `force=1`
* skips the server's cache.
* - `GET /api/remote/youtube?list=` — public. Answers a YouTube playlist's
* tracklist, which the global player lists beside the embed.
*
* @module
*/
import { Router } from "@oak/oak";
import { parseImageWidth } from "../../shared/image.ts";
import { isValidHttpUrl } from "../remote/fetch.ts";
import { fetchProxiedImage } from "../remote/image-proxy.ts";
import { resolveBandcamp } from "../remote/bandcamp-streams.ts";
import { resolveYouTubePlaylist } from "../remote/youtube-playlist.ts";
import { tryFetchRichContent } from "../services/rich-content-service.ts";
import {
APIErrorCode,
type APIFailure,
type APIResponse,
} from "../../shared/api.ts";
import type { LinkPreview } from "../../shared/dump.ts";
import type { Tralbum, YouTubePlaylist } from "../../shared/player.ts";
import { authMiddleware } from "../middleware/auth.ts";
/**
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
* An `APIException` thrown by a handler becomes the JSON error response there.
*/
const router: Router = new Router({ prefix: "/api/remote" });
// Signed-in only: an open preview would let anyone make the server fetch pages.
router.get("/preview", authMiddleware, async (ctx) => {
const url = ctx.request.url.searchParams.get("url") ?? "";
if (!isValidHttpUrl(url)) {
const responseBody: APIFailure = {
success: false,
error: { code: APIErrorCode.BAD_REQUEST, message: "Invalid URL" },
};
ctx.response.status = 400;
ctx.response.body = responseBody;
return;
}
const { ok, content } = await tryFetchRichContent(url);
const responseBody: APIResponse<LinkPreview> = {
success: true,
data: { reached: ok, richContent: content ?? null },
};
ctx.response.body = responseBody;
});
/**
* Answers with a proxied image. It is sent from this site's origin, so it is
* sandboxed in case a browser opens it as a document.
*/
function sendImage(
ctx: { response: { headers: Headers; body?: unknown } },
bytes: Uint8Array,
contentType: string,
): void {
ctx.response.headers.set("Content-Type", contentType);
ctx.response.headers.set("X-Content-Type-Options", "nosniff");
ctx.response.headers.set(
"Content-Security-Policy",
"sandbox; default-src 'none'",
);
ctx.response.headers.set("Cache-Control", "public, max-age=86400");
ctx.response.body = bytes;
}
// The frontend sends a thumbnail here when it is plain HTTP, which an HTTPS
// page won't load, or when its host's hotlink protection refused the browser.
router.get("/image", async (ctx) => {
const url = ctx.request.url.searchParams.get("url") ?? "";
if (!isValidHttpUrl(url)) {
ctx.response.status = 400;
return;
}
try {
const image = await fetchProxiedImage(
url,
parseImageWidth(ctx.request.url.searchParams.get("w")),
);
if (!image) {
ctx.response.status = 400;
return;
}
sendImage(ctx, image.bytes, image.contentType);
} catch {
ctx.response.status = 502;
}
});
// Public: it reads a public page and answers the URLs that page gives any
// visitor.
router.get("/bandcamp", async (ctx) => {
const url = ctx.request.url.searchParams.get("url") ?? "";
const force = ctx.request.url.searchParams.get("force") === "1";
const responseBody: APIResponse<Tralbum> = {
success: true,
data: await resolveBandcamp(url, { force }),
};
// Not in a shared cache: the signed URLs belong to one page fetch. An hour
// is well inside their 24 hours.
ctx.response.headers.set("Cache-Control", "private, max-age=3600");
ctx.response.body = responseBody;
});
// Public, like /bandcamp: it only reads a public page.
router.get("/youtube", async (ctx) => {
const listId = ctx.request.url.searchParams.get("list") ?? "";
const responseBody: APIResponse<YouTubePlaylist> = {
success: true,
data: await resolveYouTubePlaylist(listId),
};
ctx.response.headers.set("Cache-Control", "public, max-age=3600");
ctx.response.body = responseBody;
});
export default router;