BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

feat: geef de commitlijst de GitLab-opbouw
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
Passed b026b59a History
server.go 26.3 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}/-/commit/{sha}", s.commit)
168 mux.HandleFunc("GET /{owner}/{repo}/-/branches", s.branches)
169 mux.HandleFunc("POST /{owner}/{repo}/-/branches", s.createBranch)
170 mux.HandleFunc("POST /{owner}/{repo}/-/branches/delete", s.deleteBranch)
171 mux.HandleFunc("POST /{owner}/{repo}/-/branches/rename", s.renameBranch)
172 mux.HandleFunc("GET /{owner}/{repo}/-/compare", s.compare)
173 mux.HandleFunc("POST /{owner}/{repo}/-/markdown", s.previewMarkdown)
174 mux.HandleFunc("POST /{owner}/{repo}/-/tasks", s.toggleTask)
175 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests", s.mergeRequests)
176 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/new", s.newMR)
177 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests", s.createMR)
178 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/{number}", s.showMR)
179 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}", s.updateMR)
180 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/merge", s.mergeMR)
181 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/close", s.closeMR)
182 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reopen", s.reopenMR)
183 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews", s.postReview)
184 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews/dismiss", s.dismissReview)
185 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/notes", s.createNote)
186 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/suggestions", s.applySuggestions)
187 mux.HandleFunc("GET /{owner}/{repo}/-/issues", s.issuesPage)
188 mux.HandleFunc("GET /{owner}/{repo}/-/issues/new", s.newIssue)
189 mux.HandleFunc("POST /{owner}/{repo}/-/issues", s.createIssue)
190 mux.HandleFunc("POST /{owner}/{repo}/-/issues/labels", s.createIssueLabel)
191 mux.HandleFunc("POST /{owner}/{repo}/-/issues/milestones", s.createIssueMilestone)
192 mux.HandleFunc("GET /{owner}/{repo}/-/issues/{number}", s.showIssue)
193 mux.HandleFunc("POST /{owner}/{repo}/-/issues/{number}", s.postIssue)
194 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines", s.pipelines)
195 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines", s.runPipeline)
196 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}", s.pipeline)
197 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}", s.showJob)
198 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/log", s.jobLog)
199 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/play", s.playJob)
200 mux.HandleFunc("GET /{owner}/{repo}/-/ci/editor", s.ciEditor)
201 mux.HandleFunc("POST /{owner}/{repo}/-/ci/editor", s.saveCIEditor)
202 mux.HandleFunc("POST /{owner}/{repo}/-/ci/lint", s.lintCI)
203 mux.HandleFunc("GET /{owner}/{repo}/-/releases", s.releases)
204 mux.HandleFunc("GET /{owner}/{repo}/-/releases/{tag}/assets/{name}", s.releaseAsset)
205 mux.HandleFunc("GET /{owner}/{repo}/-/logo", s.repoLogo)
206 mux.HandleFunc("POST /{owner}/{repo}/-/logo", s.uploadRepoLogo)
207 mux.HandleFunc("POST /{owner}/{repo}/-/star", s.toggleStar)
208 mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
209 mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
210 mux.HandleFunc("POST /{owner}/{repo}/-/approvals", s.saveRepoApproval)
211 mux.HandleFunc("POST /{owner}/{repo}/-/members", s.repoMember)
212 mux.HandleFunc("POST /{owner}/{repo}/-/members/remove", s.repoMemberRemove)
213 mux.HandleFunc("POST /{owner}/{repo}/-/protected", s.addProtected)
214 mux.HandleFunc("POST /{owner}/{repo}/-/protected/remove", s.removeProtected)
215 mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags", s.addProtectedTag)
216 mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags/remove", s.removeProtectedTag)
217 mux.HandleFunc("POST /{owner}/{repo}/-/secrets", s.repoSecret)
218 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/reveal", s.repoSecretReveal)
219 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/delete", s.repoSecretDelete)
220 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks", s.repoWebhook)
221 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/delete", s.repoWebhookDelete)
222 mux.HandleFunc("POST /{owner}/{repo}/-/delete", s.deleteRepo)
223
224 return s.realIP(s.withSession(s.secure(s.gate(mux))))
225}
226
227func (s *Server) realIP(next http.Handler) http.Handler {
228 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
229 realip.Apply(r, s.Cfg.ProxySet())
230 next.ServeHTTP(w, r)
231 })
232}
233
234func (s *Server) mustTemplates() {
235 if s.byLang != nil {
236 return
237 }
238 s.byLang = map[string]*template.Template{}
239 for _, lang := range i18n.All() {
240 l := lang
241 s.byLang[string(l)] = template.Must(template.New("web").Funcs(template.FuncMap{
242 "short": func(v string) string {
243 if len(v) > 10 {
244 return v[:10]
245 }
246 return v
247 },
248 "join": strings.Join,
249 "initial": func(s string) string {
250 s = strings.TrimSpace(s)
251 if s == "" {
252 return "?"
253 }
254 r, _ := utf8.DecodeRuneInString(s)
255 return strings.ToUpper(string(r))
256 },
257 "splitPath": func(p string) []string {
258 if p == "" {
259 return nil
260 }
261 return strings.Split(p, "/")
262 },
263 "iconOf": func(name string) string { return fileIcon(name, "blob") },
264 "t": func(key string, args ...any) string { return i18n.T(l, key, args...) },
265 "date": func(t time.Time) string { return i18n.FormatDate(l, t) },
266 "tn": func(n int, one, many string) string {
267 key := many
268 if n == 1 {
269 key = one
270 }
271 return i18n.T(l, key, n)
272 },
273 "roleName": func(r access.Role) string { return i18n.T(l, "role."+string(r)) },
274 "visName": func(v string) string { return i18n.T(l, "vis."+v) },
275 "presetName": func(id string) string {
276 label := i18n.T(l, "set.preset."+id)
277 if label == "set.preset."+id {
278 return id
279 }
280 return label
281 },
282 }).ParseFS(webFS, "templates/*.html"))
283 }
284 s.tmpl = s.byLang[string(i18n.EN)]
285}
286
287func (s *Server) asset(w http.ResponseWriter, r *http.Request) {
288 name := r.PathValue("file")
289 if name == "" || strings.Contains(name, "/") || strings.Contains(name, "..") {
290 http.NotFound(w, r)
291 return
292 }
293 sub, err := fs.Sub(webFS, "static")
294 if err != nil {
295 http.Error(w, "assets", http.StatusInternalServerError)
296 return
297 }
298 http.ServeFileFS(w, r, sub, name)
299}
300
301func (s *Server) secure(next http.Handler) http.Handler {
302 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
303 w.Header().Set("X-Content-Type-Options", "nosniff")
304 w.Header().Set("X-Frame-Options", "DENY")
305 w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
306 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'")
307 next.ServeHTTP(w, r)
308 })
309}
310
311func (s *Server) withSession(next http.Handler) http.Handler {
312 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
313 p := principal{}
314 if c, err := r.Cookie("bluegit_session"); err == nil && c.Value != "" {
315 sess, err := s.Store.Session(r.Context(), c.Value)
316 if err == nil && sess.ExpiresAt.After(time.Now()) {
317 p.Session = sess
318 p.User = sess.User
319 p.OK = true
320 s.maybeExtend(r.Context(), sess)
321 }
322 }
323 next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, p)))
324 })
325}
326
327func (s *Server) maybeExtend(ctx context.Context, sess store.Session) {
328 if time.Until(sess.ExpiresAt) > 6*time.Hour {
329 return
330 }
331 sec, err := s.Auth.Extend(ctx, sess.AccessToken)
332 if err != nil || sec <= 0 {
333 return
334 }
335 _ = s.Store.UpdateSessionExpiry(ctx, sess.ID, time.Now().Add(time.Duration(sec)*time.Second))
336}
337
338func (s *Server) who(r *http.Request) principal {
339 p, _ := r.Context().Value(ctxKey{}).(principal)
340 return p
341}
342
343func (s *Server) csrfOK(w http.ResponseWriter, r *http.Request) bool {
344 if err := r.ParseForm(); err != nil {
345 http.Error(w, s.tr(r, "err.badForm"), http.StatusBadRequest)
346 return false
347 }
348 p := s.who(r)
349 if !p.OK || r.FormValue("csrf") == "" || r.FormValue("csrf") != p.Session.CSRF {
350 http.Error(w, s.tr(r, "err.badCSRF"), http.StatusBadRequest)
351 return false
352 }
353 return true
354}
355
356func (s *Server) loginRequired(w http.ResponseWriter, r *http.Request) (store.User, bool) {
357 p := s.who(r)
358 if !p.OK {
359 http.Redirect(w, r, "/login", http.StatusFound)
360 return store.User{}, false
361 }
362 return p.User, true
363}
364
365func (s *Server) setSessionCookie(w http.ResponseWriter, id string, exp time.Time) {
366 http.SetCookie(w, &http.Cookie{
367 Name: "bluegit_session",
368 Value: id,
369 Path: "/",
370 HttpOnly: true,
371 SameSite: http.SameSiteLaxMode,
372 Secure: strings.HasPrefix(s.Cfg.BaseURL, "https://"),
373 Expires: exp,
374 })
375}
376
377func (s *Server) flash(w http.ResponseWriter, notice, problem string) {
378 secure := strings.HasPrefix(s.Cfg.BaseURL, "https://")
379 if notice != "" {
380 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: url.QueryEscape(notice), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
381 }
382 if problem != "" {
383 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: url.QueryEscape(problem), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
384 }
385}
386
387func (s *Server) takeFlash(w http.ResponseWriter, r *http.Request) (string, string) {
388 notice, problem := flashVal(r, "bluegit_notice"), flashVal(r, "bluegit_error")
389 if notice != "" {
390 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: "", Path: "/", MaxAge: -1})
391 }
392 if problem != "" {
393 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: "", Path: "/", MaxAge: -1})
394 }
395 return notice, problem
396}
397
398func cookieVal(r *http.Request, name string) string {
399 c, err := r.Cookie(name)
400 if err != nil {
401 return ""
402 }
403 return c.Value
404}
405
406func flashVal(r *http.Request, name string) string {
407 raw := cookieVal(r, name)
408 if raw == "" {
409 return ""
410 }
411 v, err := url.QueryUnescape(raw)
412 if err != nil {
413 return raw
414 }
415 return v
416}
417
418func (s *Server) redirect(w http.ResponseWriter, r *http.Request, path, notice, problem string) {
419 s.flash(w, notice, problem)
420 http.Redirect(w, r, path, http.StatusSeeOther)
421}
422
423func (s *Server) langOf(r *http.Request) i18n.Lang {
424 if p := s.who(r); p.OK {
425 return i18n.Parse(p.User.Language)
426 }
427 return i18n.EN
428}
429
430func (s *Server) tr(r *http.Request, key string, args ...any) string {
431 return i18n.T(s.langOf(r), key, args...)
432}
433
434func (s *Server) trErr(r *http.Request, err error) string {
435 return i18n.Text(s.langOf(r), err)
436}
437
438func (s *Server) view(w http.ResponseWriter, r *http.Request, title string) View {
439 notice, problem := s.takeFlash(w, r)
440 lang := s.langOf(r)
441 if strings.HasPrefix(title, "title.") {
442 title = i18n.T(lang, title)
443 }
444 name := strings.TrimSpace(s.Cfg.Runner.Name)
445 if name == "" {
446 name = "Steve"
447 }
448 v := View{
449 Title: title, BaseURL: s.Cfg.BaseURL, RunnerName: name, Notice: notice, Err: problem,
450 StorageUnset: s.StoragePath() == "", Lang: string(lang), HTMLLang: htmlLang(lang),
451 Cunei: lang == i18n.Cuneiform,
452 }
453 for _, l := range i18n.All() {
454 v.Langs = append(v.Langs, LangChoice{Code: string(l), Label: l.Name()})
455 }
456 if p := s.who(r); p.OK && !isCrawler(r) {
457 u := p.User
458 v.User = &u
459 v.CSRF = p.Session.CSRF
460 }
461 pic := s.cardForPath(r.Context(), r.URL.Path, r.URL.RawQuery, r.URL.Fragment)
462 v.Social = &pic.Meta
463 return v
464}
465
466func htmlLang(l i18n.Lang) string {
467 switch l {
468 case i18n.NL:
469 return "nl"
470 case i18n.DE:
471 return "de"
472 case i18n.FR:
473 return "fr"
474 default:
475 return "en"
476 }
477}
478
479func (s *Server) render(w http.ResponseWriter, name string, v View) {
480 w.Header().Set("Content-Type", "text/html; charset=utf-8")
481 tmpl := s.byLang[v.Lang]
482 if tmpl == nil {
483 tmpl = s.tmpl
484 }
485 if err := tmpl.ExecuteTemplate(w, name, v); err != nil && s.Log != nil {
486 s.Log.Error("sjabloon", "name", name, "err", err)
487 }
488}
489
490func randomState() (string, error) {
491 b := make([]byte, 32)
492 if _, err := rand.Read(b); err != nil {
493 return "", err
494 }
495 return hex.EncodeToString(b), nil
496}
497
498// View is de gegevensset voor elk scherm.
499type View struct {
500 Title string
501 BaseURL string
502 RunnerName string
503 User *store.User
504 CSRF string
505 Notice string
506 Err string
507 Repos []store.Repo
508 Groups []store.Group
509 Repo *store.Repo
510 Role access.Role
511 CanWrite bool
512 CanAdmin bool
513 CanMerge bool
514 CanForce bool
515 CanComment bool
516 CanApply bool
517 Commits []CommitRow
518 CommitDays []CommitDay
519 CommitPrev string
520 CommitNext string
521 Commit *CommitRow
522 CommitDiff *CommitDiff
523 Entries []EntryRow
524 TreePath string
525 Blob string
526 BlobPath string
527 Binary bool
528 Branches []BranchRow
529 MRs []store.MergeRequest
530 MR *store.MergeRequest
531 MRPipe *PipeRow
532 MergeBlocks []string
533 Approval *ApprovalView
534 Reviews []ReviewRow
535 CanReview bool
536 CanApprove bool
537 CanDismiss bool
538 CanClose bool
539 CanReopen bool
540 IsOwner bool
541 Candidates []store.Member
542 Diff string
543 DiffFiles []DiffFileView
544 Pipes []store.Pipeline
545 PipeRows []PipeRow
546 Pipe *store.Pipeline
547 PipeSource string
548 PipeStatus string
549 PipeLabel string
550 PipeJobs []JobLink
551 PipeStages []StageView
552 Live bool
553 LiveURL string
554 Jobs []store.Job
555 JobPage *JobPage
556 Editor *CIEditor
557 Releases []store.Release
558 Members []store.Member
559 Secrets []store.SecretMeta
560 HookSecrets []SecretChoice
561 Hooks []HookView
562 HookEdit HookDraft
563 Patterns []string
564 TagPatterns []string
565 Tags []TagRow
566 Tokens []store.TokenInfo
567 ShowExpiry bool
568 Keys []store.SSHKey
569 CloneHTTP string
570 CloneSSH string
571 Group *store.Group
572 Tab string
573 Rev string
574 NewToken string
575 StorageUnset bool
576 StoragePath string
577 StorageFree string
578 StorageTotal string
579 MinFree string
580 Wide bool
581 Info bool
582 ShowUpdate bool
583 Update *UpdateView
584 HookDoc string
585 Spec cispec.Doc
586 SpecJSON template.JS
587 APIJSON template.JS
588 Page string
589 Lang string
590 HTMLLang string
591 Cunei bool
592 Langs []LangChoice
593 Query string
594 SortDir string
595 FlipDir string
596 Cards []RepoCard
597 Head *CommitRow
598 Files []FileRow
599 Tree []FileRow
600 Readme template.HTML
601 ReadmeName string
602 LicensePath string
603 NCommits int
604 NBranches int
605 NTags int
606 NReleases int
607 Created string
608 Lines []CodeLine
609 BlobSize string
610 FileName string
611 RevProtected bool
612 Heat *activity.Calendar
613 Notes []NoteRow
614 Profile *store.User
615 Card *ProfileCard
616 DescHTML template.HTML
617 Timeline []TimelineItem
618 CompareFrom string
619 CompareTo string
620 FormTitle string
621 Labels []string
622 CanEditMR bool
623 Issues *IssueBoard
624 IssueDoc string
625 DescTpls []string
626 TplPick string
627 FormBody string
628 Social *card.Meta
629}
630
631// LangChoice is één taal in de instellingen.
632type LangChoice struct {
633 Code, Label string
634}
635
636// RepoCard is een repository in een groepslijst.
637type RepoCard struct {
638 Repo store.Repo
639 Stars int
640 Starred bool
641 When string
642}
643
644// ProfileCard is het blok over een gebruiker, boven de activiteitenkalender.
645type ProfileCard struct {
646 User store.User
647 Name, Since, Bio, URL string
648 Heading string
649 Repos, Groups, Contrib int
650 Own bool
651}
652
653// NoteRow is een reactie in de interface.
654type NoteRow struct {
655 ID int64
656 Author, AuthorURL, Body, When, Path string
657 Start, End int
658 HasSuggestion bool
659 ParentID int64
660 HTML template.HTML
661 Replies []NoteRow
662 At time.Time
663}
664
665// DiffFileView is één bestand in de merge-request-diff.
666type DiffFileView struct {
667 Path string
668 Lines []DiffLineView
669}
670
671// DiffLineView is één diffregel, met de reacties die op het nieuwe regelnummer eindigen.
672type DiffLineView struct {
673 Kind string
674 Text string
675 Old int
676 New int
677 Notes []NoteRow
678}
679
680// TagRow is één tag op de tagspagina.
681type TagRow struct {
682 Name, Message, SHA, Short, Subject, Date string
683 Annotated, Protected, HasRelease, CanDelete bool
684 ZipURL, TarURL string
685}
686
687// FileRow is een rij in de bestandstabel of de boom.
688type FileRow struct {
689 Name, Path, Icon, Subject, When, SHA string
690 Dir bool
691 Depth int
692 Active bool
693 // Open geldt voor een map die het huidige pad bevat. De browser
694 // onthoudt afwijkingen daarvan per repository.
695 Open bool
696}
697
698// CodeLine is één regel broncode.
699type CodeLine struct {
700 N int
701 HTML template.HTML
702}
703
704// CommitRow is een commit in de interface.
705// Author is de gekoppelde gebruiker, of anders de ruwe git-naam.
706// RawName en PushedBy zijn gezet als de pusher de fallback is en de git-naam afwijkt.
707type CommitRow struct {
708 SHA, Short, Author, Who, Date, Subject, Body, When string
709 UserURL, WhoURL, Avatar, Initial, RawName, PushedBy string
710 Ident template.HTML
711 PipeID int64
712 PipeStatus, PipeLabel, PipeDuration string
713 PipeStages []StageView
714 PipeLive bool
715}
716
717// CommitDay is één dag op de commitlijst, nieuwste dag eerst.
718type CommitDay struct {
719 Label string
720 Items []CommitRow
721}
722
723// EntryRow is een bestand of map.
724type EntryRow struct {
725 Name, Type, Path string
726}
727
728// BranchRow is een branch, met of zonder bescherming.
729type BranchRow struct {
730 Name, SHA, Short, Subject, When, WhenTitle string
731 Protected, Default bool
732 Ahead, Behind int
733 PipeID int64
734 PipeStatus, PipeLabel string
735 OpenMRs []int64
736}
737
738// TimelineItem is één gebeurtenis of reactie op een merge request.
739type TimelineItem struct {
740 ID int64
741 Kind string
742 Actor, ActorURL, Text string
743 When string
744 Body string
745 HTML template.HTML
746 URL string
747 Replies []TimelineItem
748 At time.Time
749 Rank int
750}
751
752// HookView is een webhook plus de laatste pogingen.
753type HookView struct {
754 ID int64
755 Name string
756 Preset string
757 URL string
758 Method string
759 Filter string
760 Events string
761 Badges []string
762 Deliveries []store.Delivery
763}
764
765// HookDraft vult het webhookformulier bij bewerken. ID 0 is een nieuw formulier.
766type HookDraft struct {
767 ID int64
768 Name string
769 Preset string
770 Filter string
771 URL string
772 Username string
773 Avatar string
774 Icon string
775 Alias string
776 Token string
777 Chat string
778 Server string
779 Topic string
780 Home string
781 Room string
782 Method string
783 CType string
784 Headers string
785 Body string
786 OnPush bool
787 OnMR bool
788 OnOK bool
789 OnFail bool
790 OnRel bool
791 OnIssue bool
792}
793
794func repoURL(repo store.Repo) string { return "/" + repo.FullPath() }