BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

fix: haal het AUR-archief van BlueGit
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
Passed f6e2ec6c History
server.go 26.9 KiB Download Raw
1// Package server is de webinterface, de git-HTTP-server en de API.
2package server
3
4import (
5 "context"
6 "crypto/rand"
7 "embed"
8 "encoding/hex"
9 "html/template"
10 "io/fs"
11 "log/slog"
12 "net/http"
13 "net/url"
14 "strings"
15 "sync"
16 "time"
17 "unicode/utf8"
18
19 "gitlab.com/Timfa/bluegit/internal/access"
20 "gitlab.com/Timfa/bluegit/internal/activity"
21 "gitlab.com/Timfa/bluegit/internal/auth"
22 "gitlab.com/Timfa/bluegit/internal/card"
23 "gitlab.com/Timfa/bluegit/internal/cispec"
24 "gitlab.com/Timfa/bluegit/internal/config"
25 "gitlab.com/Timfa/bluegit/internal/i18n"
26 "gitlab.com/Timfa/bluegit/internal/realip"
27 "gitlab.com/Timfa/bluegit/internal/runner"
28 "gitlab.com/Timfa/bluegit/internal/store"
29)
30
31//go:embed templates/*.html static/*
32var webFS embed.FS
33
34// Server bedient BlueGit.
35type Server struct {
36 Cfg config.Config
37 Store *store.Store
38 Auth auth.Provider
39 Mail auth.Mailer
40 Dev bool
41 Git string
42 HookBin string
43 Runner *runner.Runner
44 Log *slog.Logger
45 // hookSink vangt de JSON-body af in tests, vóór het HTTP-verzoek.
46 hookSink func([]byte)
47 // StateDir is de map met database en het bestand storage_path.
48 StateDir string
49 // AfterStorage krijgt het nieuwe datadisk-pad, voor runner en SSH.
50 AfterStorage func(path string)
51 // UpdateStarter start bluegit-update.service. Nil gebruikt systemctl.
52 UpdateStarter UpdateStarter
53 updateHits updateLimiter
54 tmpl *template.Template
55 byLang map[string]*template.Template
56
57 storageMu sync.RWMutex
58 storage string
59 storageSet bool
60 cards *card.Cache
61 // mergingMR zijn merge requests die opMergeMR nu zelf afrondt.
62 // AfterPush mag hun bronbranch niet alvast verwijderen.
63 mergingMR sync.Map
64}
65
66type principal struct {
67 User store.User
68 Session store.Session
69 OK bool
70}
71
72type ctxKey struct{}
73
74// Handler is de HTTP-handler met sessies en koppen.
75func (s *Server) Handler() http.Handler {
76 s.mustTemplates()
77 mux := http.NewServeMux()
78 mux.HandleFunc("GET /assets/{file}", s.asset)
79 mux.HandleFunc("GET /-/info", s.infoPage)
80 mux.HandleFunc("GET /-/card.png", s.cardPNG)
81 mux.HandleFunc("GET /api/v1/oembed", s.oembed)
82 s.mountAPI(mux)
83 mux.HandleFunc("GET /api/v1/admin/self-update", s.selfUpdateStatus)
84 mux.HandleFunc("POST /api/v1/admin/self-update", s.selfUpdate)
85 mux.HandleFunc("GET /api/v1/webhooks/openapi.json", s.webhookSpec)
86 mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
87 w.WriteHeader(http.StatusOK)
88 _, _ = w.Write([]byte("ok\n"))
89 })
90 mux.HandleFunc("GET /login", s.login)
91 mux.HandleFunc("GET /auth/callback", s.callback)
92 mux.HandleFunc("POST /logout", s.logout)
93 mux.HandleFunc("GET /{$}", s.home)
94 mux.HandleFunc("GET /new", s.newPage)
95 mux.HandleFunc("GET /new/slug", s.slugPreview)
96 mux.HandleFunc("POST /new/repo", s.createRepo)
97 mux.HandleFunc("POST /new/group", s.createGroup)
98 mux.HandleFunc("GET /setup", s.setupPage)
99 mux.HandleFunc("POST /setup", s.setupSave)
100 mux.HandleFunc("GET /settings", s.account)
101 mux.HandleFunc("POST /settings/language", s.saveLanguage)
102 mux.HandleFunc("POST /settings/profile", s.saveProfile)
103 mux.HandleFunc("POST /settings/tokens", s.createToken)
104 mux.HandleFunc("POST /settings/tokens/delete", s.deleteToken)
105 mux.HandleFunc("POST /settings/ssh", s.addSSH)
106 mux.HandleFunc("POST /settings/ssh/delete", s.deleteSSH)
107 mux.HandleFunc("GET /settings/export", s.export)
108 mux.HandleFunc("GET /users/{username}", s.profile)
109 mux.HandleFunc("GET /groups/{path}", s.groupPage)
110 mux.HandleFunc("GET /groups/{path}/logo", s.groupLogo)
111 mux.HandleFunc("POST /groups/{path}/settings", s.saveGroup)
112 mux.HandleFunc("POST /groups/{path}/approvals", s.saveGroupApproval)
113 mux.HandleFunc("POST /groups/{path}/owner", s.transferGroup)
114 mux.HandleFunc("POST /groups/{path}/logo", s.uploadGroupLogo)
115 mux.HandleFunc("POST /groups/{path}/members", s.groupMember)
116 mux.HandleFunc("POST /groups/{path}/members/remove", s.groupMemberRemove)
117 mux.HandleFunc("POST /groups/{path}/secrets", s.groupSecret)
118 mux.HandleFunc("POST /groups/{path}/secrets/reveal", s.groupSecretReveal)
119 mux.HandleFunc("POST /groups/{path}/secrets/delete", s.groupSecretDelete)
120 mux.HandleFunc("POST /groups/{path}/webhooks", s.groupWebhook)
121 mux.HandleFunc("POST /groups/{path}/webhooks/delete", s.groupWebhookDelete)
122
123 mux.HandleFunc("GET /{owner}/{repo}/info/refs", s.gitHTTP)
124 mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP)
125 mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP)
126 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease)
127 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log", s.jobLogAPI)
128 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff", s.commitDiffAPI)
129 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/merge-requests/{number}/diff", s.mrDiffAPI)
130 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/issues", s.issuesAPI)
131 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/issues", s.issuesAPI)
132 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI)
133 mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI)
134 mux.HandleFunc("DELETE /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI)
135 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/issues/{number}/notes", s.issueNoteAPI)
136 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/labels", s.labelsAPI)
137 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/labels", s.labelsAPI)
138 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/milestones", s.milestonesAPI)
139 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/milestones", s.milestonesAPI)
140 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/webhook-secrets", s.repoWebhookSecrets)
141 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/webhooks", s.repoWebhookAPI)
142 mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/webhooks/{id}", s.repoWebhookUpdate)
143 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/secrets", s.repoSecretsAPI)
144 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/secrets", s.repoSecretCreateAPI)
145 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretRevealAPI)
146 mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretUpdateAPI)
147 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/secrets/{name}/replace", s.repoSecretReplaceAPI)
148 mux.HandleFunc("DELETE /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretDeleteAPI)
149 mux.HandleFunc("GET /api/v1/groups/{path}/webhook-secrets", s.groupWebhookSecrets)
150 mux.HandleFunc("POST /api/v1/groups/{path}/hooks", s.groupWebhookAPI)
151 mux.HandleFunc("PUT /api/v1/groups/{path}/hooks/{id}", s.groupWebhookUpdate)
152 mux.HandleFunc("GET /api/v1/groups/{path}/secrets", s.groupSecretsAPI)
153 mux.HandleFunc("POST /api/v1/groups/{path}/secrets", s.groupSecretCreateAPI)
154 mux.HandleFunc("GET /api/v1/groups/{path}/secrets/{name}", s.groupSecretRevealAPI)
155 mux.HandleFunc("PUT /api/v1/groups/{path}/secrets/{name}", s.groupSecretUpdateAPI)
156 mux.HandleFunc("POST /api/v1/groups/{path}/secrets/{name}/replace", s.groupSecretReplaceAPI)
157 mux.HandleFunc("DELETE /api/v1/groups/{path}/secrets/{name}", s.groupSecretDeleteAPI)
158 mux.HandleFunc("GET /{owner}/{repo}", s.repoHome)
159 mux.HandleFunc("GET /{owner}/{repo}/-/tree", s.treeRoot)
160 mux.HandleFunc("GET /{owner}/{repo}/-/tree/{path...}", s.tree)
161 mux.HandleFunc("GET /{owner}/{repo}/-/blob/{path...}", s.blob)
162 mux.HandleFunc("GET /{owner}/{repo}/-/commits", s.commits)
163 mux.HandleFunc("GET /{owner}/{repo}/-/tags", s.tags)
164 mux.HandleFunc("POST /{owner}/{repo}/-/tags", s.createTag)
165 mux.HandleFunc("POST /{owner}/{repo}/-/tags/delete", s.deleteTag)
166 mux.HandleFunc("GET /{owner}/{repo}/-/tags/archive", s.tagArchive)
167 mux.HandleFunc("GET /{owner}/{repo}/-/archive/{rev}/{file}", s.commitArchive)
168 mux.HandleFunc("GET /{owner}/{repo}/-/commit/{sha}", s.commit)
169 mux.HandleFunc("GET /{owner}/{repo}/-/branches/archive", s.branchArchive)
170 mux.HandleFunc("GET /{owner}/{repo}/-/branches", s.branches)
171 mux.HandleFunc("POST /{owner}/{repo}/-/branches", s.createBranch)
172 mux.HandleFunc("POST /{owner}/{repo}/-/branches/delete", s.deleteBranch)
173 mux.HandleFunc("POST /{owner}/{repo}/-/branches/rename", s.renameBranch)
174 mux.HandleFunc("GET /{owner}/{repo}/-/compare", s.compare)
175 mux.HandleFunc("POST /{owner}/{repo}/-/markdown", s.previewMarkdown)
176 mux.HandleFunc("POST /{owner}/{repo}/-/tasks", s.toggleTask)
177 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests", s.mergeRequests)
178 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/new", s.newMR)
179 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests", s.createMR)
180 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/{number}", s.showMR)
181 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}", s.updateMR)
182 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/merge", s.mergeMR)
183 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/close", s.closeMR)
184 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reopen", s.reopenMR)
185 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews", s.postReview)
186 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews/dismiss", s.dismissReview)
187 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/notes", s.createNote)
188 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/suggestions", s.applySuggestions)
189 mux.HandleFunc("GET /{owner}/{repo}/-/issues", s.issuesPage)
190 mux.HandleFunc("GET /{owner}/{repo}/-/issues/new", s.newIssue)
191 mux.HandleFunc("POST /{owner}/{repo}/-/issues", s.createIssue)
192 mux.HandleFunc("POST /{owner}/{repo}/-/issues/labels", s.createIssueLabel)
193 mux.HandleFunc("POST /{owner}/{repo}/-/issues/milestones", s.createIssueMilestone)
194 mux.HandleFunc("GET /{owner}/{repo}/-/issues/{number}", s.showIssue)
195 mux.HandleFunc("POST /{owner}/{repo}/-/issues/{number}", s.postIssue)
196 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines", s.pipelines)
197 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines", s.runPipeline)
198 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}", s.pipeline)
199 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}", s.showJob)
200 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/log", s.jobLog)
201 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/play", s.playJob)
202 mux.HandleFunc("GET /{owner}/{repo}/-/ci/editor", s.ciEditor)
203 mux.HandleFunc("POST /{owner}/{repo}/-/ci/editor", s.saveCIEditor)
204 mux.HandleFunc("POST /{owner}/{repo}/-/ci/lint", s.lintCI)
205 mux.HandleFunc("GET /{owner}/{repo}/-/releases", s.releases)
206 mux.HandleFunc("GET /{owner}/{repo}/-/releases/{tag}/assets/{name}", s.releaseAsset)
207 mux.HandleFunc("GET /{owner}/{repo}/-/logo", s.repoLogo)
208 mux.HandleFunc("POST /{owner}/{repo}/-/logo", s.uploadRepoLogo)
209 mux.HandleFunc("POST /{owner}/{repo}/-/star", s.toggleStar)
210 mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
211 mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
212 mux.HandleFunc("POST /{owner}/{repo}/-/approvals", s.saveRepoApproval)
213 mux.HandleFunc("POST /{owner}/{repo}/-/members", s.repoMember)
214 mux.HandleFunc("POST /{owner}/{repo}/-/members/remove", s.repoMemberRemove)
215 mux.HandleFunc("POST /{owner}/{repo}/-/protected", s.addProtected)
216 mux.HandleFunc("POST /{owner}/{repo}/-/protected/remove", s.removeProtected)
217 mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags", s.addProtectedTag)
218 mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags/remove", s.removeProtectedTag)
219 mux.HandleFunc("POST /{owner}/{repo}/-/secrets", s.repoSecret)
220 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/reveal", s.repoSecretReveal)
221 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/delete", s.repoSecretDelete)
222 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks", s.repoWebhook)
223 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/delete", s.repoWebhookDelete)
224 mux.HandleFunc("POST /{owner}/{repo}/-/delete", s.deleteRepo)
225
226 return s.realIP(s.withSession(s.secure(s.gate(mux))))
227}
228
229func (s *Server) realIP(next http.Handler) http.Handler {
230 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
231 realip.Apply(r, s.Cfg.ProxySet())
232 next.ServeHTTP(w, r)
233 })
234}
235
236func (s *Server) mustTemplates() {
237 if s.byLang != nil {
238 return
239 }
240 s.byLang = map[string]*template.Template{}
241 for _, lang := range i18n.All() {
242 l := lang
243 s.byLang[string(l)] = template.Must(template.New("web").Funcs(template.FuncMap{
244 "short": func(v string) string {
245 if len(v) > 10 {
246 return v[:10]
247 }
248 return v
249 },
250 "join": strings.Join,
251 "initial": func(s string) string {
252 s = strings.TrimSpace(s)
253 if s == "" {
254 return "?"
255 }
256 r, _ := utf8.DecodeRuneInString(s)
257 return strings.ToUpper(string(r))
258 },
259 "splitPath": func(p string) []string {
260 if p == "" {
261 return nil
262 }
263 return strings.Split(p, "/")
264 },
265 "iconOf": func(name string) string { return fileIcon(name, "blob") },
266 "t": func(key string, args ...any) string { return i18n.T(l, key, args...) },
267 "date": func(t time.Time) string { return i18n.FormatDate(l, t) },
268 "tn": func(n int, one, many string) string {
269 key := many
270 if n == 1 {
271 key = one
272 }
273 return i18n.T(l, key, n)
274 },
275 "roleName": func(r access.Role) string { return i18n.T(l, "role."+string(r)) },
276 "visName": func(v string) string { return i18n.T(l, "vis."+v) },
277 "presetName": func(id string) string {
278 label := i18n.T(l, "set.preset."+id)
279 if label == "set.preset."+id {
280 return id
281 }
282 return label
283 },
284 }).ParseFS(webFS, "templates/*.html"))
285 }
286 s.tmpl = s.byLang[string(i18n.EN)]
287}
288
289func (s *Server) asset(w http.ResponseWriter, r *http.Request) {
290 name := r.PathValue("file")
291 if name == "" || strings.Contains(name, "/") || strings.Contains(name, "..") {
292 http.NotFound(w, r)
293 return
294 }
295 sub, err := fs.Sub(webFS, "static")
296 if err != nil {
297 http.Error(w, "assets", http.StatusInternalServerError)
298 return
299 }
300 http.ServeFileFS(w, r, sub, name)
301}
302
303func (s *Server) secure(next http.Handler) http.Handler {
304 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
305 w.Header().Set("X-Content-Type-Options", "nosniff")
306 w.Header().Set("X-Frame-Options", "DENY")
307 w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
308 w.Header().Set("Content-Security-Policy", "default-src 'self'; img-src 'self' https://auth.timfalken.com data:; style-src 'self'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'")
309 next.ServeHTTP(w, r)
310 })
311}
312
313func (s *Server) withSession(next http.Handler) http.Handler {
314 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
315 p := principal{}
316 if c, err := r.Cookie("bluegit_session"); err == nil && c.Value != "" {
317 sess, err := s.Store.Session(r.Context(), c.Value)
318 if err == nil && sess.ExpiresAt.After(time.Now()) {
319 p.Session = sess
320 p.User = sess.User
321 p.OK = true
322 s.maybeExtend(r.Context(), sess)
323 }
324 }
325 next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, p)))
326 })
327}
328
329func (s *Server) maybeExtend(ctx context.Context, sess store.Session) {
330 if time.Until(sess.ExpiresAt) > 6*time.Hour {
331 return
332 }
333 sec, err := s.Auth.Extend(ctx, sess.AccessToken)
334 if err != nil || sec <= 0 {
335 return
336 }
337 _ = s.Store.UpdateSessionExpiry(ctx, sess.ID, time.Now().Add(time.Duration(sec)*time.Second))
338}
339
340func (s *Server) who(r *http.Request) principal {
341 p, _ := r.Context().Value(ctxKey{}).(principal)
342 return p
343}
344
345func (s *Server) csrfOK(w http.ResponseWriter, r *http.Request) bool {
346 if err := r.ParseForm(); err != nil {
347 http.Error(w, s.tr(r, "err.badForm"), http.StatusBadRequest)
348 return false
349 }
350 p := s.who(r)
351 if !p.OK || r.FormValue("csrf") == "" || r.FormValue("csrf") != p.Session.CSRF {
352 http.Error(w, s.tr(r, "err.badCSRF"), http.StatusBadRequest)
353 return false
354 }
355 return true
356}
357
358func (s *Server) loginRequired(w http.ResponseWriter, r *http.Request) (store.User, bool) {
359 p := s.who(r)
360 if !p.OK {
361 http.Redirect(w, r, "/login", http.StatusFound)
362 return store.User{}, false
363 }
364 return p.User, true
365}
366
367func (s *Server) setSessionCookie(w http.ResponseWriter, id string, exp time.Time) {
368 http.SetCookie(w, &http.Cookie{
369 Name: "bluegit_session",
370 Value: id,
371 Path: "/",
372 HttpOnly: true,
373 SameSite: http.SameSiteLaxMode,
374 Secure: strings.HasPrefix(s.Cfg.BaseURL, "https://"),
375 Expires: exp,
376 })
377}
378
379func (s *Server) flash(w http.ResponseWriter, notice, problem string) {
380 secure := strings.HasPrefix(s.Cfg.BaseURL, "https://")
381 if notice != "" {
382 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: url.QueryEscape(notice), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
383 }
384 if problem != "" {
385 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: url.QueryEscape(problem), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
386 }
387}
388
389func (s *Server) takeFlash(w http.ResponseWriter, r *http.Request) (string, string) {
390 notice, problem := flashVal(r, "bluegit_notice"), flashVal(r, "bluegit_error")
391 if notice != "" {
392 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: "", Path: "/", MaxAge: -1})
393 }
394 if problem != "" {
395 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: "", Path: "/", MaxAge: -1})
396 }
397 return notice, problem
398}
399
400func cookieVal(r *http.Request, name string) string {
401 c, err := r.Cookie(name)
402 if err != nil {
403 return ""
404 }
405 return c.Value
406}
407
408func flashVal(r *http.Request, name string) string {
409 raw := cookieVal(r, name)
410 if raw == "" {
411 return ""
412 }
413 v, err := url.QueryUnescape(raw)
414 if err != nil {
415 return raw
416 }
417 return v
418}
419
420func (s *Server) redirect(w http.ResponseWriter, r *http.Request, path, notice, problem string) {
421 s.flash(w, notice, problem)
422 http.Redirect(w, r, path, http.StatusSeeOther)
423}
424
425func (s *Server) langOf(r *http.Request) i18n.Lang {
426 if p := s.who(r); p.OK {
427 return i18n.Parse(p.User.Language)
428 }
429 return i18n.EN
430}
431
432func (s *Server) tr(r *http.Request, key string, args ...any) string {
433 return i18n.T(s.langOf(r), key, args...)
434}
435
436func (s *Server) trErr(r *http.Request, err error) string {
437 return i18n.Text(s.langOf(r), err)
438}
439
440func (s *Server) view(w http.ResponseWriter, r *http.Request, title string) View {
441 notice, problem := s.takeFlash(w, r)
442 lang := s.langOf(r)
443 if strings.HasPrefix(title, "title.") {
444 title = i18n.T(lang, title)
445 }
446 name := strings.TrimSpace(s.Cfg.Runner.Name)
447 if name == "" {
448 name = "Steve"
449 }
450 v := View{
451 Title: title, BaseURL: s.Cfg.BaseURL, RunnerName: name, Notice: notice, Err: problem,
452 StorageUnset: s.StoragePath() == "", Lang: string(lang), HTMLLang: htmlLang(lang),
453 Cunei: lang == i18n.Cuneiform,
454 }
455 for _, l := range i18n.All() {
456 v.Langs = append(v.Langs, LangChoice{Code: string(l), Label: l.Name()})
457 }
458 if p := s.who(r); p.OK && !isCrawler(r) {
459 u := p.User
460 v.User = &u
461 v.CSRF = p.Session.CSRF
462 }
463 pic := s.cardForPath(r.Context(), r.URL.Path, r.URL.RawQuery, r.URL.Fragment)
464 v.Social = &pic.Meta
465 return v
466}
467
468func htmlLang(l i18n.Lang) string {
469 switch l {
470 case i18n.NL:
471 return "nl"
472 case i18n.DE:
473 return "de"
474 case i18n.FR:
475 return "fr"
476 default:
477 return "en"
478 }
479}
480
481func (s *Server) render(w http.ResponseWriter, name string, v View) {
482 w.Header().Set("Content-Type", "text/html; charset=utf-8")
483 tmpl := s.byLang[v.Lang]
484 if tmpl == nil {
485 tmpl = s.tmpl
486 }
487 if err := tmpl.ExecuteTemplate(w, name, v); err != nil && s.Log != nil {
488 s.Log.Error("sjabloon", "name", name, "err", err)
489 }
490}
491
492func randomState() (string, error) {
493 b := make([]byte, 32)
494 if _, err := rand.Read(b); err != nil {
495 return "", err
496 }
497 return hex.EncodeToString(b), nil
498}
499
500// View is de gegevensset voor elk scherm.
501type View struct {
502 Title string
503 BaseURL string
504 RunnerName string
505 User *store.User
506 CSRF string
507 Notice string
508 Err string
509 Repos []store.Repo
510 Groups []store.Group
511 Repo *store.Repo
512 Role access.Role
513 CanWrite bool
514 CanAdmin bool
515 CanMerge bool
516 CanForce bool
517 CanComment bool
518 CanApply bool
519 Commits []CommitRow
520 CommitDays []CommitDay
521 CommitPrev string
522 CommitNext string
523 Commit *CommitRow
524 CommitDiff *CommitDiff
525 Entries []EntryRow
526 TreePath string
527 Blob string
528 BlobPath string
529 Binary bool
530 Branches []BranchRow
531 Branch *BranchBoard
532 MRs []store.MergeRequest
533 Flow *FlowBoard
534 MR *store.MergeRequest
535 Banner *MRBanner
536 MRPipe *PipeRow
537 MergeBlocks []string
538 Approval *ApprovalView
539 Reviews []ReviewRow
540 CanReview bool
541 CanApprove bool
542 CanDismiss bool
543 CanClose bool
544 CanReopen bool
545 IsOwner bool
546 Candidates []store.Member
547 Diff string
548 DiffFiles []DiffFileView
549 Pipes []store.Pipeline
550 PipeRows []PipeRow
551 Pipe *store.Pipeline
552 PipeSource string
553 PipeStatus string
554 PipeLabel string
555 PipeJobs []JobLink
556 PipeStages []StageView
557 Live bool
558 LiveURL string
559 Jobs []store.Job
560 JobPage *JobPage
561 Editor *CIEditor
562 Releases []store.Release
563 Members []store.Member
564 Secrets []store.SecretMeta
565 HookSecrets []SecretChoice
566 Hooks []HookView
567 HookEdit HookDraft
568 Patterns []string
569 TagPatterns []string
570 Tags []TagRow
571 Tokens []store.TokenInfo
572 ShowExpiry bool
573 Keys []store.SSHKey
574 CloneHTTP string
575 CloneSSH string
576 Group *store.Group
577 Tab string
578 Rev string
579 NewToken string
580 StorageUnset bool
581 StoragePath string
582 StorageFree string
583 StorageTotal string
584 MinFree string
585 Wide bool
586 Info bool
587 ShowUpdate bool
588 Update *UpdateView
589 HookDoc string
590 Spec cispec.Doc
591 SpecJSON template.JS
592 APIJSON template.JS
593 Page string
594 Lang string
595 HTMLLang string
596 Cunei bool
597 Langs []LangChoice
598 Query string
599 SortDir string
600 FlipDir string
601 Cards []RepoCard
602 Head *CommitRow
603 Files []FileRow
604 Tree []FileRow
605 Readme template.HTML
606 ReadmeName string
607 LicensePath string
608 NCommits int
609 NBranches int
610 NTags int
611 NReleases int
612 Created string
613 Lines []CodeLine
614 BlobSize string
615 FileName string
616 RevProtected bool
617 Heat *activity.Calendar
618 Notes []NoteRow
619 Profile *store.User
620 Card *ProfileCard
621 DescHTML template.HTML
622 Timeline []TimelineItem
623 CompareFrom string
624 CompareTo string
625 FormTitle string
626 Labels []string
627 CanEditMR bool
628 Issues *IssueBoard
629 IssueDoc string
630 DescTpls []string
631 TplPick string
632 FormBody string
633 Social *card.Meta
634}
635
636// LangChoice is één taal in de instellingen.
637type LangChoice struct {
638 Code, Label string
639}
640
641// RepoCard is een repository in een groepslijst.
642type RepoCard struct {
643 Repo store.Repo
644 Stars int
645 Starred bool
646 When string
647}
648
649// ProfileCard is het blok over een gebruiker, boven de activiteitenkalender.
650type ProfileCard struct {
651 User store.User
652 Name, Since, Bio, URL string
653 Heading string
654 Repos, Groups, Contrib int
655 Own bool
656}
657
658// NoteRow is een reactie in de interface.
659type NoteRow struct {
660 ID int64
661 Author, AuthorURL, Body, When, Path string
662 Start, End int
663 HasSuggestion bool
664 ParentID int64
665 HTML template.HTML
666 Replies []NoteRow
667 At time.Time
668}
669
670// DiffFileView is één bestand in de merge-request-diff.
671type DiffFileView struct {
672 Path string
673 Lines []DiffLineView
674}
675
676// DiffLineView is één diffregel, met de reacties die op het nieuwe regelnummer eindigen.
677type DiffLineView struct {
678 Kind string
679 Text string
680 Old int
681 New int
682 Notes []NoteRow
683}
684
685// TagRow is één tag op de tagspagina.
686type TagRow struct {
687 Name, Message, SHA, Short, Subject, Date, When string
688 Annotated, Protected, HasRelease, CanDelete bool
689 ZipURL, TarURL string
690}
691
692// FileRow is een rij in de bestandstabel of de boom.
693type FileRow struct {
694 Name, Path, Icon, Subject, When, SHA string
695 Dir bool
696 Depth int
697 Active bool
698 // Open geldt voor een map die het huidige pad bevat. De browser
699 // onthoudt afwijkingen daarvan per repository.
700 Open bool
701}
702
703// CodeLine is één regel broncode.
704type CodeLine struct {
705 N int
706 HTML template.HTML
707}
708
709// CommitRow is een commit in de interface.
710// Author is de gekoppelde gebruiker, of anders de ruwe git-naam.
711// RawName en PushedBy zijn gezet als de pusher de fallback is en de git-naam afwijkt.
712type CommitRow struct {
713 SHA, Short, Author, Who, Date, Subject, Body, When string
714 UserURL, WhoURL, Avatar, Initial, RawName, PushedBy string
715 Ident template.HTML
716 PipeID int64
717 PipeStatus, PipeLabel, PipeDuration string
718 PipeStages []StageView
719 PipeLive bool
720}
721
722// CommitDay is één dag op de commitlijst, nieuwste dag eerst.
723type CommitDay struct {
724 Label string
725 Items []CommitRow
726}
727
728// EntryRow is een bestand of map.
729type EntryRow struct {
730 Name, Type, Path string
731}
732
733// BranchRow is een branch, met of zonder bescherming.
734type BranchRow struct {
735 Name, SHA, Short, Subject, When, WhenTitle string
736 RepoPath, ZipURL, TarURL string
737 Protected, Default, CanEdit bool
738 Target string
739 Ahead, Behind int
740 Unix int64
741 PipeID int64
742 PipeStatus, PipeLabel string
743 OpenMRs []int64
744}
745
746// BranchBoard is de gegroepeerde branches-pagina.
747type BranchBoard struct {
748 State string
749 ShowActive, ShowStale bool
750 Active, Stale []BranchRow
751}
752
753// TimelineItem is één gebeurtenis of reactie op een merge request.
754type TimelineItem struct {
755 ID int64
756 Kind string
757 Actor, ActorURL, Text string
758 When string
759 Body string
760 HTML template.HTML
761 URL string
762 Replies []TimelineItem
763 At time.Time
764 Rank int
765}
766
767// HookView is een webhook plus de laatste pogingen.
768type HookView struct {
769 ID int64
770 Name string
771 Preset string
772 URL string
773 Method string
774 Filter string
775 Events string
776 Badges []string
777 Deliveries []store.Delivery
778}
779
780// HookDraft vult het webhookformulier bij bewerken. ID 0 is een nieuw formulier.
781type HookDraft struct {
782 ID int64
783 Name string
784 Preset string
785 Filter string
786 URL string
787 Username string
788 Avatar string
789 Icon string
790 Alias string
791 Token string
792 Chat string
793 Server string
794 Topic string
795 Home string
796 Room string
797 Method string
798 CType string
799 Headers string
800 Body string
801 OnPush bool
802 OnMR bool
803 OnOK bool
804 OnFail bool
805 OnRel bool
806 OnIssue bool
807}
808
809func repoURL(repo store.Repo) string { return "/" + repo.FullPath() }