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