BlueGit

timfa bluegit

feat: toon rijke linkkaarten voor openbare pagina's

Open Graph, Twitter Card en oEmbed, met een gecachte PNG per type. Privé, internal en vertrouwelijke issues krijgen alleen de generieke kaart, ook met een sessiecookie.

Co-authored-by: tim <tim@timfalken.com>

timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa

Authored 2026-10-22 · 3 weeks ago

Hash
0741fde9e9806280eed81777f2f403fca2922a74
Parent
a0e47f35
14 files changed +1791 −8
go.mod +2 −0
@@ -4,6 +4,7 @@ go 1.22
4 4
5 5 require (
6 6 golang.org/x/crypto v0.31.0
7 golang.org/x/image v0.21.0
7 8 gopkg.in/yaml.v3 v3.0.1
8 9 modernc.org/sqlite v1.34.5
9 10 )
@@ -15,6 +16,7 @@ require (
15 16 github.com/ncruces/go-strftime v0.1.9 // indirect
16 17 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
17 18 golang.org/x/sys v0.28.0 // indirect
19 golang.org/x/text v0.21.0 // indirect
18 20 modernc.org/libc v1.55.3 // indirect
19 21 modernc.org/mathutil v1.6.0 // indirect
20 22 modernc.org/memory v1.8.0 // indirect
@@ -4,6 +4,7 @@ go 1.22
4
4
5require (
5require (
6 golang.org/x/crypto v0.31.0
6 golang.org/x/crypto v0.31.0
7 golang.org/x/image v0.21.0
7 gopkg.in/yaml.v3 v3.0.1
8 gopkg.in/yaml.v3 v3.0.1
8 modernc.org/sqlite v1.34.5
9 modernc.org/sqlite v1.34.5
9)
10)
@@ -15,6 +16,7 @@ require (
15 github.com/ncruces/go-strftime v0.1.9 // indirect
16 github.com/ncruces/go-strftime v0.1.9 // indirect
16 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
17 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
17 golang.org/x/sys v0.28.0 // indirect
18 golang.org/x/sys v0.28.0 // indirect
19 golang.org/x/text v0.21.0 // indirect
18 modernc.org/libc v1.55.3 // indirect
20 modernc.org/libc v1.55.3 // indirect
19 modernc.org/mathutil v1.6.0 // indirect
21 modernc.org/mathutil v1.6.0 // indirect
20 modernc.org/memory v1.8.0 // indirect
22 modernc.org/memory v1.8.0 // indirect
go.sum +10 −4
@@ -12,15 +12,21 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
12 12 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
13 13 golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
14 14 golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
15 golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
16 golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
15 golang.org/x/image v0.21.0 h1:c5qV36ajHpdj4Qi0GnE0jUc/yuo33OLFaa0d+crTD5s=
16 golang.org/x/image v0.21.0/go.mod h1:vUbsLavqK/W303ZroQQVKQ+Af3Yl6Uz1Ppu5J/cLz78=
17 golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
18 golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
19 golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
20 golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
17 21 golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
18 22 golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
19 23 golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
20 24 golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
21 25 golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
22 golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
23 golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
26 golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
27 golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
28 golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
29 golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
24 30 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
25 31 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
26 32 gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
@@ -12,15 +12,21 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
12github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
12github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
13golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
13golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
14golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
14golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
15golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
15golang.org/x/image v0.21.0 h1:c5qV36ajHpdj4Qi0GnE0jUc/yuo33OLFaa0d+crTD5s=
16golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
16golang.org/x/image v0.21.0/go.mod h1:vUbsLavqK/W303ZroQQVKQ+Af3Yl6Uz1Ppu5J/cLz78=
17golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
18golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
19golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
20golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
17golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
21golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
18golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
22golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
19golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
23golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
20golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
24golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
21golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
25golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
22golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
26golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
23golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
27golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
28golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
29golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
24gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
30gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
25gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
31gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
26gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
32gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
internal/card/card.go added +608 −0
@@ -0,0 +1,608 @@
1 // Package card bouwt Open Graph-kaarten: tekst, SVG en een PNG.
2 package card
3
4 import (
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
27 const (
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.
36 type 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).
49 type Render struct {
50 Meta
51 Avatar []byte
52 }
53
54 // Blurb is de tekst voor og:description, zonder regeleinden.
55 func (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.
69 func 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.
77 func 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.
87 func 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
119 func 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.
128 func 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
142 var (
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.
151 func 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.
175 func 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.
194 func 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
239 func 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
266 func 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
293 func 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
302 func 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
334 func 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.
341 func PNG(r Render) ([]byte, error) {
342 return Raster(SVG(r))
343 }
344
345 // Raster maakt een PNG van een kaart-SVG.
346 func 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
389 func 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
398 func atoi(s string) int {
399 n, _ := strconv.Atoi(strings.TrimSpace(s))
400 return n
401 }
402
403 func 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
422 func 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
444 func 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
459 func 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
476 func 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
508 func 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
524 var (
525 faceOnce sync.Once
526 sansFont *opentype.Font
527 monoFont *opentype.Font
528 faceMu sync.Mutex
529 faces = map[string]font.Face{}
530 )
531
532 func 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.
559 type 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.
568 func 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.
576 func (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.
587 func (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.
604 func (c *Cache) Hits() int {
605 c.mu.Lock()
606 defer c.mu.Unlock()
607 return c.hits
608 }
@@ -0,0 +1,608 @@
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}
internal/card/card_test.go added +75 −0
@@ -0,0 +1,75 @@
1 package card
2
3 import (
4 "bytes"
5 "image/png"
6 "strings"
7 "testing"
8 )
9
10 func TestExcerptAndLines(t *testing.T) {
11 got := Excerpt("# Titel\n\nEen **widget** die [telt](http://x).\n\nTweede alinea.\n", 80)
12 if got != "Een widget die telt." {
13 t.Fatalf("excerpt %q", got)
14 }
15 if !strings.Contains(Excerpt("```\ngeheim\n```\n\nZichtbaar", 40), "Zichtbaar") || strings.Contains(Excerpt("```\ngeheim\n```\n\nZichtbaar", 40), "geheim") {
16 t.Fatal("codeblok")
17 }
18 from, to, ok := ParseLines("#L10-20")
19 if !ok || from != 10 || to != 20 {
20 t.Fatalf("bereik %d %d %v", from, to, ok)
21 }
22 from, to, ok = ParseLines("L4")
23 if !ok || from != 4 || to != 4 {
24 t.Fatal(from, to)
25 }
26 lines := make([]string, 25)
27 for i := range lines {
28 lines[i] = "regel-" + string(rune('a'+i))
29 }
30 src := strings.Join(lines, "\n") + "\n"
31 snip := Snippet(src, 10, 12, true)
32 if snip != "regel-j\nregel-k\nregel-l" {
33 t.Fatalf("snippet %q", snip)
34 }
35 }
36
37 func TestLockedImageOmitsSecret(t *testing.T) {
38 secret := "ZXQGEHEIM"
39 locked := Locked("https://git.example/", "https://git.example/-/card.png?locked=1", "https://git.example/api/v1/oembed?locked=1")
40 svg := SVG(locked)
41 if strings.Contains(svg, secret) || !strings.Contains(svg, LockedTitle) {
42 t.Fatalf("svg:\n%s", svg)
43 }
44 pngBytes, err := Raster(svg)
45 if err != nil {
46 t.Fatal(err)
47 }
48 cfg, err := png.DecodeConfig(bytes.NewReader(pngBytes))
49 if err != nil || cfg.Width != Width || cfg.Height != Height {
50 t.Fatalf("png %v %v", cfg, err)
51 }
52 pub := locked
53 pub.Title = secret
54 pub.Description = secret
55 pub.Kind = "repository"
56 other, err := PNG(pub)
57 if err != nil {
58 t.Fatal(err)
59 }
60 if bytes.Equal(pngBytes, other) {
61 t.Fatal("verschillende kaarten hebben dezelfde png")
62 }
63 c := NewCache(2)
64 c.Put(svg, pngBytes)
65 if _, ok := c.Get(svg); !ok || c.Hits() != 1 {
66 t.Fatal("cache")
67 }
68 }
69
70 func TestBlurb(t *testing.T) {
71 m := Meta{Description: "regel-a\nregel-b", Facts: []string{"Go", "1 star"}}
72 if m.Blurb() != "regel-a / regel-b · Go · 1 star" {
73 t.Fatalf("blurb %q", m.Blurb())
74 }
75 }
@@ -0,0 +1,75 @@
1package card
2
3import (
4 "bytes"
5 "image/png"
6 "strings"
7 "testing"
8)
9
10func TestExcerptAndLines(t *testing.T) {
11 got := Excerpt("# Titel\n\nEen **widget** die [telt](http://x).\n\nTweede alinea.\n", 80)
12 if got != "Een widget die telt." {
13 t.Fatalf("excerpt %q", got)
14 }
15 if !strings.Contains(Excerpt("```\ngeheim\n```\n\nZichtbaar", 40), "Zichtbaar") || strings.Contains(Excerpt("```\ngeheim\n```\n\nZichtbaar", 40), "geheim") {
16 t.Fatal("codeblok")
17 }
18 from, to, ok := ParseLines("#L10-20")
19 if !ok || from != 10 || to != 20 {
20 t.Fatalf("bereik %d %d %v", from, to, ok)
21 }
22 from, to, ok = ParseLines("L4")
23 if !ok || from != 4 || to != 4 {
24 t.Fatal(from, to)
25 }
26 lines := make([]string, 25)
27 for i := range lines {
28 lines[i] = "regel-" + string(rune('a'+i))
29 }
30 src := strings.Join(lines, "\n") + "\n"
31 snip := Snippet(src, 10, 12, true)
32 if snip != "regel-j\nregel-k\nregel-l" {
33 t.Fatalf("snippet %q", snip)
34 }
35}
36
37func TestLockedImageOmitsSecret(t *testing.T) {
38 secret := "ZXQGEHEIM"
39 locked := Locked("https://git.example/", "https://git.example/-/card.png?locked=1", "https://git.example/api/v1/oembed?locked=1")
40 svg := SVG(locked)
41 if strings.Contains(svg, secret) || !strings.Contains(svg, LockedTitle) {
42 t.Fatalf("svg:\n%s", svg)
43 }
44 pngBytes, err := Raster(svg)
45 if err != nil {
46 t.Fatal(err)
47 }
48 cfg, err := png.DecodeConfig(bytes.NewReader(pngBytes))
49 if err != nil || cfg.Width != Width || cfg.Height != Height {
50 t.Fatalf("png %v %v", cfg, err)
51 }
52 pub := locked
53 pub.Title = secret
54 pub.Description = secret
55 pub.Kind = "repository"
56 other, err := PNG(pub)
57 if err != nil {
58 t.Fatal(err)
59 }
60 if bytes.Equal(pngBytes, other) {
61 t.Fatal("verschillende kaarten hebben dezelfde png")
62 }
63 c := NewCache(2)
64 c.Put(svg, pngBytes)
65 if _, ok := c.Get(svg); !ok || c.Hits() != 1 {
66 t.Fatal("cache")
67 }
68}
69
70func TestBlurb(t *testing.T) {
71 m := Meta{Description: "regel-a\nregel-b", Facts: []string{"Go", "1 star"}}
72 if m.Blurb() != "regel-a / regel-b · Go · 1 star" {
73 t.Fatalf("blurb %q", m.Blurb())
74 }
75}
internal/i18n/catalog_social.go added +28 −0
@@ -0,0 +1,28 @@
1 package i18n
2
3 func init() {
4 addCatalog(en, socialEN)
5 addCatalog(nl, socialNL)
6 addCatalog(de, socialDE)
7 addCatalog(fr, socialFR)
8 }
9
10 var socialEN = map[string]string{
11 "info.sec.previews": "Link previews",
12 "info.card.lead": "BlueGit adds Open Graph, Twitter Card and oEmbed tags so a public link can show a card in chat. A repository card shows the name, the owner, the description or the first paragraph of the README, the main language, the stars, the latest commit, the avatar and a theme color. A merge request card shows the title, the status, the source and target branches, the author, the diff size, the pipeline status and the start of the description. An issue card shows the title, the status, the labels, the author and the start of the description. A group or user card shows the name, the description, the avatar and the number of repositories. Commits, pipelines, releases and files have their own cards. A file link accepts a line range as #L10-20 or as the L query, and that range is drawn as a code snippet. Each card image is a PNG drawn from SVG on the server, then cached, with an icon for the page type. The site name is BlueGit and the favicon stays the logo. A private or internal repository or group, and a confidential issue, always uses one generic card: BlueGit – inloggen vereist. The card is built as an anonymous visitor, even when the request sends a session cookie, and it never includes the name, the description or the README.",
13 }
14
15 var socialNL = map[string]string{
16 "info.sec.previews": "Linkvoorbeelden",
17 "info.card.lead": "BlueGit zet Open Graph-, Twitter Card- en oEmbed-tags zodat een openbare link een kaart toont in de chat. Een repositorykaart toont de naam, de eigenaar, de beschrijving of de eerste alinea van de README, de hoofdtaal, de sterren, de laatste commit, de avatar en een theme-color. Een merge-requestkaart toont de titel, de status, bron en doel, de auteur, de diffgrootte, de pipelinestatus en het begin van de beschrijving. Een issuekaart toont de titel, de status, de labels, de auteur en het begin van de beschrijving. Een groep- of gebruikerskaart toont de naam, de beschrijving, de avatar en het aantal repositories. Commits, pipelines, releases en bestanden hebben een eigen kaart. Een bestandslink neemt een regelbereik als #L10-20 of als de L-query, en dat bereik wordt een codefragment. Elke kaartafbeelding is een PNG die de server uit SVG tekent en daarna cachet, met een icoon voor het paginatype. De sitenaam is BlueGit en de favicon blijft het logo. Een private of internal repository of groep, en een vertrouwelijk issue, gebruikt altijd één generieke kaart: BlueGit – inloggen vereist. De kaart wordt als anonieme bezoeker gebouwd, ook als het verzoek een sessiecookie stuurt, en bevat nooit de naam, de beschrijving of de README.",
18 }
19
20 var socialDE = map[string]string{
21 "info.sec.previews": "Linkvorschauen",
22 "info.card.lead": "BlueGit setzt Open-Graph-, Twitter-Card- und oEmbed-Tags, damit ein öffentlicher Link eine Karte im Chat zeigt. Eine Repository-Karte zeigt Name, Eigentümer, Beschreibung oder den ersten Absatz der README, die Hauptsprache, die Sterne, den letzten Commit, den Avatar und eine Theme-Farbe. Eine Merge-Request-Karte zeigt Titel, Status, Quell- und Zielbranch, Autor, Diffgröße, Pipeline-Status und den Anfang der Beschreibung. Eine Issue-Karte zeigt Titel, Status, Labels, Autor und den Anfang der Beschreibung. Eine Gruppen- oder Benutzerkarte zeigt Name, Beschreibung, Avatar und die Anzahl der Repositories. Commits, Pipelines, Releases und Dateien haben eigene Karten. Ein Dateilink nimmt einen Zeilenbereich als #L10-20 oder als L-Query, und dieser Bereich wird ein Codeausschnitt. Jedes Kartenbild ist ein PNG, das der Server aus SVG zeichnet und danach zwischenspeichert, mit einem Symbol für den Seitentyp. Der Sitename ist BlueGit und das Favicon bleibt das Logo. Ein privates oder internes Repository oder eine solche Gruppe und ein vertrauliches Issue nutzen immer eine generische Karte: BlueGit – inloggen vereist. Die Karte entsteht als anonymer Besucher, auch wenn die Anfrage ein Sitzungscookie sendet, und enthält nie den Namen, die Beschreibung oder die README.",
23 }
24
25 var socialFR = map[string]string{
26 "info.sec.previews": "Aperçus de liens",
27 "info.card.lead": "BlueGit ajoute des balises Open Graph, Twitter Card et oEmbed pour qu un lien public montre une carte dans le chat. Une carte de dépôt montre le nom, le propriétaire, la description ou le premier paragraphe du README, le langage principal, les étoiles, le dernier commit, l avatar et une couleur de thème. Une carte de merge request montre le titre, le statut, les branches source et cible, l auteur, la taille du diff, le statut du pipeline et le début de la description. Une carte de ticket montre le titre, le statut, les étiquettes, l auteur et le début de la description. Une carte de groupe ou d utilisateur montre le nom, la description, l avatar et le nombre de dépôts. Les commits, les pipelines, les releases et les fichiers ont leur carte. Un lien de fichier accepte une plage de lignes comme #L10-20 ou comme paramètre L, et cette plage devient un extrait de code. Chaque image de carte est un PNG dessiné depuis du SVG sur le serveur, puis mis en cache, avec une icône du type de page. Le nom du site est BlueGit et le favicon reste le logo. Un dépôt ou un groupe privé ou interne, et un ticket confidentiel, utilisent toujours une carte générique : BlueGit – inloggen vereist. La carte est construite comme un visiteur anonyme, même si la requête envoie un cookie de session, et elle ne contient jamais le nom, la description ou le README.",
28 }
@@ -0,0 +1,28 @@
1package i18n
2
3func init() {
4 addCatalog(en, socialEN)
5 addCatalog(nl, socialNL)
6 addCatalog(de, socialDE)
7 addCatalog(fr, socialFR)
8}
9
10var socialEN = map[string]string{
11 "info.sec.previews": "Link previews",
12 "info.card.lead": "BlueGit adds Open Graph, Twitter Card and oEmbed tags so a public link can show a card in chat. A repository card shows the name, the owner, the description or the first paragraph of the README, the main language, the stars, the latest commit, the avatar and a theme color. A merge request card shows the title, the status, the source and target branches, the author, the diff size, the pipeline status and the start of the description. An issue card shows the title, the status, the labels, the author and the start of the description. A group or user card shows the name, the description, the avatar and the number of repositories. Commits, pipelines, releases and files have their own cards. A file link accepts a line range as #L10-20 or as the L query, and that range is drawn as a code snippet. Each card image is a PNG drawn from SVG on the server, then cached, with an icon for the page type. The site name is BlueGit and the favicon stays the logo. A private or internal repository or group, and a confidential issue, always uses one generic card: BlueGit – inloggen vereist. The card is built as an anonymous visitor, even when the request sends a session cookie, and it never includes the name, the description or the README.",
13}
14
15var socialNL = map[string]string{
16 "info.sec.previews": "Linkvoorbeelden",
17 "info.card.lead": "BlueGit zet Open Graph-, Twitter Card- en oEmbed-tags zodat een openbare link een kaart toont in de chat. Een repositorykaart toont de naam, de eigenaar, de beschrijving of de eerste alinea van de README, de hoofdtaal, de sterren, de laatste commit, de avatar en een theme-color. Een merge-requestkaart toont de titel, de status, bron en doel, de auteur, de diffgrootte, de pipelinestatus en het begin van de beschrijving. Een issuekaart toont de titel, de status, de labels, de auteur en het begin van de beschrijving. Een groep- of gebruikerskaart toont de naam, de beschrijving, de avatar en het aantal repositories. Commits, pipelines, releases en bestanden hebben een eigen kaart. Een bestandslink neemt een regelbereik als #L10-20 of als de L-query, en dat bereik wordt een codefragment. Elke kaartafbeelding is een PNG die de server uit SVG tekent en daarna cachet, met een icoon voor het paginatype. De sitenaam is BlueGit en de favicon blijft het logo. Een private of internal repository of groep, en een vertrouwelijk issue, gebruikt altijd één generieke kaart: BlueGit – inloggen vereist. De kaart wordt als anonieme bezoeker gebouwd, ook als het verzoek een sessiecookie stuurt, en bevat nooit de naam, de beschrijving of de README.",
18}
19
20var socialDE = map[string]string{
21 "info.sec.previews": "Linkvorschauen",
22 "info.card.lead": "BlueGit setzt Open-Graph-, Twitter-Card- und oEmbed-Tags, damit ein öffentlicher Link eine Karte im Chat zeigt. Eine Repository-Karte zeigt Name, Eigentümer, Beschreibung oder den ersten Absatz der README, die Hauptsprache, die Sterne, den letzten Commit, den Avatar und eine Theme-Farbe. Eine Merge-Request-Karte zeigt Titel, Status, Quell- und Zielbranch, Autor, Diffgröße, Pipeline-Status und den Anfang der Beschreibung. Eine Issue-Karte zeigt Titel, Status, Labels, Autor und den Anfang der Beschreibung. Eine Gruppen- oder Benutzerkarte zeigt Name, Beschreibung, Avatar und die Anzahl der Repositories. Commits, Pipelines, Releases und Dateien haben eigene Karten. Ein Dateilink nimmt einen Zeilenbereich als #L10-20 oder als L-Query, und dieser Bereich wird ein Codeausschnitt. Jedes Kartenbild ist ein PNG, das der Server aus SVG zeichnet und danach zwischenspeichert, mit einem Symbol für den Seitentyp. Der Sitename ist BlueGit und das Favicon bleibt das Logo. Ein privates oder internes Repository oder eine solche Gruppe und ein vertrauliches Issue nutzen immer eine generische Karte: BlueGit – inloggen vereist. Die Karte entsteht als anonymer Besucher, auch wenn die Anfrage ein Sitzungscookie sendet, und enthält nie den Namen, die Beschreibung oder die README.",
23}
24
25var socialFR = map[string]string{
26 "info.sec.previews": "Aperçus de liens",
27 "info.card.lead": "BlueGit ajoute des balises Open Graph, Twitter Card et oEmbed pour qu un lien public montre une carte dans le chat. Une carte de dépôt montre le nom, le propriétaire, la description ou le premier paragraphe du README, le langage principal, les étoiles, le dernier commit, l avatar et une couleur de thème. Une carte de merge request montre le titre, le statut, les branches source et cible, l auteur, la taille du diff, le statut du pipeline et le début de la description. Une carte de ticket montre le titre, le statut, les étiquettes, l auteur et le début de la description. Une carte de groupe ou d utilisateur montre le nom, la description, l avatar et le nombre de dépôts. Les commits, les pipelines, les releases et les fichiers ont leur carte. Un lien de fichier accepte une plage de lignes comme #L10-20 ou comme paramètre L, et cette plage devient un extrait de code. Chaque image de carte est un PNG dessiné depuis du SVG sur le serveur, puis mis en cache, avec une icône du type de page. Le nom du site est BlueGit et le favicon reste le logo. Un dépôt ou un groupe privé ou interne, et un ticket confidentiel, utilisent toujours une carte générique : BlueGit – inloggen vereist. La carte est construite comme un visiteur anonyme, même si la requête envoie un cookie de session, et elle ne contient jamais le nom, la description ou le README.",
28}
internal/server/issues.go +5 −1
@@ -408,7 +408,11 @@ func (s *Server) loadVisibleIssue(w http.ResponseWriter, r *http.Request, repo s
408 408 }
409 409 iss, err := s.Store.IssueByNumber(r.Context(), repo.ID, n)
410 410 if err != nil || !issueVisible(iss, u, role) {
411 http.NotFound(w, r)
411 if err == nil && iss.Confidential && isCrawler(r) {
412 s.writeLockedCard(w, r)
413 } else {
414 http.NotFound(w, r)
415 }
412 416 return store.Issue{}, false
413 417 }
414 418 return iss, true
@@ -408,7 +408,11 @@ func (s *Server) loadVisibleIssue(w http.ResponseWriter, r *http.Request, repo s
408 }
408 }
409 iss, err := s.Store.IssueByNumber(r.Context(), repo.ID, n)
409 iss, err := s.Store.IssueByNumber(r.Context(), repo.ID, n)
410 if err != nil || !issueVisible(iss, u, role) {
410 if err != nil || !issueVisible(iss, u, role) {
411 http.NotFound(w, r)
411 if err == nil && iss.Confidential && isCrawler(r) {
412 s.writeLockedCard(w, r)
413 } else {
414 http.NotFound(w, r)
415 }
412 return store.Issue{}, false
416 return store.Issue{}, false
413 }
417 }
414 return iss, true
418 return iss, true
internal/server/repo_handlers.go +7 −1
@@ -29,9 +29,15 @@ func (s *Server) guard(w http.ResponseWriter, r *http.Request, min access.Role)
29 29 return store.User{}, store.Repo{}, "", false
30 30 }
31 31 }
32 if isCrawler(r) {
33 p = principal{}
34 role = access.RoleNone
35 }
32 36 readable := role.CanRead() || repo.Visibility == "public"
33 37 if !readable {
34 if p.OK {
38 if isCrawler(r) {
39 s.writeLockedCard(w, r)
40 } else if p.OK {
35 41 http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
36 42 } else {
37 43 http.NotFound(w, r)
@@ -29,9 +29,15 @@ func (s *Server) guard(w http.ResponseWriter, r *http.Request, min access.Role)
29 return store.User{}, store.Repo{}, "", false
29 return store.User{}, store.Repo{}, "", false
30 }
30 }
31 }
31 }
32 if isCrawler(r) {
33 p = principal{}
34 role = access.RoleNone
35 }
32 readable := role.CanRead() || repo.Visibility == "public"
36 readable := role.CanRead() || repo.Visibility == "public"
33 if !readable {
37 if !readable {
34 if p.OK {
38 if isCrawler(r) {
39 s.writeLockedCard(w, r)
40 } else if p.OK {
35 http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
41 http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
36 } else {
42 } else {
37 http.NotFound(w, r)
43 http.NotFound(w, r)
internal/server/server.go +8 −1
@@ -19,6 +19,7 @@ import (
19 19 "gitlab.com/Timfa/bluegit/internal/access"
20 20 "gitlab.com/Timfa/bluegit/internal/activity"
21 21 "gitlab.com/Timfa/bluegit/internal/auth"
22 "gitlab.com/Timfa/bluegit/internal/card"
22 23 "gitlab.com/Timfa/bluegit/internal/cispec"
23 24 "gitlab.com/Timfa/bluegit/internal/config"
24 25 "gitlab.com/Timfa/bluegit/internal/i18n"
@@ -56,6 +57,7 @@ type Server struct {
56 57 storageMu sync.RWMutex
57 58 storage string
58 59 storageSet bool
60 cards *card.Cache
59 61 }
60 62
61 63 type principal struct {
@@ -72,6 +74,8 @@ func (s *Server) Handler() http.Handler {
72 74 mux := http.NewServeMux()
73 75 mux.HandleFunc("GET /assets/{file}", s.asset)
74 76 mux.HandleFunc("GET /-/info", s.infoPage)
77 mux.HandleFunc("GET /-/card.png", s.cardPNG)
78 mux.HandleFunc("GET /api/v1/oembed", s.oembed)
75 79 s.mountAPI(mux)
76 80 mux.HandleFunc("GET /api/v1/admin/self-update", s.selfUpdateStatus)
77 81 mux.HandleFunc("POST /api/v1/admin/self-update", s.selfUpdate)
@@ -445,11 +449,13 @@ func (s *Server) view(w http.ResponseWriter, r *http.Request, title string) View
445 449 for _, l := range i18n.All() {
446 450 v.Langs = append(v.Langs, LangChoice{Code: string(l), Label: l.Name()})
447 451 }
448 if p := s.who(r); p.OK {
452 if p := s.who(r); p.OK && !isCrawler(r) {
449 453 u := p.User
450 454 v.User = &u
451 455 v.CSRF = p.Session.CSRF
452 456 }
457 pic := s.cardForPath(r.Context(), r.URL.Path, r.URL.RawQuery, r.URL.Fragment)
458 v.Social = &pic.Meta
453 459 return v
454 460 }
455 461
@@ -608,6 +614,7 @@ type View struct {
608 614 DescTpls []string
609 615 TplPick string
610 616 FormBody string
617 Social *card.Meta
611 618 }
612 619
613 620 // LangChoice is één taal in de instellingen.
@@ -19,6 +19,7 @@ import (
19 "gitlab.com/Timfa/bluegit/internal/access"
19 "gitlab.com/Timfa/bluegit/internal/access"
20 "gitlab.com/Timfa/bluegit/internal/activity"
20 "gitlab.com/Timfa/bluegit/internal/activity"
21 "gitlab.com/Timfa/bluegit/internal/auth"
21 "gitlab.com/Timfa/bluegit/internal/auth"
22 "gitlab.com/Timfa/bluegit/internal/card"
22 "gitlab.com/Timfa/bluegit/internal/cispec"
23 "gitlab.com/Timfa/bluegit/internal/cispec"
23 "gitlab.com/Timfa/bluegit/internal/config"
24 "gitlab.com/Timfa/bluegit/internal/config"
24 "gitlab.com/Timfa/bluegit/internal/i18n"
25 "gitlab.com/Timfa/bluegit/internal/i18n"
@@ -56,6 +57,7 @@ type Server struct {
56 storageMu sync.RWMutex
57 storageMu sync.RWMutex
57 storage string
58 storage string
58 storageSet bool
59 storageSet bool
60 cards *card.Cache
59}
61}
60
62
61type principal struct {
63type principal struct {
@@ -72,6 +74,8 @@ func (s *Server) Handler() http.Handler {
72 mux := http.NewServeMux()
74 mux := http.NewServeMux()
73 mux.HandleFunc("GET /assets/{file}", s.asset)
75 mux.HandleFunc("GET /assets/{file}", s.asset)
74 mux.HandleFunc("GET /-/info", s.infoPage)
76 mux.HandleFunc("GET /-/info", s.infoPage)
77 mux.HandleFunc("GET /-/card.png", s.cardPNG)
78 mux.HandleFunc("GET /api/v1/oembed", s.oembed)
75 s.mountAPI(mux)
79 s.mountAPI(mux)
76 mux.HandleFunc("GET /api/v1/admin/self-update", s.selfUpdateStatus)
80 mux.HandleFunc("GET /api/v1/admin/self-update", s.selfUpdateStatus)
77 mux.HandleFunc("POST /api/v1/admin/self-update", s.selfUpdate)
81 mux.HandleFunc("POST /api/v1/admin/self-update", s.selfUpdate)
@@ -445,11 +449,13 @@ func (s *Server) view(w http.ResponseWriter, r *http.Request, title string) View
445 for _, l := range i18n.All() {
449 for _, l := range i18n.All() {
446 v.Langs = append(v.Langs, LangChoice{Code: string(l), Label: l.Name()})
450 v.Langs = append(v.Langs, LangChoice{Code: string(l), Label: l.Name()})
447 }
451 }
448 if p := s.who(r); p.OK {
452 if p := s.who(r); p.OK && !isCrawler(r) {
449 u := p.User
453 u := p.User
450 v.User = &u
454 v.User = &u
451 v.CSRF = p.Session.CSRF
455 v.CSRF = p.Session.CSRF
452 }
456 }
457 pic := s.cardForPath(r.Context(), r.URL.Path, r.URL.RawQuery, r.URL.Fragment)
458 v.Social = &pic.Meta
453 return v
459 return v
454}
460}
455
461
@@ -608,6 +614,7 @@ type View struct {
608 DescTpls []string
614 DescTpls []string
609 TplPick string
615 TplPick string
610 FormBody string
616 FormBody string
617 Social *card.Meta
611}
618}
612
619
613// LangChoice is één taal in de instellingen.
620// LangChoice is één taal in de instellingen.
internal/server/settings_handlers.go +7 −1
@@ -508,11 +508,17 @@ func (s *Server) guardGroup(w http.ResponseWriter, r *http.Request, min access.R
508 508 return store.Group{}, "", false
509 509 }
510 510 }
511 if isCrawler(r) {
512 p = principal{}
513 role = access.RoleNone
514 }
511 515 if min == access.RoleReadonly {
512 516 if role.CanRead() || g.Visibility == "public" {
513 517 return g, role, true
514 518 }
515 if p.OK {
519 if isCrawler(r) {
520 s.writeLockedCard(w, r)
521 } else if p.OK {
516 522 http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
517 523 } else {
518 524 http.NotFound(w, r)
@@ -508,11 +508,17 @@ func (s *Server) guardGroup(w http.ResponseWriter, r *http.Request, min access.R
508 return store.Group{}, "", false
508 return store.Group{}, "", false
509 }
509 }
510 }
510 }
511 if isCrawler(r) {
512 p = principal{}
513 role = access.RoleNone
514 }
511 if min == access.RoleReadonly {
515 if min == access.RoleReadonly {
512 if role.CanRead() || g.Visibility == "public" {
516 if role.CanRead() || g.Visibility == "public" {
513 return g, role, true
517 return g, role, true
514 }
518 }
515 if p.OK {
519 if isCrawler(r) {
520 s.writeLockedCard(w, r)
521 } else if p.OK {
516 http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
522 http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
517 } else {
523 } else {
518 http.NotFound(w, r)
524 http.NotFound(w, r)
internal/server/social.go added +629 −0
@@ -0,0 +1,629 @@
1 package server
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "html"
9 "image"
10 _ "image/gif"
11 _ "image/jpeg"
12 "image/png"
13 "net/http"
14 "net/url"
15 "os"
16 "strconv"
17 "strings"
18
19 "gitlab.com/Timfa/bluegit/internal/card"
20 "gitlab.com/Timfa/bluegit/internal/gitrepo"
21 "gitlab.com/Timfa/bluegit/internal/store"
22 )
23
24 func (s *Server) cardCache() *card.Cache {
25 if s.cards == nil {
26 s.cards = card.NewCache(128)
27 }
28 return s.cards
29 }
30
31 func (s *Server) absURL(path string) string {
32 base := strings.TrimRight(s.Cfg.BaseURL, "/")
33 if path == "" {
34 path = "/"
35 }
36 if !strings.HasPrefix(path, "/") {
37 path = "/" + path
38 }
39 return base + path
40 }
41
42 func (s *Server) lockedRender() card.Render {
43 return card.Locked(s.absURL("/"), s.absURL("/-/card.png?locked=1"), s.absURL("/api/v1/oembed?locked=1"))
44 }
45
46 // cardForPath bouwt de kaart als anonieme bezoeker. De sessie wordt niet gelezen.
47 func (s *Server) cardForPath(ctx context.Context, path, rawQuery, fragment string) card.Render {
48 path = "/" + strings.Trim(strings.TrimSpace(path), "/")
49 if path == "/" {
50 return s.siteRender(path, rawQuery)
51 }
52 page := s.absURL(path)
53 if rawQuery != "" {
54 page += "?" + rawQuery
55 }
56 img := s.imageFor(path, rawQuery, fragment)
57 oem := s.oembedFor(page)
58 if s.Store == nil {
59 return card.Site(page, img, oem)
60 }
61 if strings.HasPrefix(path, "/groups/") {
62 return s.groupCard(ctx, strings.TrimPrefix(path, "/groups/"), page, img, oem)
63 }
64 if strings.HasPrefix(path, "/users/") {
65 name := strings.Trim(strings.TrimPrefix(path, "/users/"), "/")
66 if i := strings.Index(name, "/"); i >= 0 {
67 name = name[:i]
68 }
69 return s.userCard(ctx, name, page, img, oem)
70 }
71 parts := strings.Split(strings.Trim(path, "/"), "/")
72 if len(parts) < 2 || strings.HasPrefix(parts[0], "-") {
73 return card.Site(page, img, oem)
74 }
75 repo, err := s.Store.RepoByPath(ctx, parts[0], strings.TrimSuffix(parts[1], ".git"))
76 if err != nil {
77 return card.Site(page, img, oem)
78 }
79 if repo.Visibility != "public" {
80 return s.lockedRender()
81 }
82 q, _ := url.ParseQuery(rawQuery)
83 return s.publicRepoCard(ctx, repo, parts[2:], q, fragment, page, img, oem)
84 }
85
86 func (s *Server) siteRender(path, rawQuery string) card.Render {
87 page := s.absURL(path)
88 if rawQuery != "" {
89 page += "?" + rawQuery
90 }
91 return card.Site(page, s.imageFor(path, rawQuery, ""), s.oembedFor(page))
92 }
93
94 func (s *Server) imageFor(path, rawQuery, fragment string) string {
95 v := url.Values{}
96 v.Set("path", path)
97 q, _ := url.ParseQuery(rawQuery)
98 if l := q.Get("L"); l != "" {
99 v.Set("L", l)
100 } else if _, _, ok := card.ParseLines(fragment); ok {
101 v.Set("L", strings.TrimPrefix(strings.TrimSpace(fragment), "#"))
102 }
103 if rev := q.Get("rev"); rev != "" {
104 v.Set("rev", rev)
105 }
106 return s.absURL("/-/card.png?" + v.Encode())
107 }
108
109 func (s *Server) oembedFor(page string) string {
110 return s.absURL("/api/v1/oembed?url=" + url.QueryEscape(page))
111 }
112
113 func (s *Server) publicRepoCard(ctx context.Context, repo store.Repo, rest []string, q url.Values, fragment, page, img, oem string) card.Render {
114 kind := ""
115 if len(rest) >= 2 && rest[0] == "-" {
116 kind = rest[1]
117 }
118 switch kind {
119 case "blob":
120 return s.fileCard(ctx, repo, strings.Join(rest[2:], "/"), q, fragment, page, img, oem)
121 case "tree":
122 return s.repoCard(ctx, repo, page, img, oem)
123 case "commit":
124 if len(rest) >= 3 {
125 return s.commitCard(ctx, repo, rest[2], page, img, oem)
126 }
127 case "merge-requests":
128 if len(rest) >= 3 && rest[2] != "new" {
129 if n, err := strconv.ParseInt(rest[2], 10, 64); err == nil {
130 return s.mrCard(ctx, repo, n, page, img, oem)
131 }
132 }
133 case "issues":
134 if len(rest) >= 3 {
135 if n, err := strconv.ParseInt(rest[2], 10, 64); err == nil && n > 0 {
136 return s.issueCard(ctx, repo, n, page, img, oem)
137 }
138 }
139 case "pipelines":
140 if len(rest) >= 3 {
141 if n, err := strconv.ParseInt(rest[2], 10, 64); err == nil && n > 0 {
142 return s.pipeCard(ctx, repo, n, page, img, oem)
143 }
144 }
145 case "releases":
146 return s.releaseCard(ctx, repo, page, img, oem)
147 }
148 return s.repoCard(ctx, repo, page, img, oem)
149 }
150
151 func (s *Server) repoCard(ctx context.Context, repo store.Repo, page, img, oem string) card.Render {
152 prose := card.Excerpt(repo.Description, 180)
153 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
154 rev := repo.DefaultBranch
155 if prose == "" && s.StoragePath() != "" {
156 if entries, err := gitrepo.Tree(ctx, s.Git, dir, rev, ""); err == nil {
157 readme, _ := findDocs(entries)
158 if readme != "" {
159 if text, binary, err := gitrepo.Blob(ctx, s.Git, dir, rev, readme, 80_000); err == nil && !binary {
160 prose = card.Excerpt(text, 180)
161 }
162 }
163 }
164 }
165 var facts []string
166 if lang := s.repoLanguage(ctx, dir, rev); lang != "" {
167 facts = append(facts, lang)
168 }
169 if counts, _, err := s.Store.StarInfo(ctx, 0, []int64{repo.ID}); err == nil {
170 facts = append(facts, starLabel(counts[repo.ID]))
171 }
172 if s.StoragePath() != "" {
173 if c, err := gitrepo.LastCommit(ctx, s.Git, dir, rev, ""); err == nil && c.SHA != "" {
174 short := c.SHA
175 if len(short) > 8 {
176 short = short[:8]
177 }
178 facts = append(facts, short+" "+card.Clip(c.Subject, 72))
179 }
180 }
181 return card.Render{Meta: card.Meta{
182 Title: repo.OwnerPath + "/" + repo.Name, Description: prose, URL: page, Image: img, OEmbed: oem,
183 Theme: "#1f6feb", Kind: "repository", Facts: facts, Initial: repo.Name,
184 }, Avatar: s.avatarForRepo(ctx, repo)}
185 }
186
187 func (s *Server) fileCard(ctx context.Context, repo store.Repo, rel string, q url.Values, fragment, page, img, oem string) card.Render {
188 rel, err := cleanRel(rel)
189 base := s.repoCard(ctx, repo, page, img, oem)
190 if err != nil || rel == "" || s.StoragePath() == "" {
191 return base
192 }
193 rev := safeRev(q.Get("rev"), repo.DefaultBranch)
194 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
195 text, binary, err := gitrepo.Blob(ctx, s.Git, dir, rev, rel, 80_000)
196 name := rel
197 if i := strings.LastIndex(rel, "/"); i >= 0 {
198 name = rel[i+1:]
199 }
200 from, to, ranged := lineBounds(q, fragment)
201 desc := "Binary file"
202 if err == nil && !binary {
203 desc = card.Snippet(text, from, to, ranged)
204 }
205 facts := []string{repo.OwnerPath + "/" + repo.Name}
206 if lang := langByName(name); lang != "" {
207 facts = append(facts, lang)
208 }
209 if ranged {
210 if from == to {
211 facts = append(facts, fmt.Sprintf("L%d", from))
212 } else {
213 facts = append(facts, fmt.Sprintf("L%d-%d", from, to))
214 }
215 }
216 return card.Render{Meta: card.Meta{
217 Title: name, Description: desc, URL: page, Image: img, OEmbed: oem,
218 Theme: "#1f6feb", Kind: "file", Facts: facts, Initial: name,
219 }, Avatar: base.Avatar}
220 }
221
222 func (s *Server) commitCard(ctx context.Context, repo store.Repo, sha, page, img, oem string) card.Render {
223 base := s.repoCard(ctx, repo, page, img, oem)
224 if !safeSHA(sha) || s.StoragePath() == "" {
225 return base
226 }
227 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
228 c, err := gitrepo.Show(ctx, s.Git, dir, sha)
229 if err != nil {
230 return base
231 }
232 short := c.SHA
233 if len(short) > 8 {
234 short = short[:8]
235 }
236 facts := []string{c.Author, short}
237 if changes, err := gitrepo.CommitChanges(ctx, s.Git, dir, c.SHA); err == nil {
238 add, del := 0, 0
239 for _, ch := range changes {
240 add += ch.Added
241 del += ch.Deleted
242 }
243 facts = append(facts, fmt.Sprintf("+%d −%d", add, del), fmt.Sprintf("%d files", len(changes)))
244 }
245 return card.Render{Meta: card.Meta{
246 Title: card.Clip(c.Subject, 90), Description: card.Excerpt(c.Body, 180), URL: page, Image: img, OEmbed: oem,
247 Theme: "#0c3f86", Kind: "commit", Facts: facts, Initial: c.Author,
248 }, Avatar: base.Avatar}
249 }
250
251 func (s *Server) mrCard(ctx context.Context, repo store.Repo, number int64, page, img, oem string) card.Render {
252 base := s.repoCard(ctx, repo, page, img, oem)
253 mr, err := s.Store.MergeRequestByNumber(ctx, repo.ID, number)
254 if err != nil {
255 return base
256 }
257 status := mr.Status
258 if mr.Draft && status == "open" {
259 status = "draft"
260 }
261 facts := []string{status, mr.SourceBranch + " → " + mr.TargetBranch, mr.Author}
262 if s.StoragePath() != "" {
263 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
264 if changes, err := gitrepo.CompareChanges(ctx, s.Git, dir, mr.TargetBranch, mr.SourceBranch); err == nil {
265 add, del := 0, 0
266 for _, ch := range changes {
267 add += ch.Added
268 del += ch.Deleted
269 }
270 facts = append(facts, fmt.Sprintf("+%d −%d", add, del))
271 }
272 }
273 if p, err := s.Store.LatestMergePipeline(ctx, repo.ID, mr.ID); err == nil {
274 jobs, _ := s.Store.JobsByPipeline(ctx, p.ID)
275 facts = append(facts, displayStatus(p.Status, jobs))
276 }
277 theme := "#1f6feb"
278 switch status {
279 case "merged":
280 theme = "#146c43"
281 case "closed":
282 theme = "#5c6b80"
283 }
284 return card.Render{Meta: card.Meta{
285 Title: "!" + strconv.FormatInt(mr.Number, 10) + " " + mr.Title,
286 Description: card.Excerpt(mr.Description, 180), URL: page, Image: img, OEmbed: oem,
287 Theme: theme, Kind: "merge_request", Facts: facts, Initial: mr.Author,
288 }, Avatar: base.Avatar}
289 }
290
291 func (s *Server) issueCard(ctx context.Context, repo store.Repo, number int64, page, img, oem string) card.Render {
292 iss, err := s.Store.IssueByNumber(ctx, repo.ID, number)
293 if err != nil {
294 return s.repoCard(ctx, repo, page, img, oem)
295 }
296 if iss.Confidential {
297 return s.lockedRender()
298 }
299 var labels []string
300 for _, l := range iss.Labels {
301 labels = append(labels, l.Name)
302 }
303 facts := []string{iss.Status}
304 if len(labels) > 0 {
305 facts = append(facts, strings.Join(labels, ", "))
306 }
307 facts = append(facts, iss.Author)
308 return card.Render{Meta: card.Meta{
309 Title: "#" + strconv.FormatInt(iss.Number, 10) + " " + iss.Title,
310 Description: card.Excerpt(iss.Description, 180), URL: page, Image: img, OEmbed: oem,
311 Theme: "#9a6700", Kind: "issue", Facts: facts, Initial: iss.Author,
312 }, Avatar: s.avatarForRepo(ctx, repo)}
313 }
314
315 func (s *Server) pipeCard(ctx context.Context, repo store.Repo, id int64, page, img, oem string) card.Render {
316 base := s.repoCard(ctx, repo, page, img, oem)
317 p, err := s.Store.PipelineByID(ctx, repo.ID, id)
318 if err != nil {
319 return base
320 }
321 jobs, _ := s.Store.JobsByPipeline(ctx, p.ID)
322 status := displayStatus(p.Status, jobs)
323 theme := "#1f6feb"
324 switch status {
325 case "passed":
326 theme = "#146c43"
327 case "failed":
328 theme = "#9f2d2d"
329 case "running":
330 theme = "#9a6700"
331 }
332 facts := []string{status}
333 if p.Ref != "" {
334 facts = append(facts, strings.TrimPrefix(p.Ref, "refs/heads/"))
335 }
336 if p.CommitTitle != "" {
337 facts = append(facts, card.Clip(p.CommitTitle, 72))
338 }
339 if p.Actor != "" {
340 facts = append(facts, p.Actor)
341 }
342 return card.Render{Meta: card.Meta{
343 Title: "#" + strconv.FormatInt(p.ID, 10) + " " + status, Description: card.Excerpt(p.CommitTitle, 180),
344 URL: page, Image: img, OEmbed: oem, Theme: theme, Kind: "pipeline", Facts: facts, Initial: repo.Name,
345 }, Avatar: base.Avatar}
346 }
347
348 func (s *Server) releaseCard(ctx context.Context, repo store.Repo, page, img, oem string) card.Render {
349 base := s.repoCard(ctx, repo, page, img, oem)
350 list, err := s.Store.ListReleases(ctx, repo.ID)
351 if err != nil || len(list) == 0 {
352 return card.Render{Meta: card.Meta{
353 Title: "Releases", Description: repo.OwnerPath + "/" + repo.Name, URL: page, Image: img, OEmbed: oem,
354 Theme: "#146c43", Kind: "release", Initial: repo.Name,
355 }, Avatar: base.Avatar}
356 }
357 rel := list[0]
358 title := rel.Tag
359 if rel.Name != "" {
360 title = rel.Tag + " · " + rel.Name
361 }
362 return card.Render{Meta: card.Meta{
363 Title: title, Description: card.Excerpt(rel.Body, 180), URL: page, Image: img, OEmbed: oem,
364 Theme: "#146c43", Kind: "release", Facts: []string{repo.OwnerPath + "/" + repo.Name, rel.Tag}, Initial: repo.Name,
365 }, Avatar: base.Avatar}
366 }
367
368 func (s *Server) groupCard(ctx context.Context, rest, page, img, oem string) card.Render {
369 name := rest
370 if i := strings.Index(name, "/"); i >= 0 {
371 name = name[:i]
372 }
373 g, err := s.Store.GroupByPath(ctx, name)
374 if err != nil {
375 return card.Site(page, img, oem)
376 }
377 if g.Visibility != "public" {
378 return s.lockedRender()
379 }
380 n, _ := s.Store.CountRepos(ctx, "group", g.ID, true)
381 return card.Render{Meta: card.Meta{
382 Title: g.Name, Description: card.Excerpt(g.Description, 180), URL: page, Image: img, OEmbed: oem,
383 Theme: "#6f42c1", Kind: "group", Facts: []string{repoLabel(n)}, Initial: g.Name,
384 }, Avatar: s.readLogo("group", g.ID, g.LogoMIME)}
385 }
386
387 func (s *Server) userCard(ctx context.Context, name, page, img, oem string) card.Render {
388 u, err := s.Store.UserByUsername(ctx, name)
389 if err != nil {
390 return card.Site(page, img, oem)
391 }
392 n, _ := s.Store.CountRepos(ctx, "user", u.ID, true)
393 return card.Render{Meta: card.Meta{
394 Title: u.Username, Description: "Public profile", URL: page, Image: img, OEmbed: oem,
395 Theme: "#1f6feb", Kind: "user", Facts: []string{repoLabel(n)}, Initial: u.Username,
396 }}
397 }
398
399 func (s *Server) avatarForRepo(ctx context.Context, repo store.Repo) []byte {
400 if b := s.readLogo("repo", repo.ID, repo.LogoMIME); len(b) > 0 {
401 return b
402 }
403 if repo.OwnerKind != "group" {
404 return nil
405 }
406 g, err := s.Store.GroupByID(ctx, repo.OwnerID)
407 if err != nil {
408 return nil
409 }
410 return s.readLogo("group", g.ID, g.LogoMIME)
411 }
412
413 func (s *Server) readLogo(kind string, id int64, mime string) []byte {
414 if mime != "image/png" && mime != "image/jpeg" && mime != "image/gif" {
415 return nil
416 }
417 path, err := s.logoPath(kind, id)
418 if err != nil {
419 return nil
420 }
421 data, err := os.ReadFile(path)
422 if err != nil {
423 return nil
424 }
425 img, _, err := image.Decode(bytes.NewReader(data))
426 if err != nil {
427 return nil
428 }
429 var buf bytes.Buffer
430 if err := png.Encode(&buf, img); err != nil {
431 return nil
432 }
433 return buf.Bytes()
434 }
435
436 func (s *Server) repoLanguage(ctx context.Context, dir, rev string) string {
437 if s.StoragePath() == "" {
438 return ""
439 }
440 entries, err := gitrepo.TreeAll(ctx, s.Git, dir, rev)
441 if err != nil {
442 return ""
443 }
444 counts := map[string]int{}
445 for _, e := range entries {
446 if e.Type != "blob" {
447 continue
448 }
449 if strings.Contains(e.Name, "vendor/") || strings.Contains(e.Name, "node_modules/") {
450 continue
451 }
452 if lang := langByName(e.Name); lang != "" {
453 counts[lang]++
454 }
455 }
456 best, n := "", 0
457 for lang, c := range counts {
458 if c > n || (c == n && lang < best) {
459 best, n = lang, c
460 }
461 }
462 return best
463 }
464
465 func langByName(name string) string {
466 low := strings.ToLower(name)
467 if i := strings.LastIndex(low, "/"); i >= 0 {
468 low = low[i+1:]
469 }
470 ext := ""
471 if i := strings.LastIndex(low, "."); i >= 0 {
472 ext = low[i:]
473 }
474 if lang, ok := extLang[ext]; ok {
475 return lang
476 }
477 switch low {
478 case "dockerfile":
479 return "Dockerfile"
480 case "makefile":
481 return "Makefile"
482 default:
483 return ""
484 }
485 }
486
487 var extLang = map[string]string{
488 ".go": "Go", ".py": "Python", ".js": "JavaScript", ".jsx": "JavaScript", ".ts": "TypeScript", ".tsx": "TypeScript",
489 ".rs": "Rust", ".java": "Java", ".rb": "Ruby", ".php": "PHP", ".c": "C", ".h": "C", ".cpp": "C++", ".cc": "C++",
490 ".cs": "C#", ".swift": "Swift", ".kt": "Kotlin", ".html": "HTML", ".css": "CSS", ".scss": "SCSS", ".vue": "Vue",
491 ".sh": "Shell", ".yml": "YAML", ".yaml": "YAML", ".sql": "SQL", ".lua": "Lua",
492 }
493
494 func starLabel(n int) string {
495 if n == 1 {
496 return "1 star"
497 }
498 return strconv.Itoa(n) + " stars"
499 }
500
501 func repoLabel(n int) string {
502 if n == 1 {
503 return "1 repository"
504 }
505 return strconv.Itoa(n) + " repositories"
506 }
507
508 func lineBounds(q url.Values, fragment string) (from, to int, ok bool) {
509 if from, to, ok = card.ParseLines(fragment); ok {
510 return from, to, true
511 }
512 return card.ParseLines(q.Get("L"))
513 }
514
515 func (s *Server) cardPNG(w http.ResponseWriter, r *http.Request) {
516 var rend card.Render
517 if r.URL.Query().Get("locked") == "1" {
518 rend = s.lockedRender()
519 } else {
520 path := r.URL.Query().Get("path")
521 if !strings.HasPrefix(path, "/") || strings.Contains(path, "..") || strings.Contains(path, "\\") {
522 http.NotFound(w, r)
523 return
524 }
525 q := url.Values{}
526 if l := r.URL.Query().Get("L"); l != "" {
527 q.Set("L", l)
528 }
529 if rev := r.URL.Query().Get("rev"); rev != "" {
530 q.Set("rev", rev)
531 }
532 rend = s.cardForPath(r.Context(), path, q.Encode(), "")
533 }
534 svg := card.SVG(rend)
535 pngBytes, hit := s.cardCache().Get(svg)
536 if !hit {
537 var err error
538 pngBytes, err = card.Raster(svg)
539 if err != nil {
540 http.Error(w, "card", http.StatusInternalServerError)
541 return
542 }
543 s.cardCache().Put(svg, pngBytes)
544 }
545 w.Header().Set("Content-Type", "image/png")
546 w.Header().Set("Cache-Control", "public, max-age=300")
547 w.Header().Set("X-Content-Type-Options", "nosniff")
548 if hit {
549 w.Header().Set("X-Card-Cache", "hit")
550 } else {
551 w.Header().Set("X-Card-Cache", "miss")
552 }
553 _, _ = w.Write(pngBytes)
554 }
555
556 func (s *Server) oembed(w http.ResponseWriter, r *http.Request) {
557 var rend card.Render
558 if r.URL.Query().Get("locked") == "1" {
559 rend = s.lockedRender()
560 } else {
561 raw := r.URL.Query().Get("url")
562 u, err := url.Parse(raw)
563 if err != nil || u.Path == "" {
564 http.NotFound(w, r)
565 return
566 }
567 rend = s.cardForPath(r.Context(), u.Path, u.RawQuery, u.Fragment)
568 }
569 w.Header().Set("Content-Type", "application/json; charset=utf-8")
570 w.Header().Set("Cache-Control", "no-store")
571 _ = json.NewEncoder(w).Encode(map[string]any{
572 "version": "1.0",
573 "type": "link",
574 "title": rend.Title,
575 "description": rend.Blurb(),
576 "provider_name": "BlueGit",
577 "provider_url": s.absURL("/"),
578 "thumbnail_url": rend.Image,
579 "thumbnail_width": card.Width,
580 "thumbnail_height": card.Height,
581 })
582 }
583
584 func (s *Server) writeLockedCard(w http.ResponseWriter, r *http.Request) {
585 m := s.lockedRender().Meta
586 w.Header().Set("Content-Type", "text/html; charset=utf-8")
587 w.Header().Set("Cache-Control", "no-store")
588 w.Header().Set("X-Robots-Tag", "noindex")
589 w.WriteHeader(http.StatusOK)
590 title := html.EscapeString(m.Title)
591 fmt.Fprintf(w, `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>%s</title>%s<link rel="icon" href="/assets/logo.svg" type="image/svg+xml"></head><body><p>%s</p></body></html>`,
592 title, metaHTML(m), title)
593 }
594
595 func metaHTML(m card.Meta) string {
596 esc := html.EscapeString
597 var b strings.Builder
598 fmt.Fprintf(&b, `<meta name="theme-color" content="%s">`, esc(m.Theme))
599 fmt.Fprintf(&b, `<meta name="description" content="%s">`, esc(m.Blurb()))
600 b.WriteString(`<meta property="og:site_name" content="BlueGit">`)
601 b.WriteString(`<meta property="og:type" content="website">`)
602 fmt.Fprintf(&b, `<meta property="og:title" content="%s">`, esc(m.Title))
603 fmt.Fprintf(&b, `<meta property="og:description" content="%s">`, esc(m.Blurb()))
604 fmt.Fprintf(&b, `<meta property="og:url" content="%s">`, esc(m.URL))
605 fmt.Fprintf(&b, `<meta property="og:image" content="%s">`, esc(m.Image))
606 b.WriteString(`<meta property="og:image:type" content="image/png">`)
607 fmt.Fprintf(&b, `<meta property="og:image:width" content="%d">`, card.Width)
608 fmt.Fprintf(&b, `<meta property="og:image:height" content="%d">`, card.Height)
609 b.WriteString(`<meta name="twitter:card" content="summary_large_image">`)
610 fmt.Fprintf(&b, `<meta name="twitter:title" content="%s">`, esc(m.Title))
611 fmt.Fprintf(&b, `<meta name="twitter:description" content="%s">`, esc(m.Blurb()))
612 fmt.Fprintf(&b, `<meta name="twitter:image" content="%s">`, esc(m.Image))
613 fmt.Fprintf(&b, `<link rel="alternate" type="application/json+oembed" href="%s" title="BlueGit">`, esc(m.OEmbed))
614 return b.String()
615 }
616
617 func isCrawler(r *http.Request) bool {
618 ua := strings.ToLower(r.Header.Get("User-Agent"))
619 for _, name := range []string{
620 "discordbot", "slackbot", "twitterbot", "facebookexternalhit", "linkedinbot",
621 "telegrambot", "whatsapp", "embedly", "iframely", "redditbot", "pinterestbot",
622 "skypeuripreview",
623 } {
624 if strings.Contains(ua, name) {
625 return true
626 }
627 }
628 return false
629 }
@@ -0,0 +1,629 @@
1package server
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "html"
9 "image"
10 _ "image/gif"
11 _ "image/jpeg"
12 "image/png"
13 "net/http"
14 "net/url"
15 "os"
16 "strconv"
17 "strings"
18
19 "gitlab.com/Timfa/bluegit/internal/card"
20 "gitlab.com/Timfa/bluegit/internal/gitrepo"
21 "gitlab.com/Timfa/bluegit/internal/store"
22)
23
24func (s *Server) cardCache() *card.Cache {
25 if s.cards == nil {
26 s.cards = card.NewCache(128)
27 }
28 return s.cards
29}
30
31func (s *Server) absURL(path string) string {
32 base := strings.TrimRight(s.Cfg.BaseURL, "/")
33 if path == "" {
34 path = "/"
35 }
36 if !strings.HasPrefix(path, "/") {
37 path = "/" + path
38 }
39 return base + path
40}
41
42func (s *Server) lockedRender() card.Render {
43 return card.Locked(s.absURL("/"), s.absURL("/-/card.png?locked=1"), s.absURL("/api/v1/oembed?locked=1"))
44}
45
46// cardForPath bouwt de kaart als anonieme bezoeker. De sessie wordt niet gelezen.
47func (s *Server) cardForPath(ctx context.Context, path, rawQuery, fragment string) card.Render {
48 path = "/" + strings.Trim(strings.TrimSpace(path), "/")
49 if path == "/" {
50 return s.siteRender(path, rawQuery)
51 }
52 page := s.absURL(path)
53 if rawQuery != "" {
54 page += "?" + rawQuery
55 }
56 img := s.imageFor(path, rawQuery, fragment)
57 oem := s.oembedFor(page)
58 if s.Store == nil {
59 return card.Site(page, img, oem)
60 }
61 if strings.HasPrefix(path, "/groups/") {
62 return s.groupCard(ctx, strings.TrimPrefix(path, "/groups/"), page, img, oem)
63 }
64 if strings.HasPrefix(path, "/users/") {
65 name := strings.Trim(strings.TrimPrefix(path, "/users/"), "/")
66 if i := strings.Index(name, "/"); i >= 0 {
67 name = name[:i]
68 }
69 return s.userCard(ctx, name, page, img, oem)
70 }
71 parts := strings.Split(strings.Trim(path, "/"), "/")
72 if len(parts) < 2 || strings.HasPrefix(parts[0], "-") {
73 return card.Site(page, img, oem)
74 }
75 repo, err := s.Store.RepoByPath(ctx, parts[0], strings.TrimSuffix(parts[1], ".git"))
76 if err != nil {
77 return card.Site(page, img, oem)
78 }
79 if repo.Visibility != "public" {
80 return s.lockedRender()
81 }
82 q, _ := url.ParseQuery(rawQuery)
83 return s.publicRepoCard(ctx, repo, parts[2:], q, fragment, page, img, oem)
84}
85
86func (s *Server) siteRender(path, rawQuery string) card.Render {
87 page := s.absURL(path)
88 if rawQuery != "" {
89 page += "?" + rawQuery
90 }
91 return card.Site(page, s.imageFor(path, rawQuery, ""), s.oembedFor(page))
92}
93
94func (s *Server) imageFor(path, rawQuery, fragment string) string {
95 v := url.Values{}
96 v.Set("path", path)
97 q, _ := url.ParseQuery(rawQuery)
98 if l := q.Get("L"); l != "" {
99 v.Set("L", l)
100 } else if _, _, ok := card.ParseLines(fragment); ok {
101 v.Set("L", strings.TrimPrefix(strings.TrimSpace(fragment), "#"))
102 }
103 if rev := q.Get("rev"); rev != "" {
104 v.Set("rev", rev)
105 }
106 return s.absURL("/-/card.png?" + v.Encode())
107}
108
109func (s *Server) oembedFor(page string) string {
110 return s.absURL("/api/v1/oembed?url=" + url.QueryEscape(page))
111}
112
113func (s *Server) publicRepoCard(ctx context.Context, repo store.Repo, rest []string, q url.Values, fragment, page, img, oem string) card.Render {
114 kind := ""
115 if len(rest) >= 2 && rest[0] == "-" {
116 kind = rest[1]
117 }
118 switch kind {
119 case "blob":
120 return s.fileCard(ctx, repo, strings.Join(rest[2:], "/"), q, fragment, page, img, oem)
121 case "tree":
122 return s.repoCard(ctx, repo, page, img, oem)
123 case "commit":
124 if len(rest) >= 3 {
125 return s.commitCard(ctx, repo, rest[2], page, img, oem)
126 }
127 case "merge-requests":
128 if len(rest) >= 3 && rest[2] != "new" {
129 if n, err := strconv.ParseInt(rest[2], 10, 64); err == nil {
130 return s.mrCard(ctx, repo, n, page, img, oem)
131 }
132 }
133 case "issues":
134 if len(rest) >= 3 {
135 if n, err := strconv.ParseInt(rest[2], 10, 64); err == nil && n > 0 {
136 return s.issueCard(ctx, repo, n, page, img, oem)
137 }
138 }
139 case "pipelines":
140 if len(rest) >= 3 {
141 if n, err := strconv.ParseInt(rest[2], 10, 64); err == nil && n > 0 {
142 return s.pipeCard(ctx, repo, n, page, img, oem)
143 }
144 }
145 case "releases":
146 return s.releaseCard(ctx, repo, page, img, oem)
147 }
148 return s.repoCard(ctx, repo, page, img, oem)
149}
150
151func (s *Server) repoCard(ctx context.Context, repo store.Repo, page, img, oem string) card.Render {
152 prose := card.Excerpt(repo.Description, 180)
153 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
154 rev := repo.DefaultBranch
155 if prose == "" && s.StoragePath() != "" {
156 if entries, err := gitrepo.Tree(ctx, s.Git, dir, rev, ""); err == nil {
157 readme, _ := findDocs(entries)
158 if readme != "" {
159 if text, binary, err := gitrepo.Blob(ctx, s.Git, dir, rev, readme, 80_000); err == nil && !binary {
160 prose = card.Excerpt(text, 180)
161 }
162 }
163 }
164 }
165 var facts []string
166 if lang := s.repoLanguage(ctx, dir, rev); lang != "" {
167 facts = append(facts, lang)
168 }
169 if counts, _, err := s.Store.StarInfo(ctx, 0, []int64{repo.ID}); err == nil {
170 facts = append(facts, starLabel(counts[repo.ID]))
171 }
172 if s.StoragePath() != "" {
173 if c, err := gitrepo.LastCommit(ctx, s.Git, dir, rev, ""); err == nil && c.SHA != "" {
174 short := c.SHA
175 if len(short) > 8 {
176 short = short[:8]
177 }
178 facts = append(facts, short+" "+card.Clip(c.Subject, 72))
179 }
180 }
181 return card.Render{Meta: card.Meta{
182 Title: repo.OwnerPath + "/" + repo.Name, Description: prose, URL: page, Image: img, OEmbed: oem,
183 Theme: "#1f6feb", Kind: "repository", Facts: facts, Initial: repo.Name,
184 }, Avatar: s.avatarForRepo(ctx, repo)}
185}
186
187func (s *Server) fileCard(ctx context.Context, repo store.Repo, rel string, q url.Values, fragment, page, img, oem string) card.Render {
188 rel, err := cleanRel(rel)
189 base := s.repoCard(ctx, repo, page, img, oem)
190 if err != nil || rel == "" || s.StoragePath() == "" {
191 return base
192 }
193 rev := safeRev(q.Get("rev"), repo.DefaultBranch)
194 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
195 text, binary, err := gitrepo.Blob(ctx, s.Git, dir, rev, rel, 80_000)
196 name := rel
197 if i := strings.LastIndex(rel, "/"); i >= 0 {
198 name = rel[i+1:]
199 }
200 from, to, ranged := lineBounds(q, fragment)
201 desc := "Binary file"
202 if err == nil && !binary {
203 desc = card.Snippet(text, from, to, ranged)
204 }
205 facts := []string{repo.OwnerPath + "/" + repo.Name}
206 if lang := langByName(name); lang != "" {
207 facts = append(facts, lang)
208 }
209 if ranged {
210 if from == to {
211 facts = append(facts, fmt.Sprintf("L%d", from))
212 } else {
213 facts = append(facts, fmt.Sprintf("L%d-%d", from, to))
214 }
215 }
216 return card.Render{Meta: card.Meta{
217 Title: name, Description: desc, URL: page, Image: img, OEmbed: oem,
218 Theme: "#1f6feb", Kind: "file", Facts: facts, Initial: name,
219 }, Avatar: base.Avatar}
220}
221
222func (s *Server) commitCard(ctx context.Context, repo store.Repo, sha, page, img, oem string) card.Render {
223 base := s.repoCard(ctx, repo, page, img, oem)
224 if !safeSHA(sha) || s.StoragePath() == "" {
225 return base
226 }
227 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
228 c, err := gitrepo.Show(ctx, s.Git, dir, sha)
229 if err != nil {
230 return base
231 }
232 short := c.SHA
233 if len(short) > 8 {
234 short = short[:8]
235 }
236 facts := []string{c.Author, short}
237 if changes, err := gitrepo.CommitChanges(ctx, s.Git, dir, c.SHA); err == nil {
238 add, del := 0, 0
239 for _, ch := range changes {
240 add += ch.Added
241 del += ch.Deleted
242 }
243 facts = append(facts, fmt.Sprintf("+%d −%d", add, del), fmt.Sprintf("%d files", len(changes)))
244 }
245 return card.Render{Meta: card.Meta{
246 Title: card.Clip(c.Subject, 90), Description: card.Excerpt(c.Body, 180), URL: page, Image: img, OEmbed: oem,
247 Theme: "#0c3f86", Kind: "commit", Facts: facts, Initial: c.Author,
248 }, Avatar: base.Avatar}
249}
250
251func (s *Server) mrCard(ctx context.Context, repo store.Repo, number int64, page, img, oem string) card.Render {
252 base := s.repoCard(ctx, repo, page, img, oem)
253 mr, err := s.Store.MergeRequestByNumber(ctx, repo.ID, number)
254 if err != nil {
255 return base
256 }
257 status := mr.Status
258 if mr.Draft && status == "open" {
259 status = "draft"
260 }
261 facts := []string{status, mr.SourceBranch + " → " + mr.TargetBranch, mr.Author}
262 if s.StoragePath() != "" {
263 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
264 if changes, err := gitrepo.CompareChanges(ctx, s.Git, dir, mr.TargetBranch, mr.SourceBranch); err == nil {
265 add, del := 0, 0
266 for _, ch := range changes {
267 add += ch.Added
268 del += ch.Deleted
269 }
270 facts = append(facts, fmt.Sprintf("+%d −%d", add, del))
271 }
272 }
273 if p, err := s.Store.LatestMergePipeline(ctx, repo.ID, mr.ID); err == nil {
274 jobs, _ := s.Store.JobsByPipeline(ctx, p.ID)
275 facts = append(facts, displayStatus(p.Status, jobs))
276 }
277 theme := "#1f6feb"
278 switch status {
279 case "merged":
280 theme = "#146c43"
281 case "closed":
282 theme = "#5c6b80"
283 }
284 return card.Render{Meta: card.Meta{
285 Title: "!" + strconv.FormatInt(mr.Number, 10) + " " + mr.Title,
286 Description: card.Excerpt(mr.Description, 180), URL: page, Image: img, OEmbed: oem,
287 Theme: theme, Kind: "merge_request", Facts: facts, Initial: mr.Author,
288 }, Avatar: base.Avatar}
289}
290
291func (s *Server) issueCard(ctx context.Context, repo store.Repo, number int64, page, img, oem string) card.Render {
292 iss, err := s.Store.IssueByNumber(ctx, repo.ID, number)
293 if err != nil {
294 return s.repoCard(ctx, repo, page, img, oem)
295 }
296 if iss.Confidential {
297 return s.lockedRender()
298 }
299 var labels []string
300 for _, l := range iss.Labels {
301 labels = append(labels, l.Name)
302 }
303 facts := []string{iss.Status}
304 if len(labels) > 0 {
305 facts = append(facts, strings.Join(labels, ", "))
306 }
307 facts = append(facts, iss.Author)
308 return card.Render{Meta: card.Meta{
309 Title: "#" + strconv.FormatInt(iss.Number, 10) + " " + iss.Title,
310 Description: card.Excerpt(iss.Description, 180), URL: page, Image: img, OEmbed: oem,
311 Theme: "#9a6700", Kind: "issue", Facts: facts, Initial: iss.Author,
312 }, Avatar: s.avatarForRepo(ctx, repo)}
313}
314
315func (s *Server) pipeCard(ctx context.Context, repo store.Repo, id int64, page, img, oem string) card.Render {
316 base := s.repoCard(ctx, repo, page, img, oem)
317 p, err := s.Store.PipelineByID(ctx, repo.ID, id)
318 if err != nil {
319 return base
320 }
321 jobs, _ := s.Store.JobsByPipeline(ctx, p.ID)
322 status := displayStatus(p.Status, jobs)
323 theme := "#1f6feb"
324 switch status {
325 case "passed":
326 theme = "#146c43"
327 case "failed":
328 theme = "#9f2d2d"
329 case "running":
330 theme = "#9a6700"
331 }
332 facts := []string{status}
333 if p.Ref != "" {
334 facts = append(facts, strings.TrimPrefix(p.Ref, "refs/heads/"))
335 }
336 if p.CommitTitle != "" {
337 facts = append(facts, card.Clip(p.CommitTitle, 72))
338 }
339 if p.Actor != "" {
340 facts = append(facts, p.Actor)
341 }
342 return card.Render{Meta: card.Meta{
343 Title: "#" + strconv.FormatInt(p.ID, 10) + " " + status, Description: card.Excerpt(p.CommitTitle, 180),
344 URL: page, Image: img, OEmbed: oem, Theme: theme, Kind: "pipeline", Facts: facts, Initial: repo.Name,
345 }, Avatar: base.Avatar}
346}
347
348func (s *Server) releaseCard(ctx context.Context, repo store.Repo, page, img, oem string) card.Render {
349 base := s.repoCard(ctx, repo, page, img, oem)
350 list, err := s.Store.ListReleases(ctx, repo.ID)
351 if err != nil || len(list) == 0 {
352 return card.Render{Meta: card.Meta{
353 Title: "Releases", Description: repo.OwnerPath + "/" + repo.Name, URL: page, Image: img, OEmbed: oem,
354 Theme: "#146c43", Kind: "release", Initial: repo.Name,
355 }, Avatar: base.Avatar}
356 }
357 rel := list[0]
358 title := rel.Tag
359 if rel.Name != "" {
360 title = rel.Tag + " · " + rel.Name
361 }
362 return card.Render{Meta: card.Meta{
363 Title: title, Description: card.Excerpt(rel.Body, 180), URL: page, Image: img, OEmbed: oem,
364 Theme: "#146c43", Kind: "release", Facts: []string{repo.OwnerPath + "/" + repo.Name, rel.Tag}, Initial: repo.Name,
365 }, Avatar: base.Avatar}
366}
367
368func (s *Server) groupCard(ctx context.Context, rest, page, img, oem string) card.Render {
369 name := rest
370 if i := strings.Index(name, "/"); i >= 0 {
371 name = name[:i]
372 }
373 g, err := s.Store.GroupByPath(ctx, name)
374 if err != nil {
375 return card.Site(page, img, oem)
376 }
377 if g.Visibility != "public" {
378 return s.lockedRender()
379 }
380 n, _ := s.Store.CountRepos(ctx, "group", g.ID, true)
381 return card.Render{Meta: card.Meta{
382 Title: g.Name, Description: card.Excerpt(g.Description, 180), URL: page, Image: img, OEmbed: oem,
383 Theme: "#6f42c1", Kind: "group", Facts: []string{repoLabel(n)}, Initial: g.Name,
384 }, Avatar: s.readLogo("group", g.ID, g.LogoMIME)}
385}
386
387func (s *Server) userCard(ctx context.Context, name, page, img, oem string) card.Render {
388 u, err := s.Store.UserByUsername(ctx, name)
389 if err != nil {
390 return card.Site(page, img, oem)
391 }
392 n, _ := s.Store.CountRepos(ctx, "user", u.ID, true)
393 return card.Render{Meta: card.Meta{
394 Title: u.Username, Description: "Public profile", URL: page, Image: img, OEmbed: oem,
395 Theme: "#1f6feb", Kind: "user", Facts: []string{repoLabel(n)}, Initial: u.Username,
396 }}
397}
398
399func (s *Server) avatarForRepo(ctx context.Context, repo store.Repo) []byte {
400 if b := s.readLogo("repo", repo.ID, repo.LogoMIME); len(b) > 0 {
401 return b
402 }
403 if repo.OwnerKind != "group" {
404 return nil
405 }
406 g, err := s.Store.GroupByID(ctx, repo.OwnerID)
407 if err != nil {
408 return nil
409 }
410 return s.readLogo("group", g.ID, g.LogoMIME)
411}
412
413func (s *Server) readLogo(kind string, id int64, mime string) []byte {
414 if mime != "image/png" && mime != "image/jpeg" && mime != "image/gif" {
415 return nil
416 }
417 path, err := s.logoPath(kind, id)
418 if err != nil {
419 return nil
420 }
421 data, err := os.ReadFile(path)
422 if err != nil {
423 return nil
424 }
425 img, _, err := image.Decode(bytes.NewReader(data))
426 if err != nil {
427 return nil
428 }
429 var buf bytes.Buffer
430 if err := png.Encode(&buf, img); err != nil {
431 return nil
432 }
433 return buf.Bytes()
434}
435
436func (s *Server) repoLanguage(ctx context.Context, dir, rev string) string {
437 if s.StoragePath() == "" {
438 return ""
439 }
440 entries, err := gitrepo.TreeAll(ctx, s.Git, dir, rev)
441 if err != nil {
442 return ""
443 }
444 counts := map[string]int{}
445 for _, e := range entries {
446 if e.Type != "blob" {
447 continue
448 }
449 if strings.Contains(e.Name, "vendor/") || strings.Contains(e.Name, "node_modules/") {
450 continue
451 }
452 if lang := langByName(e.Name); lang != "" {
453 counts[lang]++
454 }
455 }
456 best, n := "", 0
457 for lang, c := range counts {
458 if c > n || (c == n && lang < best) {
459 best, n = lang, c
460 }
461 }
462 return best
463}
464
465func langByName(name string) string {
466 low := strings.ToLower(name)
467 if i := strings.LastIndex(low, "/"); i >= 0 {
468 low = low[i+1:]
469 }
470 ext := ""
471 if i := strings.LastIndex(low, "."); i >= 0 {
472 ext = low[i:]
473 }
474 if lang, ok := extLang[ext]; ok {
475 return lang
476 }
477 switch low {
478 case "dockerfile":
479 return "Dockerfile"
480 case "makefile":
481 return "Makefile"
482 default:
483 return ""
484 }
485}
486
487var extLang = map[string]string{
488 ".go": "Go", ".py": "Python", ".js": "JavaScript", ".jsx": "JavaScript", ".ts": "TypeScript", ".tsx": "TypeScript",
489 ".rs": "Rust", ".java": "Java", ".rb": "Ruby", ".php": "PHP", ".c": "C", ".h": "C", ".cpp": "C++", ".cc": "C++",
490 ".cs": "C#", ".swift": "Swift", ".kt": "Kotlin", ".html": "HTML", ".css": "CSS", ".scss": "SCSS", ".vue": "Vue",
491 ".sh": "Shell", ".yml": "YAML", ".yaml": "YAML", ".sql": "SQL", ".lua": "Lua",
492}
493
494func starLabel(n int) string {
495 if n == 1 {
496 return "1 star"
497 }
498 return strconv.Itoa(n) + " stars"
499}
500
501func repoLabel(n int) string {
502 if n == 1 {
503 return "1 repository"
504 }
505 return strconv.Itoa(n) + " repositories"
506}
507
508func lineBounds(q url.Values, fragment string) (from, to int, ok bool) {
509 if from, to, ok = card.ParseLines(fragment); ok {
510 return from, to, true
511 }
512 return card.ParseLines(q.Get("L"))
513}
514
515func (s *Server) cardPNG(w http.ResponseWriter, r *http.Request) {
516 var rend card.Render
517 if r.URL.Query().Get("locked") == "1" {
518 rend = s.lockedRender()
519 } else {
520 path := r.URL.Query().Get("path")
521 if !strings.HasPrefix(path, "/") || strings.Contains(path, "..") || strings.Contains(path, "\\") {
522 http.NotFound(w, r)
523 return
524 }
525 q := url.Values{}
526 if l := r.URL.Query().Get("L"); l != "" {
527 q.Set("L", l)
528 }
529 if rev := r.URL.Query().Get("rev"); rev != "" {
530 q.Set("rev", rev)
531 }
532 rend = s.cardForPath(r.Context(), path, q.Encode(), "")
533 }
534 svg := card.SVG(rend)
535 pngBytes, hit := s.cardCache().Get(svg)
536 if !hit {
537 var err error
538 pngBytes, err = card.Raster(svg)
539 if err != nil {
540 http.Error(w, "card", http.StatusInternalServerError)
541 return
542 }
543 s.cardCache().Put(svg, pngBytes)
544 }
545 w.Header().Set("Content-Type", "image/png")
546 w.Header().Set("Cache-Control", "public, max-age=300")
547 w.Header().Set("X-Content-Type-Options", "nosniff")
548 if hit {
549 w.Header().Set("X-Card-Cache", "hit")
550 } else {
551 w.Header().Set("X-Card-Cache", "miss")
552 }
553 _, _ = w.Write(pngBytes)
554}
555
556func (s *Server) oembed(w http.ResponseWriter, r *http.Request) {
557 var rend card.Render
558 if r.URL.Query().Get("locked") == "1" {
559 rend = s.lockedRender()
560 } else {
561 raw := r.URL.Query().Get("url")
562 u, err := url.Parse(raw)
563 if err != nil || u.Path == "" {
564 http.NotFound(w, r)
565 return
566 }
567 rend = s.cardForPath(r.Context(), u.Path, u.RawQuery, u.Fragment)
568 }
569 w.Header().Set("Content-Type", "application/json; charset=utf-8")
570 w.Header().Set("Cache-Control", "no-store")
571 _ = json.NewEncoder(w).Encode(map[string]any{
572 "version": "1.0",
573 "type": "link",
574 "title": rend.Title,
575 "description": rend.Blurb(),
576 "provider_name": "BlueGit",
577 "provider_url": s.absURL("/"),
578 "thumbnail_url": rend.Image,
579 "thumbnail_width": card.Width,
580 "thumbnail_height": card.Height,
581 })
582}
583
584func (s *Server) writeLockedCard(w http.ResponseWriter, r *http.Request) {
585 m := s.lockedRender().Meta
586 w.Header().Set("Content-Type", "text/html; charset=utf-8")
587 w.Header().Set("Cache-Control", "no-store")
588 w.Header().Set("X-Robots-Tag", "noindex")
589 w.WriteHeader(http.StatusOK)
590 title := html.EscapeString(m.Title)
591 fmt.Fprintf(w, `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>%s</title>%s<link rel="icon" href="/assets/logo.svg" type="image/svg+xml"></head><body><p>%s</p></body></html>`,
592 title, metaHTML(m), title)
593}
594
595func metaHTML(m card.Meta) string {
596 esc := html.EscapeString
597 var b strings.Builder
598 fmt.Fprintf(&b, `<meta name="theme-color" content="%s">`, esc(m.Theme))
599 fmt.Fprintf(&b, `<meta name="description" content="%s">`, esc(m.Blurb()))
600 b.WriteString(`<meta property="og:site_name" content="BlueGit">`)
601 b.WriteString(`<meta property="og:type" content="website">`)
602 fmt.Fprintf(&b, `<meta property="og:title" content="%s">`, esc(m.Title))
603 fmt.Fprintf(&b, `<meta property="og:description" content="%s">`, esc(m.Blurb()))
604 fmt.Fprintf(&b, `<meta property="og:url" content="%s">`, esc(m.URL))
605 fmt.Fprintf(&b, `<meta property="og:image" content="%s">`, esc(m.Image))
606 b.WriteString(`<meta property="og:image:type" content="image/png">`)
607 fmt.Fprintf(&b, `<meta property="og:image:width" content="%d">`, card.Width)
608 fmt.Fprintf(&b, `<meta property="og:image:height" content="%d">`, card.Height)
609 b.WriteString(`<meta name="twitter:card" content="summary_large_image">`)
610 fmt.Fprintf(&b, `<meta name="twitter:title" content="%s">`, esc(m.Title))
611 fmt.Fprintf(&b, `<meta name="twitter:description" content="%s">`, esc(m.Blurb()))
612 fmt.Fprintf(&b, `<meta name="twitter:image" content="%s">`, esc(m.Image))
613 fmt.Fprintf(&b, `<link rel="alternate" type="application/json+oembed" href="%s" title="BlueGit">`, esc(m.OEmbed))
614 return b.String()
615}
616
617func isCrawler(r *http.Request) bool {
618 ua := strings.ToLower(r.Header.Get("User-Agent"))
619 for _, name := range []string{
620 "discordbot", "slackbot", "twitterbot", "facebookexternalhit", "linkedinbot",
621 "telegrambot", "whatsapp", "embedly", "iframely", "redditbot", "pinterestbot",
622 "skypeuripreview",
623 } {
624 if strings.Contains(ua, name) {
625 return true
626 }
627 }
628 return false
629}
internal/server/social_test.go added +381 −0
@@ -0,0 +1,381 @@
1 package server
2
3 import (
4 "bytes"
5 "context"
6 "database/sql"
7 "image/png"
8 "net/http"
9 "net/http/cookiejar"
10 "net/http/httptest"
11 "net/url"
12 "path/filepath"
13 "strconv"
14 "strings"
15 "testing"
16
17 "gitlab.com/Timfa/bluegit/internal/access"
18 "gitlab.com/Timfa/bluegit/internal/auth"
19 "gitlab.com/Timfa/bluegit/internal/card"
20 "gitlab.com/Timfa/bluegit/internal/config"
21 "gitlab.com/Timfa/bluegit/internal/store"
22
23 _ "modernc.org/sqlite"
24 )
25
26 func TestLinkPreviews(t *testing.T) {
27 storage := t.TempDir()
28 st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
29 if err != nil {
30 t.Fatal(err)
31 }
32 t.Cleanup(func() { _ = st.Close() })
33 cfg := config.Config{
34 BaseURL: "http://git.example", Listen: "127.0.0.1:0", StoragePath: storage,
35 Auth: config.Auth{Mode: "dev", DevUser: "tim", DevAuthID: 1, UserAgent: "test", BaseURL: "https://auth.timfalken.com"},
36 Git: config.Git{Binary: "git", DefaultBranch: "master"},
37 }
38 srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "tim", AuthID: 1}, Dev: true, Git: "git", HookBin: "/bin/true"}
39 ts := httptest.NewServer(srv.Handler())
40 t.Cleanup(ts.Close)
41 ctx := context.Background()
42
43 jar, _ := cookiejar.New(nil)
44 tim := &http.Client{Jar: jar}
45 anon := &http.Client{}
46 page := read(t, mustGet(t, tim, ts.URL+"/login"))
47 page = read(t, mustPost(t, tim, ts.URL+"/new/repo", url.Values{
48 "csrf": {csrfOf(t, page)}, "name": {"widgets"}, "visibility": {"public"},
49 }))
50 page = read(t, mustPost(t, tim, ts.URL+"/settings/tokens", url.Values{"csrf": {csrfOf(t, page)}, "name": {"tim"}}))
51 token := between(page, `<p class="code">`, "</p>")
52 me, err := st.UserByUsername(ctx, "tim")
53 if err != nil {
54 t.Fatal(err)
55 }
56
57 work := t.TempDir()
58 git(t, work, "init", "-b", "master")
59 git(t, work, "config", "user.email", "tim@example")
60 git(t, work, "config", "user.name", "tim")
61 var lines []string
62 for i := 1; i <= 25; i++ {
63 lines = append(lines, "L"+twoDigits(i)+"-marker")
64 }
65 writeFile(t, filepath.Join(work, "main.go"), strings.Join(lines, "\n")+"\n")
66 writeFile(t, filepath.Join(work, "README.md"), "# Widgets\n\nEen widget die telt.\n\nTweede alinea.\n")
67 git(t, work, "add", ".")
68 git(t, work, "commit", "-m", "Fix the gate")
69 remote := strings.Replace(ts.URL, "http://", "http://tim:"+token+"@", 1) + "/tim/widgets.git"
70 git(t, work, "remote", "add", "origin", remote)
71 git(t, work, "push", "-u", "origin", "master")
72 sha := strings.TrimSpace(mustGit(t, work, "rev-parse", "HEAD"))
73
74 page = read(t, mustGet(t, tim, ts.URL+"/tim/widgets"))
75 read(t, mustPost(t, tim, ts.URL+"/tim/widgets/-/star", url.Values{"csrf": {csrfOf(t, page)}}))
76
77 home := read(t, mustGet(t, anon, ts.URL+"/tim/widgets"))
78 blob := socialBlob(home)
79 for _, want := range []string{
80 "tim/widgets", "Een widget die telt.", "Go", "1 star", "Fix the gate",
81 "BlueGit", "summary_large_image", "#1f6feb", "application/json+oembed", "/assets/logo.svg",
82 } {
83 if !strings.Contains(home, want) {
84 t.Fatalf("repo-kaart mist %q\n%s", want, home)
85 }
86 }
87 if strings.Contains(blob, "Tweede alinea") {
88 t.Fatal("tweede alinea hoort niet in de kaart")
89 }
90 img := ts.URL + "/-/card.png?path=" + url.QueryEscape("/tim/widgets")
91 first := mustGet(t, anon, img)
92 if first.Header.Get("X-Card-Cache") != "miss" || first.Header.Get("Content-Type") != "image/png" {
93 t.Fatalf("cache %s type %s", first.Header.Get("X-Card-Cache"), first.Header.Get("Content-Type"))
94 }
95 png1 := []byte(read(t, first))
96 cfgPNG, err := png.DecodeConfig(bytes.NewReader(png1))
97 if err != nil || cfgPNG.Width != card.Width || cfgPNG.Height != card.Height {
98 t.Fatalf("png %v %v", cfgPNG, err)
99 }
100 second := mustGet(t, anon, img)
101 if second.Header.Get("X-Card-Cache") != "hit" {
102 t.Fatalf("tweede keer %s", second.Header.Get("X-Card-Cache"))
103 }
104 if !bytes.Equal(png1, []byte(read(t, second))) {
105 t.Fatal("cache levert andere bytes")
106 }
107
108 filePage := read(t, mustGet(t, anon, ts.URL+"/tim/widgets/-/blob/main.go?L=10-12"))
109 fileBlob := socialBlob(filePage)
110 for _, want := range []string{"main.go", "L10-marker", "L12-marker", "L10-12"} {
111 if !strings.Contains(fileBlob, want) {
112 t.Fatalf("bestand mist %q\n%s", want, fileBlob)
113 }
114 }
115 if strings.Contains(fileBlob, "L01-marker") || strings.Contains(fileBlob, "L25-marker") {
116 t.Fatalf("verkeerde regels:\n%s", fileBlob)
117 }
118 frag := srv.cardForPath(ctx, "/tim/widgets/-/blob/main.go", "", "#L10-12")
119 if !strings.Contains(frag.Description, "L10-marker") || strings.Contains(frag.Description, "L01-marker") {
120 t.Fatalf("fragment %q", frag.Description)
121 }
122
123 commitPage := read(t, mustGet(t, anon, ts.URL+"/tim/widgets/-/commit/"+sha))
124 if !strings.Contains(socialBlob(commitPage), "Fix the gate") {
125 t.Fatalf("commit:\n%s", socialBlob(commitPage))
126 }
127
128 git(t, work, "checkout", "-b", "feature")
129 writeFile(t, filepath.Join(work, "main.go"), "package main\nextra\n")
130 git(t, work, "add", "main.go")
131 git(t, work, "commit", "-m", "extra regel")
132 git(t, work, "push", "-u", "origin", "feature")
133 repo, err := st.RepoByPath(ctx, "tim", "widgets")
134 if err != nil {
135 t.Fatal(err)
136 }
137 mr, err := st.CreateMergeRequest(ctx, repo.ID, me.ID, "Fix the gate", "Eerste stuk van de merge request.", "feature", "master")
138 if err != nil {
139 t.Fatal(err)
140 }
141 pipeID, err := st.CreatePipeline(ctx, repo.ID, sha, "refs/heads/feature", "merge_request", "tim", "Fix the gate", []store.NewJob{{
142 Name: "test", Stage: "test", Image: "alpine", Script: "true",
143 }})
144 if err != nil {
145 t.Fatal(err)
146 }
147 if err := st.AttachPipelineMR(ctx, pipeID, mr.ID); err != nil {
148 t.Fatal(err)
149 }
150 mrPage := read(t, mustGet(t, anon, ts.URL+"/tim/widgets/-/merge-requests/1"))
151 mrBlob := socialBlob(mrPage)
152 for _, want := range []string{"!1 Fix the gate", "open", "feature → master", "tim", "Eerste stuk", "pending", "&#43;2 −25"} {
153 if !strings.Contains(mrBlob, want) {
154 t.Fatalf("mr mist %q\n%s", want, mrBlob)
155 }
156 }
157
158 lab, err := st.UpsertLabel(ctx, repo.ID, "bug", "#428fdc")
159 if err != nil {
160 t.Fatal(err)
161 }
162 if _, err := st.CreateIssue(ctx, repo.ID, me.ID, store.NewIssue{
163 Title: "Login fails", Description: "Het formulier weigert.", LabelIDs: []int64{lab.ID},
164 }); err != nil {
165 t.Fatal(err)
166 }
167 issuePage := read(t, mustGet(t, anon, ts.URL+"/tim/widgets/-/issues/1"))
168 issueBlob := socialBlob(issuePage)
169 for _, want := range []string{"#1 Login fails", "open", "bug", "tim", "Het formulier weigert."} {
170 if !strings.Contains(issueBlob, want) {
171 t.Fatalf("issue mist %q\n%s", want, issueBlob)
172 }
173 }
174
175 if _, err := st.CreateIssue(ctx, repo.ID, me.ID, store.NewIssue{
176 Title: "ZXQCONF", Description: "ZXQCONFBODY", Confidential: true,
177 }); err != nil {
178 t.Fatal(err)
179 }
180 secretIssue := read(t, mustGet(t, tim, ts.URL+"/tim/widgets/-/issues/2"))
181 if !strings.Contains(secretIssue, "ZXQCONF") {
182 t.Fatal("de auteur ziet het issue niet")
183 }
184 if strings.Contains(socialBlob(secretIssue), "ZXQCONF") || strings.Contains(socialBlob(secretIssue), "ZXQCONFBODY") {
185 t.Fatalf("vertrouwelijk lekt in de kaart:\n%s", socialBlob(secretIssue))
186 }
187 if !strings.Contains(socialBlob(secretIssue), card.LockedTitle) {
188 t.Fatal("geen generieke kaart")
189 }
190 crawl := crawlerGet(t, tim, ts.URL+"/tim/widgets/-/issues/2")
191 if crawl.StatusCode != http.StatusOK {
192 t.Fatalf("crawler %d", crawl.StatusCode)
193 }
194 crawlBody := read(t, crawl)
195 if strings.Contains(crawlBody, "ZXQCONF") || strings.Contains(crawlBody, "ZXQCONFBODY") || !strings.Contains(crawlBody, card.LockedTitle) {
196 t.Fatalf("crawler-issue:\n%s", crawlBody)
197 }
198
199 pipePage := read(t, mustGet(t, anon, ts.URL+"/tim/widgets/-/pipelines/"+strconv.FormatInt(pipeID, 10)))
200 if !strings.Contains(socialBlob(pipePage), "pending") || !strings.Contains(socialBlob(pipePage), "Fix the gate") {
201 t.Fatalf("pipeline:\n%s", socialBlob(pipePage))
202 }
203 if _, err := st.CreateRelease(ctx, repo.ID, "v1.0.0", sha, "Eerste uitgave", "Een release voor de kaart.", me.ID, 0, nil); err != nil {
204 t.Fatal(err)
205 }
206 relPage := read(t, mustGet(t, anon, ts.URL+"/tim/widgets/-/releases"))
207 relBlob := socialBlob(relPage)
208 for _, want := range []string{"v1.0.0", "Eerste uitgave", "Een release voor de kaart."} {
209 if !strings.Contains(relBlob, want) {
210 t.Fatalf("release mist %q\n%s", want, relBlob)
211 }
212 }
213
214 g, err := st.CreateGroup(ctx, me.ID, "Kaartgroep", "kaartgroep", "Groep voor kaarten", access.RoleDeveloper)
215 if err != nil {
216 t.Fatal(err)
217 }
218 if err := st.UpdateGroup(ctx, g.ID, "Groep voor kaarten", "public", access.RoleDeveloper); err != nil {
219 t.Fatal(err)
220 }
221 if _, err := st.CreateRepo(ctx, "group", g.ID, "publiek", "een repo", "master", "public"); err != nil {
222 t.Fatal(err)
223 }
224 groupPage := read(t, mustGet(t, anon, ts.URL+"/groups/kaartgroep"))
225 groupBlob := socialBlob(groupPage)
226 for _, want := range []string{"Kaartgroep", "Groep voor kaarten", "1 repository"} {
227 if !strings.Contains(groupBlob, want) {
228 t.Fatalf("groep mist %q\n%s", want, groupBlob)
229 }
230 }
231 if _, err := st.CreateGroup(ctx, me.ID, "ZXQGROUP", "zxqgroup", "ZXQGROUPBODY", access.RoleDeveloper); err != nil {
232 t.Fatal(err)
233 }
234 hiddenGroup := crawlerGet(t, tim, ts.URL+"/groups/zxqgroup")
235 hiddenBody := read(t, hiddenGroup)
236 if hiddenGroup.StatusCode != http.StatusOK || strings.Contains(hiddenBody, "ZXQGROUP") || !strings.Contains(hiddenBody, card.LockedTitle) {
237 t.Fatalf("groep-crawler %d\n%s", hiddenGroup.StatusCode, hiddenBody)
238 }
239
240 userPage := read(t, mustGet(t, anon, ts.URL+"/users/tim"))
241 if !strings.Contains(socialBlob(userPage), "tim") || !strings.Contains(socialBlob(userPage), "1 repository") {
242 t.Fatalf("gebruiker:\n%s", socialBlob(userPage))
243 }
244
245 page = read(t, mustGet(t, tim, ts.URL+"/new"))
246 read(t, mustPost(t, tim, ts.URL+"/new/repo", url.Values{
247 "csrf": {csrfOf(t, page)}, "name": {"zxqpriv"}, "description": {"ZXQPRIVREADME"}, "visibility": {"private"},
248 }))
249 privWork := t.TempDir()
250 git(t, privWork, "init", "-b", "master")
251 git(t, privWork, "config", "user.email", "tim@example")
252 git(t, privWork, "config", "user.name", "tim")
253 writeFile(t, filepath.Join(privWork, "README.md"), "ZXQPRIVREADME\n")
254 git(t, privWork, "add", ".")
255 git(t, privWork, "commit", "-m", "geheim")
256 privRemote := strings.Replace(ts.URL, "http://", "http://tim:"+token+"@", 1) + "/tim/zxqpriv.git"
257 git(t, privWork, "remote", "add", "origin", privRemote)
258 git(t, privWork, "push", "-u", "origin", "master")
259
260 owned := read(t, mustGet(t, tim, ts.URL+"/tim/zxqpriv"))
261 if !strings.Contains(owned, "zxqpriv") {
262 t.Fatal("eigenaar ziet de repository niet")
263 }
264 ownedBlob := socialBlob(owned)
265 if strings.Contains(ownedBlob, "zxqpriv") || strings.Contains(ownedBlob, "ZXQPRIVREADME") || !strings.Contains(ownedBlob, card.LockedTitle) {
266 t.Fatalf("prive-kaart met cookie:\n%s", ownedBlob)
267 }
268 plain, err := anon.Get(ts.URL + "/tim/zxqpriv")
269 if err != nil {
270 t.Fatal(err)
271 }
272 if plain.StatusCode != http.StatusNotFound {
273 t.Fatalf("anoniem %d", plain.StatusCode)
274 }
275 plain.Body.Close()
276 bot := crawlerGet(t, anon, ts.URL+"/tim/zxqpriv")
277 botBody := read(t, bot)
278 if bot.StatusCode != http.StatusOK || strings.Contains(botBody, "zxqpriv") || strings.Contains(botBody, "ZXQPRIVREADME") || !strings.Contains(botBody, card.LockedTitle) {
279 t.Fatalf("crawler-prive %d\n%s", bot.StatusCode, botBody)
280 }
281 lockPNG := []byte(read(t, mustGet(t, tim, ts.URL+"/-/card.png?locked=1")))
282 privPNG := []byte(read(t, mustGet(t, tim, ts.URL+"/-/card.png?path="+url.QueryEscape("/tim/zxqpriv"))))
283 if !bytes.Equal(lockPNG, privPNG) {
284 t.Fatal("prive-afbeelding wijkt af van de generieke kaart")
285 }
286 confPNG := []byte(read(t, mustGet(t, tim, ts.URL+"/-/card.png?path="+url.QueryEscape("/tim/widgets/-/issues/2"))))
287 if !bytes.Equal(lockPNG, confPNG) {
288 t.Fatal("vertrouwelijke afbeelding wijkt af")
289 }
290
291 if _, err := st.CreateRepo(ctx, "user", me.ID, "zxqint", "ZXQINTBODY", "master", "private"); err != nil {
292 t.Fatal(err)
293 }
294 db, err := sql.Open("sqlite", "file:"+filepath.Join(storage, "bluegit.db")+"?_pragma=busy_timeout(5000)")
295 if err != nil {
296 t.Fatal(err)
297 }
298 defer db.Close()
299 if _, err := db.Exec(`UPDATE repos SET visibility = 'internal' WHERE name = 'zxqint'`); err != nil {
300 t.Fatal(err)
301 }
302 internalPage := read(t, mustGet(t, tim, ts.URL+"/tim/zxqint"))
303 internalBlob := socialBlob(internalPage)
304 if strings.Contains(internalBlob, "zxqint") || strings.Contains(internalBlob, "ZXQINTBODY") || !strings.Contains(internalBlob, card.LockedTitle) {
305 t.Fatalf("internal:\n%s", internalBlob)
306 }
307 bot = crawlerGet(t, tim, ts.URL+"/tim/zxqint")
308 botBody = read(t, bot)
309 if strings.Contains(botBody, "zxqint") || strings.Contains(botBody, "ZXQINTBODY") || !strings.Contains(botBody, card.LockedTitle) {
310 t.Fatalf("crawler-internal:\n%s", botBody)
311 }
312
313 oem := read(t, mustGet(t, tim, ts.URL+"/api/v1/oembed?url="+url.QueryEscape("http://git.example/tim/widgets")))
314 if !strings.Contains(oem, `"provider_name":"BlueGit"`) || !strings.Contains(oem, "tim/widgets") || !strings.Contains(oem, "Een widget die telt.") {
315 t.Fatalf("oembed:\n%s", oem)
316 }
317 oemPriv := read(t, mustGet(t, tim, ts.URL+"/api/v1/oembed?url="+url.QueryEscape("http://git.example/tim/zxqpriv")))
318 if strings.Contains(oemPriv, "zxqpriv") || strings.Contains(oemPriv, "ZXQPRIVREADME") || !strings.Contains(oemPriv, card.LockedTitle) {
319 t.Fatalf("oembed prive:\n%s", oemPriv)
320 }
321
322 info := read(t, mustGet(t, anon, ts.URL+"/-/info"))
323 for _, want := range []string{`id="previews"`, "Open Graph", card.LockedTitle, "#L10-20"} {
324 if !strings.Contains(info, want) {
325 t.Fatalf("info mist %q", want)
326 }
327 }
328 }
329
330 func twoDigits(n int) string {
331 if n < 10 {
332 return "0" + string(rune('0'+n))
333 }
334 return string(rune('0'+n/10)) + string(rune('0'+n%10))
335 }
336
337 func socialBlob(page string) string {
338 var b strings.Builder
339 for _, key := range []string{"og:title", "og:description", "og:url", "og:image", "og:site_name", "twitter:title", "twitter:description", "twitter:image", "description", "theme-color"} {
340 b.WriteString(metaContent(page, "property", key))
341 b.WriteString("\n")
342 b.WriteString(metaContent(page, "name", key))
343 b.WriteString("\n")
344 }
345 const needle = `application/json+oembed" href="`
346 if i := strings.Index(page, needle); i >= 0 {
347 rest := page[i+len(needle):]
348 if j := strings.Index(rest, `"`); j >= 0 {
349 b.WriteString(rest[:j])
350 }
351 }
352 return b.String()
353 }
354
355 func metaContent(page, attr, key string) string {
356 tag := attr + `="` + key + `" content="`
357 i := strings.Index(page, tag)
358 if i < 0 {
359 return ""
360 }
361 rest := page[i+len(tag):]
362 j := strings.Index(rest, `"`)
363 if j < 0 {
364 return ""
365 }
366 return rest[:j]
367 }
368
369 func crawlerGet(t *testing.T, c *http.Client, raw string) *http.Response {
370 t.Helper()
371 req, err := http.NewRequest(http.MethodGet, raw, nil)
372 if err != nil {
373 t.Fatal(err)
374 }
375 req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)")
376 res, err := c.Do(req)
377 if err != nil {
378 t.Fatal(err)
379 }
380 return res
381 }
@@ -0,0 +1,381 @@
1package server
2
3import (
4 "bytes"
5 "context"
6 "database/sql"
7 "image/png"
8 "net/http"
9 "net/http/cookiejar"
10 "net/http/httptest"
11 "net/url"
12 "path/filepath"
13 "strconv"
14 "strings"
15 "testing"
16
17 "gitlab.com/Timfa/bluegit/internal/access"
18 "gitlab.com/Timfa/bluegit/internal/auth"
19 "gitlab.com/Timfa/bluegit/internal/card"
20 "gitlab.com/Timfa/bluegit/internal/config"
21 "gitlab.com/Timfa/bluegit/internal/store"
22
23 _ "modernc.org/sqlite"
24)
25
26func TestLinkPreviews(t *testing.T) {
27 storage := t.TempDir()
28 st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
29 if err != nil {
30 t.Fatal(err)
31 }
32 t.Cleanup(func() { _ = st.Close() })
33 cfg := config.Config{
34 BaseURL: "http://git.example", Listen: "127.0.0.1:0", StoragePath: storage,
35 Auth: config.Auth{Mode: "dev", DevUser: "tim", DevAuthID: 1, UserAgent: "test", BaseURL: "https://auth.timfalken.com"},
36 Git: config.Git{Binary: "git", DefaultBranch: "master"},
37 }
38 srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "tim", AuthID: 1}, Dev: true, Git: "git", HookBin: "/bin/true"}
39 ts := httptest.NewServer(srv.Handler())
40 t.Cleanup(ts.Close)
41 ctx := context.Background()
42
43 jar, _ := cookiejar.New(nil)
44 tim := &http.Client{Jar: jar}
45 anon := &http.Client{}
46 page := read(t, mustGet(t, tim, ts.URL+"/login"))
47 page = read(t, mustPost(t, tim, ts.URL+"/new/repo", url.Values{
48 "csrf": {csrfOf(t, page)}, "name": {"widgets"}, "visibility": {"public"},
49 }))
50 page = read(t, mustPost(t, tim, ts.URL+"/settings/tokens", url.Values{"csrf": {csrfOf(t, page)}, "name": {"tim"}}))
51 token := between(page, `<p class="code">`, "</p>")
52 me, err := st.UserByUsername(ctx, "tim")
53 if err != nil {
54 t.Fatal(err)
55 }
56
57 work := t.TempDir()
58 git(t, work, "init", "-b", "master")
59 git(t, work, "config", "user.email", "tim@example")
60 git(t, work, "config", "user.name", "tim")
61 var lines []string
62 for i := 1; i <= 25; i++ {
63 lines = append(lines, "L"+twoDigits(i)+"-marker")
64 }
65 writeFile(t, filepath.Join(work, "main.go"), strings.Join(lines, "\n")+"\n")
66 writeFile(t, filepath.Join(work, "README.md"), "# Widgets\n\nEen widget die telt.\n\nTweede alinea.\n")
67 git(t, work, "add", ".")
68 git(t, work, "commit", "-m", "Fix the gate")
69 remote := strings.Replace(ts.URL, "http://", "http://tim:"+token+"@", 1) + "/tim/widgets.git"
70 git(t, work, "remote", "add", "origin", remote)
71 git(t, work, "push", "-u", "origin", "master")
72 sha := strings.TrimSpace(mustGit(t, work, "rev-parse", "HEAD"))
73
74 page = read(t, mustGet(t, tim, ts.URL+"/tim/widgets"))
75 read(t, mustPost(t, tim, ts.URL+"/tim/widgets/-/star", url.Values{"csrf": {csrfOf(t, page)}}))
76
77 home := read(t, mustGet(t, anon, ts.URL+"/tim/widgets"))
78 blob := socialBlob(home)
79 for _, want := range []string{
80 "tim/widgets", "Een widget die telt.", "Go", "1 star", "Fix the gate",
81 "BlueGit", "summary_large_image", "#1f6feb", "application/json+oembed", "/assets/logo.svg",
82 } {
83 if !strings.Contains(home, want) {
84 t.Fatalf("repo-kaart mist %q\n%s", want, home)
85 }
86 }
87 if strings.Contains(blob, "Tweede alinea") {
88 t.Fatal("tweede alinea hoort niet in de kaart")
89 }
90 img := ts.URL + "/-/card.png?path=" + url.QueryEscape("/tim/widgets")
91 first := mustGet(t, anon, img)
92 if first.Header.Get("X-Card-Cache") != "miss" || first.Header.Get("Content-Type") != "image/png" {
93 t.Fatalf("cache %s type %s", first.Header.Get("X-Card-Cache"), first.Header.Get("Content-Type"))
94 }
95 png1 := []byte(read(t, first))
96 cfgPNG, err := png.DecodeConfig(bytes.NewReader(png1))
97 if err != nil || cfgPNG.Width != card.Width || cfgPNG.Height != card.Height {
98 t.Fatalf("png %v %v", cfgPNG, err)
99 }
100 second := mustGet(t, anon, img)
101 if second.Header.Get("X-Card-Cache") != "hit" {
102 t.Fatalf("tweede keer %s", second.Header.Get("X-Card-Cache"))
103 }
104 if !bytes.Equal(png1, []byte(read(t, second))) {
105 t.Fatal("cache levert andere bytes")
106 }
107
108 filePage := read(t, mustGet(t, anon, ts.URL+"/tim/widgets/-/blob/main.go?L=10-12"))
109 fileBlob := socialBlob(filePage)
110 for _, want := range []string{"main.go", "L10-marker", "L12-marker", "L10-12"} {
111 if !strings.Contains(fileBlob, want) {
112 t.Fatalf("bestand mist %q\n%s", want, fileBlob)
113 }
114 }
115 if strings.Contains(fileBlob, "L01-marker") || strings.Contains(fileBlob, "L25-marker") {
116 t.Fatalf("verkeerde regels:\n%s", fileBlob)
117 }
118 frag := srv.cardForPath(ctx, "/tim/widgets/-/blob/main.go", "", "#L10-12")
119 if !strings.Contains(frag.Description, "L10-marker") || strings.Contains(frag.Description, "L01-marker") {
120 t.Fatalf("fragment %q", frag.Description)
121 }
122
123 commitPage := read(t, mustGet(t, anon, ts.URL+"/tim/widgets/-/commit/"+sha))
124 if !strings.Contains(socialBlob(commitPage), "Fix the gate") {
125 t.Fatalf("commit:\n%s", socialBlob(commitPage))
126 }
127
128 git(t, work, "checkout", "-b", "feature")
129 writeFile(t, filepath.Join(work, "main.go"), "package main\nextra\n")
130 git(t, work, "add", "main.go")
131 git(t, work, "commit", "-m", "extra regel")
132 git(t, work, "push", "-u", "origin", "feature")
133 repo, err := st.RepoByPath(ctx, "tim", "widgets")
134 if err != nil {
135 t.Fatal(err)
136 }
137 mr, err := st.CreateMergeRequest(ctx, repo.ID, me.ID, "Fix the gate", "Eerste stuk van de merge request.", "feature", "master")
138 if err != nil {
139 t.Fatal(err)
140 }
141 pipeID, err := st.CreatePipeline(ctx, repo.ID, sha, "refs/heads/feature", "merge_request", "tim", "Fix the gate", []store.NewJob{{
142 Name: "test", Stage: "test", Image: "alpine", Script: "true",
143 }})
144 if err != nil {
145 t.Fatal(err)
146 }
147 if err := st.AttachPipelineMR(ctx, pipeID, mr.ID); err != nil {
148 t.Fatal(err)
149 }
150 mrPage := read(t, mustGet(t, anon, ts.URL+"/tim/widgets/-/merge-requests/1"))
151 mrBlob := socialBlob(mrPage)
152 for _, want := range []string{"!1 Fix the gate", "open", "feature → master", "tim", "Eerste stuk", "pending", "&#43;2 −25"} {
153 if !strings.Contains(mrBlob, want) {
154 t.Fatalf("mr mist %q\n%s", want, mrBlob)
155 }
156 }
157
158 lab, err := st.UpsertLabel(ctx, repo.ID, "bug", "#428fdc")
159 if err != nil {
160 t.Fatal(err)
161 }
162 if _, err := st.CreateIssue(ctx, repo.ID, me.ID, store.NewIssue{
163 Title: "Login fails", Description: "Het formulier weigert.", LabelIDs: []int64{lab.ID},
164 }); err != nil {
165 t.Fatal(err)
166 }
167 issuePage := read(t, mustGet(t, anon, ts.URL+"/tim/widgets/-/issues/1"))
168 issueBlob := socialBlob(issuePage)
169 for _, want := range []string{"#1 Login fails", "open", "bug", "tim", "Het formulier weigert."} {
170 if !strings.Contains(issueBlob, want) {
171 t.Fatalf("issue mist %q\n%s", want, issueBlob)
172 }
173 }
174
175 if _, err := st.CreateIssue(ctx, repo.ID, me.ID, store.NewIssue{
176 Title: "ZXQCONF", Description: "ZXQCONFBODY", Confidential: true,
177 }); err != nil {
178 t.Fatal(err)
179 }
180 secretIssue := read(t, mustGet(t, tim, ts.URL+"/tim/widgets/-/issues/2"))
181 if !strings.Contains(secretIssue, "ZXQCONF") {
182 t.Fatal("de auteur ziet het issue niet")
183 }
184 if strings.Contains(socialBlob(secretIssue), "ZXQCONF") || strings.Contains(socialBlob(secretIssue), "ZXQCONFBODY") {
185 t.Fatalf("vertrouwelijk lekt in de kaart:\n%s", socialBlob(secretIssue))
186 }
187 if !strings.Contains(socialBlob(secretIssue), card.LockedTitle) {
188 t.Fatal("geen generieke kaart")
189 }
190 crawl := crawlerGet(t, tim, ts.URL+"/tim/widgets/-/issues/2")
191 if crawl.StatusCode != http.StatusOK {
192 t.Fatalf("crawler %d", crawl.StatusCode)
193 }
194 crawlBody := read(t, crawl)
195 if strings.Contains(crawlBody, "ZXQCONF") || strings.Contains(crawlBody, "ZXQCONFBODY") || !strings.Contains(crawlBody, card.LockedTitle) {
196 t.Fatalf("crawler-issue:\n%s", crawlBody)
197 }
198
199 pipePage := read(t, mustGet(t, anon, ts.URL+"/tim/widgets/-/pipelines/"+strconv.FormatInt(pipeID, 10)))
200 if !strings.Contains(socialBlob(pipePage), "pending") || !strings.Contains(socialBlob(pipePage), "Fix the gate") {
201 t.Fatalf("pipeline:\n%s", socialBlob(pipePage))
202 }
203 if _, err := st.CreateRelease(ctx, repo.ID, "v1.0.0", sha, "Eerste uitgave", "Een release voor de kaart.", me.ID, 0, nil); err != nil {
204 t.Fatal(err)
205 }
206 relPage := read(t, mustGet(t, anon, ts.URL+"/tim/widgets/-/releases"))
207 relBlob := socialBlob(relPage)
208 for _, want := range []string{"v1.0.0", "Eerste uitgave", "Een release voor de kaart."} {
209 if !strings.Contains(relBlob, want) {
210 t.Fatalf("release mist %q\n%s", want, relBlob)
211 }
212 }
213
214 g, err := st.CreateGroup(ctx, me.ID, "Kaartgroep", "kaartgroep", "Groep voor kaarten", access.RoleDeveloper)
215 if err != nil {
216 t.Fatal(err)
217 }
218 if err := st.UpdateGroup(ctx, g.ID, "Groep voor kaarten", "public", access.RoleDeveloper); err != nil {
219 t.Fatal(err)
220 }
221 if _, err := st.CreateRepo(ctx, "group", g.ID, "publiek", "een repo", "master", "public"); err != nil {
222 t.Fatal(err)
223 }
224 groupPage := read(t, mustGet(t, anon, ts.URL+"/groups/kaartgroep"))
225 groupBlob := socialBlob(groupPage)
226 for _, want := range []string{"Kaartgroep", "Groep voor kaarten", "1 repository"} {
227 if !strings.Contains(groupBlob, want) {
228 t.Fatalf("groep mist %q\n%s", want, groupBlob)
229 }
230 }
231 if _, err := st.CreateGroup(ctx, me.ID, "ZXQGROUP", "zxqgroup", "ZXQGROUPBODY", access.RoleDeveloper); err != nil {
232 t.Fatal(err)
233 }
234 hiddenGroup := crawlerGet(t, tim, ts.URL+"/groups/zxqgroup")
235 hiddenBody := read(t, hiddenGroup)
236 if hiddenGroup.StatusCode != http.StatusOK || strings.Contains(hiddenBody, "ZXQGROUP") || !strings.Contains(hiddenBody, card.LockedTitle) {
237 t.Fatalf("groep-crawler %d\n%s", hiddenGroup.StatusCode, hiddenBody)
238 }
239
240 userPage := read(t, mustGet(t, anon, ts.URL+"/users/tim"))
241 if !strings.Contains(socialBlob(userPage), "tim") || !strings.Contains(socialBlob(userPage), "1 repository") {
242 t.Fatalf("gebruiker:\n%s", socialBlob(userPage))
243 }
244
245 page = read(t, mustGet(t, tim, ts.URL+"/new"))
246 read(t, mustPost(t, tim, ts.URL+"/new/repo", url.Values{
247 "csrf": {csrfOf(t, page)}, "name": {"zxqpriv"}, "description": {"ZXQPRIVREADME"}, "visibility": {"private"},
248 }))
249 privWork := t.TempDir()
250 git(t, privWork, "init", "-b", "master")
251 git(t, privWork, "config", "user.email", "tim@example")
252 git(t, privWork, "config", "user.name", "tim")
253 writeFile(t, filepath.Join(privWork, "README.md"), "ZXQPRIVREADME\n")
254 git(t, privWork, "add", ".")
255 git(t, privWork, "commit", "-m", "geheim")
256 privRemote := strings.Replace(ts.URL, "http://", "http://tim:"+token+"@", 1) + "/tim/zxqpriv.git"
257 git(t, privWork, "remote", "add", "origin", privRemote)
258 git(t, privWork, "push", "-u", "origin", "master")
259
260 owned := read(t, mustGet(t, tim, ts.URL+"/tim/zxqpriv"))
261 if !strings.Contains(owned, "zxqpriv") {
262 t.Fatal("eigenaar ziet de repository niet")
263 }
264 ownedBlob := socialBlob(owned)
265 if strings.Contains(ownedBlob, "zxqpriv") || strings.Contains(ownedBlob, "ZXQPRIVREADME") || !strings.Contains(ownedBlob, card.LockedTitle) {
266 t.Fatalf("prive-kaart met cookie:\n%s", ownedBlob)
267 }
268 plain, err := anon.Get(ts.URL + "/tim/zxqpriv")
269 if err != nil {
270 t.Fatal(err)
271 }
272 if plain.StatusCode != http.StatusNotFound {
273 t.Fatalf("anoniem %d", plain.StatusCode)
274 }
275 plain.Body.Close()
276 bot := crawlerGet(t, anon, ts.URL+"/tim/zxqpriv")
277 botBody := read(t, bot)
278 if bot.StatusCode != http.StatusOK || strings.Contains(botBody, "zxqpriv") || strings.Contains(botBody, "ZXQPRIVREADME") || !strings.Contains(botBody, card.LockedTitle) {
279 t.Fatalf("crawler-prive %d\n%s", bot.StatusCode, botBody)
280 }
281 lockPNG := []byte(read(t, mustGet(t, tim, ts.URL+"/-/card.png?locked=1")))
282 privPNG := []byte(read(t, mustGet(t, tim, ts.URL+"/-/card.png?path="+url.QueryEscape("/tim/zxqpriv"))))
283 if !bytes.Equal(lockPNG, privPNG) {
284 t.Fatal("prive-afbeelding wijkt af van de generieke kaart")
285 }
286 confPNG := []byte(read(t, mustGet(t, tim, ts.URL+"/-/card.png?path="+url.QueryEscape("/tim/widgets/-/issues/2"))))
287 if !bytes.Equal(lockPNG, confPNG) {
288 t.Fatal("vertrouwelijke afbeelding wijkt af")
289 }
290
291 if _, err := st.CreateRepo(ctx, "user", me.ID, "zxqint", "ZXQINTBODY", "master", "private"); err != nil {
292 t.Fatal(err)
293 }
294 db, err := sql.Open("sqlite", "file:"+filepath.Join(storage, "bluegit.db")+"?_pragma=busy_timeout(5000)")
295 if err != nil {
296 t.Fatal(err)
297 }
298 defer db.Close()
299 if _, err := db.Exec(`UPDATE repos SET visibility = 'internal' WHERE name = 'zxqint'`); err != nil {
300 t.Fatal(err)
301 }
302 internalPage := read(t, mustGet(t, tim, ts.URL+"/tim/zxqint"))
303 internalBlob := socialBlob(internalPage)
304 if strings.Contains(internalBlob, "zxqint") || strings.Contains(internalBlob, "ZXQINTBODY") || !strings.Contains(internalBlob, card.LockedTitle) {
305 t.Fatalf("internal:\n%s", internalBlob)
306 }
307 bot = crawlerGet(t, tim, ts.URL+"/tim/zxqint")
308 botBody = read(t, bot)
309 if strings.Contains(botBody, "zxqint") || strings.Contains(botBody, "ZXQINTBODY") || !strings.Contains(botBody, card.LockedTitle) {
310 t.Fatalf("crawler-internal:\n%s", botBody)
311 }
312
313 oem := read(t, mustGet(t, tim, ts.URL+"/api/v1/oembed?url="+url.QueryEscape("http://git.example/tim/widgets")))
314 if !strings.Contains(oem, `"provider_name":"BlueGit"`) || !strings.Contains(oem, "tim/widgets") || !strings.Contains(oem, "Een widget die telt.") {
315 t.Fatalf("oembed:\n%s", oem)
316 }
317 oemPriv := read(t, mustGet(t, tim, ts.URL+"/api/v1/oembed?url="+url.QueryEscape("http://git.example/tim/zxqpriv")))
318 if strings.Contains(oemPriv, "zxqpriv") || strings.Contains(oemPriv, "ZXQPRIVREADME") || !strings.Contains(oemPriv, card.LockedTitle) {
319 t.Fatalf("oembed prive:\n%s", oemPriv)
320 }
321
322 info := read(t, mustGet(t, anon, ts.URL+"/-/info"))
323 for _, want := range []string{`id="previews"`, "Open Graph", card.LockedTitle, "#L10-20"} {
324 if !strings.Contains(info, want) {
325 t.Fatalf("info mist %q", want)
326 }
327 }
328}
329
330func twoDigits(n int) string {
331 if n < 10 {
332 return "0" + string(rune('0'+n))
333 }
334 return string(rune('0'+n/10)) + string(rune('0'+n%10))
335}
336
337func socialBlob(page string) string {
338 var b strings.Builder
339 for _, key := range []string{"og:title", "og:description", "og:url", "og:image", "og:site_name", "twitter:title", "twitter:description", "twitter:image", "description", "theme-color"} {
340 b.WriteString(metaContent(page, "property", key))
341 b.WriteString("\n")
342 b.WriteString(metaContent(page, "name", key))
343 b.WriteString("\n")
344 }
345 const needle = `application/json+oembed" href="`
346 if i := strings.Index(page, needle); i >= 0 {
347 rest := page[i+len(needle):]
348 if j := strings.Index(rest, `"`); j >= 0 {
349 b.WriteString(rest[:j])
350 }
351 }
352 return b.String()
353}
354
355func metaContent(page, attr, key string) string {
356 tag := attr + `="` + key + `" content="`
357 i := strings.Index(page, tag)
358 if i < 0 {
359 return ""
360 }
361 rest := page[i+len(tag):]
362 j := strings.Index(rest, `"`)
363 if j < 0 {
364 return ""
365 }
366 return rest[:j]
367}
368
369func crawlerGet(t *testing.T, c *http.Client, raw string) *http.Response {
370 t.Helper()
371 req, err := http.NewRequest(http.MethodGet, raw, nil)
372 if err != nil {
373 t.Fatal(err)
374 }
375 req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)")
376 res, err := c.Do(req)
377 if err != nil {
378 t.Fatal(err)
379 }
380 return res
381}
internal/server/templates/info.html +2 −0
@@ -67,6 +67,8 @@
67 67 <pre class="spec-example">{{.IssueDoc}}</pre>
68 68 <h2 id="templates">{{t "info.sec.templates"}}</h2>
69 69 <p>{{t "info.tpl.lead"}}</p>
70 <h2 id="previews">{{t "info.sec.previews"}}</h2>
71 <p>{{t "info.card.lead"}}</p>
70 72 <script type="application/json" id="bluegit-ci-spec">{{.SpecJSON}}</script>
71 73 <script type="application/json" id="bluegit-api">{{.APIJSON}}</script>
72 74 </article>
@@ -67,6 +67,8 @@
67 <pre class="spec-example">{{.IssueDoc}}</pre>
67 <pre class="spec-example">{{.IssueDoc}}</pre>
68 <h2 id="templates">{{t "info.sec.templates"}}</h2>
68 <h2 id="templates">{{t "info.sec.templates"}}</h2>
69 <p>{{t "info.tpl.lead"}}</p>
69 <p>{{t "info.tpl.lead"}}</p>
70 <h2 id="previews">{{t "info.sec.previews"}}</h2>
71 <p>{{t "info.card.lead"}}</p>
70 <script type="application/json" id="bluegit-ci-spec">{{.SpecJSON}}</script>
72 <script type="application/json" id="bluegit-ci-spec">{{.SpecJSON}}</script>
71 <script type="application/json" id="bluegit-api">{{.APIJSON}}</script>
73 <script type="application/json" id="bluegit-api">{{.APIJSON}}</script>
72</article>
74</article>
internal/server/templates/layout.html +18 −0
@@ -5,6 +5,24 @@
5 5 <meta charset="utf-8">
6 6 <meta name="viewport" content="width=device-width, initial-scale=1">
7 7 <title>{{if .Title}}{{.Title}} · {{end}}BlueGit</title>
8 {{if .Social}}
9 <meta name="theme-color" content="{{.Social.Theme}}">
10 <meta name="description" content="{{.Social.Blurb}}">
11 <meta property="og:site_name" content="BlueGit">
12 <meta property="og:type" content="website">
13 <meta property="og:title" content="{{.Social.Title}}">
14 <meta property="og:description" content="{{.Social.Blurb}}">
15 <meta property="og:url" content="{{.Social.URL}}">
16 <meta property="og:image" content="{{.Social.Image}}">
17 <meta property="og:image:type" content="image/png">
18 <meta property="og:image:width" content="1200">
19 <meta property="og:image:height" content="630">
20 <meta name="twitter:card" content="summary_large_image">
21 <meta name="twitter:title" content="{{.Social.Title}}">
22 <meta name="twitter:description" content="{{.Social.Blurb}}">
23 <meta name="twitter:image" content="{{.Social.Image}}">
24 <link rel="alternate" type="application/json+oembed" href="{{.Social.OEmbed}}" title="BlueGit">
25 {{end}}
8 26 <link rel="icon" href="/assets/logo.svg" type="image/svg+xml">
9 27 <link rel="stylesheet" href="/assets/style.css">
10 28 </head>
@@ -5,6 +5,24 @@
5 <meta charset="utf-8">
5 <meta charset="utf-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1">
6 <meta name="viewport" content="width=device-width, initial-scale=1">
7 <title>{{if .Title}}{{.Title}} · {{end}}BlueGit</title>
7 <title>{{if .Title}}{{.Title}} · {{end}}BlueGit</title>
8 {{if .Social}}
9 <meta name="theme-color" content="{{.Social.Theme}}">
10 <meta name="description" content="{{.Social.Blurb}}">
11 <meta property="og:site_name" content="BlueGit">
12 <meta property="og:type" content="website">
13 <meta property="og:title" content="{{.Social.Title}}">
14 <meta property="og:description" content="{{.Social.Blurb}}">
15 <meta property="og:url" content="{{.Social.URL}}">
16 <meta property="og:image" content="{{.Social.Image}}">
17 <meta property="og:image:type" content="image/png">
18 <meta property="og:image:width" content="1200">
19 <meta property="og:image:height" content="630">
20 <meta name="twitter:card" content="summary_large_image">
21 <meta name="twitter:title" content="{{.Social.Title}}">
22 <meta name="twitter:description" content="{{.Social.Blurb}}">
23 <meta name="twitter:image" content="{{.Social.Image}}">
24 <link rel="alternate" type="application/json+oembed" href="{{.Social.OEmbed}}" title="BlueGit">
25 {{end}}
8 <link rel="icon" href="/assets/logo.svg" type="image/svg+xml">
26 <link rel="icon" href="/assets/logo.svg" type="image/svg+xml">
9 <link rel="stylesheet" href="/assets/style.css">
27 <link rel="stylesheet" href="/assets/style.css">
10</head>
28</head>
internal/store/repos.go +11 −0
@@ -303,6 +303,17 @@ func (s *Store) ListRepoIDs(ctx context.Context, userID int64) ([]int64, error)
303 303 return ids, rows.Err()
304 304 }
305 305
306 // CountRepos telt repositories van een eigenaar. publicOnly slaat privé over.
307 func (s *Store) CountRepos(ctx context.Context, ownerKind string, ownerID int64, publicOnly bool) (int, error) {
308 q := `SELECT COUNT(*) FROM repos WHERE owner_kind = ? AND owner_id = ?`
309 if publicOnly {
310 q += ` AND visibility = 'public'`
311 }
312 var n int
313 err := s.db.QueryRowContext(ctx, q, ownerKind, ownerID).Scan(&n)
314 return n, err
315 }
316
306 317 // ReposByGroup geeft de repositories van een groep.
307 318 func (s *Store) ReposByGroup(ctx context.Context, groupID int64) ([]Repo, error) {
308 319 rows, err := s.db.QueryContext(ctx, repoSelect+` WHERE r.owner_kind = 'group' AND r.owner_id = ? ORDER BY r.name`, groupID)
@@ -303,6 +303,17 @@ func (s *Store) ListRepoIDs(ctx context.Context, userID int64) ([]int64, error)
303 return ids, rows.Err()
303 return ids, rows.Err()
304}
304}
305
305
306// CountRepos telt repositories van een eigenaar. publicOnly slaat privé over.
307func (s *Store) CountRepos(ctx context.Context, ownerKind string, ownerID int64, publicOnly bool) (int, error) {
308 q := `SELECT COUNT(*) FROM repos WHERE owner_kind = ? AND owner_id = ?`
309 if publicOnly {
310 q += ` AND visibility = 'public'`
311 }
312 var n int
313 err := s.db.QueryRowContext(ctx, q, ownerKind, ownerID).Scan(&n)
314 return n, err
315}
316
306// ReposByGroup geeft de repositories van een groep.
317// ReposByGroup geeft de repositories van een groep.
307func (s *Store) ReposByGroup(ctx context.Context, groupID int64) ([]Repo, error) {
318func (s *Store) ReposByGroup(ctx context.Context, groupID int64) ([]Repo, error) {
308 rows, err := s.db.QueryContext(ctx, repoSelect+` WHERE r.owner_kind = 'group' AND r.owner_id = ? ORDER BY r.name`, groupID)
319 rows, err := s.db.QueryContext(ctx, repoSelect+` WHERE r.owner_kind = 'group' AND r.owner_id = ? ORDER BY r.name`, groupID)