Something went wrong. Try again.
A Gemini Protocol capsule for viewing Bluesky, Standard Site & similar records from the Atmosphere
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544// Package render turns Bluesky data into gemtext (text/gemini).//// Each page that the server serves has a template in templates/; the exported// funcs here build the page's data and execute its template. Sub-renders with// fiddly whitespace or union-type branching (post summaries, embeds, document// blocks) live in this file and are exposed to the templates as funcs (see// templates.go).package render
import ( "fmt" "io" "strings" "time"
"tangled.org/byjp.me/deepsky/internal/bsky" "tangled.org/byjp.me/deepsky/internal/doc")
// PageSize is the number of items shown per list page.const PageSize = 10
// Viewer is the atproto account a request's client certificate is bound to.type Viewer struct { DID string Handle string}
// Name returns the handle if known, otherwise the DID.func (v *Viewer) Name() string { if v.Handle != "" { return v.Handle } return v.DID}
// Ref returns the actor reference to use in /p/ URLs (handle preferred).func (v *Viewer) Ref() string { if v.Handle != "" { return v.Handle } return v.DID}
// ListItem is one entry on a post-list page.type ListItem struct { Post *bsky.PostView RepostBy string // handle of the reposter, if this entry is a repost Reply bool // this entry is a reply}
// PubGroup is a publication and its documents for the publications page. Pub is// nil for the "loose" group of documents not tied to a known publication.type PubGroup struct { Pub *bsky.Publication Docs []bsky.Document}
// --- page renderers: build data, execute the matching template ---
// Index writes the site landing page, greeting the viewer if recognised.func Index(w io.Writer, v *Viewer) { execute(w, "index.tmpl", v) }
type meData struct { Viewer *Viewer FP string}
// Me writes the identity page describing how the server sees the visitor:// recognised (Viewer set), a cert present but unlinked (FP set), or anonymous.func Me(w io.Writer, v *Viewer, fp string) { execute(w, "me.tmpl", meData{v, fp}) }
type profileData struct { Actor string P *bsky.Profile PubCount int // publication count; negative means unknown (omit it)}
// Profile writes a profile page: account details and links to the post lists.// pubCount is the number of publications; pass a negative value to omit it (the// only count cheap enough to fetch alongside the profile — posts come from the// profile itself, and replies/reposts/likes have no inexpensive total).func Profile(w io.Writer, urlActor string, p *bsky.Profile, pubCount int) { execute(w, "profile.tmpl", profileData{urlActor, p, pubCount})}
type listData struct { Title string Actor string BasePath string Items []ListItem NextCursor string}
// ListPage writes a titled list of post summaries with a pagination footer.// actor is the profile whose list this is (shown as a link back to it);// basePath is the list's own path (e.g. "/p/alice/posts/") used for the "More"// link; nextCursor, if non-empty, yields that link.func ListPage(w io.Writer, title, actor, basePath string, items []ListItem, nextCursor string) { execute(w, "list.tmpl", listData{title, actor, basePath, items, nextCursor})}
type searchData struct { Query string Actors []bsky.ActorView NextCursor string}
// SearchResults writes a page of people-search results for query, with a// pagination footer that carries the query forward.func SearchResults(w io.Writer, query string, actors []bsky.ActorView, nextCursor string) { execute(w, "search.tmpl", searchData{query, actors, nextCursor})}
// Post writes the full page for a single post. Images are linked as relative// .webp files served by this server (see the image route); the post's URL must// therefore end in a slash for the links to resolve correctly.func Post(w io.Writer, p *bsky.PostView) { execute(w, "post.tmpl", p) }
type publicationsData struct { Actor string Groups []PubGroup Truncated bool}
// Any reports whether any group has renderable content, so the template can// fall back to "No publications yet." (mirrors the old hasAny check).func (d publicationsData) Any() bool { for _, g := range d.Groups { if g.Pub != nil || len(g.Docs) > 0 { return true } } return false}
// Publications writes the publications directory: each publication and its// documents, followed by any loose documents.func Publications(w io.Writer, urlActor string, groups []PubGroup, truncated bool) { execute(w, "publications.tmpl", publicationsData{urlActor, groups, truncated})}
type publicationData struct { Actor string RKey string Pub *bsky.Publication Docs []bsky.Document NextCursor string}
// Publication writes a single publication's page: its details and a paginated// list of its documents (newest first). nextCursor, if non-empty, yields a// "More" link.func Publication(w io.Writer, urlActor, rkey string, pub *bsky.Publication, docs []bsky.Document, nextCursor string) { execute(w, "publication.tmpl", publicationData{urlActor, rkey, pub, docs, nextCursor})}
type documentData struct { Actor string Doc *bsky.Document Blocks []doc.Block Pub *bsky.Publication}
// Document writes a full document page. blocks is the parsed body; pub is the// owning publication (for the canonical web link), if known.func Document(w io.Writer, urlActor string, d *bsky.Document, blocks []doc.Block, pub *bsky.Publication) { execute(w, "document.tmpl", documentData{urlActor, d, blocks, pub})}
// --- sub-renderers (exposed to templates via funcMap) and helpers ---
// writeSummary renders one post as a linked summary for a list page.func writeSummary(w io.Writer, it ListItem) { post := it.Post switch { case it.RepostBy != "": fmt.Fprintf(w, "↻ Reposted by @%s\n", it.RepostBy) case it.Reply: if path := replyParentPath(post.Record); path != "" { fmt.Fprintf(w, "=> %s ↩ In reply to a post\n", path) } else { fmt.Fprintln(w, "↩ Reply") } }
if date := isoDate(post.Record.CreatedAt); date != "" { fmt.Fprintf(w, "=> %s %s %s\n", postPath(post.Author, post.TID()), date, post.Author.Name()) } else { fmt.Fprintf(w, "=> %s %s\n", postPath(post.Author, post.TID()), post.Author.Name()) } if text := strings.TrimSpace(post.Record.Text); text != "" { fmt.Fprintln(w, oneParagraph(text, 280)) } writeSummaryImages(w, post) writeSummaryExternal(w, post.Embed) if att := attachmentSummary(post.Embed); att != "" { fmt.Fprintf(w, "%s\n", att) } fmt.Fprintf(w, "%s replies · %s reposts · %s likes\n\n", number(post.ReplyCount), number(post.RepostCount), number(post.LikeCount))}
// writeSummaryImages links a list summary's images into the post's own image// route (the same images the post page links relatively), so a thumbnail can be// followed without opening the post first.func writeSummaryImages(w io.Writer, post *bsky.PostView) { base := postPath(post.Author, post.TID()) for i, img := range post.Embed.MediaImages() { alt := oneLine(img.Alt) if alt == "" { alt = fmt.Sprintf("Image %d", i+1) } fmt.Fprintf(w, "=> %simg-%d.webp 🖼️ %s\n", base, i, alt) }}
// writeSummaryExternal links a list summary's external/link-card embed straight// to its target, with the card's title (or the URL) as the label.func writeSummaryExternal(w io.Writer, e *bsky.Embed) { ext := e.MediaExternal() if ext == nil || ext.URI == "" { return } title := strings.TrimSpace(ext.Title) if title == "" { title = ext.URI } fmt.Fprintf(w, "=> %s 🔗 %s\n", ext.URI, oneLine(title))}
// linkLabel picks the label for a post link: the post's own anchor text when it// added a custom label, or a generic note when the text is just the URL.func linkLabel(l bsky.Link) string { return linkLabelFor(l.Text, l.URI, "Link from post")}
// linkLabelFor returns text as a link label, falling back to generic when the// text is empty or merely a rendering of the URL.func linkLabelFor(text, uri, generic string) string { text = strings.TrimSpace(text) if text == "" || isURLText(text, uri) { return generic } return oneLine(text)}
// isURLText reports whether text is merely a (possibly shortened) rendering of// uri, as opposed to a human-written label.func isURLText(text, uri string) bool { norm := func(s string) string { s = strings.ToLower(strings.TrimSpace(s)) s = strings.TrimPrefix(s, "https://") s = strings.TrimPrefix(s, "http://") s = strings.TrimPrefix(s, "www.") return strings.TrimRight(s, "/") } t := norm(strings.TrimRight(text, ".…")) // Bluesky shortens with a trailing … if t == "" { return true } return strings.HasPrefix(norm(uri), t)}
// writeEmbed renders images, external cards and quoted posts as gemtext.// authorDID is the DID of the embedding post's author, used to detect// self-quotes.func writeEmbed(w io.Writer, authorDID string, e *bsky.Embed) { if e == nil { return }
for i, img := range e.MediaImages() { alt := oneLine(img.Alt) if alt == "" { alt = fmt.Sprintf("Image %d", i+1) } // Relative link, served by this server from the Bluesky CDN. The CDN's // size-limited variant is WebP regardless of the URL's format hint. fmt.Fprintf(w, "=> img-%d.webp 🖼️ %s\n", i, alt) }
if ext := e.MediaExternal(); ext != nil && ext.URI != "" { title := strings.TrimSpace(ext.Title) if title == "" { title = ext.URI } fmt.Fprintf(w, "=> %s 🔗 %s\n", ext.URI, oneLine(title)) if d := strings.TrimSpace(ext.Description); d != "" { fmt.Fprintln(w, oneParagraph(d, 200)) } }
if e.Type == "app.bsky.embed.video#view" && e.Playlist != "" { alt := strings.TrimSpace(e.Alt) if alt == "" { alt = "Video" } fmt.Fprintf(w, "=> %s 🎬 %s\n", e.Playlist, oneLine(alt)) }
if q := e.Quoted(); q != nil { if q.Author.DID != "" && q.Author.DID == authorDID { fmt.Fprint(w, "\n## Quoting themselves\n") } else { fmt.Fprintf(w, "\n## Quoting %s (@%s)\n", q.Author.Name(), q.Author.Handle) } if text := strings.TrimSpace(q.Value.Text); text != "" { writeQuoted(w, oneParagraph(text, 280)) } fmt.Fprintf(w, "=> %s View quoted post\n", postPath(q.Author, bsky.RKeyFromURI(q.URI))) }}
// attachmentSummary gives a short inline note about a post's embed for use in// list summaries (where the full embed is not rendered).func attachmentSummary(e *bsky.Embed) string { if e == nil { return "" } var parts []string // Images and link cards are surfaced as their own links in summaries, so // they aren't repeated here. if e.Type == "app.bsky.embed.video#view" { parts = append(parts, "video") } if e.Quoted() != nil { parts = append(parts, "quoted post") } if len(parts) == 0 { return "" } return "[" + strings.Join(parts, ", ") + "]"}
// maxPubDocs is how many documents are previewed under each publication.const maxPubDocs = 3
// PreviewDocs returns the documents shown inline under a publication on the// publications directory (capped at maxPubDocs).func (g PubGroup) PreviewDocs() []bsky.Document { if len(g.Docs) > maxPubDocs { return g.Docs[:maxPubDocs] } return g.Docs}
// RKey is the publication's record key, for building its page link.func (g PubGroup) RKey() string { if g.Pub == nil { return "" } return bsky.RKeyFromURI(g.Pub.URI)}
// writeDocLink renders one document as a link line with its date.func writeDocLink(w io.Writer, urlActor string, d bsky.Document) { title := strings.TrimSpace(d.Title) if title == "" { title = "(untitled)" } prefix := "" if date := isoDate(d.PublishedAt); date != "" { prefix = date + " " } fmt.Fprintf(w, "=> /p/%s/documents/%s/ %s%s\n", urlActor, d.RKey, prefix, oneLine(title))}
// docRule separates a document's metadata header from its body.const docRule = "──────────"
// writeBlocks renders parsed document blocks as gemtext.func writeBlocks(w io.Writer, blocks []doc.Block) { imgIndex, olCount := 0, 0 for _, b := range blocks { if b.Kind != doc.ListItem { olCount = 0 } switch b.Kind { case doc.Heading: fmt.Fprintf(w, "%s %s\n\n", strings.Repeat("#", min(b.Level+1, 3)), oneLine(b.Text)) case doc.Code: fmt.Fprintf(w, "```\n%s\n```\n\n", strings.TrimRight(b.Text, "\n")) case doc.Quote: writeQuoted(w, b.Text) writeBlockLinks(w, b.Links) fmt.Fprintln(w) case doc.ListItem: marker := "*" if b.Ordered { olCount++ marker = fmt.Sprintf("%d.", olCount) } fmt.Fprintf(w, "%s %s\n", marker, oneLine(b.Text)) writeBlockLinks(w, b.Links) case doc.Image: alt := oneLine(b.Alt) if alt == "" { alt = fmt.Sprintf("Image %d", imgIndex+1) } fmt.Fprintf(w, "=> img-%d.%s 🖼️ %s\n\n", imgIndex, mimeExt(b.MIME), alt) imgIndex++ case doc.Embed: fmt.Fprintf(w, "=> %s 🔗 %s\n\n", b.URL, b.URL) default: // Paragraph if text := strings.TrimSpace(b.Text); text != "" { fmt.Fprintln(w, b.Text) } writeBlockLinks(w, b.Links) fmt.Fprintln(w) } }}
// writeBlockLinks surfaces a block's links as gemtext link lines.func writeBlockLinks(w io.Writer, links []doc.Link) { for _, l := range links { fmt.Fprintf(w, "=> %s %s\n", l.URI, linkLabelFor(l.Text, l.URI, l.URI)) }}
// webURL returns the document's canonical web address, if derivable.func webURL(d *bsky.Document, pub *bsky.Publication) string { if d.CanonicalURL != "" { return d.CanonicalURL } if pub != nil && pub.URL != "" && d.Path != "" { return strings.TrimRight(pub.URL, "/") + "/" + strings.TrimPrefix(d.Path, "/") } return ""}
// mimeExt maps an image MIME type to a file extension (cosmetic only).func mimeExt(mime string) string { switch mime { case "image/png": return "png" case "image/webp": return "webp" case "image/gif": return "gif" default: return "jpg" }}
// atName renders an actor reference for display: "@handle" for a handle, or the// DID unchanged (DIDs aren't @-prefixed).func atName(actor string) string { if actor == "" || strings.HasPrefix(actor, "did:") { return actor } return "@" + actor}
// actorRef prefers a handle for readable URLs, falling back to the DID.func actorRef(a bsky.Author) string { if a.Handle != "" && a.Handle != "handle.invalid" { return a.Handle } return a.DID}
// postPath builds the gemini path to a post's page. The trailing slash matters:// it makes the post's relative image links resolve under the post.func postPath(a bsky.Author, tid string) string { return "/p/" + actorRef(a) + "/p/" + tid + "/"}
// replyParentPath returns the gemini path to the post a reply replies to, or ""// when the record isn't a reply or lacks a usable parent reference. The parent// is addressed by DID (the record only carries the DID, not a handle).func replyParentPath(r bsky.PostRecord) string { if r.Reply == nil || r.Reply.Parent.URI == "" { return "" } did, _, rkey := bsky.ParseATURI(r.Reply.Parent.URI) if did == "" || rkey == "" { return "" } return "/p/" + did + "/p/" + rkey + "/"}
// writeQuoted writes text as gemtext quote lines, one per source line.func writeQuoted(w io.Writer, text string) { for _, line := range strings.Split(text, "\n") { fmt.Fprintf(w, "> %s\n", line) }}
// isoDate formats an RFC3339 timestamp as YYYY-MM-DD, or "" if unparseable.// List rows lead with this; detail pages use fuller date-times.func isoDate(s string) string { if t, ok := parseTime(s); ok { return t.Format("2006-01-02") } return ""}
func parseTime(s string) (time.Time, bool) { if s == "" { return time.Time{}, false } if t, err := time.Parse(time.RFC3339, s); err == nil { return t.UTC(), true } return time.Time{}, false}
// oneLine collapses whitespace so a value is safe on a gemtext link line.func oneLine(s string) string { return strings.Join(strings.Fields(s), " ")}
// oneParagraph collapses newlines to spaces and truncates to max runes.func oneParagraph(s string, max int) string { s = strings.Join(strings.Fields(s), " ") r := []rune(s) if len(r) > max { return strings.TrimSpace(string(r[:max])) + "…" } return s}
// number formats counts with thousands separators (e.g. 12,345).func number(n int) string { s := fmt.Sprint(n) neg := strings.HasPrefix(s, "-") if neg { s = s[1:] } var b strings.Builder for i, c := range s { if i > 0 && (len(s)-i)%3 == 0 { b.WriteByte(',') } b.WriteRune(c) } if neg { return "-" + b.String() } return b.String()}