BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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