BlueGit

timfa bluegit

Files

bluegit / internal / card / card.go

card.go

feat: toon rijke linkkaarten voor openbare pagina's
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
0741fde9 History
card.go 15.2 KiB Download Raw
1// Package card bouwt Open Graph-kaarten: tekst, SVG en een PNG.
2package card
3
4import (
5 "bytes"
6 "encoding/base64"
7 "encoding/xml"
8 "fmt"
9 "image"
10 "image/color"
11 _ "image/gif"
12 _ "image/jpeg"
13 "image/png"
14 "regexp"
15 "strconv"
16 "strings"
17 "sync"
18 "unicode/utf8"
19
20 "golang.org/x/image/font"
21 "golang.org/x/image/font/gofont/gomono"
22 "golang.org/x/image/font/gofont/goregular"
23 "golang.org/x/image/font/opentype"
24 "golang.org/x/image/math/fixed"
25)
26
27const (
28 Width = 1200
29 Height = 630
30 // LockedTitle is de enige tekst op een niet-openbare kaart.
31 LockedTitle = "BlueGit – inloggen vereist"
32 lockedBody = "This page is not public."
33)
34
35// Meta is wat in de HTML-head en in oEmbed staat.
36type Meta struct {
37 Title string
38 Description string
39 URL string
40 Image string
41 OEmbed string
42 Theme string
43 Kind string
44 Facts []string
45 Initial string
46}
47
48// Render is een kaart plus een optionele avatar (PNG of JPEG).
49type Render struct {
50 Meta
51 Avatar []byte
52}
53
54// Blurb is de tekst voor og:description, zonder regeleinden.
55func (m Meta) Blurb() string {
56 prose := strings.ReplaceAll(m.Description, "\n", " / ")
57 prose = strings.Join(strings.Fields(prose), " ")
58 facts := strings.Join(m.Facts, " · ")
59 if prose == "" {
60 return facts
61 }
62 if facts == "" {
63 return prose
64 }
65 return prose + " · " + facts
66}
67
68// Locked is de generieke kaart. url en image mogen geen bronnaam bevatten.
69func Locked(pageURL, imageURL, oembed string) Render {
70 return Render{Meta: Meta{
71 Title: LockedTitle, Description: lockedBody, URL: pageURL, Image: imageURL,
72 OEmbed: oembed, Theme: "#142033", Kind: "locked",
73 }}
74}
75
76// Site is de kaart van BlueGit zelf.
77func Site(pageURL, imageURL, oembed string) Render {
78 return Render{Meta: Meta{
79 Title: "BlueGit", Description: "Git hosting with merge requests, issues and pipelines.",
80 URL: pageURL, Image: imageURL, OEmbed: oembed, Theme: "#1f6feb", Kind: "site",
81 Initial: "B",
82 }}
83}
84
85// Excerpt haalt de eerste alinea uit Markdown en kort die in.
86// Een kop boven de alinea telt niet mee.
87func Excerpt(src string, limit int) string {
88 src = fenceRe.ReplaceAllString(src, "\n")
89 src = imageRe.ReplaceAllString(src, " ")
90 src = linkRe.ReplaceAllString(src, "$1")
91 src = htmlRe.ReplaceAllString(src, " ")
92 var paras []string
93 var cur []string
94 flush := func() {
95 if len(cur) == 0 {
96 return
97 }
98 text := strings.Join(strings.Fields(cleanLine(strings.Join(cur, " "))), " ")
99 cur = nil
100 if text != "" {
101 paras = append(paras, text)
102 }
103 }
104 for _, line := range strings.Split(src, "\n") {
105 line = strings.TrimSpace(line)
106 if line == "" || strings.HasPrefix(line, "#") {
107 flush()
108 continue
109 }
110 cur = append(cur, line)
111 }
112 flush()
113 if len(paras) == 0 {
114 return ""
115 }
116 return Clip(paras[0], limit)
117}
118
119func cleanLine(s string) string {
120 s = strings.TrimLeft(s, ">*-_ ")
121 s = strings.ReplaceAll(s, "`", "")
122 s = strings.ReplaceAll(s, "*", "")
123 s = strings.ReplaceAll(s, "_", "")
124 return s
125}
126
127// Clip kapt op een runengrens af.
128func Clip(s string, limit int) string {
129 if limit < 1 || utf8.RuneCountInString(s) <= limit {
130 return s
131 }
132 out := make([]rune, 0, limit)
133 for _, r := range s {
134 if len(out) == limit-1 {
135 break
136 }
137 out = append(out, r)
138 }
139 return strings.TrimSpace(string(out)) + "…"
140}
141
142var (
143 fenceRe = regexp.MustCompile("(?s)```.*?```")
144 imageRe = regexp.MustCompile(`!\[[^\]]*\]\([^)]*\)`)
145 linkRe = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`)
146 htmlRe = regexp.MustCompile(`<[^>]+>`)
147 lineRe = regexp.MustCompile(`(?i)^L?(\d+)(?:-(\d+))?$`)
148)
149
150// ParseLines leest #L10-20, L10-20 of 10-20. De tweede grens is inclusief.
151func ParseLines(token string) (from, to int, ok bool) {
152 token = strings.TrimSpace(strings.TrimPrefix(token, "#"))
153 m := lineRe.FindStringSubmatch(token)
154 if m == nil {
155 return 0, 0, false
156 }
157 from, _ = strconv.Atoi(m[1])
158 if from < 1 {
159 return 0, 0, false
160 }
161 to = from
162 if m[2] != "" {
163 to, _ = strconv.Atoi(m[2])
164 }
165 if to < from {
166 return 0, 0, false
167 }
168 if to-from > 11 {
169 to = from + 11
170 }
171 return from, to, true
172}
173
174// Snippet geeft de gevraagde regels, of anders de eerste regels.
175func Snippet(text string, from, to int, withRange bool) string {
176 lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n")
177 if len(lines) > 0 && lines[len(lines)-1] == "" {
178 lines = lines[:len(lines)-1]
179 }
180 if !withRange {
181 from, to = 1, 8
182 }
183 if from < 1 {
184 from = 1
185 }
186 var out []string
187 for n := from; n <= to && n <= len(lines); n++ {
188 out = append(out, lines[n-1])
189 }
190 return strings.Join(out, "\n")
191}
192
193// SVG tekent de kaart. Avatar is PNG of JPEG, of leeg.
194func SVG(r Render) string {
195 theme := r.Theme
196 if theme == "" {
197 theme = "#1f6feb"
198 }
199 var b strings.Builder
200 b.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630">`)
201 b.WriteString(`<rect width="1200" height="630" fill="#071526"/>`)
202 fmt.Fprintf(&b, `<rect width="18" height="630" fill="%s"/>`, theme)
203 b.WriteString(`<rect x="56" y="48" width="1088" height="534" rx="28" fill="#ffffff"/>`)
204 fmt.Fprintf(&b, `<circle cx="150" cy="168" r="52" fill="%s"/>`, theme)
205 if len(r.Avatar) > 0 {
206 fmt.Fprintf(&b, `<image href="data:image/png;base64,%s" x="98" y="116" width="104" height="104"/>`, base64.StdEncoding.EncodeToString(r.Avatar))
207 } else if r.Initial != "" {
208 fmt.Fprintf(&b, `<text x="150" y="184" font-size="48" font-family="sans" fill="#ffffff" text-anchor="middle">%s</text>`, xmlText(clipInitial(r.Initial)))
209 } else {
210 b.WriteString(icon(r.Kind, 128, 144, "#ffffff"))
211 }
212 fmt.Fprintf(&b, `<text x="224" y="150" font-size="28" font-family="sans" fill="#5c6b80">%s</text>`, xmlText("BlueGit"))
213 fmt.Fprintf(&b, `<text x="360" y="150" font-size="28" font-family="sans" fill="%s">%s</text>`, theme, xmlText(kindLabel(r.Kind)))
214 y := 214
215 for _, line := range wrap(r.Title, 32, 2) {
216 fmt.Fprintf(&b, `<text x="224" y="%d" font-size="48" font-family="sans" fill="#142033">%s</text>`, y, xmlText(line))
217 y += 58
218 }
219 descY := 340
220 if r.Kind == "file" && strings.Contains(r.Description, "\n") {
221 for i, line := range strings.Split(r.Description, "\n") {
222 if i == 8 {
223 break
224 }
225 fmt.Fprintf(&b, `<text x="100" y="%d" font-size="26" font-family="mono" fill="#142033">%s</text>`, descY, xmlText(Clip(line, 62)))
226 descY += 34
227 }
228 } else {
229 for _, line := range wrap(r.Description, 52, 3) {
230 fmt.Fprintf(&b, `<text x="100" y="%d" font-size="30" font-family="sans" fill="#142033">%s</text>`, descY, xmlText(line))
231 descY += 42
232 }
233 }
234 fmt.Fprintf(&b, `<text x="100" y="540" font-size="26" font-family="sans" fill="%s">%s</text>`, theme, xmlText(strings.Join(r.Facts, " · ")))
235 b.WriteString(`</svg>`)
236 return b.String()
237}
238
239func kindLabel(kind string) string {
240 switch kind {
241 case "repository":
242 return "Repository"
243 case "merge_request":
244 return "Merge request"
245 case "issue":
246 return "Issue"
247 case "group":
248 return "Group"
249 case "user":
250 return "User"
251 case "commit":
252 return "Commit"
253 case "pipeline":
254 return "Pipeline"
255 case "release":
256 return "Release"
257 case "file":
258 return "File"
259 case "locked":
260 return "Private"
261 default:
262 return "BlueGit"
263 }
264}
265
266func icon(kind string, x, y int, fill string) string {
267 switch kind {
268 case "merge_request":
269 return fmt.Sprintf(`<circle cx="%d" cy="%d" r="8" fill="%s"/><circle cx="%d" cy="%d" r="8" fill="%s"/><circle cx="%d" cy="%d" r="8" fill="%s"/>`,
270 x+6, y+8, fill, x+22, y+8, fill, x+14, y+28, fill)
271 case "issue":
272 return fmt.Sprintf(`<circle cx="%d" cy="%d" r="16" fill="none"/><circle cx="%d" cy="%d" r="14" fill="%s"/><circle cx="%d" cy="%d" r="5" fill="#071526"/>`,
273 x+18, y+18, x+18, y+18, fill, x+18, y+18)
274 case "group":
275 return fmt.Sprintf(`<circle cx="%d" cy="%d" r="8" fill="%s"/><circle cx="%d" cy="%d" r="8" fill="%s"/><circle cx="%d" cy="%d" r="8" fill="%s"/>`,
276 x+6, y+16, fill, x+22, y+16, fill, x+14, y+30, fill)
277 case "pipeline":
278 return fmt.Sprintf(`<rect x="%d" y="%d" width="8" height="28" rx="2" fill="%s"/><rect x="%d" y="%d" width="8" height="18" rx="2" fill="%s"/><rect x="%d" y="%d" width="8" height="24" rx="2" fill="%s"/>`,
279 x+4, y+4, fill, x+16, y+14, fill, x+28, y+8, fill)
280 case "release":
281 return fmt.Sprintf(`<rect x="%d" y="%d" width="28" height="20" rx="4" fill="%s"/><circle cx="%d" cy="%d" r="4" fill="#071526"/>`,
282 x+6, y+10, fill, x+16, y+20)
283 case "file":
284 return fmt.Sprintf(`<rect x="%d" y="%d" width="26" height="32" rx="3" fill="%s"/>`, x+8, y+4, fill)
285 case "locked":
286 return fmt.Sprintf(`<circle cx="%d" cy="%d" r="8" fill="none"/><rect x="%d" y="%d" width="22" height="16" rx="3" fill="%s"/><circle cx="%d" cy="%d" r="7" fill="%s"/>`,
287 x+18, y+10, x+7, y+16, fill, x+18, y+8, fill)
288 default:
289 return fmt.Sprintf(`<rect x="%d" y="%d" width="30" height="22" rx="3" fill="%s"/>`, x+6, y+10, fill)
290 }
291}
292
293func clipInitial(s string) string {
294 s = strings.TrimSpace(s)
295 if s == "" {
296 return ""
297 }
298 r, _ := utf8.DecodeRuneInString(s)
299 return strings.ToUpper(string(r))
300}
301
302func wrap(s string, width, max int) []string {
303 s = strings.Join(strings.Fields(s), " ")
304 if s == "" || max < 1 {
305 return nil
306 }
307 words := strings.Fields(s)
308 var lines []string
309 var cur string
310 for _, w := range words {
311 if cur == "" {
312 cur = w
313 continue
314 }
315 if utf8.RuneCountInString(cur)+1+utf8.RuneCountInString(w) > width {
316 lines = append(lines, cur)
317 cur = w
318 if len(lines) == max {
319 break
320 }
321 continue
322 }
323 cur += " " + w
324 }
325 if len(lines) < max && cur != "" {
326 lines = append(lines, cur)
327 }
328 if len(lines) > max {
329 lines = lines[:max]
330 }
331 return lines
332}
333
334func xmlText(s string) string {
335 var b bytes.Buffer
336 _ = xml.EscapeText(&b, []byte(s))
337 return b.String()
338}
339
340// PNG rastert de SVG van deze kaart. Alleen de vormen die SVG() schrijft.
341func PNG(r Render) ([]byte, error) {
342 return Raster(SVG(r))
343}
344
345// Raster maakt een PNG van een kaart-SVG.
346func Raster(svg string) ([]byte, error) {
347 img := image.NewNRGBA(image.Rect(0, 0, Width, Height))
348 dec := xml.NewDecoder(strings.NewReader(svg))
349 for {
350 tok, err := dec.Token()
351 if err != nil {
352 break
353 }
354 se, ok := tok.(xml.StartElement)
355 if !ok {
356 continue
357 }
358 switch se.Name.Local {
359 case "rect":
360 fillRound(img, atoi(attr(se, "x")), atoi(attr(se, "y")), atoi(attr(se, "width")), atoi(attr(se, "height")), atoi(attr(se, "rx")), parseColor(attr(se, "fill")))
361 case "circle":
362 fillCircle(img, atoi(attr(se, "cx")), atoi(attr(se, "cy")), atoi(attr(se, "r")), parseColor(attr(se, "fill")))
363 case "image":
364 drawDataImage(img, attr(se, "href"), atoi(attr(se, "x")), atoi(attr(se, "y")), atoi(attr(se, "width")), atoi(attr(se, "height")))
365 case "text":
366 var text string
367 for {
368 t, err := dec.Token()
369 if err != nil {
370 break
371 }
372 if _, ok := t.(xml.EndElement); ok {
373 break
374 }
375 if cd, ok := t.(xml.CharData); ok {
376 text += string(cd)
377 }
378 }
379 drawText(img, text, atoi(attr(se, "x")), atoi(attr(se, "y")), atoi(attr(se, "font-size")), attr(se, "font-family"), attr(se, "text-anchor"), parseColor(attr(se, "fill")))
380 }
381 }
382 var buf bytes.Buffer
383 if err := png.Encode(&buf, img); err != nil {
384 return nil, err
385 }
386 return buf.Bytes(), nil
387}
388
389func attr(se xml.StartElement, name string) string {
390 for _, a := range se.Attr {
391 if a.Name.Local == name {
392 return a.Value
393 }
394 }
395 return ""
396}
397
398func atoi(s string) int {
399 n, _ := strconv.Atoi(strings.TrimSpace(s))
400 return n
401}
402
403func parseColor(s string) color.NRGBA {
404 s = strings.TrimSpace(s)
405 if s == "" || s == "none" {
406 return color.NRGBA{}
407 }
408 s = strings.TrimPrefix(s, "#")
409 if len(s) == 3 {
410 s = string([]byte{s[0], s[0], s[1], s[1], s[2], s[2]})
411 }
412 if len(s) != 6 {
413 return color.NRGBA{A: 255}
414 }
415 v, err := strconv.ParseUint(s, 16, 32)
416 if err != nil {
417 return color.NRGBA{A: 255}
418 }
419 return color.NRGBA{R: uint8(v >> 16), G: uint8(v >> 8), B: uint8(v), A: 255}
420}
421
422func fillRound(img *image.NRGBA, x, y, w, h, rx int, c color.NRGBA) {
423 if c.A == 0 || w <= 0 || h <= 0 {
424 return
425 }
426 if rx <= 0 {
427 fillRect(img, x, y, w, h, c)
428 return
429 }
430 if rx > w/2 {
431 rx = w / 2
432 }
433 if rx > h/2 {
434 rx = h / 2
435 }
436 fillRect(img, x+rx, y, w-2*rx, h, c)
437 fillRect(img, x, y+rx, w, h-2*rx, c)
438 fillCircle(img, x+rx, y+rx, rx, c)
439 fillCircle(img, x+w-rx, y+rx, rx, c)
440 fillCircle(img, x+rx, y+h-rx, rx, c)
441 fillCircle(img, x+w-rx, y+h-rx, rx, c)
442}
443
444func fillRect(img *image.NRGBA, x, y, w, h int, c color.NRGBA) {
445 b := img.Bounds()
446 for yy := y; yy < y+h; yy++ {
447 if yy < b.Min.Y || yy >= b.Max.Y {
448 continue
449 }
450 for xx := x; xx < x+w; xx++ {
451 if xx < b.Min.X || xx >= b.Max.X {
452 continue
453 }
454 img.SetNRGBA(xx, yy, c)
455 }
456 }
457}
458
459func fillCircle(img *image.NRGBA, cx, cy, r int, c color.NRGBA) {
460 if c.A == 0 || r <= 0 {
461 return
462 }
463 rr := r * r
464 for y := cy - r; y <= cy+r; y++ {
465 for x := cx - r; x <= cx+r; x++ {
466 dx, dy := x-cx, y-cy
467 if dx*dx+dy*dy <= rr {
468 if image.Pt(x, y).In(img.Bounds()) {
469 img.SetNRGBA(x, y, c)
470 }
471 }
472 }
473 }
474}
475
476func drawDataImage(img *image.NRGBA, href string, x, y, w, h int) {
477 i := strings.Index(href, "base64,")
478 if i < 0 || w < 1 || h < 1 {
479 return
480 }
481 raw, err := base64.StdEncoding.DecodeString(href[i+7:])
482 if err != nil {
483 return
484 }
485 src, _, err := image.Decode(bytes.NewReader(raw))
486 if err != nil {
487 return
488 }
489 sb := src.Bounds()
490 rad := w / 2
491 for yy := 0; yy < h; yy++ {
492 for xx := 0; xx < w; xx++ {
493 dx, dy := xx-w/2, yy-h/2
494 if dx*dx+dy*dy > rad*rad {
495 continue
496 }
497 sx := sb.Min.X + xx*sb.Dx()/w
498 sy := sb.Min.Y + yy*sb.Dy()/h
499 c := color.NRGBAModel.Convert(src.At(sx, sy)).(color.NRGBA)
500 if c.A == 0 {
501 continue
502 }
503 img.SetNRGBA(x+xx, y+yy, c)
504 }
505 }
506}
507
508func drawText(img *image.NRGBA, text string, x, y, size int, family, anchor string, c color.NRGBA) {
509 if text == "" || c.A == 0 || size < 8 {
510 return
511 }
512 face := faceFor(family, size)
513 if face == nil {
514 return
515 }
516 d := font.Drawer{Dst: img, Src: image.NewUniform(c), Face: face}
517 if anchor == "middle" {
518 x -= d.MeasureString(text).Round() / 2
519 }
520 d.Dot = fixed.P(x, y)
521 d.DrawString(text)
522}
523
524var (
525 faceOnce sync.Once
526 sansFont *opentype.Font
527 monoFont *opentype.Font
528 faceMu sync.Mutex
529 faces = map[string]font.Face{}
530)
531
532func faceFor(family string, size int) font.Face {
533 faceOnce.Do(func() {
534 sansFont, _ = opentype.Parse(goregular.TTF)
535 monoFont, _ = opentype.Parse(gomono.TTF)
536 })
537 src := sansFont
538 if family == "mono" {
539 src = monoFont
540 }
541 if src == nil {
542 return nil
543 }
544 key := family + "/" + strconv.Itoa(size)
545 faceMu.Lock()
546 defer faceMu.Unlock()
547 if f, ok := faces[key]; ok {
548 return f
549 }
550 f, err := opentype.NewFace(src, &opentype.FaceOptions{Size: float64(size), DPI: 72, Hinting: font.HintingNone})
551 if err != nil {
552 return nil
553 }
554 faces[key] = f
555 return f
556}
557
558// Cache bewaart PNG-bytes op de SVG-tekst.
559type Cache struct {
560 mu sync.Mutex
561 max int
562 order []string
563 png map[string][]byte
564 hits int
565}
566
567// NewCache maakt een cache met een maximum aantal kaarten.
568func NewCache(max int) *Cache {
569 if max < 1 {
570 max = 1
571 }
572 return &Cache{max: max, png: map[string][]byte{}}
573}
574
575// Get levert een eerder gerasterde SVG.
576func (c *Cache) Get(svg string) ([]byte, bool) {
577 c.mu.Lock()
578 defer c.mu.Unlock()
579 b, ok := c.png[svg]
580 if ok {
581 c.hits++
582 }
583 return b, ok
584}
585
586// Put bewaart een PNG.
587func (c *Cache) Put(svg string, b []byte) {
588 c.mu.Lock()
589 defer c.mu.Unlock()
590 if _, ok := c.png[svg]; ok {
591 c.png[svg] = b
592 return
593 }
594 if len(c.order) >= c.max {
595 drop := c.order[0]
596 c.order = c.order[1:]
597 delete(c.png, drop)
598 }
599 c.order = append(c.order, svg)
600 c.png[svg] = b
601}
602
603// Hits telt treffers sinds het starten.
604func (c *Cache) Hits() int {
605 c.mu.Lock()
606 defer c.mu.Unlock()
607 return c.hits
608}