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