BlueGit

timfa bluegit

Files

bluegit / internal / server / social.go

social.go

social.go 19.2 KiB Download Raw
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 rev := repo.DefaultBranch
154 if prose == "" && s.StoragePath() != "" {
155 if entries, err := s.cTree(ctx, repo, rev, ""); err == nil {
156 readme, _ := findDocs(entries)
157 if readme != "" {
158 if text, binary, err := s.cDoc(ctx, repo, rev, readme, 80_000); err == nil && !binary {
159 prose = card.Excerpt(text, 180)
160 }
161 }
162 }
163 }
164 var facts []string
165 if lang := s.repoLanguage(ctx, repo, rev); lang != "" {
166 facts = append(facts, lang)
167 }
168 if counts, _, err := s.Store.StarInfo(ctx, 0, []int64{repo.ID}); err == nil {
169 facts = append(facts, starLabel(counts[repo.ID]))
170 }
171 if s.StoragePath() != "" {
172 if c, err := s.cLastCommit(ctx, repo, rev, ""); err == nil && c.SHA != "" {
173 short := c.SHA
174 if len(short) > 8 {
175 short = short[:8]
176 }
177 facts = append(facts, short+" "+card.Clip(c.Subject, 72))
178 }
179 }
180 return card.Render{Meta: card.Meta{
181 Title: repo.OwnerPath + "/" + repo.Name, Description: prose, URL: page, Image: img, OEmbed: oem,
182 Theme: "#1f6feb", Kind: "repository", Facts: facts, Initial: repo.Name,
183 }, Avatar: s.avatarForRepo(ctx, repo)}
184}
185
186func (s *Server) fileCard(ctx context.Context, repo store.Repo, rel string, q url.Values, fragment, page, img, oem string) card.Render {
187 rel, err := cleanRel(rel)
188 base := s.repoCard(ctx, repo, page, img, oem)
189 if err != nil || rel == "" || s.StoragePath() == "" {
190 return base
191 }
192 rev := safeRev(q.Get("rev"), repo.DefaultBranch)
193 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
194 text, binary, err := gitrepo.Blob(ctx, s.Git, dir, rev, rel, 80_000)
195 name := rel
196 if i := strings.LastIndex(rel, "/"); i >= 0 {
197 name = rel[i+1:]
198 }
199 from, to, ranged := lineBounds(q, fragment)
200 desc := "Binary file"
201 if err == nil && !binary {
202 desc = card.Snippet(text, from, to, ranged)
203 }
204 facts := []string{repo.OwnerPath + "/" + repo.Name}
205 if lang := langByName(name); lang != "" {
206 facts = append(facts, lang)
207 }
208 if ranged {
209 if from == to {
210 facts = append(facts, fmt.Sprintf("L%d", from))
211 } else {
212 facts = append(facts, fmt.Sprintf("L%d-%d", from, to))
213 }
214 }
215 return card.Render{Meta: card.Meta{
216 Title: name, Description: desc, URL: page, Image: img, OEmbed: oem,
217 Theme: "#1f6feb", Kind: "file", Facts: facts, Initial: name,
218 }, Avatar: base.Avatar}
219}
220
221func (s *Server) commitCard(ctx context.Context, repo store.Repo, sha, page, img, oem string) card.Render {
222 base := s.repoCard(ctx, repo, page, img, oem)
223 if !safeSHA(sha) || s.StoragePath() == "" {
224 return base
225 }
226 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
227 c, err := gitrepo.Show(ctx, s.Git, dir, sha)
228 if err != nil {
229 return base
230 }
231 short := c.SHA
232 if len(short) > 8 {
233 short = short[:8]
234 }
235 facts := []string{c.Author, short}
236 if changes, err := gitrepo.CommitFileChanges(ctx, s.Git, dir, c.SHA); err == nil {
237 add, del := 0, 0
238 for _, ch := range changes {
239 add += ch.Added
240 del += ch.Deleted
241 }
242 facts = append(facts, fmt.Sprintf("+%d −%d", add, del), fmt.Sprintf("%d files", len(changes)))
243 }
244 return card.Render{Meta: card.Meta{
245 Title: card.Clip(c.Subject, 90), Description: card.Excerpt(c.Body, 180), URL: page, Image: img, OEmbed: oem,
246 Theme: "#0c3f86", Kind: "commit", Facts: facts, Initial: c.Author,
247 }, Avatar: base.Avatar}
248}
249
250func (s *Server) mrCard(ctx context.Context, repo store.Repo, number int64, page, img, oem string) card.Render {
251 base := s.repoCard(ctx, repo, page, img, oem)
252 mr, err := s.Store.MergeRequestByNumber(ctx, repo.ID, number)
253 if err != nil {
254 return base
255 }
256 status := mr.Status
257 if mr.Draft && status == "open" {
258 status = "draft"
259 }
260 facts := []string{status, mr.SourceBranch + " → " + mr.TargetBranch, mr.Author}
261 if s.StoragePath() != "" {
262 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
263 if changes, err := gitrepo.CompareChanges(ctx, s.Git, dir, mr.TargetBranch, mr.SourceBranch); err == nil {
264 add, del := 0, 0
265 for _, ch := range changes {
266 add += ch.Added
267 del += ch.Deleted
268 }
269 facts = append(facts, fmt.Sprintf("+%d −%d", add, del))
270 }
271 }
272 if p, err := s.Store.LatestMergePipeline(ctx, repo.ID, mr.ID); err == nil {
273 jobs, _ := s.Store.JobsByPipeline(ctx, p.ID)
274 facts = append(facts, displayStatus(p.Status, jobs))
275 }
276 theme := "#1f6feb"
277 switch status {
278 case "merged":
279 theme = "#146c43"
280 case "closed":
281 theme = "#5c6b80"
282 }
283 return card.Render{Meta: card.Meta{
284 Title: "!" + strconv.FormatInt(mr.Number, 10) + " " + mr.Title,
285 Description: card.Excerpt(mr.Description, 180), URL: page, Image: img, OEmbed: oem,
286 Theme: theme, Kind: "merge_request", Facts: facts, Initial: mr.Author,
287 }, Avatar: base.Avatar}
288}
289
290func (s *Server) issueCard(ctx context.Context, repo store.Repo, number int64, page, img, oem string) card.Render {
291 iss, err := s.Store.IssueByNumber(ctx, repo.ID, number)
292 if err != nil {
293 return s.repoCard(ctx, repo, page, img, oem)
294 }
295 if iss.Confidential {
296 return s.lockedRender()
297 }
298 var labels []string
299 for _, l := range iss.Labels {
300 labels = append(labels, l.Name)
301 }
302 facts := []string{iss.Status}
303 if len(labels) > 0 {
304 facts = append(facts, strings.Join(labels, ", "))
305 }
306 facts = append(facts, iss.Author)
307 return card.Render{Meta: card.Meta{
308 Title: "#" + strconv.FormatInt(iss.Number, 10) + " " + iss.Title,
309 Description: card.Excerpt(iss.Description, 180), URL: page, Image: img, OEmbed: oem,
310 Theme: "#9a6700", Kind: "issue", Facts: facts, Initial: iss.Author,
311 }, Avatar: s.avatarForRepo(ctx, repo)}
312}
313
314func (s *Server) pipeCard(ctx context.Context, repo store.Repo, id int64, page, img, oem string) card.Render {
315 base := s.repoCard(ctx, repo, page, img, oem)
316 p, err := s.Store.PipelineByID(ctx, repo.ID, id)
317 if err != nil {
318 return base
319 }
320 jobs, _ := s.Store.JobsByPipeline(ctx, p.ID)
321 status := displayStatus(p.Status, jobs)
322 theme := "#1f6feb"
323 switch status {
324 case "passed":
325 theme = "#146c43"
326 case "failed":
327 theme = "#9f2d2d"
328 case "running":
329 theme = "#9a6700"
330 }
331 facts := []string{status}
332 if p.Ref != "" {
333 facts = append(facts, strings.TrimPrefix(p.Ref, "refs/heads/"))
334 }
335 if p.CommitTitle != "" {
336 facts = append(facts, card.Clip(p.CommitTitle, 72))
337 }
338 if p.Actor != "" {
339 facts = append(facts, p.Actor)
340 }
341 return card.Render{Meta: card.Meta{
342 Title: "#" + strconv.FormatInt(p.ID, 10) + " " + status, Description: card.Excerpt(p.CommitTitle, 180),
343 URL: page, Image: img, OEmbed: oem, Theme: theme, Kind: "pipeline", Facts: facts, Initial: repo.Name,
344 }, Avatar: base.Avatar}
345}
346
347func (s *Server) releaseCard(ctx context.Context, repo store.Repo, page, img, oem string) card.Render {
348 base := s.repoCard(ctx, repo, page, img, oem)
349 list, err := s.Store.ListReleases(ctx, repo.ID)
350 if err != nil || len(list) == 0 {
351 return card.Render{Meta: card.Meta{
352 Title: "Releases", Description: repo.OwnerPath + "/" + repo.Name, URL: page, Image: img, OEmbed: oem,
353 Theme: "#146c43", Kind: "release", Initial: repo.Name,
354 }, Avatar: base.Avatar}
355 }
356 rel := list[0]
357 title := rel.Tag
358 if rel.Name != "" {
359 title = rel.Tag + " · " + rel.Name
360 }
361 return card.Render{Meta: card.Meta{
362 Title: title, Description: card.Excerpt(rel.Body, 180), URL: page, Image: img, OEmbed: oem,
363 Theme: "#146c43", Kind: "release", Facts: []string{repo.OwnerPath + "/" + repo.Name, rel.Tag}, Initial: repo.Name,
364 }, Avatar: base.Avatar}
365}
366
367func (s *Server) groupCard(ctx context.Context, rest, page, img, oem string) card.Render {
368 name := rest
369 if i := strings.Index(name, "/"); i >= 0 {
370 name = name[:i]
371 }
372 g, err := s.Store.GroupByPath(ctx, name)
373 if err != nil {
374 return card.Site(page, img, oem)
375 }
376 if g.Visibility != "public" {
377 return s.lockedRender()
378 }
379 n, _ := s.Store.CountRepos(ctx, "group", g.ID, true)
380 return card.Render{Meta: card.Meta{
381 Title: g.Name, Description: card.Excerpt(g.Description, 180), URL: page, Image: img, OEmbed: oem,
382 Theme: "#6f42c1", Kind: "group", Facts: []string{repoLabel(n)}, Initial: g.Name,
383 }, Avatar: s.readLogo("group", g.ID, g.LogoMIME)}
384}
385
386func (s *Server) userCard(ctx context.Context, name, page, img, oem string) card.Render {
387 u, err := s.Store.UserByUsername(ctx, name)
388 if err != nil {
389 return card.Site(page, img, oem)
390 }
391 n, _ := s.Store.CountRepos(ctx, "user", u.ID, true)
392 title := u.Username
393 if name := strings.TrimSpace(u.DisplayName); name != "" {
394 title = name
395 }
396 desc := "Public profile"
397 if bio := strings.TrimSpace(u.Bio); bio != "" {
398 desc = card.Excerpt(bio, 180)
399 }
400 return card.Render{Meta: card.Meta{
401 Title: title, Description: desc, URL: page, Image: img, OEmbed: oem,
402 Theme: "#1f6feb", Kind: "user", Facts: []string{repoLabel(n)}, Initial: u.Username,
403 }}
404}
405
406func (s *Server) avatarForRepo(ctx context.Context, repo store.Repo) []byte {
407 if b := s.readLogo("repo", repo.ID, repo.LogoMIME); len(b) > 0 {
408 return b
409 }
410 if repo.OwnerKind != "group" {
411 return nil
412 }
413 g, err := s.Store.GroupByID(ctx, repo.OwnerID)
414 if err != nil {
415 return nil
416 }
417 return s.readLogo("group", g.ID, g.LogoMIME)
418}
419
420func (s *Server) readLogo(kind string, id int64, mime string) []byte {
421 if mime != "image/png" && mime != "image/jpeg" && mime != "image/gif" {
422 return nil
423 }
424 path, err := s.logoPath(kind, id)
425 if err != nil {
426 return nil
427 }
428 data, err := os.ReadFile(path)
429 if err != nil {
430 return nil
431 }
432 img, _, err := image.Decode(bytes.NewReader(data))
433 if err != nil {
434 return nil
435 }
436 var buf bytes.Buffer
437 if err := png.Encode(&buf, img); err != nil {
438 return nil
439 }
440 return buf.Bytes()
441}
442
443func (s *Server) repoLanguage(ctx context.Context, repo store.Repo, rev string) string {
444 if s.StoragePath() == "" {
445 return ""
446 }
447 entries, err := s.cTreeAll(ctx, repo, rev)
448 if err != nil {
449 return ""
450 }
451 counts := map[string]int{}
452 for _, e := range entries {
453 if e.Type != "blob" {
454 continue
455 }
456 if strings.Contains(e.Name, "vendor/") || strings.Contains(e.Name, "node_modules/") {
457 continue
458 }
459 if lang := langByName(e.Name); lang != "" {
460 counts[lang]++
461 }
462 }
463 best, n := "", 0
464 for lang, c := range counts {
465 if c > n || (c == n && lang < best) {
466 best, n = lang, c
467 }
468 }
469 return best
470}
471
472func langByName(name string) string {
473 low := strings.ToLower(name)
474 if i := strings.LastIndex(low, "/"); i >= 0 {
475 low = low[i+1:]
476 }
477 ext := ""
478 if i := strings.LastIndex(low, "."); i >= 0 {
479 ext = low[i:]
480 }
481 if lang, ok := extLang[ext]; ok {
482 return lang
483 }
484 switch low {
485 case "dockerfile":
486 return "Dockerfile"
487 case "makefile":
488 return "Makefile"
489 default:
490 return ""
491 }
492}
493
494var extLang = map[string]string{
495 ".go": "Go", ".py": "Python", ".js": "JavaScript", ".jsx": "JavaScript", ".ts": "TypeScript", ".tsx": "TypeScript",
496 ".rs": "Rust", ".java": "Java", ".rb": "Ruby", ".php": "PHP", ".c": "C", ".h": "C", ".cpp": "C++", ".cc": "C++",
497 ".cs": "C#", ".swift": "Swift", ".kt": "Kotlin", ".html": "HTML", ".css": "CSS", ".scss": "SCSS", ".vue": "Vue",
498 ".sh": "Shell", ".yml": "YAML", ".yaml": "YAML", ".sql": "SQL", ".lua": "Lua",
499}
500
501func starLabel(n int) string {
502 if n == 1 {
503 return "1 star"
504 }
505 return strconv.Itoa(n) + " stars"
506}
507
508func repoLabel(n int) string {
509 if n == 1 {
510 return "1 repository"
511 }
512 return strconv.Itoa(n) + " repositories"
513}
514
515func lineBounds(q url.Values, fragment string) (from, to int, ok bool) {
516 if from, to, ok = card.ParseLines(fragment); ok {
517 return from, to, true
518 }
519 return card.ParseLines(q.Get("L"))
520}
521
522func (s *Server) cardPNG(w http.ResponseWriter, r *http.Request) {
523 var rend card.Render
524 if r.URL.Query().Get("locked") == "1" {
525 rend = s.lockedRender()
526 } else {
527 path := r.URL.Query().Get("path")
528 if !strings.HasPrefix(path, "/") || strings.Contains(path, "..") || strings.Contains(path, "\\") {
529 http.NotFound(w, r)
530 return
531 }
532 q := url.Values{}
533 if l := r.URL.Query().Get("L"); l != "" {
534 q.Set("L", l)
535 }
536 if rev := r.URL.Query().Get("rev"); rev != "" {
537 q.Set("rev", rev)
538 }
539 rend = s.cardForPath(r.Context(), path, q.Encode(), "")
540 }
541 svg := card.SVG(rend)
542 pngBytes, hit := s.cardCache().Get(svg)
543 if !hit {
544 var err error
545 pngBytes, err = card.Raster(svg)
546 if err != nil {
547 http.Error(w, "card", http.StatusInternalServerError)
548 return
549 }
550 s.cardCache().Put(svg, pngBytes)
551 }
552 w.Header().Set("Content-Type", "image/png")
553 w.Header().Set("Cache-Control", "public, max-age=300")
554 w.Header().Set("X-Content-Type-Options", "nosniff")
555 if hit {
556 w.Header().Set("X-Card-Cache", "hit")
557 } else {
558 w.Header().Set("X-Card-Cache", "miss")
559 }
560 _, _ = w.Write(pngBytes)
561}
562
563func (s *Server) oembed(w http.ResponseWriter, r *http.Request) {
564 var rend card.Render
565 if r.URL.Query().Get("locked") == "1" {
566 rend = s.lockedRender()
567 } else {
568 raw := r.URL.Query().Get("url")
569 u, err := url.Parse(raw)
570 if err != nil || u.Path == "" {
571 http.NotFound(w, r)
572 return
573 }
574 rend = s.cardForPath(r.Context(), u.Path, u.RawQuery, u.Fragment)
575 }
576 w.Header().Set("Content-Type", "application/json; charset=utf-8")
577 w.Header().Set("Cache-Control", "no-store")
578 _ = json.NewEncoder(w).Encode(map[string]any{
579 "version": "1.0",
580 "type": "link",
581 "title": rend.Title,
582 "description": rend.Blurb(),
583 "provider_name": "BlueGit",
584 "provider_url": s.absURL("/"),
585 "thumbnail_url": rend.Image,
586 "thumbnail_width": card.Width,
587 "thumbnail_height": card.Height,
588 })
589}
590
591func (s *Server) writeLockedCard(w http.ResponseWriter, r *http.Request) {
592 m := s.lockedRender().Meta
593 w.Header().Set("Content-Type", "text/html; charset=utf-8")
594 w.Header().Set("Cache-Control", "no-store")
595 w.Header().Set("X-Robots-Tag", "noindex")
596 w.WriteHeader(http.StatusOK)
597 title := html.EscapeString(m.Title)
598 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>`,
599 title, metaHTML(m), title)
600}
601
602func metaHTML(m card.Meta) string {
603 esc := html.EscapeString
604 var b strings.Builder
605 fmt.Fprintf(&b, `<meta name="theme-color" content="%s">`, esc(m.Theme))
606 fmt.Fprintf(&b, `<meta name="description" content="%s">`, esc(m.Blurb()))
607 b.WriteString(`<meta property="og:site_name" content="BlueGit">`)
608 b.WriteString(`<meta property="og:type" content="website">`)
609 fmt.Fprintf(&b, `<meta property="og:title" content="%s">`, esc(m.Title))
610 fmt.Fprintf(&b, `<meta property="og:description" content="%s">`, esc(m.Blurb()))
611 fmt.Fprintf(&b, `<meta property="og:url" content="%s">`, esc(m.URL))
612 fmt.Fprintf(&b, `<meta property="og:image" content="%s">`, esc(m.Image))
613 b.WriteString(`<meta property="og:image:type" content="image/png">`)
614 fmt.Fprintf(&b, `<meta property="og:image:width" content="%d">`, card.Width)
615 fmt.Fprintf(&b, `<meta property="og:image:height" content="%d">`, card.Height)
616 b.WriteString(`<meta name="twitter:card" content="summary_large_image">`)
617 fmt.Fprintf(&b, `<meta name="twitter:title" content="%s">`, esc(m.Title))
618 fmt.Fprintf(&b, `<meta name="twitter:description" content="%s">`, esc(m.Blurb()))
619 fmt.Fprintf(&b, `<meta name="twitter:image" content="%s">`, esc(m.Image))
620 fmt.Fprintf(&b, `<link rel="alternate" type="application/json+oembed" href="%s" title="BlueGit">`, esc(m.OEmbed))
621 return b.String()
622}
623
624func isCrawler(r *http.Request) bool {
625 ua := strings.ToLower(r.Header.Get("User-Agent"))
626 for _, name := range []string{
627 "discordbot", "slackbot", "twitterbot", "facebookexternalhit", "linkedinbot",
628 "telegrambot", "whatsapp", "embedly", "iframely", "redditbot", "pinterestbot",
629 "skypeuripreview",
630 } {
631 if strings.Contains(ua, name) {
632 return true
633 }
634 }
635 return false
636}