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// library.go is a person's own fonts: the page where they upload font
4// files, see what they have, and delete a family. A deck uses one of
5// these fonts by recording it and listing its ref (deckfonts.go,
6// meta.fontFiles); this file only keeps the library itself.
7//
8// The bytes live in the object store (Config.Blobs), content-addressed;
9// the database holds one LibraryFont row per face. A deployment with no
10// store has no library: the page says so and the upload answers 503.
11
12import (
13 "context"
14 "encoding/json"
15 "errors"
16 "fmt"
17 "html/template"
18 "io"
19 "mime"
20 "mime/multipart"
21 "net/http"
22 "net/url"
23 "sort"
24 "strings"
25
26 "github.com/go-chi/chi/v5"
27 "gorm.io/gorm"
28
29 "amadan.net/oficina/estilo.git/typeface"
30 "amadan.net/oficina/slides/internal/slides/fonts"
31 "amadan.net/rastrillo/rastrillo"
32)
33
34// maxFontUploadFiles bounds one request: this many files of the largest
35// size, plus a little for the multipart framing.
36const maxFontUploadFiles = 16
37
38// cssFamilyName is a family name as a stylesheet may carry it, by
39// deck.FontCSSName, the one pattern the document and layout take too:
40// the name with every other character removed, and anything before its
41// first letter or digit. A name with nothing left is "Uploaded font N",
42// n being how many families the person already has plus one. It is an
43// identifier, never shown as copy; the page shows Family.
44func cssFamilyName(family string, n int) string {
45 var b strings.Builder
46 for _, r := range family {
47 switch {
48 case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9',
49 r == ' ', r == '.', r == '_', r == '-':
50 b.WriteRune(r)
51 }
52 }
53 // deck.FontCSSName's first character is a letter or digit.
54 out := strings.TrimLeft(strings.Join(strings.Fields(b.String()), " "), " ._-")
55 if len(out) > 100 {
56 out = strings.TrimSpace(out[:100])
57 }
58 if out == "" {
59 return fmt.Sprintf("Uploaded font %d", n)
60 }
61 return out
62}
63
64// reservedFontName reports whether css is a name a deck's stylesheet
65// already means something by, compared as a browser compares family
66// names (without regard to case): a catalog family's, which an upload
67// would join in document.fonts (an upload called "Liberation Serif"
68// beside the built-in Serif faces), or a CSS generic family keyword,
69// which a stack would read as the generic rather than the upload.
70func reservedFontName(css string) bool {
71 for _, f := range fonts.Families() {
72 if strings.EqualFold(css, f.CSSName()) {
73 return true
74 }
75 }
76 switch strings.ToLower(css) {
77 case "serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui", "ui-serif",
78 "ui-sans-serif", "ui-monospace", "ui-rounded", "math", "emoji", "fangsong":
79 return true
80 }
81 return false
82}
83
84// --- the page ---
85
86type fontFamilyRow struct {
87 // Sample numbers the family's sample: its name, set in the family
88 // (fontsPage.SampleCSS).
89 Sample int
90 Name string
91 Styles string
92 StyleNames string
93 NoPictures string
94 DeleteHref string
95 DeleteLabel string
96 DeleteAria string
97}
98
99type fontsPage struct {
100 shell
101 Title string
102 Intro string
103 Rights string
104 Available bool
105 Unavailable string
106 Action string
107 Label string
108 Hint string
109 Submit string
110 Empty string
111 Added string
112 Refused []string
113 Families []fontFamilyRow
114 // SampleCSS declares each family's sample face, loaded from the
115 // library route its owner alone can read (libraryFile), and sets each
116 // sample in it. Built from generated names, hex refs and fixed
117 // formats only.
118 SampleCSS template.CSS
119}
120
121func (a *app) fontsPageFor(w http.ResponseWriter, r *http.Request, u User, status int, added int, refused []string) {
122 var rows []LibraryFont
123 if err := a.db.G.WithContext(r.Context()).Where("owner = ?", actorFor(u)).
124 Order("family, weight, italic, id").Find(&rows).Error; err != nil {
125 a.fail(w, r, "list fonts", err)
126 return
127 }
128 title := rastrillo.T(r, "slides.fonts.title")
129 page := fontsPage{
130 shell: a.shellFor(r, u, frame{parts: []string{title}, ret: "/fonts"}),
131 Title: title,
132 Intro: rastrillo.T(r, "slides.fonts.intro"),
133 Rights: rastrillo.T(r, "slides.fonts.rights"),
134 Available: a.cfg.Blobs != nil,
135 Unavailable: rastrillo.T(r, "slides.fonts.unavailable"),
136 Action: "/fonts",
137 Label: rastrillo.T(r, "slides.fonts.upload.label"),
138 Hint: rastrillo.T(r, "slides.fonts.upload.hint"),
139 Submit: rastrillo.T(r, "slides.fonts.upload.submit"),
140 Empty: rastrillo.T(r, "slides.fonts.empty"),
141 Refused: refused,
142 }
143 switch {
144 case added == 1:
145 page.Added = rastrillo.T(r, "slides.fonts.uploaded.one")
146 case added > 1:
147 page.Added = rastrillo.Tf(r, "slides.fonts.uploaded", "n", added)
148 }
149
150 // Rows come ordered by family; fold neighbours that share a CSS name.
151 byName := map[string]*fontFamilyRow{}
152 faces := map[string][]LibraryFont{}
153 var names []string
154 count := map[string]int{}
155 styles := map[string][]string{}
156 pictures := map[string]bool{}
157 for _, f := range rows {
158 if _, ok := byName[f.CSSName]; !ok {
159 byName[f.CSSName] = &fontFamilyRow{Name: f.Family}
160 names = append(names, f.CSSName)
161 pictures[f.CSSName] = true
162 }
163 count[f.CSSName]++
164 faces[f.CSSName] = append(faces[f.CSSName], f)
165 styles[f.CSSName] = append(styles[f.CSSName], f.Style)
166 if !f.Pictures {
167 pictures[f.CSSName] = false
168 }
169 }
170 sort.SliceStable(names, func(i, j int) bool {
171 return strings.ToLower(byName[names[i]].Name) < strings.ToLower(byName[names[j]].Name)
172 })
173 var sample strings.Builder
174 for i, css := range names {
175 row := byName[css]
176 row.Sample = i + 1
177 face := sampleFace(faces[css])
178 // font-display: block, so a sample is never drawn in the page's
179 // own face first and then swapped in its own.
180 fmt.Fprintf(&sample, "@font-face{font-family:'slides-sample-%d';src:url(/fonts/files/%s) format('%s');font-display:block}"+
181 "[slides-font-sample=\"%d\"]{font-family:'slides-sample-%d',system-ui,sans-serif}\n",
182 row.Sample, face.Ref, sampleFormats[face.Format], row.Sample, row.Sample)
183 if count[css] == 1 {
184 row.Styles = rastrillo.T(r, "slides.fonts.styles.one")
185 } else {
186 row.Styles = rastrillo.Tf(r, "slides.fonts.styles", "n", count[css])
187 }
188 row.StyleNames = strings.Join(styles[css], ", ")
189 if !pictures[css] {
190 row.NoPictures = rastrillo.T(r, "slides.fonts.pictures.no")
191 }
192 row.DeleteHref = "/fonts/delete?family=" + url.QueryEscape(css)
193 row.DeleteLabel = rastrillo.T(r, "slides.fonts.delete")
194 row.DeleteAria = row.DeleteLabel + " " + row.Name
195 page.Families = append(page.Families, *row)
196 }
197 page.SampleCSS = template.CSS(sample.String())
198 if status != http.StatusOK {
199 w.WriteHeader(status)
200 }
201 render(w, "fonts", page)
202}
203
204// fonts serves GET /fonts: the page, or, asked for JSON, the person's
205// families as Deck settings offers them ([{value, label}], deckfonts.go's
206// yourFonts), which the editor asks for again when its window has focus
207// again (fixtures/deck-fonts.mjs's refreshYourFonts).
208func (a *app) fonts(w http.ResponseWriter, r *http.Request) {
209 u, ok := a.viewer(w, r)
210 if !ok {
211 return
212 }
213 w.Header().Add("Vary", "Accept")
214 if strings.Contains(r.Header.Get("Accept"), "application/json") {
215 yours, err := a.yourFonts(r.Context(), u)
216 if err != nil {
217 a.fail(w, r, "list fonts", err)
218 return
219 }
220 type family struct {
221 Value string `json:"value"`
222 Label string `json:"label"`
223 }
224 out := make([]family, 0, len(yours))
225 for _, f := range yours {
226 out = append(out, family{f.Value, f.Label})
227 }
228 w.Header().Set("Content-Type", "application/json")
229 w.Header().Set("Cache-Control", "no-store")
230 json.NewEncoder(w).Encode(out)
231 return
232 }
233 a.fontsPageFor(w, r, u, http.StatusOK, 0, nil)
234}
235
236// libraryFile serves GET /fonts/files/{ref}: a file of the signed-in
237// person's own library, to them alone, for the page's samples. Anyone
238// else, and any ref that is not theirs, is the 404 of a file that does
239// not exist.
240func (a *app) libraryFile(w http.ResponseWriter, r *http.Request) {
241 u, ok := a.viewer(w, r)
242 if !ok {
243 return
244 }
245 ref := chi.URLParam(r, "ref")
246 if !fontRefPattern.MatchString(ref) || a.cfg.Blobs == nil {
247 a.notFound(w, r)
248 return
249 }
250 var n int64
251 if err := a.db.G.WithContext(r.Context()).Model(&LibraryFont{}).
252 Where("owner = ? AND ref = ?", actorFor(u), ref).Count(&n).Error; err != nil {
253 a.fail(w, r, "look up a library font", err)
254 return
255 }
256 if n == 0 {
257 a.notFound(w, r)
258 return
259 }
260 a.streamFont(w, r, ref)
261}
262
263// sampleFace is the face a family's sample is set in: upright before
264// italic, then the one nearest 400.
265func sampleFace(rows []LibraryFont) LibraryFont {
266 best := rows[0]
267 score := func(f LibraryFont) int {
268 d := 0
269 switch {
270 case f.WeightMax < 400:
271 d = 400 - f.WeightMax
272 case f.WeightMin > 400:
273 d = f.WeightMin - 400
274 }
275 if f.Italic {
276 d += 10000
277 }
278 return d
279 }
280 for _, f := range rows[1:] {
281 if score(f) < score(best) {
282 best = f
283 }
284 }
285 return best
286}
287
288// sampleFormats is a stored format as CSS format().
289var sampleFormats = map[string]string{"ttf": "truetype", "otf": "opentype", "woff": "woff", "woff2": "woff2"}
290
291// --- POST /fonts ---
292
293// uploadFonts takes one or more files in the multipart field "file".
294// Each is read with a hard limit, inspected, checked against the
295// person's limits and stored on its own; a refusal is listed under the
296// form and never stops the files beside it. 200 if anything was added,
297// 422 if there were refusals and nothing was.
298func (a *app) uploadFonts(w http.ResponseWriter, r *http.Request) {
299 u, ok := a.viewer(w, r)
300 if !ok {
301 return
302 }
303 store := a.cfg.Blobs
304 if store == nil {
305 a.fontsPageFor(w, r, u, http.StatusServiceUnavailable, 0, nil)
306 return
307 }
308 r.Body = http.MaxBytesReader(w, r.Body, maxFontUploadFiles*typeface.MaxBytes+(1<<20))
309 mt, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
310 if err != nil || !strings.HasPrefix(mt, "multipart/") || params["boundary"] == "" {
311 a.fontsPageFor(w, r, u, http.StatusUnprocessableEntity, 0, nil)
312 return
313 }
314 mr := multipart.NewReader(r.Body, params["boundary"])
315
316 var added int
317 var refused []string
318 for {
319 part, err := mr.NextPart()
320 if err == io.EOF { // exactly: a truncated stream wraps EOF and is not the end
321 break
322 }
323 if err != nil {
324 var tooBig *http.MaxBytesError
325 if errors.As(err, &tooBig) {
326 refused = append(refused, rastrillo.Tf(r, "slides.fonts.refused.big", "name", "…"))
327 break
328 }
329 // A stream that cannot be parsed: what was added stays, and
330 // the page says the generic "that didn't work"; with nothing
331 // added it is a 400.
332 a.logger.Info("slides: a font upload would not parse", "err", err)
333 if added == 0 && len(refused) == 0 {
334 a.errorPage(w, r, http.StatusBadRequest, kindStatus, "")
335 return
336 }
337 refused = append(refused, rastrillo.T(r, "slides.error.422.heading"))
338 break
339 }
340 if part.FormName() != "file" || part.FileName() == "" {
341 continue
342 }
343 name := part.FileName()
344 raw, err := io.ReadAll(io.LimitReader(part, typeface.MaxBytes+1))
345 if err != nil {
346 var tooBig *http.MaxBytesError
347 if errors.As(err, &tooBig) {
348 refused = append(refused, rastrillo.Tf(r, "slides.fonts.refused.big", "name", name))
349 break
350 }
351 refused = append(refused, rastrillo.Tf(r, "slides.fonts.refused.broken", "name", name))
352 continue
353 }
354 msg, err := a.addFont(r, u, name, raw)
355 if err != nil {
356 a.fail(w, r, "store a font", err)
357 return
358 }
359 if msg != "" {
360 refused = append(refused, msg)
361 continue
362 }
363 added++
364 }
365 status := http.StatusOK
366 if added == 0 {
367 status = http.StatusUnprocessableEntity
368 }
369 a.fontsPageFor(w, r, u, status, added, refused)
370}
371
372// addFont inspects, checks and stores one file. It answers the
373// refusal's text, or "" when the file was added; an error is a failure
374// of ours (the store, the database), not a refusal.
375func (a *app) addFont(r *http.Request, u User, name string, raw []byte) (string, error) {
376 ctx := r.Context()
377 face, err := typeface.Inspect(raw)
378 switch {
379 case errors.Is(err, typeface.ErrTooBig):
380 return rastrillo.Tf(r, "slides.fonts.refused.big", "name", name), nil
381 case errors.Is(err, typeface.ErrNotAFont):
382 return rastrillo.Tf(r, "slides.fonts.refused.notfont", "name", name), nil
383 case err != nil:
384 return rastrillo.Tf(r, "slides.fonts.refused.broken", "name", name), nil
385 }
386 owner := actorFor(u)
387
388 // One upload or delete at a time: the quota check, the CSS-name
389 // choice, the object write and the row insert are one step, and a
390 // deletion's reference count and object delete are one step, so
391 // neither can slip between the other's halves. The app is one
392 // process with one writer; a mutex says that without holding the
393 // database's only write connection across a store that may itself
394 // write there. Every byte of the file was read and inspected above:
395 // only the checks, the allocation, Put and the insert run locked.
396 a.traceFont("queued")
397 a.fontMu.Lock()
398 defer a.fontMu.Unlock()
399
400 var mine []LibraryFont
401 if err := a.db.G.WithContext(ctx).Where("owner = ?", owner).Find(&mine).Error; err != nil {
402 return "", err
403 }
404 families := map[string]string{} // CSS name by Family
405 cssTaken := map[string]bool{}
406 inFamily := 0
407 for _, f := range mine {
408 if f.Ref == face.Ref {
409 return rastrillo.Tf(r, "slides.fonts.refused.duplicate", "name", name), nil
410 }
411 families[f.Family] = f.CSSName
412 cssTaken[f.CSSName] = true
413 if f.Family == face.Family {
414 inFamily++
415 }
416 }
417 css, known := families[face.Family]
418 if known && inFamily >= typeface.MaxFacesPerFamily {
419 return rastrillo.Tf(r, "slides.fonts.refused.faces", "family", face.Family), nil
420 }
421 if !known {
422 if len(families) >= typeface.MaxFamilies {
423 return rastrillo.T(r, "slides.fonts.refused.families"), nil
424 }
425 css = cssFamilyName(face.Family, len(families)+1)
426 for n := len(families) + 2; cssTaken[css] || reservedFontName(css); n++ {
427 // Two families that clean to one name must not share it:
428 // the name is what a delete is asked for by. Nor may one
429 // take a name a stylesheet already means something by.
430 css = fmt.Sprintf("%s %d", cssFamilyName(face.Family, len(families)+1), n)
431 }
432 }
433
434 a.traceFont("checked")
435 stored, err := a.cfg.Blobs.Put(ctx, strings.NewReader(string(raw)), face.ContentType())
436 if err != nil {
437 return "", fmt.Errorf("put font: %w", err)
438 }
439 if stored.Hash != face.Ref {
440 return "", fmt.Errorf("the store keyed a font %s, typeface says %s", stored.Hash, face.Ref)
441 }
442 a.traceFont("stored")
443 row := LibraryFont{
444 Owner: owner, Family: face.Family, CSSName: css, Ref: face.Ref,
445 Format: string(face.Format), Outline: string(face.Outline), Style: face.Style,
446 Weight: face.Weight, WeightMin: face.WeightMin, WeightMax: face.WeightMax,
447 Italic: face.Italic, Variable: face.Variable, Pictures: face.Pictures(),
448 Size: int64(len(raw)),
449 }
450 if err := a.db.G.WithContext(ctx).Create(&row).Error; err != nil {
451 // A concurrent upload of the same file lands here on the unique
452 // index; the object is the other row's too, so it stays.
453 var n int64
454 if a.db.G.WithContext(ctx).Model(&LibraryFont{}).
455 Where("owner = ? AND ref = ?", owner, face.Ref).Count(&n); n > 0 {
456 return rastrillo.Tf(r, "slides.fonts.refused.duplicate", "name", name), nil
457 }
458 a.dropFontObject(ctx, face.Ref)
459 return "", err
460 }
461 return "", nil
462}
463
464// dropFontObject deletes a font's object unless some library row (any
465// owner) or some deck (a DeckFont row, deckfonts.go) still names it: a
466// deck that took a family keeps it after the library lets it go. The
467// caller holds fontMu.
468func (a *app) dropFontObject(ctx context.Context, ref string) {
469 if a.cfg.Blobs == nil {
470 return
471 }
472 for _, model := range []any{&LibraryFont{}, &DeckFont{}} {
473 var n int64
474 if err := a.db.G.WithContext(ctx).Model(model).Where("ref = ?", ref).Count(&n).Error; err != nil {
475 // Unknown is not zero: keep the object. A later upload of
476 // the same font finds it already there.
477 a.logger.Error("slides: count a font's references", "ref", ref, "err", err)
478 return
479 }
480 if n > 0 {
481 return
482 }
483 }
484 if err := a.cfg.Blobs.Delete(ctx, fontObjectKey(ref)); err != nil {
485 a.logger.Warn("slides: delete a font object", "ref", ref, "err", err)
486 }
487}
488
489// --- GET/POST /fonts/delete ---
490
491type fontDeletePage struct {
492 shell
493 Title string
494 Body string
495 Action string
496 Hidden [][2]string
497 Label string
498 CancelHref string
499 CancelLabel string
500 BackHref string
501 BackLabel string
502}
503
504// ownFontFamily is the person's rows for one CSS family name.
505func (a *app) ownFontFamily(ctx context.Context, u User, css string) ([]LibraryFont, error) {
506 var rows []LibraryFont
507 if css == "" {
508 return nil, nil
509 }
510 err := a.db.G.WithContext(ctx).Where("owner = ? AND css_name = ?", actorFor(u), css).Find(&rows).Error
511 return rows, err
512}
513
514// confirmDeleteFont serves GET /fonts/delete?family=: the question on
515// its own page; the GET changes nothing.
516func (a *app) confirmDeleteFont(w http.ResponseWriter, r *http.Request) {
517 u, ok := a.viewer(w, r)
518 if !ok {
519 return
520 }
521 rows, err := a.ownFontFamily(r.Context(), u, r.URL.Query().Get("family"))
522 if err != nil {
523 a.fail(w, r, "read a font family", err)
524 return
525 }
526 if len(rows) == 0 {
527 a.notFound(w, r)
528 return
529 }
530 title := rastrillo.Tf(r, "slides.fonts.delete.title", "family", rows[0].Family)
531 render(w, "fonts_confirm", fontDeletePage{
532 shell: a.shellFor(r, u, frame{parts: []string{title}, ret: "/fonts"}),
533 Title: title,
534 Body: rastrillo.T(r, "slides.fonts.delete.body"),
535 Action: "/fonts/delete",
536 Hidden: [][2]string{{"family", rows[0].CSSName}},
537 Label: rastrillo.T(r, "slides.fonts.delete.submit"),
538 CancelHref: "/fonts",
539 CancelLabel: rastrillo.T(r, "slides.cancel"),
540 BackHref: "/fonts",
541 BackLabel: rastrillo.T(r, "slides.fonts.title"),
542 })
543}
544
545// deleteFont serves POST /fonts/delete. The person's rows for the
546// family go in one transaction; an object goes only when no other row,
547// anyone's, and no deck still names it.
548func (a *app) deleteFont(w http.ResponseWriter, r *http.Request) {
549 u, ok := a.viewer(w, r)
550 if !ok {
551 return
552 }
553 // The body is read before the lock is taken: a stalled request must
554 // not hold up every other person's fonts.
555 family := r.FormValue("family")
556 a.traceFont("delete")
557 a.fontMu.Lock()
558 defer a.fontMu.Unlock()
559 rows, err := a.ownFontFamily(r.Context(), u, family)
560 if err != nil {
561 a.fail(w, r, "read a font family", err)
562 return
563 }
564 if len(rows) == 0 {
565 a.notFound(w, r)
566 return
567 }
568 ids := make([]uint, len(rows))
569 for i, f := range rows {
570 ids[i] = f.ID
571 }
572 if err := a.db.G.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error {
573 return tx.Where("id IN ?", ids).Delete(&LibraryFont{}).Error
574 }); err != nil {
575 a.fail(w, r, "delete a font family", err)
576 return
577 }
578 for _, f := range rows {
579 a.dropFontObject(r.Context(), f.Ref)
580 }
581 http.Redirect(w, r, "/fonts", http.StatusSeeOther)
582}
583
584// traceFont tells a test which step an upload or delete has reached; nil
585// in production.
586func (a *app) traceFont(stage string) {
587 if a.fontTrace != nil {
588 a.fontTrace(stage)
589 }
590}
591
592// SetFontTrace is the test seam for ordering two font requests against
593// each other without a clock: f is called at "queued" (an upload, just
594// before it takes the lock), "checked" and "stored" (inside its critical
595// section), "delete" (a deletion, just before it takes the lock) and
596// "pick" (POST /d/{sqid}/fonts, its deck found, just before the lock).
597func (a *app) SetFontTrace(f func(stage string)) { a.fontTrace = f }
598