oficina / slides Public

Fonts: a library of your own fonts

A Fonts page (GET/POST /fonts, with its own delete confirm page) where a
person uploads font files, sees their families and deletes one. Each file
is inspected with estilo's typeface package, stored with Blobs.Put (a hash
that differs from Face.Ref is an error) and recorded as a LibraryFont row,
unique per (owner, ref). Refusals are listed per file; limits are 16 faces
per family and 32 families. An object is deleted only when no row of any
owner still names it. Without a store the page says so and POST is 503.

go.mod replaces estilo with the typeface worktree (plan F1); the credits
inventory gains brotli.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b9d80a1cab37ad5531c22d34894160c2f8237301 parent c35c120
14 files changed, +899 −3
  • go.mod +3 −0
  • go.sum +4 −2
  • internal/slides/app.go +6 −0
  • internal/slides/chrome.go +2 −1
  • internal/slides/credits/notices.json +11 −0
  • internal/slides/library.go +416 −0
  • internal/slides/locales/en.toml +27 −0
  • internal/slides/migrations/0011_create_library_fonts.sql +6 −0
  • internal/slides/migrations/schema.sql +6 −0
  • internal/slides/models.go +33 −0
  • internal/slides/render.go +2 −0
  • internal/slides/templates/fonts.html +57 −0
  • internal/slides/templates/fonts_confirm.html +12 −0
  • internal/slidestest/library_test.go +314 −0
