oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1// thumbs.go serves a slide as a picture (spec §4.2): one SVG per
2// slide, on every surface a deck can be read from.
3//
4// Four routes, one body:
5//
6// GET /d/{sqid}/slides/{id}.svg the session cookie
7// GET /s/{token}/slides/{id}.svg a share link
8// GET /p/{session}/slides/{id}.svg a talk in progress
9// GET /api/v1/decks/{sqid}/slides/{id}.svg a bearer token
10//
11// Each is the deck's own capability with the slide on the end, exactly
12// as the asset routes are (assets.go's comment on why there are four of
13// those). What differs between them is who is let in and where the
14// pictures inside come from; what does not differ is the picture, which
15// is internal/slides/layout measured and internal/slides/svg written,
16// the same two calls the PDF makes.
17//
18// # Why an SVG and not the HTML
19//
20// The editor strip used to hold nine copies of a slide's whole DOM,
21// scaled down by a CSS transform: nine sections, every block, every
22// run, live in the page and re-laid-out on every resize. A thumbnail is
23// now one <img>. It is smaller to send, cheaper to paint, and — the
24// part that matters — it is the SAME picture the export is, because
25// both come off one paint list.
26//
27// The `.html` route stays (editor.go's deckSlide): the stage swaps real
28// markup in, because the stage is what a person types into.
29//
30// # Caching
31//
32// The tag is the deck's seq, the slide's id and the requested width.
33// Seq changes on every accepted edit, so a strip that re-fetches nine
34// thumbnails after a keystroke gets nine 304s for the eight that did
35// not change. must-revalidate rather than a max-age: a thumbnail is a
36// picture of a document being edited, and one that is thirty seconds
37// stale is a bug report.
38package slides
39
40import (
41 "context"
42 "net/http"
43 "strconv"
44 "strings"
45
46 "github.com/go-chi/chi/v5"
47
48 "amadan.net/oficina/slides/internal/slides/deck"
49 "amadan.net/oficina/slides/internal/slides/layout"
50 "amadan.net/oficina/slides/internal/slides/svg"
51)
52
53// thumbMaxWidth bounds the ?w= a caller may ask for. Nothing rasters
54// today — an SVG scales, so the parameter changes nothing about the
55// bytes — but it is READ and it is in the ETag, so the day a raster
56// twin lands, every cache in between already has the width in its key
57// rather than one PNG standing in for every size.
58const thumbMaxWidth = 4096
59
60// thumbWidth reads ?w=. Anything that is not a plausible width is
61// dropped rather than refused: it is a rendering hint on a read, and a
62// caller that sent a typo should get the slide.
63func thumbWidth(raw string) string {
64 n, err := strconv.Atoi(strings.TrimSpace(raw))
65 if err != nil || n <= 0 || n > thumbMaxWidth {
66 return ""
67 }
68 return strconv.Itoa(n)
69}
70
71// --- GET /s/{token}/slides/{id}.svg ---
72
73// sharedSlideThumb serves a thumbnail to somebody holding a share link.
74// The token is the whole capability, as it is for the page and for the
75// images on it.
76func (a *app) sharedSlideThumb(w http.ResponseWriter, r *http.Request) {
77 d, _, ok := a.deckForShareLink(w, r, chi.URLParam(r, "token"))
78 if !ok {
79 return
80 }
81 a.serveThumb(w, r, d, "/s/"+chi.URLParam(r, "token"), func() { a.notFound(w, r) })
82}
83
84// --- GET /p/{session}/slides/{id}.svg ---
85
86// presentSlideThumb serves a thumbnail to a screen watching a talk —
87// the presenter's own notes window and the remote in a pocket, both of
88// which show the current slide and the next one small.
89func (a *app) presentSlideThumb(w http.ResponseWriter, r *http.Request) {
90 p, ok := a.presentationFor(w, r)
91 if !ok {
92 return
93 }
94 d, ok := a.deckOf(w, r, p)
95 if !ok {
96 return
97 }
98 a.serveThumb(w, r, d, "/p/"+p.Sqid, func() { a.notFound(w, r) })
99}
100
101// serveThumb is the whole body, once.
102//
103// base is the surface's own root — "/d/{sqid}", "/s/{token}",
104// "/p/{session}" — and the images inside the picture are served from
105// base + "/assets", so a thumbnail fetched by an unauthenticated
106// audience does not point at a route only a member can reach.
107//
108// missing is how THIS surface says "no such slide": the app's own 404
109// page on the three browser routes, the API's JSON shape on the fourth.
110// Nothing about the answer differs but its wrapper, and passing it in
111// is what keeps a bearer-token caller from being handed HTML.
112func (a *app) serveThumb(w http.ResponseWriter, r *http.Request, d Deck, base string, missing func()) {
113 slideID, ok := strings.CutSuffix(chi.URLParam(r, "file"), ".svg")
114 if !ok || slideID == "" {
115 missing()
116 return
117 }
118 width := thumbWidth(r.URL.Query().Get("w"))
119
120 // Seq, slide and width: the three things that change these bytes,
121 // with the share links, which decide the follow-along codes drawn
122 // (followCodes) and change no seq when one is revoked.
123 // The tag goes on the two responses that ARE this representation
124 // and never on the 404 — a tag on "there is no such slide" invites
125 // a cache to treat the absence as the thing (editor.go says the
126 // same about the HTML twin).
127 etag := strconv.Quote(strconv.FormatInt(d.Seq, 10) + a.linksStamp(r.Context(), d) + "-" + slideID + "-" + width)
128 // A reader's route answers 304 only after the slide is known to be
129 // one it may see (a wildcard tag matches everything, parked slides
130 // included), so it pays a deck open; the editor and the API, which
131 // filter nothing, keep the quick answer.
132 reader := strings.HasPrefix(base, "/s/") || strings.HasPrefix(base, "/p/")
133 notModified := func() {
134 thumbHeaders(w, etag)
135 w.WriteHeader(http.StatusNotModified)
136 }
137 conditional := matchesETag(r.Header.Get("If-None-Match"), etag)
138 if conditional && !reader {
139 notModified()
140 return
141 }
142
143 h, view, err := a.openDeck(r.Context(), d)
144 if err != nil {
145 a.fail(w, r, "open a deck to draw a thumbnail", err)
146 return
147 }
148 defer h.Close(r.Context())
149 // The editor's route (/d/…) and the API describe the whole deck; a
150 // share link and a presentation session are readers, and a parked
151 // slide is not there for them.
152 if reader {
153 view = view.ForReaders()
154 }
155
156 index := -1
157 for i, s := range view.Slides {
158 if s.ID == slideID {
159 index = i
160 break
161 }
162 }
163 if index < 0 {
164 missing()
165 return
166 }
167 if conditional {
168 notModified()
169 return
170 }
171
172 out, err := a.thumbnail(r, d, view, index, base)
173 if err != nil {
174 a.fail(w, r, "draw a thumbnail", err)
175 return
176 }
177 thumbHeaders(w, etag)
178 w.Header().Set("Content-Length", strconv.Itoa(len(out)))
179 w.WriteHeader(http.StatusOK)
180 w.Write(out)
181}
182
183// thumbnail is the picture itself: measure, then write.
184//
185// The label is the slide's own (viewer.go's slideLabel — its first
186// heading, or "Slide n"), and it goes in the document's <title>, where
187// role="img" makes it the name of the whole picture. The <img> that
188// shows it carries the same words in its alt, because an alt is what a
189// browser reads and it never opens the file to find a title.
190func (a *app) thumbnail(r *http.Request, d Deck, view *deck.Deck, index int, base string) ([]byte, error) {
191 paint, warnings, err := layout.New(view, layout.Options{
192 Fonts: a.fontLoader(r.Context(), d.ID),
193 QR: a.followCodes(r.Context(), d, view, base),
194 }).Layout(index)
195 if err != nil {
196 return nil, err
197 }
198 // §11's degrade-loudly rule, at the volume a thumbnail deserves:
199 // the picture is drawn either way, and a person is not shown a
200 // warning about a slide they are looking at nine of. The export
201 // (task 4) is where these reach somebody.
202 for _, warn := range warnings {
203 a.logger.Debug("slides: thumbnail warning",
204 "deck", d.Sqid, "slide", view.Slides[index].ID, "kind", warn.Kind, "detail", warn.Detail)
205 }
206 assets := assetBaseFor(base)
207 return svg.Encode(paint, svg.Options{
208 Title: slideLabel(r, view.Slides[index], index+1),
209 EmbedFonts: true,
210 InlineImages: a.assetBytes(r.Context(), d, view),
211 AssetURL: func(id string) string {
212 asset, ok := view.Assets[id]
213 if !ok || !assetRefPattern.MatchString(asset.Ref) {
214 return ""
215 }
216 return assets + "/" + asset.Ref
217 },
218 }), nil
219}
220
221// assetBytes reads an asset's bytes for the serialiser to inline.
222//
223// It has to inline. A thumbnail is shown in an `<img src>`, and a
224// browser renders an SVG referenced that way in a mode that fetches
225// nothing at all: an <image href="/d/…/assets/…"> inside one is simply
226// not loaded, however good the capability on it is. So the bytes go in
227// as a data URI or the picture is not in the thumbnail. (The URL is
228// still written when this cannot resolve one — that is the case where
229// somebody opened the .svg itself, where it does load.)
230//
231// The verified-asset row is checked, exactly as serveAsset checks it
232// and for exactly the same reason: registerAsset READ the bytes and
233// sanitised the SVG among them, and the row is the record that it did.
234// Without it a member could presign a PUT for an unsanitised SVG, name
235// its ref in a `register_asset` op — which nothing checks — and have it
236// spliced into a document this app serves from its own origin.
237//
238// Returns nil when this deployment has no object store, which turns
239// InlineImages off in the serialiser rather than making it ask nine
240// times.
241//
242// A context rather than the request: the PDF export uses this same
243// reader (exports.go), and a job outlives its request.
244func (a *app) assetBytes(ctx context.Context, d Deck, view *deck.Deck) func(string) ([]byte, string, bool) {
245 store := a.cfg.Blobs
246 if store == nil {
247 return nil
248 }
249 var verified []string
250 if err := a.db.G.WithContext(ctx).Model(&DeckAsset{}).
251 Where("deck_id = ?", d.ID).Pluck("ref", &verified).Error; err != nil {
252 a.logger.Error("slides: list verified assets for a thumbnail", "deck", d.Sqid, "err", err)
253 return nil
254 }
255 if len(verified) == 0 {
256 return nil
257 }
258 ok := make(map[string]bool, len(verified))
259 for _, ref := range verified {
260 ok[ref] = true
261 }
262
263 // One slide can name one asset several times (a picture in two
264 // columns), and a background is an op of its own. Read once.
265 seen := map[string][]byte{}
266 return func(id string) ([]byte, string, bool) {
267 asset, found := view.Assets[id]
268 if !found || !assetRefPattern.MatchString(asset.Ref) || !ok[asset.Ref] {
269 return nil, "", false
270 }
271 raw, read := seen[asset.Ref]
272 if !read {
273 b, err := a.readAsset(ctx, store, asset.Ref)
274 if err != nil {
275 // Not a failure of the request: the slide is drawn
276 // without the picture, which is what the browser shows
277 // for a broken <img> anyway.
278 a.logger.Error("slides: read an asset for a thumbnail",
279 "deck", d.Sqid, "ref", asset.Ref, "err", err)
280 b = nil
281 }
282 seen[asset.Ref] = b
283 raw = b
284 }
285 if len(raw) == 0 {
286 return nil, "", false
287 }
288 kind := sniffImage(raw)
289 if kind == "" {
290 return nil, "", false
291 }
292 return raw, kind, true
293 }
294}
295
296// thumbHeaders is the header set a thumbnail carries, on the 200 and on
297// the 304 alike.
298//
299// The Content-Security-Policy is the same argument assetHeaders makes:
300// an SVG comes back from this app's OWN origin, so anything executable
301// inside one would run with every cookie this app has. Nothing here
302// writes a script and every embedded picture was sanitised at
303// registration — and this says that even a document that somehow got
304// past both can load nothing and reach nowhere. img-src is 'self' and
305// data: because those are the two places a picture inside one legally
306// comes from: the surface's own asset route, and the bytes inlined into
307// the file.
308//
309// private, because the URL is the deck's capability and not the
310// object's: a shared cache must not hand this to the next person who
311// asks.
312func thumbHeaders(w http.ResponseWriter, etag string) {
313 w.Header().Set("Content-Type", "image/svg+xml; charset=utf-8")
314 w.Header().Set("X-Content-Type-Options", "nosniff")
315 // font-src data: for the uploaded faces a picture carries in its own
316 // <style> (svg.Options.EmbedFonts); it loads no font from anywhere.
317 w.Header().Set("Content-Security-Policy",
318 "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; font-src data:")
319 w.Header().Set("ETag", etag)
320 w.Header().Set("Cache-Control", "private, max-age=0, must-revalidate")
321}
322