this repo has no description
1package routes
2
3import (
4 "compress/gzip"
5 "errors"
6 "fmt"
7 "html/template"
8 "log"
9 "net/http"
10 "os"
11 "path/filepath"
12 "sort"
13 "strconv"
14 "strings"
15 "time"
16
17 comatproto "github.com/bluesky-social/indigo/api/atproto"
18 lexutil "github.com/bluesky-social/indigo/lex/util"
19 "github.com/dustin/go-humanize"
20 "github.com/go-chi/chi/v5"
21 "github.com/go-git/go-git/v5/plumbing"
22 "github.com/google/uuid"
23 "github.com/gorilla/sessions"
24 shbild "github.com/icyphox/bild/api/bild"
25 "github.com/icyphox/bild/auth"
26 "github.com/icyphox/bild/config"
27 "github.com/icyphox/bild/db"
28 "github.com/icyphox/bild/git"
29 "github.com/russross/blackfriday/v2"
30 "golang.org/x/crypto/ssh"
31)
32
33type Handle struct {
34 c *config.Config
35 t *template.Template
36 s *sessions.CookieStore
37 db *db.DB
38 auth *auth.Auth
39}
40
41func (h *Handle) Index(w http.ResponseWriter, r *http.Request) {
42 name := displayRepoName(r)
43 path := filepath.Join(h.c.Repo.ScanPath, name)
44 dirs, err := os.ReadDir(path)
45 if err != nil {
46 h.Write500(w)
47 log.Printf("reading scan path: %s", err)
48 return
49 }
50
51 type info struct {
52 DisplayName, Name, Desc, Idle string
53 d time.Time
54 }
55
56 infos := []info{}
57
58 for _, dir := range dirs {
59 name := dir.Name()
60 if !dir.IsDir() || h.isIgnored(name) || h.isUnlisted(name) {
61 continue
62 }
63
64 gr, err := git.Open(path, "")
65 if err != nil {
66 log.Println(err)
67 continue
68 }
69
70 c, err := gr.LastCommit()
71 if err != nil {
72 h.Write500(w)
73 log.Println(err)
74 return
75 }
76
77 infos = append(infos, info{
78 DisplayName: trimDotGit(name),
79 Name: name,
80 Desc: getDescription(path),
81 Idle: humanize.Time(c.Author.When),
82 d: c.Author.When,
83 })
84 }
85
86 sort.Slice(infos, func(i, j int) bool {
87 return infos[j].d.Before(infos[i].d)
88 })
89
90 data := make(map[string]interface{})
91 data["meta"] = h.c.Meta
92 data["info"] = infos
93
94 if err := h.t.ExecuteTemplate(w, "index", data); err != nil {
95 log.Println(err)
96 return
97 }
98}
99
100func (h *Handle) RepoIndex(w http.ResponseWriter, r *http.Request) {
101 name := displayRepoName(r)
102 if h.isIgnored(name) {
103 h.Write404(w)
104 return
105 }
106
107 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
108
109 gr, err := git.Open(path, "")
110 if err != nil {
111 if errors.Is(err, plumbing.ErrReferenceNotFound) {
112 h.t.ExecuteTemplate(w, "repo/empty", nil)
113 return
114 } else {
115 h.Write404(w)
116 return
117 }
118 }
119 commits, err := gr.Commits()
120 if err != nil {
121 h.Write500(w)
122 log.Println(err)
123 return
124 }
125
126 var readmeContent template.HTML
127 for _, readme := range h.c.Repo.Readme {
128 ext := filepath.Ext(readme)
129 content, _ := gr.FileContent(readme)
130 if len(content) > 0 {
131 switch ext {
132 case ".md", ".mkd", ".markdown":
133 unsafe := blackfriday.Run(
134 []byte(content),
135 blackfriday.WithExtensions(blackfriday.CommonExtensions),
136 )
137 html := sanitize(unsafe)
138 readmeContent = template.HTML(html)
139 default:
140 safe := sanitize([]byte(content))
141 readmeContent = template.HTML(
142 fmt.Sprintf(`<pre>%s</pre>`, safe),
143 )
144 }
145 break
146 }
147 }
148
149 if readmeContent == "" {
150 log.Printf("no readme found for %s", name)
151 }
152
153 mainBranch, err := gr.FindMainBranch(h.c.Repo.MainBranch)
154 if err != nil {
155 h.Write500(w)
156 log.Println(err)
157 return
158 }
159
160 if len(commits) >= 3 {
161 commits = commits[:3]
162 }
163
164 data := make(map[string]any)
165 data["name"] = name
166 data["displayname"] = trimDotGit(name)
167 data["ref"] = mainBranch
168 data["readme"] = readmeContent
169 data["commits"] = commits
170 data["desc"] = getDescription(path)
171 data["servername"] = h.c.Server.Name
172 data["meta"] = h.c.Meta
173 data["gomod"] = isGoModule(gr)
174
175 if err := h.t.ExecuteTemplate(w, "repo/repo", data); err != nil {
176 log.Println(err)
177 return
178 }
179
180 return
181}
182
183func (h *Handle) RepoTree(w http.ResponseWriter, r *http.Request) {
184 name := displayRepoName(r)
185 if h.isIgnored(name) {
186 h.Write404(w)
187 return
188 }
189 treePath := chi.URLParam(r, "*")
190 ref := chi.URLParam(r, "ref")
191
192 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
193 gr, err := git.Open(path, ref)
194 if err != nil {
195 h.Write404(w)
196 return
197 }
198
199 files, err := gr.FileTree(treePath)
200 if err != nil {
201 h.Write500(w)
202 log.Println(err)
203 return
204 }
205
206 data := make(map[string]any)
207 data["name"] = name
208 data["displayname"] = trimDotGit(name)
209 data["ref"] = ref
210 data["parent"] = treePath
211 data["desc"] = getDescription(path)
212 data["dotdot"] = filepath.Dir(treePath)
213
214 h.listFiles(files, data, w)
215 return
216}
217
218func (h *Handle) FileContent(w http.ResponseWriter, r *http.Request) {
219 var raw bool
220 if rawParam, err := strconv.ParseBool(r.URL.Query().Get("raw")); err == nil {
221 raw = rawParam
222 }
223
224 name := displayRepoName(r)
225
226 if h.isIgnored(name) {
227 h.Write404(w)
228 return
229 }
230 treePath := chi.URLParam(r, "*")
231 ref := chi.URLParam(r, "ref")
232
233 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
234 gr, err := git.Open(path, ref)
235 if err != nil {
236 h.Write404(w)
237 return
238 }
239
240 contents, err := gr.FileContent(treePath)
241 if err != nil {
242 h.Write500(w)
243 return
244 }
245 data := make(map[string]any)
246 data["name"] = name
247 data["displayname"] = trimDotGit(name)
248 data["ref"] = ref
249 data["desc"] = getDescription(path)
250 data["path"] = treePath
251
252 safe := sanitize([]byte(contents))
253
254 if raw {
255 h.showRaw(string(safe), w)
256 } else {
257 if h.c.Meta.SyntaxHighlight == "" {
258 h.showFile(string(safe), data, w)
259 } else {
260 h.showFileWithHighlight(treePath, string(safe), data, w)
261 }
262 }
263}
264
265func (h *Handle) Archive(w http.ResponseWriter, r *http.Request) {
266 name := displayRepoName(r)
267 if h.isIgnored(name) {
268 h.Write404(w)
269 return
270 }
271
272 file := chi.URLParam(r, "file")
273
274 // TODO: extend this to add more files compression (e.g.: xz)
275 if !strings.HasSuffix(file, ".tar.gz") {
276 h.Write404(w)
277 return
278 }
279
280 ref := strings.TrimSuffix(file, ".tar.gz")
281
282 // This allows the browser to use a proper name for the file when
283 // downloading
284 filename := fmt.Sprintf("%s-%s.tar.gz", name, ref)
285 setContentDisposition(w, filename)
286 setGZipMIME(w)
287
288 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
289 gr, err := git.Open(path, ref)
290 if err != nil {
291 h.Write404(w)
292 return
293 }
294
295 gw := gzip.NewWriter(w)
296 defer gw.Close()
297
298 prefix := fmt.Sprintf("%s-%s", name, ref)
299 err = gr.WriteTar(gw, prefix)
300 if err != nil {
301 // once we start writing to the body we can't report error anymore
302 // so we are only left with printing the error.
303 log.Println(err)
304 return
305 }
306
307 err = gw.Flush()
308 if err != nil {
309 // once we start writing to the body we can't report error anymore
310 // so we are only left with printing the error.
311 log.Println(err)
312 return
313 }
314}
315
316func (h *Handle) Log(w http.ResponseWriter, r *http.Request) {
317 name := displayRepoName(r)
318 if h.isIgnored(name) {
319 h.Write404(w)
320 return
321 }
322 ref := chi.URLParam(r, "ref")
323
324 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
325 gr, err := git.Open(path, ref)
326 if err != nil {
327 h.Write404(w)
328 return
329 }
330
331 commits, err := gr.Commits()
332 if err != nil {
333 h.Write500(w)
334 log.Println(err)
335 return
336 }
337
338 data := make(map[string]interface{})
339 data["commits"] = commits
340 data["meta"] = h.c.Meta
341 data["name"] = name
342 data["displayname"] = trimDotGit(name)
343 data["ref"] = ref
344 data["desc"] = getDescription(path)
345 data["log"] = true
346
347 if err := h.t.ExecuteTemplate(w, "repo/log", data); err != nil {
348 log.Println(err)
349 return
350 }
351}
352
353func (h *Handle) Diff(w http.ResponseWriter, r *http.Request) {
354 name := displayRepoName(r)
355 if h.isIgnored(name) {
356 h.Write404(w)
357 return
358 }
359 ref := chi.URLParam(r, "ref")
360
361 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
362 gr, err := git.Open(path, ref)
363 if err != nil {
364 h.Write404(w)
365 return
366 }
367
368 diff, err := gr.Diff()
369 if err != nil {
370 h.Write500(w)
371 log.Println(err)
372 return
373 }
374
375 data := make(map[string]interface{})
376
377 data["commit"] = diff.Commit
378 data["stat"] = diff.Stat
379 data["diff"] = diff.Diff
380 data["meta"] = h.c.Meta
381 data["name"] = name
382 data["displayname"] = trimDotGit(name)
383 data["ref"] = ref
384 data["desc"] = getDescription(path)
385
386 if err := h.t.ExecuteTemplate(w, "repo/commit", data); err != nil {
387 log.Println(err)
388 return
389 }
390}
391
392func (h *Handle) Refs(w http.ResponseWriter, r *http.Request) {
393 name := chi.URLParam(r, "name")
394 if h.isIgnored(name) {
395 h.Write404(w)
396 return
397 }
398
399 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
400 gr, err := git.Open(path, "")
401 if err != nil {
402 h.Write404(w)
403 return
404 }
405
406 tags, err := gr.Tags()
407 if err != nil {
408 // Non-fatal, we *should* have at least one branch to show.
409 log.Println(err)
410 }
411
412 branches, err := gr.Branches()
413 if err != nil {
414 log.Println(err)
415 h.Write500(w)
416 return
417 }
418
419 data := make(map[string]interface{})
420
421 data["meta"] = h.c.Meta
422 data["name"] = name
423 data["displayname"] = trimDotGit(name)
424 data["branches"] = branches
425 data["tags"] = tags
426 data["desc"] = getDescription(path)
427
428 if err := h.t.ExecuteTemplate(w, "repo/refs", data); err != nil {
429 log.Println(err)
430 return
431 }
432}
433
434func (h *Handle) Collaborators(w http.ResponseWriter, r *http.Request) {
435 // put repo resolution in middleware
436 repoOwnerHandle := chi.URLParam(r, "user")
437 repoOwner, err := auth.ResolveIdent(r.Context(), repoOwnerHandle)
438 if err != nil {
439 log.Println("invalid did")
440 http.Error(w, "invalid did", http.StatusNotFound)
441 return
442 }
443 repoName := chi.URLParam(r, "name")
444
445 switch r.Method {
446 case http.MethodGet:
447 // TODO fetch a list of collaborators and their access rights
448 http.Error(w, "unimpl 1", http.StatusInternalServerError)
449 return
450 case http.MethodPut:
451 newUser := r.FormValue("newUser")
452 if newUser == "" {
453 // TODO: htmx this
454 http.Error(w, "unimpl 2", http.StatusInternalServerError)
455 return
456 }
457 newUserIdentity, err := auth.ResolveIdent(r.Context(), newUser)
458 if err != nil {
459 // TODO: htmx this
460 log.Println("invalid handle")
461 http.Error(w, "unimpl 3", http.StatusBadRequest)
462 return
463 }
464 err = h.db.SetWriter(newUserIdentity.DID.String(), repoOwner.DID.String(), repoName)
465 if err != nil {
466 // TODO: htmx this
467 log.Println("failed to add collaborator")
468 http.Error(w, "unimpl 4", http.StatusInternalServerError)
469 return
470 }
471
472 log.Println("success")
473 return
474
475 }
476}
477
478func (h *Handle) ServeStatic(w http.ResponseWriter, r *http.Request) {
479 f := chi.URLParam(r, "file")
480 f = filepath.Clean(filepath.Join(h.c.Dirs.Static, f))
481
482 http.ServeFile(w, r, f)
483}
484
485func (h *Handle) Login(w http.ResponseWriter, r *http.Request) {
486 switch r.Method {
487 case http.MethodGet:
488 if err := h.t.ExecuteTemplate(w, "user/login", nil); err != nil {
489 log.Println(err)
490 return
491 }
492 case http.MethodPost:
493 username := r.FormValue("username")
494 appPassword := r.FormValue("app_password")
495
496 atSession, err := h.auth.CreateInitialSession(w, r, username, appPassword)
497 if err != nil {
498 h.WriteOOBNotice(w, "login", "Invalid username or app password.")
499 log.Printf("creating initial session: %s", err)
500 return
501 }
502
503 err = h.auth.StoreSession(r, w, &atSession, nil)
504 if err != nil {
505 h.WriteOOBNotice(w, "login", "Failed to store session.")
506 log.Printf("storing session: %s", err)
507 return
508 }
509
510 log.Printf("successfully saved session for %s (%s)", atSession.Handle, atSession.Did)
511 http.Redirect(w, r, "/", http.StatusSeeOther)
512 return
513 }
514}
515
516func (h *Handle) Keys(w http.ResponseWriter, r *http.Request) {
517 session, _ := h.s.Get(r, "bild-session")
518 did := session.Values["did"].(string)
519
520 switch r.Method {
521 case http.MethodGet:
522 keys, err := h.db.GetPublicKeys(did)
523 if err != nil {
524 h.WriteOOBNotice(w, "keys", "Failed to list keys. Try again later.")
525 log.Println(err)
526 return
527 }
528
529 data := make(map[string]interface{})
530 data["keys"] = keys
531 if err := h.t.ExecuteTemplate(w, "settings/keys", data); err != nil {
532 log.Println(err)
533 return
534 }
535 case http.MethodPut:
536 key := r.FormValue("key")
537 name := r.FormValue("name")
538 client, _ := h.auth.AuthorizedClient(r)
539
540 _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key))
541 if err != nil {
542 h.WriteOOBNotice(w, "keys", "Invalid public key. Check your formatting and try again.")
543 log.Printf("parsing public key: %s", err)
544 return
545 }
546
547 if err := h.db.AddPublicKey(did, name, key); err != nil {
548 h.WriteOOBNotice(w, "keys", "Failed to add key.")
549 log.Printf("adding public key: %s", err)
550 return
551 }
552
553 // store in pds too
554 resp, err := comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
555 Collection: "sh.bild.publicKey",
556 Repo: did,
557 Rkey: uuid.New().String(),
558 Record: &lexutil.LexiconTypeDecoder{Val: &shbild.PublicKey{
559 Created: time.Now().String(),
560 Key: key,
561 Name: name,
562 }},
563 })
564
565 // invalid record
566 if err != nil {
567 h.WriteOOBNotice(w, "keys", "Invalid inputs. Check your formatting and try again.")
568 log.Printf("failed to create record: %s", err)
569 return
570 }
571
572 log.Println("created atproto record: ", resp.Uri)
573
574 h.WriteOOBNotice(w, "keys", "Key added!")
575 return
576 }
577}
578
579func (h *Handle) NewRepo(w http.ResponseWriter, r *http.Request) {
580 session, _ := h.s.Get(r, "bild-session")
581 did := session.Values["did"].(string)
582 handle := session.Values["handle"].(string)
583
584 switch r.Method {
585 case http.MethodGet:
586 if err := h.t.ExecuteTemplate(w, "repo/new", nil); err != nil {
587 log.Println(err)
588 return
589 }
590 case http.MethodPut:
591 name := r.FormValue("name")
592 description := r.FormValue("description")
593
594 repoPath := filepath.Join(h.c.Repo.ScanPath, did, name)
595 err := git.InitBare(repoPath)
596 if err != nil {
597 h.WriteOOBNotice(w, "repo", "Error creating repo. Try again later.")
598 return
599 }
600
601 // For use by repoguard
602 didPath := filepath.Join(repoPath, "did")
603 err = os.WriteFile(didPath, []byte(did), 0644)
604 if err != nil {
605 h.WriteOOBNotice(w, "repo", "Error creating repo. Try again later.")
606 return
607 }
608
609 // TODO: add repo & setting-to-owner must happen in the same transaction
610 err = h.db.AddRepo(did, name, description)
611 if err != nil {
612 log.Println(err)
613 h.WriteOOBNotice(w, "repo", "Error creating repo. Try again later.")
614 return
615 }
616 // current user is set to owner of did/name repo
617 err = h.db.SetOwner(did, did, name)
618 if err != nil {
619 log.Println(err)
620 h.WriteOOBNotice(w, "repo", "Error creating repo. Try again later.")
621 return
622 }
623
624 w.Header().Set("HX-Redirect", fmt.Sprintf("/@%s/%s", handle, name))
625 w.WriteHeader(http.StatusOK)
626 }
627}
628
629func (h *Handle) Timeline(w http.ResponseWriter, r *http.Request) {
630 session, err := h.s.Get(r, "bild-session")
631 user := make(map[string]string)
632 if err != nil || session.IsNew {
633 // user is not logged in
634 } else {
635 user["handle"] = session.Values["handle"].(string)
636 user["did"] = session.Values["did"].(string)
637 }
638
639 if err := h.t.ExecuteTemplate(w, "timeline", user); err != nil {
640 log.Println(err)
641 return
642 }
643}