diff --git a/go.mod b/go.mod
index bd825d0..f190c29 100644
--- a/go.mod
+++ b/go.mod
@@ -30,6 +30,7 @@ require (
require (
amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect
github.com/BurntSushi/toml v1.6.0 // indirect
+ github.com/andybalholm/brotli v1.2.7 // indirect
github.com/carlosframework/rastrillo v0.23.0 // indirect
github.com/danieljoos/wincred v1.2.3 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
@@ -76,3 +77,5 @@ tool (
// time. Deleting this line breaks the gate, not the app.
amadan.net/rastrillo/rastrillo/cmd/rastrillo
)
+
+replace amadan.net/oficina/estilo.git => ../estilo-typeface
diff --git a/go.sum b/go.sum
index 3105c07..a67dc3d 100644
--- a/go.sum
+++ b/go.sum
@@ -1,7 +1,5 @@
amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000 h1:L07nc+dmLI7c1PBkSkbnrjOK5f8p6OBbA/yTxznxCAw=
amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA=
-amadan.net/oficina/estilo.git v0.0.0-20261122204240-6238a478888e h1:g2EvXlQAleAEFsc4yIBvS7ycMG3GyuEySEOia0yo8nY=
-amadan.net/oficina/estilo.git v0.0.0-20261122204240-6238a478888e/go.mod h1:2UFIFrbTrhew8EFM0C94WmTo2OASM2pHEgT4jzeE/s8=
amadan.net/oficina/home/connect v0.0.0-20261121235253-98726fac99a7 h1:hytRIC++gbCt0rLcNn2O+EcPKkBdnfEodINDo8gT6jw=
amadan.net/oficina/home/connect v0.0.0-20261121235253-98726fac99a7/go.mod h1:B45bHBZF5AtFJqy4d1qSDNDOqYcNkSz1qD20TLF1DI8=
amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 h1:AFDuOio0MxNxN9ZWVc3lul1QHkNjNUCO56kXpe/Fw3I=
@@ -20,6 +18,8 @@ amadan.net/rastrillo/rastrillo/money v0.1.0 h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonaj
amadan.net/rastrillo/rastrillo/money v0.1.0/go.mod h1:cmgkjBEIQh1pFSYvQk0UU6oPYS8kSDypdT9+t4Flx0U=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
+github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A=
+github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/carlosframework/rastrillo v0.23.0 h1:tKAAlwPt4Pg/rkqk7o6jvV12bbZ0r34oEVpuOlKfX7w=
github.com/carlosframework/rastrillo v0.23.0/go.mod h1:pZlrE5F5OhspvZFzef0DrfjHAjA8FXycb9J5/8vc8Tw=
github.com/chromedp/cdproto v0.158.6 h1:jaKiXWuhcxbvKbSe8U6Dp5U4Hcj2w6lETYgZqBD5n34=
@@ -94,6 +94,8 @@ github.com/tdewolff/test v1.0.12 h1:7F21DqIajswxuche0geHdrUZRCWE4oko4b7bcmkkrxk=
github.com/tdewolff/test v1.0.12/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8=
github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU=
github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0=
+github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
+github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs=
diff --git a/internal/slides/app.go b/internal/slides/app.go
index 2f3994c..f60347f 100644
--- a/internal/slides/app.go
+++ b/internal/slides/app.go
@@ -278,6 +278,12 @@ func New(d *db.DB, cfg Config) (*http.ServeMux, *app, error) {
r.Get("/agents", a.agents)
r.Post("/agents", a.createAgent)
r.Post("/agents/{id}/revoke", a.revokeAgent)
+ // A person's own fonts (library.go). Deleting gets its own page,
+ // like a deck's.
+ r.Get("/fonts", a.fonts)
+ r.Post("/fonts", a.uploadFonts)
+ r.Get("/fonts/delete", a.confirmDeleteFont)
+ r.Post("/fonts/delete", a.deleteFont)
})
mux := http.NewServeMux()
diff --git a/internal/slides/chrome.go b/internal/slides/chrome.go
index b2cb4eb..72b42f0 100644
--- a/internal/slides/chrome.go
+++ b/internal/slides/chrome.go
@@ -258,7 +258,8 @@ func (a *app) account(r *http.Request, v viewerState, ret string) *chrome.Accoun
}
// Agents (agents.go): the tokens that let a program drive this
// person's decks. A page, so a link and no ellipsis.
- acc.Items = []estilomenu.Item{{Href: "/agents", Label: rastrillo.T(r, "slides.account.agents")}}
+ acc.Items = []estilomenu.Item{{Href: "/agents", Label: rastrillo.T(r, "slides.account.agents")},
+ {Href: "/fonts", Label: rastrillo.T(r, "slides.account.fonts")}}
if a.offersHomeLink(r, v) {
acc.Items = append(acc.Items, estilomenu.Item{Href: "/account/home", Label: rastrillo.T(r, "slides.home.menu_action")})
}
diff --git a/internal/slides/credits/notices.json b/internal/slides/credits/notices.json
index ff08d92..6244826 100644
--- a/internal/slides/credits/notices.json
+++ b/internal/slides/credits/notices.json
@@ -605,6 +605,17 @@
}
]
},
+ {
+ "Name": "github.com/andybalholm/brotli",
+ "Version": "v1.2.7",
+ "SourceURL": "https://pkg.go.dev/github.com/andybalholm/brotli@v1.2.7",
+ "Notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
+ }
+ ]
+ },
{
"Name": "github.com/carlosframework/rastrillo",
"Version": "v0.23.0",
diff --git a/internal/slides/library.go b/internal/slides/library.go
new file mode 100644
index 0000000..14b6dc9
--- /dev/null
+++ b/internal/slides/library.go
@@ -0,0 +1,416 @@
+package slides
+
+// library.go is a person's own fonts: the page where they upload font
+// files, see what they have, and delete a family. A deck uses one of
+// these fonts by listing its ref (meta.fontFiles, fontstore.go); this
+// file only keeps the library itself.
+//
+// The bytes live in the object store (Config.Blobs), content-addressed;
+// the database holds one LibraryFont row per face. A deployment with no
+// store has no library: the page says so and the upload answers 503.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "mime"
+ "mime/multipart"
+ "net/http"
+ "net/url"
+ "sort"
+ "strings"
+
+ "gorm.io/gorm"
+
+ "amadan.net/oficina/estilo.git/typeface"
+ "amadan.net/rastrillo/rastrillo"
+)
+
+// maxFontUploadFiles bounds one request: this many files of the largest
+// size, plus a little for the multipart framing.
+const maxFontUploadFiles = 16
+
+// cssFamilyName is a family name as a stylesheet may carry it: the name
+// with every character render's fontPattern would refuse removed, and
+// the two that would split or quote a font-family list (comma and
+// apostrophe) too. A name with nothing left is "Uploaded font N", n
+// being how many families the person already has plus one. It is an
+// identifier, never shown as copy; the page shows Family.
+func cssFamilyName(family string, n int) string {
+ var b strings.Builder
+ for _, r := range family {
+ switch {
+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9',
+ r == ' ', r == '.', r == '_', r == '-':
+ b.WriteRune(r)
+ }
+ }
+ out := strings.Join(strings.Fields(b.String()), " ")
+ if len(out) > 100 {
+ out = strings.TrimSpace(out[:100])
+ }
+ if out == "" {
+ return fmt.Sprintf("Uploaded font %d", n)
+ }
+ return out
+}
+
+// --- the page ---
+
+type fontFamilyRow struct {
+ Name string
+ Styles string
+ StyleNames string
+ NoPictures string
+ DeleteHref string
+ DeleteLabel string
+ DeleteAria string
+}
+
+type fontsPage struct {
+ shell
+ Title string
+ Intro string
+ Rights string
+ Available bool
+ Unavailable string
+ Action string
+ Label string
+ Hint string
+ Submit string
+ Empty string
+ Added string
+ Refused []string
+ Families []fontFamilyRow
+}
+
+func (a *app) fontsPageFor(w http.ResponseWriter, r *http.Request, u User, status int, added int, refused []string) {
+ var rows []LibraryFont
+ if err := a.db.G.WithContext(r.Context()).Where("owner = ?", actorFor(u)).
+ Order("family, weight, italic, id").Find(&rows).Error; err != nil {
+ a.fail(w, r, "list fonts", err)
+ return
+ }
+ title := rastrillo.T(r, "slides.fonts.title")
+ page := fontsPage{
+ shell: a.shellFor(r, u, frame{parts: []string{title}, ret: "/fonts"}),
+ Title: title,
+ Intro: rastrillo.T(r, "slides.fonts.intro"),
+ Rights: rastrillo.T(r, "slides.fonts.rights"),
+ Available: a.cfg.Blobs != nil,
+ Unavailable: rastrillo.T(r, "slides.fonts.unavailable"),
+ Action: "/fonts",
+ Label: rastrillo.T(r, "slides.fonts.upload.label"),
+ Hint: rastrillo.T(r, "slides.fonts.upload.hint"),
+ Submit: rastrillo.T(r, "slides.fonts.upload.submit"),
+ Empty: rastrillo.T(r, "slides.fonts.empty"),
+ Refused: refused,
+ }
+ switch {
+ case added == 1:
+ page.Added = rastrillo.T(r, "slides.fonts.uploaded.one")
+ case added > 1:
+ page.Added = rastrillo.Tf(r, "slides.fonts.uploaded", "n", added)
+ }
+
+ // Rows come ordered by family; fold neighbours that share a CSS name.
+ byName := map[string]*fontFamilyRow{}
+ var names []string
+ count := map[string]int{}
+ styles := map[string][]string{}
+ pictures := map[string]bool{}
+ for _, f := range rows {
+ if _, ok := byName[f.CSSName]; !ok {
+ byName[f.CSSName] = &fontFamilyRow{Name: f.Family}
+ names = append(names, f.CSSName)
+ pictures[f.CSSName] = true
+ }
+ count[f.CSSName]++
+ styles[f.CSSName] = append(styles[f.CSSName], f.Style)
+ if !f.Pictures {
+ pictures[f.CSSName] = false
+ }
+ }
+ sort.SliceStable(names, func(i, j int) bool {
+ return strings.ToLower(byName[names[i]].Name) < strings.ToLower(byName[names[j]].Name)
+ })
+ for _, css := range names {
+ row := byName[css]
+ if count[css] == 1 {
+ row.Styles = rastrillo.T(r, "slides.fonts.styles.one")
+ } else {
+ row.Styles = rastrillo.Tf(r, "slides.fonts.styles", "n", count[css])
+ }
+ row.StyleNames = strings.Join(styles[css], ", ")
+ if !pictures[css] {
+ row.NoPictures = rastrillo.T(r, "slides.fonts.pictures.no")
+ }
+ row.DeleteHref = "/fonts/delete?family=" + url.QueryEscape(css)
+ row.DeleteLabel = rastrillo.T(r, "slides.fonts.delete")
+ row.DeleteAria = row.DeleteLabel + " " + row.Name
+ page.Families = append(page.Families, *row)
+ }
+ if status != http.StatusOK {
+ w.WriteHeader(status)
+ }
+ render(w, "fonts", page)
+}
+
+// fonts serves GET /fonts.
+func (a *app) fonts(w http.ResponseWriter, r *http.Request) {
+ u, ok := a.viewer(w, r)
+ if !ok {
+ return
+ }
+ a.fontsPageFor(w, r, u, http.StatusOK, 0, nil)
+}
+
+// --- POST /fonts ---
+
+// uploadFonts takes one or more files in the multipart field "file".
+// Each is read with a hard limit, inspected, checked against the
+// person's limits and stored on its own; a refusal is listed under the
+// form and never stops the files beside it. 200 if anything was added,
+// 422 if there were refusals and nothing was.
+func (a *app) uploadFonts(w http.ResponseWriter, r *http.Request) {
+ u, ok := a.viewer(w, r)
+ if !ok {
+ return
+ }
+ store := a.cfg.Blobs
+ if store == nil {
+ a.fontsPageFor(w, r, u, http.StatusServiceUnavailable, 0, nil)
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, maxFontUploadFiles*typeface.MaxBytes+(1<<20))
+ mt, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if err != nil || !strings.HasPrefix(mt, "multipart/") || params["boundary"] == "" {
+ a.fontsPageFor(w, r, u, http.StatusUnprocessableEntity, 0, nil)
+ return
+ }
+ mr := multipart.NewReader(r.Body, params["boundary"])
+
+ var added int
+ var refused []string
+ for {
+ part, err := mr.NextPart()
+ if err != nil {
+ var tooBig *http.MaxBytesError
+ if errors.As(err, &tooBig) {
+ refused = append(refused, rastrillo.Tf(r, "slides.fonts.refused.big", "name", "…"))
+ }
+ break
+ }
+ if part.FormName() != "file" || part.FileName() == "" {
+ continue
+ }
+ name := part.FileName()
+ raw, err := io.ReadAll(io.LimitReader(part, typeface.MaxBytes+1))
+ if err != nil {
+ var tooBig *http.MaxBytesError
+ if errors.As(err, &tooBig) {
+ refused = append(refused, rastrillo.Tf(r, "slides.fonts.refused.big", "name", name))
+ break
+ }
+ refused = append(refused, rastrillo.Tf(r, "slides.fonts.refused.broken", "name", name))
+ continue
+ }
+ msg, err := a.addFont(r, u, name, raw)
+ if err != nil {
+ a.fail(w, r, "store a font", err)
+ return
+ }
+ if msg != "" {
+ refused = append(refused, msg)
+ continue
+ }
+ added++
+ }
+ status := http.StatusOK
+ if added == 0 {
+ status = http.StatusUnprocessableEntity
+ }
+ a.fontsPageFor(w, r, u, status, added, refused)
+}
+
+// addFont inspects, checks and stores one file. It answers the
+// refusal's text, or "" when the file was added; an error is a failure
+// of ours (the store, the database), not a refusal.
+func (a *app) addFont(r *http.Request, u User, name string, raw []byte) (string, error) {
+ ctx := r.Context()
+ face, err := typeface.Inspect(raw)
+ switch {
+ case errors.Is(err, typeface.ErrTooBig):
+ return rastrillo.Tf(r, "slides.fonts.refused.big", "name", name), nil
+ case errors.Is(err, typeface.ErrNotAFont):
+ return rastrillo.Tf(r, "slides.fonts.refused.notfont", "name", name), nil
+ case err != nil:
+ return rastrillo.Tf(r, "slides.fonts.refused.broken", "name", name), nil
+ }
+ owner := actorFor(u)
+
+ var mine []LibraryFont
+ if err := a.db.G.WithContext(ctx).Where("owner = ?", owner).Find(&mine).Error; err != nil {
+ return "", err
+ }
+ families := map[string]string{} // CSS name by Family
+ cssTaken := map[string]bool{}
+ inFamily := 0
+ for _, f := range mine {
+ if f.Ref == face.Ref {
+ return rastrillo.Tf(r, "slides.fonts.refused.duplicate", "name", name), nil
+ }
+ families[f.Family] = f.CSSName
+ cssTaken[f.CSSName] = true
+ if f.Family == face.Family {
+ inFamily++
+ }
+ }
+ css, known := families[face.Family]
+ if known && inFamily >= typeface.MaxFacesPerFamily {
+ return rastrillo.Tf(r, "slides.fonts.refused.faces", "family", face.Family), nil
+ }
+ if !known {
+ if len(families) >= typeface.MaxFamilies {
+ return rastrillo.T(r, "slides.fonts.refused.families"), nil
+ }
+ css = cssFamilyName(face.Family, len(families)+1)
+ for n := len(families) + 2; cssTaken[css]; n++ {
+ // Two families that clean to one name must not share it:
+ // the name is what a delete is asked for by.
+ css = fmt.Sprintf("%s %d", cssFamilyName(face.Family, len(families)+1), n)
+ }
+ }
+
+ stored, err := a.cfg.Blobs.Put(ctx, strings.NewReader(string(raw)), face.ContentType())
+ if err != nil {
+ return "", fmt.Errorf("put font: %w", err)
+ }
+ if stored.Hash != face.Ref {
+ return "", fmt.Errorf("the store keyed a font %s, typeface says %s", stored.Hash, face.Ref)
+ }
+ row := LibraryFont{
+ Owner: owner, Family: face.Family, CSSName: css, Ref: face.Ref,
+ Format: string(face.Format), Outline: string(face.Outline), Style: face.Style,
+ Weight: face.Weight, WeightMin: face.WeightMin, WeightMax: face.WeightMax,
+ Italic: face.Italic, Variable: face.Variable, Pictures: face.Pictures(),
+ Size: int64(len(raw)),
+ }
+ if err := a.db.G.WithContext(ctx).Create(&row).Error; err != nil {
+ // A concurrent upload of the same file lands here on the unique
+ // index; the object is the other row's too, so it stays.
+ var n int64
+ if a.db.G.WithContext(ctx).Model(&LibraryFont{}).
+ Where("owner = ? AND ref = ?", owner, face.Ref).Count(&n); n > 0 {
+ return rastrillo.Tf(r, "slides.fonts.refused.duplicate", "name", name), nil
+ }
+ a.dropFontObject(ctx, face.Ref)
+ return "", err
+ }
+ return "", nil
+}
+
+// dropFontObject deletes a font's object unless some library row (any
+// owner) still names it.
+func (a *app) dropFontObject(ctx context.Context, ref string) {
+ if a.cfg.Blobs == nil {
+ return
+ }
+ var n int64
+ if err := a.db.G.WithContext(ctx).Model(&LibraryFont{}).Where("ref = ?", ref).Count(&n).Error; err != nil || n > 0 {
+ return
+ }
+ if err := a.cfg.Blobs.Delete(ctx, fontObjectKey(ref)); err != nil {
+ a.logger.Warn("slides: delete a font object", "ref", ref, "err", err)
+ }
+}
+
+// --- GET/POST /fonts/delete ---
+
+type fontDeletePage struct {
+ shell
+ Title string
+ Body string
+ Action string
+ Hidden [][2]string
+ Label string
+ CancelHref string
+ CancelLabel string
+ BackHref string
+ BackLabel string
+}
+
+// ownFontFamily is the person's rows for one CSS family name.
+func (a *app) ownFontFamily(ctx context.Context, u User, css string) ([]LibraryFont, error) {
+ var rows []LibraryFont
+ if css == "" {
+ return nil, nil
+ }
+ err := a.db.G.WithContext(ctx).Where("owner = ? AND css_name = ?", actorFor(u), css).Find(&rows).Error
+ return rows, err
+}
+
+// confirmDeleteFont serves GET /fonts/delete?family=: the question on
+// its own page; the GET changes nothing.
+func (a *app) confirmDeleteFont(w http.ResponseWriter, r *http.Request) {
+ u, ok := a.viewer(w, r)
+ if !ok {
+ return
+ }
+ rows, err := a.ownFontFamily(r.Context(), u, r.URL.Query().Get("family"))
+ if err != nil {
+ a.fail(w, r, "read a font family", err)
+ return
+ }
+ if len(rows) == 0 {
+ a.notFound(w, r)
+ return
+ }
+ title := rastrillo.Tf(r, "slides.fonts.delete.title", "family", rows[0].Family)
+ render(w, "fonts_confirm", fontDeletePage{
+ shell: a.shellFor(r, u, frame{parts: []string{title}, ret: "/fonts"}),
+ Title: title,
+ Body: rastrillo.T(r, "slides.fonts.delete.body"),
+ Action: "/fonts/delete",
+ Hidden: [][2]string{{"family", rows[0].CSSName}},
+ Label: rastrillo.T(r, "slides.fonts.delete.submit"),
+ CancelHref: "/fonts",
+ CancelLabel: rastrillo.T(r, "slides.cancel"),
+ BackHref: "/fonts",
+ BackLabel: rastrillo.T(r, "slides.fonts.title"),
+ })
+}
+
+// deleteFont serves POST /fonts/delete. The person's rows for the
+// family go in one transaction; an object goes only when no other row,
+// anyone's, still names it.
+func (a *app) deleteFont(w http.ResponseWriter, r *http.Request) {
+ u, ok := a.viewer(w, r)
+ if !ok {
+ return
+ }
+ rows, err := a.ownFontFamily(r.Context(), u, r.FormValue("family"))
+ if err != nil {
+ a.fail(w, r, "read a font family", err)
+ return
+ }
+ if len(rows) == 0 {
+ a.notFound(w, r)
+ return
+ }
+ ids := make([]uint, len(rows))
+ for i, f := range rows {
+ ids[i] = f.ID
+ }
+ if err := a.db.G.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error {
+ return tx.Where("id IN ?", ids).Delete(&LibraryFont{}).Error
+ }); err != nil {
+ a.fail(w, r, "delete a font family", err)
+ return
+ }
+ for _, f := range rows {
+ a.dropFontObject(r.Context(), f.Ref)
+ }
+ http.Redirect(w, r, "/fonts", http.StatusSeeOther)
+}
diff --git a/internal/slides/locales/en.toml b/internal/slides/locales/en.toml
index 60ab41b..3aa67bb 100644
--- a/internal/slides/locales/en.toml
+++ b/internal/slides/locales/en.toml
@@ -873,3 +873,30 @@ slides.home.choose_new_action = "I’m new here — continue with Oficina ID"
slides.credits.title = "Open source"
slides.credits.help = "Help"
slides.credits.missing = "No notice file is included in this release."
+
+# slides.fonts.* — GET/POST /fonts, a person's own font library
+# (library.go). Words approved by Paul's copy review.
+slides.account.fonts = "Fonts"
+slides.fonts.title = "Fonts"
+slides.fonts.intro = "Fonts you upload here can be used in any of your decks. Everyone who can see a deck sees it in its font."
+slides.fonts.rights = "Upload only fonts your licence lets you use on the web."
+slides.fonts.upload.label = "Font files"
+slides.fonts.upload.hint = "TTF, OTF, WOFF or WOFF2, up to 10 MB each."
+slides.fonts.upload.submit = "Upload"
+slides.fonts.empty = "No fonts yet."
+slides.fonts.styles = "{n} styles"
+slides.fonts.styles.one = "1 style"
+slides.fonts.pictures.no = "Slide pictures and PDFs use the deck's next font."
+slides.fonts.delete = "Delete"
+slides.fonts.delete.title = "Delete {family}?"
+slides.fonts.delete.body = "Decks already using it keep it. You won't be able to pick it for new decks."
+slides.fonts.delete.submit = "Delete font"
+slides.fonts.unavailable = "Fonts aren't available here yet."
+slides.fonts.refused.notfont = "{name} isn't a font file."
+slides.fonts.refused.broken = "{name} looks damaged and can't be used."
+slides.fonts.refused.big = "{name} is over 10 MB."
+slides.fonts.refused.faces = "{family} already has 16 styles."
+slides.fonts.refused.families = "You can keep up to 32 font families."
+slides.fonts.refused.duplicate = "{name} is already in your fonts."
+slides.fonts.uploaded = "{n} files added."
+slides.fonts.uploaded.one = "1 file added."
diff --git a/internal/slides/migrations/0011_create_library_fonts.sql b/internal/slides/migrations/0011_create_library_fonts.sql
new file mode 100644
index 0000000..279ed74
--- /dev/null
+++ b/internal/slides/migrations/0011_create_library_fonts.sql
@@ -0,0 +1,6 @@
+CREATE TABLE `library_fonts` (`id` integer PRIMARY KEY AUTOINCREMENT,`owner` text,`family` text,`css_name` text,`ref` text,`format` text,`outline` text,`style` text,`weight` integer,`weight_min` integer,`weight_max` integer,`italic` numeric,`variable` numeric,`pictures` numeric,`size` integer,`created_at` datetime);
+
+CREATE UNIQUE INDEX `idx_library_fonts_owner_ref` ON `library_fonts`(`owner`,`ref`);
+
+CREATE INDEX `idx_library_fonts_owner` ON `library_fonts`(`owner`);
+
diff --git a/internal/slides/migrations/schema.sql b/internal/slides/migrations/schema.sql
index 79db592..e1e765c 100644
--- a/internal/slides/migrations/schema.sql
+++ b/internal/slides/migrations/schema.sql
@@ -15,6 +15,8 @@ CREATE TABLE `deck_updates` (`id` integer PRIMARY KEY AUTOINCREMENT,`deck_id` in
CREATE TABLE `decks` (`id` integer PRIMARY KEY AUTOINCREMENT,`sqid` text,`title` text,`owner_id` integer,`rung` text,`theme` text,`seq` integer,`created_at` datetime,`updated_at` datetime);
+CREATE TABLE `library_fonts` (`id` integer PRIMARY KEY AUTOINCREMENT,`owner` text,`family` text,`css_name` text,`ref` text,`format` text,`outline` text,`style` text,`weight` integer,`weight_min` integer,`weight_max` integer,`italic` numeric,`variable` numeric,`pictures` numeric,`size` integer,`created_at` datetime);
+
CREATE TABLE `presentation_links` (`presentation_id` integer,`link_id` text,`n` integer,`updated_at` datetime);
CREATE TABLE `presentation_presses` (`presentation_id` integer,`press_id` text,`created_at` datetime);
@@ -47,6 +49,10 @@ CREATE INDEX `idx_decks_owner_id` ON `decks`(`owner_id`);
CREATE UNIQUE INDEX `idx_decks_sqid` ON `decks`(`sqid`);
+CREATE INDEX `idx_library_fonts_owner` ON `library_fonts`(`owner`);
+
+CREATE UNIQUE INDEX `idx_library_fonts_owner_ref` ON `library_fonts`(`owner`,`ref`);
+
CREATE UNIQUE INDEX `idx_presentation_links_link` ON `presentation_links`(`presentation_id`,`link_id`);
CREATE UNIQUE INDEX `idx_presentation_presses_press` ON `presentation_presses`(`presentation_id`,`press_id`);
diff --git a/internal/slides/models.go b/internal/slides/models.go
index 2ab7834..1934130 100644
--- a/internal/slides/models.go
+++ b/internal/slides/models.go
@@ -20,6 +20,7 @@ var Models = []any{
&PresentationPress{},
&PresentationLink{},
&Agent{},
+ &LibraryFont{},
}
// User is a person who has signed in here — spec §6.1's
@@ -435,3 +436,35 @@ type Agent struct {
CreatedAt time.Time
RevokedAt *time.Time
}
+
+// LibraryFont is one face a person has uploaded to their own font
+// library (library.go): a row per file, grouped on screen by Family.
+//
+// Owner is the person's actor string (actorFor), the form a deck's
+// history already names them by, and Ref is the typeface package's
+// SHA-256 of the file, which is also the key the bytes live under in
+// the object store. A person cannot hold one file twice; two people
+// holding the same file share one object, which is why deleting a row
+// deletes the object only when no other row names it.
+//
+// CSSName is the family as a font-family name a stylesheet can carry
+// (cssFamilyName), kept apart from Family, which is what the font's own
+// name table says and may hold anything.
+type LibraryFont struct {
+ ID uint
+ Owner string `gorm:"index;uniqueIndex:idx_library_fonts_owner_ref"`
+ Family string
+ CSSName string
+ Ref string `gorm:"uniqueIndex:idx_library_fonts_owner_ref"`
+ Format string
+ Outline string
+ Style string
+ Weight int
+ WeightMin int
+ WeightMax int
+ Italic bool
+ Variable bool
+ Pictures bool
+ Size int64
+ CreatedAt time.Time
+}
diff --git a/internal/slides/render.go b/internal/slides/render.go
index 3e17a2d..b539883 100644
--- a/internal/slides/render.go
+++ b/internal/slides/render.go
@@ -118,6 +118,8 @@ var pageFiles = map[string][]string{
"export_status": nil,
"share": nil,
"agents": nil,
+ "fonts": nil,
+ "fonts_confirm": nil,
// The presenting screens: three share one partial, so the remote
// and the presenter view cannot drift on what a button is called or
// where it posts.
diff --git a/internal/slides/templates/fonts.html b/internal/slides/templates/fonts.html
new file mode 100644
index 0000000..2430b95
--- /dev/null
+++ b/internal/slides/templates/fonts.html
@@ -0,0 +1,57 @@
+{{/* fonts — GET /fonts, a person's own font library.
+
+ A plain form: the file field takes several files, the answer is the
+ page itself with what was added and what was refused, and nothing
+ needs a script. */}}
+{{define "content"}}{{$L := localizer $}}
+{{template "page-header" dict "L" $L "Title" .Title}}
+
+<div rst-box rst-stack>
+ <p>{{.Intro}}</p>
+</div>
+
+{{if .Added}}<div rst-box><p role="status">{{.Added}}</p></div>{{end}}
+{{if .Refused}}
+<div rst-box>
+ <ul role="alert">
+ {{range .Refused}}<li>{{.}}</li>{{end}}
+ </ul>
+</div>
+{{end}}
+
+{{if .Families}}
+<div rst-list>
+ {{range .Families}}
+ <div rst-row>
+ <span rst-row-main>
+ {{.Name}}
+ <small rst-row-sub>{{.Styles}}{{if .StyleNames}}: {{.StyleNames}}{{end}}</small>
+ {{if .NoPictures}}<small rst-row-sub>{{.NoPictures}}</small>{{end}}
+ </span>
+ <a rst-btn="ghost" class="rst-danger" href="{{.DeleteHref}}" aria-label="{{.DeleteAria}}">{{.DeleteLabel}}</a>
+ </div>
+ {{end}}
+</div>
+{{else}}
+<div rst-box>
+ <p>{{.Empty}}</p>
+</div>
+{{end}}
+
+<div rst-box>
+ {{if .Available}}
+ <form method="post" action="{{.Action}}" enctype="multipart/form-data" rst-form>
+ <div rst-field>
+ <label rst-field-label for="fonts-file">{{.Label}}</label>
+ <input rst-input id="fonts-file" name="file" type="file" multiple required
+ accept=".ttf,.otf,.woff,.woff2" aria-describedby="fonts-file-hint">
+ <small rst-field-hint id="fonts-file-hint">{{.Hint}}</small>
+ </div>
+ <p>{{.Rights}}</p>
+ {{template "form-foot" dict "L" $L "Submit" .Submit}}
+ </form>
+ {{else}}
+ <p>{{.Unavailable}}</p>
+ {{end}}
+</div>
+{{end}}
diff --git a/internal/slides/templates/fonts_confirm.html b/internal/slides/templates/fonts_confirm.html
new file mode 100644
index 0000000..4752edc
--- /dev/null
+++ b/internal/slides/templates/fonts_confirm.html
@@ -0,0 +1,12 @@
+{{/* fonts_confirm — GET /fonts/delete?family=, the destructive action's
+ own page (deck_delete's shape). The GET changes nothing. */}}
+{{define "content"}}{{$L := localizer $}}
+{{template "back-nav" dict "L" $L "Href" .BackHref "Label" .BackLabel}}
+{{template "page-header" dict "L" $L "Title" .Title}}
+<div rst-box rst-stack>
+ <p>{{.Body}}</p>
+ {{template "confirm-form" dict "L" $L
+ "Action" .Action "Label" .Label "Danger" true "Hidden" .Hidden
+ "CancelHref" .CancelHref "CancelLabel" .CancelLabel}}
+</div>
+{{end}}
diff --git a/internal/slidestest/library_test.go b/internal/slidestest/library_test.go
new file mode 100644
index 0000000..3eb1ab3
--- /dev/null
+++ b/internal/slidestest/library_test.go
@@ -0,0 +1,314 @@
+package slidestest
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "html"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/slides/internal/slides"
+ "amadan.net/rastrillo/rastrillo/blobs"
+)
+
+// The library tests upload Liberation (SIL OFL), which the app already
+// ships, so no font file is added for them.
+
+type upFile struct {
+ name string
+ data []byte
+}
+
+func libFont(t *testing.T, name string) []byte {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join("..", "slides", "static", "fonts", name))
+ if err != nil {
+ t.Fatalf("read %s: %v", name, err)
+ }
+ return b
+}
+
+func uploadFonts(t *testing.T, a *testApp, cookies []*http.Cookie, files ...upFile) *httptest.ResponseRecorder {
+ t.Helper()
+ var body bytes.Buffer
+ mw := multipart.NewWriter(&body)
+ for _, f := range files {
+ w, err := mw.CreateFormFile("file", f.name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w.Write(f.data)
+ }
+ mw.Close()
+ req := httptest.NewRequest(http.MethodPost, "/fonts", &body)
+ req.Header.Set("Content-Type", mw.FormDataContentType())
+ req.Header.Set("Origin", testOrigin)
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ for _, c := range cookies {
+ req.AddCookie(c)
+ }
+ rec := httptest.NewRecorder()
+ a.ServeHTTP(rec, req)
+ // The page escapes an apostrophe; the messages are read as text.
+ rec.Body = bytes.NewBufferString(html.UnescapeString(rec.Body.String()))
+ return rec
+}
+
+func countRows(t *testing.T, a *testApp, where string, args ...any) int64 {
+ t.Helper()
+ var n int64
+ if err := a.db.G.Model(&slides.LibraryFont{}).Where(where, args...).Count(&n).Error; err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+func hasObject(store blobs.Store, ref string) bool {
+ rc, err := store.Get(context.Background(), ref)
+ if err != nil {
+ return false
+ }
+ rc.Close()
+ return true
+}
+
+func sha(b []byte) string {
+ s := sha256.Sum256(b)
+ return hex.EncodeToString(s[:])
+}
+
+func TestUploadAFontAndSeeItListed(t *testing.T) {
+ store := dirStore(t)
+ a := newAppWithStore(t, store)
+ cookies := signedIn(t, a, allowedAddress)
+
+ empty := mustGet(t, a, "/fonts", http.StatusOK, cookies).Body.String()
+ if !strings.Contains(empty, "No fonts yet.") {
+ t.Errorf("an empty library is not said to be empty:\n%s", empty)
+ }
+
+ reg, bold := libFont(t, "LiberationSans-Regular.ttf"), libFont(t, "LiberationSans-Bold.ttf")
+ rec := uploadFonts(t, a, cookies, upFile{"a.ttf", reg}, upFile{"b.ttf", bold})
+ if rec.Code != http.StatusOK {
+ t.Fatalf("POST /fonts: %d\n%s", rec.Code, rec.Body)
+ }
+ if !strings.Contains(rec.Body.String(), "2 files added.") {
+ t.Errorf("the count of files added is not shown:\n%s", rec.Body)
+ }
+ var rows []slides.LibraryFont
+ if err := a.db.G.Order("weight").Find(&rows).Error; err != nil {
+ t.Fatal(err)
+ }
+ if len(rows) != 2 {
+ t.Fatalf("%d rows, want 2", len(rows))
+ }
+ if rows[0].Ref != sha(reg) || rows[0].Family != "Liberation Sans" || rows[0].CSSName != "Liberation Sans" ||
+ rows[0].Weight != 400 || rows[0].Size != int64(len(reg)) || rows[0].Owner == "" || rows[0].Format != "ttf" {
+ t.Errorf("row %+v does not describe the uploaded face", rows[0])
+ }
+ if !hasObject(store, rows[0].Ref) || !hasObject(store, rows[1].Ref) {
+ t.Errorf("the bytes are not in the store under their refs")
+ }
+ page := html.UnescapeString(mustGet(t, a, "/fonts", http.StatusOK, cookies).Body.String())
+ if !strings.Contains(page, "Liberation Sans") || !strings.Contains(page, "2 styles") {
+ t.Errorf("the family and its styles are not listed:\n%s", page)
+ }
+ if !strings.Contains(page, "/fonts/delete?family=Liberation+Sans") && !strings.Contains(page, "/fonts/delete?family=Liberation%20Sans") {
+ t.Errorf("no delete link for the family:\n%s", page)
+ }
+
+ // The same file again is refused, and adds nothing.
+ again := uploadFonts(t, a, cookies, upFile{"a.ttf", reg})
+ if again.Code != http.StatusUnprocessableEntity || !strings.Contains(again.Body.String(), "a.ttf is already in your fonts.") {
+ t.Errorf("a repeat upload: %d\n%s", again.Code, again.Body)
+ }
+ if n := countRows(t, a, "1 = 1"); n != 2 {
+ t.Errorf("%d rows after a repeat, want 2", n)
+ }
+}
+
+func TestUploadRefusesWhatIsNotAFont(t *testing.T) {
+ store := dirStore(t)
+ a := newAppWithStore(t, store)
+ cookies := signedIn(t, a, allowedAddress)
+
+ png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte{1}, 200)...)
+ good := libFont(t, "LiberationSans-Regular.ttf")
+ cases := []struct {
+ name string
+ file upFile
+ want string
+ }{
+ {"png", upFile{"pic.ttf", png}, "pic.ttf isn't a font file."},
+ {"big", upFile{"huge.ttf", append(append([]byte{}, good...), make([]byte, 11<<20)...)}, "huge.ttf is over 10 MB."},
+ {"truncated", upFile{"cut.ttf", good[:len(good)/3]}, "cut.ttf looks damaged and can't be used."},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ rec := uploadFonts(t, a, cookies, c.file)
+ if rec.Code != http.StatusUnprocessableEntity {
+ t.Fatalf("status %d, want 422\n%s", rec.Code, rec.Body)
+ }
+ if !strings.Contains(rec.Body.String(), c.want) {
+ t.Errorf("missing %q:\n%s", c.want, rec.Body)
+ }
+ if n := countRows(t, a, "1 = 1"); n != 0 {
+ t.Errorf("%d rows after a refusal", n)
+ }
+ if hasObject(store, sha(c.file.data)) {
+ t.Errorf("a refused file was stored")
+ }
+ })
+ }
+
+ // One refusal does not stop the good file beside it.
+ rec := uploadFonts(t, a, cookies, upFile{"pic.ttf", png}, upFile{"ok.ttf", good})
+ body := rec.Body.String()
+ if rec.Code != http.StatusOK || !strings.Contains(body, "pic.ttf isn't a font file.") || !strings.Contains(body, "1 file added.") {
+ t.Errorf("mixed upload: %d\n%s", rec.Code, body)
+ }
+}
+
+func TestTheLibraryLimits(t *testing.T) {
+ a := newAppWithStore(t, dirStore(t))
+ cookies := signedIn(t, a, allowedAddress)
+ mustGet(t, a, "/fonts", http.StatusOK, cookies) // the person's row exists once they have been seen
+ var u slides.User
+ if err := a.db.G.Where("email = ?", allowedAddress).Take(&u).Error; err != nil {
+ t.Fatal(err)
+ }
+ owner := fmt.Sprintf("person:%d", u.ID)
+ seed := func(family, css string, i int) {
+ row := slides.LibraryFont{Owner: owner, Family: family, CSSName: css, Ref: sha([]byte(fmt.Sprintf("%s-%d", family, i))), Format: "ttf", Outline: "truetype", Weight: 400}
+ if err := a.db.G.Create(&row).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i := 0; i < 16; i++ {
+ seed("Liberation Sans", "Liberation Sans", i)
+ }
+ rec := uploadFonts(t, a, cookies, upFile{"x.ttf", libFont(t, "LiberationSans-Regular.ttf")})
+ if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "Liberation Sans already has 16 styles.") {
+ t.Errorf("17th face: %d\n%s", rec.Code, rec.Body)
+ }
+
+ if err := a.db.G.Where("1 = 1").Delete(&slides.LibraryFont{}).Error; err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 32; i++ {
+ seed(fmt.Sprintf("Family %d", i), fmt.Sprintf("Family %d", i), 0)
+ }
+ rec = uploadFonts(t, a, cookies, upFile{"x.ttf", libFont(t, "LiberationSans-Regular.ttf")})
+ if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "You can keep up to 32 font families.") {
+ t.Errorf("33rd family: %d\n%s", rec.Code, rec.Body)
+ }
+ if n := countRows(t, a, "ref = ?", sha(libFont(t, "LiberationSans-Regular.ttf"))); n != 0 {
+ t.Errorf("the refused face was recorded")
+ }
+}
+
+func TestALibraryIsOnlyItsOwners(t *testing.T) {
+ a := newAppWithStore(t, dirStore(t))
+ one := signedIn(t, a, allowedAddress)
+ if rec := uploadFonts(t, a, one, upFile{"a.ttf", libFont(t, "LiberationSans-Regular.ttf")}); rec.Code != http.StatusOK {
+ t.Fatalf("upload: %d", rec.Code)
+ }
+ // Another person's library, seeded: the first person sees none of it.
+ other := slides.LibraryFont{Owner: "person:999", Family: "Secret Face", CSSName: "Secret Face", Ref: sha([]byte("x")), Format: "ttf", Outline: "truetype", Weight: 400}
+ if err := a.db.G.Create(&other).Error; err != nil {
+ t.Fatal(err)
+ }
+ page := mustGet(t, a, "/fonts", http.StatusOK, one).Body.String()
+ if strings.Contains(page, "Secret Face") {
+ t.Errorf("another person's family is listed")
+ }
+ if rec := get(t, a, "/fonts/delete?family=Secret+Face", one...); rec.Code != http.StatusNotFound {
+ t.Errorf("confirm page for another person's family: %d, want 404", rec.Code)
+ }
+ post(t, a, "/fonts/delete", url.Values{"family": {"Secret Face"}}, one...)
+ if n := countRows(t, a, "owner = ?", "person:999"); n != 1 {
+ t.Errorf("another person's family was deleted")
+ }
+}
+
+func TestDeletingAFamilyRemovesItsRows(t *testing.T) {
+ store := dirStore(t)
+ a := newAppWithStore(t, store)
+ cookies := signedIn(t, a, allowedAddress)
+ reg, mono := libFont(t, "LiberationSans-Regular.ttf"), libFont(t, "LiberationMono-Regular.ttf")
+ uploadFonts(t, a, cookies, upFile{"a.ttf", reg}, upFile{"m.ttf", mono})
+
+ confirm := mustGet(t, a, "/fonts/delete?family=Liberation+Sans", http.StatusOK, cookies).Body.String()
+ if !strings.Contains(confirm, "Delete Liberation Sans?") || !strings.Contains(confirm, "Delete font") {
+ t.Errorf("confirm page:\n%s", confirm)
+ }
+ if n := countRows(t, a, "1 = 1"); n != 2 {
+ t.Fatalf("the GET deleted something: %d rows", n)
+ }
+
+ // A second owner holds the same bytes as the mono face: that object
+ // must stay when the first person's family goes.
+ if err := a.db.G.Create(&slides.LibraryFont{Owner: "person:999", Family: "Liberation Mono", CSSName: "Liberation Mono", Ref: sha(mono), Format: "ttf", Outline: "truetype", Weight: 400}).Error; err != nil {
+ t.Fatal(err)
+ }
+ rec := post(t, a, "/fonts/delete", url.Values{"family": {"Liberation Sans"}}, cookies...)
+ if rec.Code != http.StatusSeeOther {
+ t.Fatalf("delete: %d\n%s", rec.Code, rec.Body)
+ }
+ if hasObject(store, sha(reg)) {
+ t.Errorf("an unreferenced object was kept")
+ }
+ if n := countRows(t, a, "ref = ?", sha(reg)); n != 0 {
+ t.Errorf("rows remain")
+ }
+ post(t, a, "/fonts/delete", url.Values{"family": {"Liberation Mono"}}, cookies...)
+ if !hasObject(store, sha(mono)) {
+ t.Errorf("an object another library still holds was deleted")
+ }
+ if n := countRows(t, a, "owner = ?", "person:999"); n != 1 {
+ t.Errorf("the other library lost its row")
+ }
+}
+
+func TestTheFontsPageWorksWithoutScripts(t *testing.T) {
+ a := newAppWithStore(t, dirStore(t))
+ cookies := signedIn(t, a, allowedAddress)
+ body := mustGet(t, a, "/fonts", http.StatusOK, cookies).Body.String()
+ for _, want := range []string{`method="post"`, `action="/fonts"`, `enctype="multipart/form-data"`, `type="file"`, `name="file"`, "multiple", "Upload", "Upload only fonts your licence lets you use on the web."} {
+ if !strings.Contains(body, want) {
+ t.Errorf("the form lacks %q:\n%s", want, body)
+ }
+ }
+
+ // No store: the page says so, and the POST answers 503.
+ b := newApp(t)
+ c := signedIn(t, b, allowedAddress)
+ page := mustGet(t, b, "/fonts", http.StatusOK, c).Body.String()
+ if !strings.Contains(page, "Fonts aren&#39;t available here yet.") && !strings.Contains(page, "Fonts aren't available here yet.") {
+ t.Errorf("no-store page lacks the unavailable line:\n%s", page)
+ }
+ if strings.Contains(page, `type="file"`) {
+ t.Errorf("no-store page still offers the form")
+ }
+ if rec := uploadFonts(t, b, c, upFile{"a.ttf", libFont(t, "LiberationSans-Regular.ttf")}); rec.Code != http.StatusServiceUnavailable {
+ t.Errorf("POST without a store: %d, want 503", rec.Code)
+ }
+}
+
+func TestTheAccountMenuListsFonts(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ body := mustGet(t, a, "/", http.StatusOK, cookies).Body.String()
+ if !strings.Contains(body, `href="/fonts"`) || !strings.Contains(body, ">Fonts<") {
+ t.Errorf("the account menu has no Fonts link:\n%s", body)
+ }
+}