Files
tenant-registry/internal/branding/derive.go
T
sharang 0b0343b680
ci / shared (push) Successful in 12s
ci / test (push) Successful in 8m18s
ci / image (push) Successful in 51s
feat(branding): derive colour and logo from the signup domain (#155, part 2) (#159)
2026-12-01 13:33:08 +00:00

301 lines
7.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package branding
import (
"bytes"
"context"
"encoding/json"
"net/url"
"path"
"sort"
"strconv"
"strings"
"golang.org/x/net/html"
)
// Result is one derivation. Color and Logo may both be empty: the page was
// read but has neither (the product then looks as today).
type Result struct {
Domain string
Color string // "#rrggbb" or ""
ColorSource string // theme-color | manifest | logo | ""
Logo []byte // 256×256 PNG or nil
LogoETag string
LogoSource string // URL the logo came from
LogoSHA256 string // of the fetched bytes
HTMLSHA256 string
}
// page is what the home page declares.
type page struct {
themeColors []themeColor
manifest string
icons []iconRef // rel=icon / shortcut icon
apple []iconRef // rel=apple-touch-icon
}
type themeColor struct {
content string
hasMedia bool
}
type iconRef struct {
href string
size int // largest edge in sizes, 0 when unknown
typ string
order int
}
// Derive reads domain's home page and returns its branding. The same
// fetched bytes always give the same result.
func (f *Fetcher) Derive(ctx context.Context, domain string) (*Result, error) {
domain = RegistrableDomain(domain)
if domain == "" {
return nil, ErrOffDomain
}
home, err := f.home(ctx, domain)
if err != nil {
return nil, err
}
res := &Result{Domain: domain, HTMLSHA256: sha256Hex(home.body)}
pg := parsePage(home.body)
var man *manifest
if pg.manifest != "" {
if u, err := home.url.Parse(pg.manifest); err == nil {
if m, err := f.get(ctx, u, domain, MaxImageBytes, "application/manifest+json,application/json"); err == nil {
man = parseManifest(m.body, m.url)
}
}
}
// Colour 1 and 2: the first theme-color without a media query, then
// the manifest's theme_color; white, black and grey are skipped.
for _, tc := range pg.themeColors {
if !tc.hasMedia {
if c := CSSBrandColor(tc.content); c != "" {
res.Color, res.ColorSource = c, "theme-color"
}
break
}
}
if res.Color == "" && man != nil {
if c := CSSBrandColor(man.themeColor); c != "" {
res.Color, res.ColorSource = c, "manifest"
}
}
// The logo: the first candidate that can be fetched and decoded.
for _, u := range logoCandidates(pg, man, home.url) {
img, err := f.get(ctx, u, domain, MaxImageBytes+1, "image/png,image/x-icon,image/jpeg;q=0.9,image/*;q=0.5")
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
continue
}
png, etag, err := NormalizeLogo(img.body)
if err != nil {
continue // SVG, too large or not an image: the next candidate
}
res.Logo, res.LogoETag, res.LogoSource, res.LogoSHA256 = png, etag, img.url.String(), sha256Hex(img.body)
break
}
// Colour 3: the logo's dominant brand colour.
if res.Color == "" && res.Logo != nil {
if img, err := DecodeImage(res.Logo); err == nil {
if c := DominantColor(img); c != "" {
res.Color, res.ColorSource = c, "logo"
}
}
}
return res, nil
}
// logoCandidates in the order of #155 step 4: the manifest's largest PNG
// icon of at least 128 px, apple-touch-icon, the largest PNG/ICO/JPEG
// rel=icon, /favicon.ico. Within a step, larger first.
func logoCandidates(pg page, man *manifest, base *url.URL) []*url.URL {
var out []*url.URL
seen := map[string]bool{}
add := func(refBase *url.URL, refs []iconRef) {
sort.SliceStable(refs, func(i, j int) bool {
if refs[i].size != refs[j].size {
return refs[i].size > refs[j].size
}
return refs[i].order < refs[j].order
})
for _, r := range refs {
u, err := refBase.Parse(strings.TrimSpace(r.href))
if err != nil || seen[u.String()] {
continue
}
seen[u.String()] = true
out = append(out, u)
}
}
if man != nil {
var pngs []iconRef
for _, ic := range man.icons {
if ic.size >= 128 && isType(ic, "png") {
pngs = append(pngs, ic)
}
}
add(man.url, pngs)
}
add(base, slicesClone(pg.apple))
var icons []iconRef
for _, ic := range pg.icons {
if isType(ic, "png") || isType(ic, "ico") || isType(ic, "jpeg") {
icons = append(icons, ic)
}
}
add(base, icons)
add(base, []iconRef{{href: "/favicon.ico"}})
return out
}
func slicesClone(in []iconRef) []iconRef { return append([]iconRef(nil), in...) }
// isType matches an icon by its type attribute, else by its file
// extension.
func isType(ic iconRef, kind string) bool {
t := strings.ToLower(strings.TrimSpace(ic.typ))
if t != "" {
switch kind {
case "png":
return t == "image/png"
case "ico":
return t == "image/x-icon" || t == "image/vnd.microsoft.icon" || t == "image/ico"
case "jpeg":
return t == "image/jpeg" || t == "image/jpg"
}
return false
}
p := strings.ToLower(ic.href)
if i := strings.IndexAny(p, "?#"); i >= 0 {
p = p[:i]
}
switch ext := path.Ext(p); kind {
case "png":
return ext == ".png"
case "ico":
return ext == ".ico"
case "jpeg":
return ext == ".jpg" || ext == ".jpeg"
}
return false
}
// parsePage collects theme-color, the manifest link and icon links.
func parsePage(body []byte) page {
var pg page
z := html.NewTokenizer(bytes.NewReader(body))
order := 0
for {
tt := z.Next()
if tt == html.ErrorToken {
return pg
}
if tt != html.StartTagToken && tt != html.SelfClosingTagToken {
continue
}
name, hasAttr := z.TagName()
if !hasAttr {
continue
}
attrs := map[string]string{}
for {
k, v, more := z.TagAttr()
key := strings.ToLower(string(k))
if _, dup := attrs[key]; !dup {
attrs[key] = string(v)
}
if !more {
break
}
}
switch string(name) {
case "meta":
if strings.EqualFold(strings.TrimSpace(attrs["name"]), "theme-color") {
_, media := attrs["media"]
pg.themeColors = append(pg.themeColors, themeColor{content: attrs["content"], hasMedia: media && strings.TrimSpace(attrs["media"]) != ""})
}
case "link":
href := strings.TrimSpace(attrs["href"])
if href == "" {
continue
}
rels := strings.Fields(strings.ToLower(attrs["rel"]))
ref := iconRef{href: href, size: largestSize(attrs["sizes"]), typ: attrs["type"], order: order}
order++
switch {
case contains(rels, "manifest"):
if pg.manifest == "" {
pg.manifest = href
}
case contains(rels, "apple-touch-icon"), contains(rels, "apple-touch-icon-precomposed"):
pg.apple = append(pg.apple, ref)
case contains(rels, "icon"):
pg.icons = append(pg.icons, ref)
}
}
}
}
func contains(list []string, s string) bool {
for _, v := range list {
if v == s {
return true
}
}
return false
}
// largestSize reads sizes="16x16 32x32" as its largest edge; "any" and
// unreadable values count 0.
func largestSize(sizes string) int {
best := 0
for _, s := range strings.Fields(strings.ToLower(sizes)) {
w, h, ok := strings.Cut(s, "x")
if !ok {
continue
}
wi, err1 := strconv.Atoi(w)
hi, err2 := strconv.Atoi(h)
if err1 != nil || err2 != nil {
continue
}
best = max(best, min(wi, hi))
}
return best
}
type manifest struct {
themeColor string
icons []iconRef
url *url.URL
}
func parseManifest(body []byte, u *url.URL) *manifest {
var raw struct {
ThemeColor string `json:"theme_color"`
Icons []struct {
Src string `json:"src"`
Sizes string `json:"sizes"`
Type string `json:"type"`
} `json:"icons"`
}
if json.Unmarshal(body, &raw) != nil {
return nil
}
m := &manifest{themeColor: raw.ThemeColor, url: u}
for i, ic := range raw.Icons {
if strings.TrimSpace(ic.Src) == "" {
continue
}
m.icons = append(m.icons, iconRef{href: ic.Src, size: largestSize(ic.Sizes), typ: ic.Type, order: i})
}
return m
}