saturn
- 187 commits
- 2 branches
- 0 tags
- updated
- CI 2/2
feat: add support for video embeds in micro posts
SignedGitea couldn't verify the signature.
Showing 5 changed files with 258 additions and 12 deletions.
MICRO.md
+35 −5
@@ -32,8 +32,8 @@ replaces its inner HTML. The attribute value picks what gets rendered:3232| Mode | Renders | Used on |3333|---|---|---|3434| `latest-activity` | one row's worth of content for an `<li class="activity-item">`: icon, `NEW MICRO POST — <text>` link (or `3 NEW MICRO POSTS` when several landed on the same Pacific day), and a `1 SEP` style date. The text is capped at 140 characters server-side; the row never wraps and css fades whatever does not fit | `/` (activity feed) |35| `latest-featured` | one `<article class="micro-post micro-featured">` for the newest post, timestamp linking to its anchor on `/blog/micro/`, images included | `/` (recent post card), `/blog` |36| `all` | every post as `<article class="micro-post">`, newest first, each with an `id` anchor, images included | `/blog/micro/` |35| `latest-featured` | one `<article class="micro-post micro-featured">` for the newest post, timestamp linking to its anchor on `/blog/micro/`, media included | `/` (recent post card), `/blog` |36| `all` | every post as `<article class="micro-post">`, newest first, each with an `id` anchor, media included | `/blog/micro/` |37373838Anchor ids are the record key (the last path segment of the `at://` URI, a3939TID). The old `YYYY-MM-DD-N` convention is gone.@@ -64,7 +64,35 @@ and `data-replies` injection is a separate path, documented in `SOCIAL.md`.64646565If the new page needs images, add `https://atproto.danieldaum.net` to6666`img-src` in that page's CSP meta tag. Only the three pages listed above have67that today.67that today. Video is same-origin (see below) and is covered by the68`media-src 'self'` every page already carries.6970## Media7172A post can carry a set of images (`app.bsky.embed.images`) or one video73(`app.bsky.embed.video`); the middleware renders both below the text, in74`latest-featured` and `all`. A quote-with-media post75(`app.bsky.embed.recordWithMedia`) keeps its media and drops the quote.7677Images are `<img>` tags pointing straight at the PDS's78`com.atproto.sync.getBlob`, which is why the PDS origin is in `img-src`.7980Video is different. The PDS answers every blob request with the whole file81and no `Accept-Ranges`, and Safari (so every browser on iOS) will not play a82video it cannot seek into. So the `<video>` src is `/media/<cid>`, served by83`functions/media/[cid].js`: it fetches the blob from the PDS once, stores it84in the Cloudflare cache (immutable, blobs are content-addressed), and lets the85Cache API answer every request after that, `Range` included. On the first,86cold request the function slices the range itself. Only image and video87content types are passed through; the cid has to look like a base32 CIDv1 or88nothing is fetched.8990`/media/*` is in `_routes.json` so it reaches the function. No CSP change is91needed for it: it is same-origin.9293The player is not autoplayed or muted, it is `controls` and94`preload="metadata"`, and it sits above the card's stretched permalink in the95stacking order so the controls take the tap instead of the card.68966997## Local dev7098@@ -89,7 +117,9 @@ Deliberately left out of this pass. Everything below renders as plain text or89117is ignored:9011891119- rich text facets: links, mentions and hashtags are not linkified92- quote posts and quote-with-media: the quoted record is dropped, only my text shows120- quote posts: the quoted record is dropped, only my text shows (a121 quote-with-media keeps the media, see above)93122- external link cards94- video embeds123- video posters: the record has no thumbnail, so the player shows the first124 frame once metadata loads95125- threading: replies are filtered out entirely, and thread structure is ignored
_routes.json
+2 −2
@@ -1,6 +1,6 @@11{22 "version": 1,3 "description": "Only these paths run through functions/. Everything else (pages, css, fonts, images) is served straight from the static asset store, which is faster and edge-cacheable. Keep in step with ALLOWED_PATHS in functions/_middleware.js and isBlogPost() in functions/_lib/social.js.",4 "include": ["/", "/index.html", "/blog", "/blog/*", "/api/*"],3 "description": "Only these paths run through functions/. Everything else (pages, css, fonts, images) is served straight from the static asset store, which is faster and edge-cacheable. Keep in step with ALLOWED_PATHS in functions/_middleware.js and isBlogPost() in functions/_lib/social.js. /media/* is the blob proxy in functions/media/, see MICRO.md.",4 "include": ["/", "/index.html", "/blog", "/blog/*", "/api/*", "/media/*"],55 "exclude": []66}
functions/_middleware.js
+48 −4
@@ -138,7 +138,7 @@ async function fetchPosts() {138138 rkey: rkeyFromUri(r.uri),139139 text: r.value.text,140140 createdAt: r.value.createdAt || "",141 images: imagesFrom(r.value.embed),141 ...mediaFrom(r.value.embed),142142 }))143143 .filter((p) => p.rkey)144144 .sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));@@ -179,6 +179,15 @@ function rkeyFromUri(uri) {179179 return idx === -1 ? "" : uri.slice(idx + 1);180180}181181182// Media attached to a post: a set of images or one video, the two things the183// Bluesky app can attach. A quote-with-media post carries the same embed one184// level down under `media`, so it is unwrapped here and the quoted record is185// dropped. Anything else (link cards, bare quotes) yields no media.186function mediaFrom(embed) {187 const media = embed?.$type === "app.bsky.embed.recordWithMedia" ? embed.media : embed;188 return { images: imagesFrom(media), video: videoFrom(media) };189}190182191function imagesFrom(embed) {183192 if (!embed || embed.$type !== "app.bsky.embed.images" || !Array.isArray(embed.images)) {184193 return [];@@ -188,6 +197,23 @@ function imagesFrom(embed) {188197 .filter((img) => typeof img.cid === "string" && img.cid.length > 0);189198}190199200// The aspect ratio is optional on the record; when present it is written201// out as width/height attributes so the box is reserved before the video's202// metadata has loaded and the page does not jump.203function videoFrom(embed) {204 if (!embed || embed.$type !== "app.bsky.embed.video") {205 return null;206 }207 const cid = embed.video?.ref?.$link;208 if (typeof cid !== "string" || cid.length === 0) {209 return null;210 }211 const ratio = embed.aspectRatio;212 const width = Number.isInteger(ratio?.width) && ratio.width > 0 ? ratio.width : 0;213 const height = Number.isInteger(ratio?.height) && ratio.height > 0 ? ratio.height : 0;214 return { cid, alt: typeof embed.alt === "string" ? embed.alt : "", width, height };215}216191217// ---------------------------------------------------------------------------192218// rendering193219@@ -215,6 +241,7 @@ function renderArticle(post, { featured }) {215241 `<img class="micro-img" src="${blobUrl(img.cid)}" alt="${escapeHtml(img.alt)}" loading="lazy" />`216242 )217243 .join("\n ");244 const video = post.video ? renderVideo(post.video) : "";218245219246 return [220247 `<article${id} class="${cls}">`,@@ -224,6 +251,7 @@ function renderArticle(post, { featured }) {224251 ` </p>`,225252 ` <p class="micro-body">${formatBody(post.text)}</p>`,226253 images ? ` ${images}` : null,254 video ? ` ${video}` : null,227255 `</article>`,228256 ]229257 .filter((line) => line !== null)@@ -245,6 +273,16 @@ function renderActivityItem(posts) {245273 ].join("\n");246274}247275276// Not autoplayed and not muted: it is a post attachment, the visitor presses277// play. `playsinline` keeps iOS from taking over the screen on tap. The link278// inside is what a browser without <video> support gets.279function renderVideo(video) {280 const src = mediaUrl(video.cid);281 const size = video.width && video.height ? ` width="${video.width}" height="${video.height}"` : "";282 const label = video.alt ? ` aria-label="${escapeHtml(video.alt)}"` : "";283 return `<video class="micro-video" src="${src}"${size}${label} controls playsinline preload="metadata"><a href="${src}">VIDEO</a></video>`;284}285248286function blobUrl(cid) {249287 const url = new URL("/xrpc/com.atproto.sync.getBlob", PDS_HOST);250288 url.searchParams.set("did", REPO_DID);@@ -252,6 +290,13 @@ function blobUrl(cid) {252290 return escapeHtml(url.toString());253291}254292293// Video is served through /media/<cid> (functions/media/[cid].js) rather than294// straight from the PDS: the PDS ignores Range requests, and Safari will not295// play a video it cannot seek. Images keep going to the PDS directly.296function mediaUrl(cid) {297 return escapeHtml(`/media/${encodeURIComponent(cid)}`);298}299255300// ---------------------------------------------------------------------------256301// rendering: likes and replies257302@@ -451,8 +496,7 @@ function partsOf(formatter, date) {451496// Deliberately NOT implemented in this pass:452497//453498// - rich text facets: links, mentions and hashtags render as plain text454// - quote posts (app.bsky.embed.record) and quote-with-media455// (app.bsky.embed.recordWithMedia): the embed is ignored, only the text shows499// - quote posts (app.bsky.embed.record): the quoted record is ignored, only500// the text shows. quote-with-media keeps its images or video, drops the quote456501// - external link cards (app.bsky.embed.external)457// - video embeds (app.bsky.embed.video)458502// - threading: replies are filtered out entirely, thread structure is ignored
functions/media/[cid].jsadded
+160 −0
@@ -0,0 +1,160 @@1// GET /media/<cid>: one blob from my PDS, served same-origin with Range2// support. See MICRO.md.3//4// The PDS answers every request for a blob with the whole file and no5// Accept-Ranges, and Safari (so every browser on iOS) refuses to play a6// video it cannot seek into. Cloudflare's Cache API does honour Range on a7// cached object, so the blob is stored there once and every later request,8// ranged or not, is served from the edge. Blobs are content-addressed, which9// is why the cache entry can be immutable.10//11// This route serves blobs only; a page that fails to reach it just shows an12// empty player. It is not on the middleware's fail-open path.1314const PDS_HOST = "https://atproto.danieldaum.net";15const REPO_DID = "did:plc:be2e4qfe6docqcysyxxwvsor";1617// CIDv1 in base32, the only form the PDS hands out. Anything else is refused18// before a request is made upstream.19const CID_RE = /^b[a-z2-7]{20,}$/;2021// Only media is proxied. The PDS sets the type from the record, so it is22// trusted here, but a blob of any other type is not something a page embeds.23const MEDIA_TYPE_RE = /^(image|video)\//;2425export async function onRequestGet(context) {26 const { request, params } = context;27 const cid = params.cid;28 if (typeof cid !== "string" || !CID_RE.test(cid)) {29 return plain("not found", 404);30 }3132 const cache = caches.default;33 // The key is the canonical URL without the query string, so /media/<cid>34 // and /media/<cid>?x share an entry. Range is carried on the lookup35 // request, which is what makes the Cache API return a 206.36 const keyUrl = new URL(request.url);37 keyUrl.search = "";38 const lookup = new Request(keyUrl.toString(), { headers: rangeOnly(request) });3940 let response = await cache.match(lookup);41 if (response) {42 return response;43 }4445 let upstream;46 try {47 upstream = await fetch(blobUrl(cid));48 } catch {49 return plain("bad gateway", 502);50 }51 if (!upstream.ok) {52 return plain("not found", upstream.status === 404 ? 404 : 502);53 }54 const type = upstream.headers.get("content-type") || "";55 if (!MEDIA_TYPE_RE.test(type)) {56 return plain("not found", 404);57 }5859 // Everything goes through memory once so the cached copy and the response60 // are built from the same bytes. Only the first request for a blob at a61 // given PoP pays for this.62 let body;63 try {64 body = await upstream.arrayBuffer();65 } catch {66 return plain("bad gateway", 502);67 }68 const headers = mediaHeaders(type, body.byteLength);69 context.waitUntil(cache.put(lookup.url, new Response(body.slice(0), { status: 200, headers })));7071 return ranged(request, body, headers);72}7374// The range parsing here only runs on a cache miss; the Cache API does the75// same job on every hit. One range, bytes only. Anything the parser does not76// understand gets the whole file, which is what the spec asks for.77function ranged(request, body, headers) {78 const length = body.byteLength;79 const range = parseRange(request.headers.get("range"), length);80 if (range === null) {81 return new Response(body, { status: 200, headers });82 }83 if (range === false) {84 const h = new Headers(headers);85 h.set("content-range", `bytes */${length}`);86 h.delete("content-length");87 return new Response(null, { status: 416, headers: h });88 }89 const [start, end] = range;90 const h = new Headers(headers);91 h.set("content-range", `bytes ${start}-${end}/${length}`);92 h.set("content-length", String(end - start + 1));93 return new Response(body.slice(start, end + 1), { status: 206, headers: h });94}9596// null: no usable range, serve everything. false: unsatisfiable, 416.97// [start, end]: inclusive byte range within the file.98function parseRange(header, length) {99 if (!header || length === 0) {100 return null;101 }102 const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim());103 if (!m || (m[1] === "" && m[2] === "")) {104 return null;105 }106 let start;107 let end;108 if (m[1] === "") {109 // suffix range: the last N bytes110 const suffix = Number(m[2]);111 if (suffix === 0) {112 return false;113 }114 start = Math.max(0, length - suffix);115 end = length - 1;116 } else {117 start = Number(m[1]);118 end = m[2] === "" ? length - 1 : Math.min(Number(m[2]), length - 1);119 }120 if (start >= length || start > end) {121 return false;122 }123 return [start, end];124}125126function mediaHeaders(type, length) {127 return {128 "content-type": type,129 "content-length": String(length),130 "accept-ranges": "bytes",131 // content-addressed: the bytes behind a cid never change132 "cache-control": "public, max-age=31536000, immutable",133 "x-content-type-options": "nosniff",134 // a blob must never be able to run anything, whatever it claims to be135 "content-security-policy": "default-src 'none'; sandbox",136 };137}138139function rangeOnly(request) {140 const headers = new Headers();141 const range = request.headers.get("range");142 if (range) {143 headers.set("range", range);144 }145 return headers;146}147148function blobUrl(cid) {149 const url = new URL("/xrpc/com.atproto.sync.getBlob", PDS_HOST);150 url.searchParams.set("did", REPO_DID);151 url.searchParams.set("cid", cid);152 return url.toString();153}154155function plain(text, status) {156 return new Response(text, {157 status,158 headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },159 });160}
global.css
+13 −1
@@ -1114,7 +1114,8 @@ hr {11141114}1115111511161116/* media attachment: sits below the text, bluesky-style */1117.micro-img {1117.micro-img,1118.micro-video {11181119 width: auto;11191120 max-width: 100%;11201121 max-height: 24rem;@@ -1124,6 +1125,17 @@ hr {11241125 align-self: flex-start;11251126}112611271128/* the timestamp's ::after is stretched over the whole card, so the player has1129 to sit above it or every tap on the controls opens the permalink instead.1130 height: auto beats the height attribute so the aspect ratio holds when the1131 box is narrower than the video */1132.micro-video {1133 position: relative;1134 z-index: 1;1135 height: auto;1136 background: var(--borders);1137}113811271139@media (max-width: 480px) {11281140 .micro-post {11291141 padding: 1.25rem 0.75rem;