oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1package slides
2
3// deckfonts.go is a font from a person's library put to use in a deck,
4// and the deck serving it.
5//
6// POST /d/{sqid}/fonts record a family of mine for this deck
7// GET {surface}/fonts/{ref} the bytes, by the deck's own capability
8//
9// It is the pictures' design (assets.go) on fonts. The POST does NOT
10// write the document: it answers the family as meta.fontFiles carries it
11// (deck.FontFamily), and the editor commits one set_meta with it — the
12// same op path, update log and undo stack as every other change
13// (fixtures/deck-fonts.mjs). What the POST writes is one DeckFont row per
14// face, saying this deck took the file from a library its editor owns,
15// because meta.fontFiles is a list any member or agent can write with
16// any ref. A font is served only when both say so: the row, and the
17// deck's own list (or, to the person who picked it, the row and their
18// own library: deckFont). So a deck serves nothing it was not given, a
19// share link to one deck is not a way to another deck's fonts, and
20// knowing a ref is never a way to read a file.
21//
22// Undo takes the set_meta back and leaves the rows: they only let the
23// deck serve a ref it lists, and a redo lists it again.
24
25import (
26 "context"
27 "encoding/binary"
28 "encoding/json"
29 "errors"
30 "fmt"
31 "io"
32 "net/http"
33 "sort"
34 "strings"
35
36 "github.com/go-chi/chi/v5"
37 "gorm.io/gorm"
38 "gorm.io/gorm/clause"
39
40 "amadan.net/oficina/estilo.git/typeface"
41 "amadan.net/oficina/slides/internal/slides/deck"
42 "amadan.net/rastrillo/rastrillo/blobs"
43)
44
45// maxFontFamilyName is the longest Family meta.fontFiles takes
46// (core/src/schema.rs's MAX_FONT_NAME), in characters. A library family
47// may be longer (typeface allows 256); the deck gets it cut.
48const maxFontFamilyName = 200
49
50// errDeckGone is a pick whose deck was deleted after it was found.
51var errDeckGone = errors.New("slides: the deck was deleted")
52
53// fontFail is a refusal of POST /d/{sqid}/fonts. The editor shows no
54// words for one — the field goes back to what the deck has — so the
55// answer is a code for a log, not copy.
56func fontFail(w http.ResponseWriter, status int, code string) {
57 w.Header().Set("Content-Type", "application/json")
58 w.WriteHeader(status)
59 json.NewEncoder(w).Encode(map[string]string{"error": code})
60}
61
62// --- POST /d/{sqid}/fonts ---
63
64// pickDeckFont records one family of the signed-in person's library for
65// a deck they can edit, and answers it as meta.fontFiles carries it.
66// 404 for a family that is not theirs, someone else's included: the
67// answer for "not yours" and "no such family" is one answer.
68func (a *app) pickDeckFont(w http.ResponseWriter, r *http.Request) {
69 u, ok := a.viewer(w, r)
70 if !ok {
71 return
72 }
73 d, ok := a.deckFor(w, r, u)
74 if !ok {
75 return
76 }
77 r.Body = http.MaxBytesReader(w, r.Body, 4<<10)
78 var body struct {
79 Family string `json:"family"`
80 }
81 if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
82 fontFail(w, http.StatusBadRequest, "invalid")
83 return
84 }
85 ctx := r.Context()
86 guard := a.deckGuard(ctx, u, d)
87
88 // Under the library's lock: a delete of this family cannot count
89 // its references between the read below and the rows going in, and
90 // so cannot take the bytes away from a deck that has just got them.
91 a.traceFont("pick")
92 a.fontMu.Lock()
93 defer a.fontMu.Unlock()
94 rows, err := a.ownFontFamily(ctx, u, body.Family)
95 if err != nil {
96 a.fail(w, r, "read a font family", err)
97 return
98 }
99 if len(rows) == 0 {
100 fontFail(w, http.StatusNotFound, "not_found")
101 return
102 }
103 // The deck names the family, not the picker's library: the name must
104 // be unique among the families the deck lists, whoever's they are.
105 h, view, err := a.openDeck(ctx, d)
106 if err != nil {
107 // A deck deleted since it was found cannot be opened: the
108 // answer is the transaction's below, not found.
109 var n int64
110 if cerr := a.db.G.WithContext(ctx).Model(&Deck{}).Where("id = ?", d.ID).Count(&n).Error; cerr == nil && n == 0 {
111 fontFail(w, http.StatusNotFound, "not_found")
112 return
113 }
114 a.fail(w, r, "open a deck to name a font", err)
115 return
116 }
117 h.Close(ctx)
118 css := deckFontName(view.Meta.FontFiles, rows)
119 // The deck was found before the lock; a deletion may have finished
120 // since (deleteDeck takes the same lock). It is looked for again in
121 // the transaction the rows go in, so no row is ever written for a
122 // deck that is gone: one would hold the font's object for good.
123 if err := a.guarded(ctx, guard, func(db *gorm.DB) error {
124 return db.Transaction(func(tx *gorm.DB) error {
125 var n int64
126 if err := tx.Model(&Deck{}).Where("id = ?", d.ID).Count(&n).Error; err != nil {
127 return err
128 }
129 if n == 0 {
130 return errDeckGone
131 }
132 for _, f := range rows {
133 if err := tx.Clauses(clause.OnConflict{DoNothing: true}).
134 Create(&DeckFont{DeckID: d.ID, Ref: f.Ref}).Error; err != nil {
135 return err
136 }
137 }
138 return nil
139 })
140 }); err != nil {
141 if errors.Is(err, errDeckGone) {
142 fontFail(w, http.StatusNotFound, "not_found")
143 return
144 }
145 if a.guardRefused(w, r, err) {
146 return
147 }
148 a.fail(w, r, "record a deck font", err)
149 return
150 }
151 w.Header().Set("Content-Type", "application/json")
152 w.Header().Set("Cache-Control", "no-store")
153 json.NewEncoder(w).Encode(fontFamilyOf(rows, css))
154}
155
156// deckFontName is the CSS name a deck gives a family picked from a
157// library (rows, one family's faces). A family the deck lists already
158// that shares a file with it is this same family, perhaps with faces
159// added since, and keeps its name. Otherwise the library's name, with
160// " 2", " 3" … added while a family the deck lists has it, compared as
161// a browser compares family names (without regard to case), or while
162// it is one a stack already means something by. So two people's
163// libraries can each hold a font called Brand, and a deck that uses
164// both calls them Brand and Brand 2 (final review, I3).
165func deckFontName(listed []deck.FontFamily, rows []LibraryFont) string {
166 mine := map[string]bool{}
167 for _, f := range rows {
168 mine[f.Ref] = true
169 }
170 taken := map[string]bool{}
171 for _, fam := range listed {
172 for _, face := range fam.Faces {
173 if mine[face.Ref] {
174 return fam.CSS
175 }
176 }
177 taken[strings.ToLower(fam.CSS)] = true
178 }
179 base := rows[0].CSSName
180 css := base
181 for n := 2; taken[strings.ToLower(css)] || reservedFontName(css); n++ {
182 css = fmt.Sprintf("%s %d", base, n)
183 }
184 return css
185}
186
187// fontFamilyOf is one library family as meta.fontFiles carries it, under
188// the CSS name css, its faces lightest first and upright before italic.
189func fontFamilyOf(rows []LibraryFont, css string) deck.FontFamily {
190 sort.SliceStable(rows, func(i, j int) bool {
191 if rows[i].WeightMin != rows[j].WeightMin {
192 return rows[i].WeightMin < rows[j].WeightMin
193 }
194 if rows[i].Italic != rows[j].Italic {
195 return !rows[i].Italic
196 }
197 return rows[i].ID < rows[j].ID
198 })
199 family := []rune(rows[0].Family)
200 if len(family) > maxFontFamilyName {
201 family = family[:maxFontFamilyName]
202 }
203 fam := deck.FontFamily{Family: string(family), CSS: css, Faces: make([]deck.FontFace, 0, len(rows))}
204 for _, f := range rows {
205 fam.Faces = append(fam.Faces, deck.FontFace{
206 Ref: f.Ref, Format: f.Format, Weight: [2]int{f.WeightMin, f.WeightMax},
207 Italic: f.Italic, Pictures: f.Pictures,
208 })
209 }
210 return fam
211}
212
213// yourFonts is the person's library families for Deck settings' font
214// fields: the CSS name, which the editor posts, and the family's own
215// name, which it shows. Sorted by name, as the Fonts page lists them.
216func (a *app) yourFonts(ctx context.Context, u User) ([]selectOption, error) {
217 var rows []LibraryFont
218 if err := a.db.G.WithContext(ctx).Where("owner = ?", actorFor(u)).
219 Order("family, id").Find(&rows).Error; err != nil {
220 return nil, err
221 }
222 seen := map[string]bool{}
223 var out []selectOption
224 for _, f := range rows {
225 if seen[f.CSSName] {
226 continue
227 }
228 seen[f.CSSName] = true
229 out = append(out, selectOption{Value: f.CSSName, Label: f.Family})
230 }
231 sort.SliceStable(out, func(i, j int) bool {
232 return strings.ToLower(out[i].Label) < strings.ToLower(out[j].Label)
233 })
234 return out, nil
235}
236
237// --- GET {surface}/fonts/{ref} ---
238
239// deckFont serves a deck's font to a signed-in reader of the deck. A
240// recorded ref the deck does not list yet is served to the person whose
241// own library holds it: their pick, whose faces the editor loads before
242// it commits the set_meta that lists them (fixtures/editor-fonts.mjs),
243// so the change waits for its font like any other. Those bytes are
244// theirs already; nobody else gets them until the deck lists them.
245func (a *app) deckFont(w http.ResponseWriter, r *http.Request) {
246 u, ok := a.viewer(w, r)
247 if !ok {
248 return
249 }
250 d, ok := a.deckFor(w, r, u)
251 if !ok {
252 return
253 }
254 a.serveFont(w, r, d, func(ref string) bool {
255 var n int64
256 err := a.db.G.WithContext(r.Context()).Model(&LibraryFont{}).
257 Where("owner = ? AND ref = ?", actorFor(u), ref).Count(&n).Error
258 return err == nil && n > 0
259 })
260}
261
262// sharedFont serves a deck's font to somebody holding a share link.
263func (a *app) sharedFont(w http.ResponseWriter, r *http.Request) {
264 d, _, ok := a.deckForShareLink(w, r, chi.URLParam(r, "token"))
265 if !ok {
266 return
267 }
268 a.serveFont(w, r, d, nil)
269}
270
271// presentFont serves a deck's font to a projector, a presenter's phone
272// or an audience following along (presentation.go).
273func (a *app) presentFont(w http.ResponseWriter, r *http.Request) {
274 p, ok := a.presentationFor(w, r)
275 if !ok {
276 return
277 }
278 d, ok := a.deckOf(w, r, p)
279 if !ok {
280 return
281 }
282 a.serveFont(w, r, d, nil)
283}
284
285// serveFont is the one body behind all three: the ref must have a
286// DeckFont row for this deck AND be listed in the deck's
287// meta.fontFiles (or, where yours is given, be the reader's own:
288// deckFont); then the bytes, with typeface's headers. Fonts are
289// deck-wide, so a parked slide changes nothing here.
290//
291// Always streamed through this app, never a redirect to a presigned
292// URL: the pages load fonts from 'self' only.
293func (a *app) serveFont(w http.ResponseWriter, r *http.Request, d Deck, yours func(ref string) bool) {
294 ref := chi.URLParam(r, "ref")
295 store := a.cfg.Blobs
296 if !fontRefPattern.MatchString(ref) || store == nil {
297 a.notFound(w, r)
298 return
299 }
300 recorded, err := a.deckFontRefs(r.Context(), d.ID)
301 if err != nil {
302 a.fail(w, r, "look up a deck's fonts", err)
303 return
304 }
305 if !recorded[ref] {
306 a.notFound(w, r)
307 return
308 }
309 h, view, err := a.openDeck(r.Context(), d)
310 if err != nil {
311 a.fail(w, r, "open a deck to serve a font", err)
312 return
313 }
314 defer h.Close(r.Context())
315 if !listsFont(view.Meta.FontFiles, ref) && (yours == nil || !yours(ref)) {
316 a.notFound(w, r)
317 return
318 }
319 a.streamFont(w, r, ref)
320}
321
322// streamFont writes the font file ref from the store, with typeface's
323// headers, once a caller has said who may have it (serveFont for a deck,
324// libraryFile for its owner). The ref must already match fontRefPattern.
325func (a *app) streamFont(w http.ResponseWriter, r *http.Request, ref string) {
326 store := a.cfg.Blobs
327 rc, err := store.Get(r.Context(), fontObjectKey(ref))
328 if err != nil {
329 if errors.Is(err, blobs.ErrNotFound) {
330 a.notFound(w, r)
331 return
332 }
333 a.fail(w, r, "read a font", err)
334 return
335 }
336 defer rc.Close()
337 // The media type is read off the bytes, not off the deck's list,
338 // which anyone who can edit the deck can write.
339 head := make([]byte, 4)
340 if _, err := io.ReadFull(rc, head); err != nil {
341 a.notFound(w, r)
342 return
343 }
344 format, ok := fontFormatOf(head)
345 if !ok {
346 a.notFound(w, r)
347 return
348 }
349 typeface.Headers(w, format)
350 // The ref is the file's hash: an honest strong validator.
351 w.Header().Set("ETag", `"`+ref+`"`)
352 if match := r.Header.Get("If-None-Match"); match != "" && strings.Contains(match, `"`+ref+`"`) {
353 w.WriteHeader(http.StatusNotModified)
354 return
355 }
356 w.Write(head)
357 io.Copy(w, io.LimitReader(rc, maxFontFileBytes-int64(len(head))))
358}
359
360// deckFontRefs is every ref a deck recorded (DeckFont).
361func (a *app) deckFontRefs(ctx context.Context, deckID int64) (map[string]bool, error) {
362 var refs []string
363 if err := a.db.G.WithContext(ctx).Model(&DeckFont{}).
364 Where("deck_id = ?", deckID).Pluck("ref", &refs).Error; err != nil {
365 return nil, err
366 }
367 out := make(map[string]bool, len(refs))
368 for _, ref := range refs {
369 out[ref] = true
370 }
371 return out, nil
372}
373
374// listsFont reports whether a deck's meta.fontFiles names ref.
375func listsFont(families []deck.FontFamily, ref string) bool {
376 for _, fam := range families {
377 for _, face := range fam.Faces {
378 if face.Ref == ref {
379 return true
380 }
381 }
382 }
383 return false
384}
385
386// fontFormatOf is a font file's container by its first four bytes, the
387// signatures typeface.Inspect reads (the file was inspected whole when
388// it was uploaded).
389func fontFormatOf(head []byte) (typeface.Format, bool) {
390 if len(head) < 4 {
391 return "", false
392 }
393 switch binary.BigEndian.Uint32(head) {
394 case 0x00010000, 0x74727565: // TrueType, 'true'
395 return typeface.TTF, true
396 case 0x4F54544F: // 'OTTO'
397 return typeface.OTF, true
398 case 0x774F4646: // 'wOFF'
399 return typeface.WOFF, true
400 case 0x774F4632: // 'wOF2'
401 return typeface.WOFF2, true
402 }
403 return "", false
404}
405