From 21b822de42cd9a5ec25c90386c621f8167fa5885 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ferdinand=20M=C3=BCtsch?= Date: Fri, 9 Oct 2020 21:37:16 +0200 Subject: [PATCH] chore: minor code enhancements --- config/templates.go | 9 +++++++++ main.go | 1 - models/models.go | 1 + routes/public.go | 24 ++++++++++++------------ routes/routes.go | 2 +- routes/settings.go | 28 ++++++++++++++-------------- routes/summary.go | 12 ++++++------ scripts/push_sample_data.py | 8 ++++---- services/aggregation.go | 2 +- services/summary.go | 1 + static/assets/app.js | 4 ++-- version.txt | 2 +- views/imprint.tpl.html | 3 ++- views/index.tpl.html | 3 ++- views/settings.tpl.html | 9 +++++---- views/signup.tpl.html | 5 ++++- views/summary.tpl.html | 13 +++++++------ 17 files changed, 72 insertions(+), 55 deletions(-) create mode 100644 config/templates.go diff --git a/config/templates.go b/config/templates.go new file mode 100644 index 0000000..c7c94f8 --- /dev/null +++ b/config/templates.go @@ -0,0 +1,9 @@ +package config + +const ( + IndexTemplate = "index.tpl.html" + ImprintTemplate = "imprint.tpl.html" + SignupTemplate = "signup.tpl.html" + SettingsTemplate = "settings.tpl.html" + SummaryTemplate = "summary.tpl.html" +) diff --git a/main.go b/main.go index 7ba9e4e..11d5cb3 100644 --- a/main.go +++ b/main.go @@ -64,7 +64,6 @@ func main() { log.Println(err) log.Fatal("could not connect to database") } - // TODO: Graceful shutdown defer db.Close() // Migrate database schema diff --git a/models/models.go b/models/models.go index af32826..b65fe20 100644 --- a/models/models.go +++ b/models/models.go @@ -1,4 +1,5 @@ package models func init() { + // nothing no init here, yet } diff --git a/routes/public.go b/routes/public.go index 5ad3900..016d9d8 100644 --- a/routes/public.go +++ b/routes/public.go @@ -3,7 +3,7 @@ package routes import ( "fmt" "github.com/gorilla/schema" - config2 "github.com/muety/wakapi/config" + conf "github.com/muety/wakapi/config" "github.com/muety/wakapi/middlewares" "github.com/muety/wakapi/models" "github.com/muety/wakapi/services" @@ -14,7 +14,7 @@ import ( ) type IndexHandler struct { - config *config2.Config + config *conf.Config userSrvc *services.UserService keyValueSrvc *services.KeyValueService } @@ -24,7 +24,7 @@ var signupDecoder = schema.NewDecoder() func NewIndexHandler(userService *services.UserService, keyValueService *services.KeyValueService) *IndexHandler { return &IndexHandler{ - config: config2.Get(), + config: conf.Get(), userSrvc: userService, keyValueSrvc: keyValueService, } @@ -44,7 +44,7 @@ func (h *IndexHandler) GetIndex(w http.ResponseWriter, r *http.Request) { return } - templates["index.tpl.html"].Execute(w, nil) + templates[conf.IndexTemplate].Execute(w, nil) } func (h *IndexHandler) GetImprint(w http.ResponseWriter, r *http.Request) { @@ -57,7 +57,7 @@ func (h *IndexHandler) GetImprint(w http.ResponseWriter, r *http.Request) { text = data.Value } - templates["imprint.tpl.html"].Execute(w, &struct { + templates[conf.ImprintTemplate].Execute(w, &struct { HtmlText string }{HtmlText: text}) } @@ -133,11 +133,11 @@ func (h *IndexHandler) GetSignup(w http.ResponseWriter, r *http.Request) { return } - if handleAlerts(w, r, "signup.tpl.html") { + if handleAlerts(w, r, conf.SignupTemplate) { return } - templates["signup.tpl.html"].Execute(w, nil) + templates[conf.SignupTemplate].Execute(w, nil) } func (h *IndexHandler) PostSignup(w http.ResponseWriter, r *http.Request) { @@ -152,26 +152,26 @@ func (h *IndexHandler) PostSignup(w http.ResponseWriter, r *http.Request) { var signup models.Signup if err := r.ParseForm(); err != nil { - respondAlert(w, "missing parameters", "", "signup.tpl.html", http.StatusBadRequest) + respondAlert(w, "missing parameters", "", conf.SignupTemplate, http.StatusBadRequest) return } if err := signupDecoder.Decode(&signup, r.PostForm); err != nil { - respondAlert(w, "missing parameters", "", "signup.tpl.html", http.StatusBadRequest) + respondAlert(w, "missing parameters", "", conf.SignupTemplate, http.StatusBadRequest) return } if !signup.IsValid() { - respondAlert(w, "invalid parameters", "", "signup.tpl.html", http.StatusBadRequest) + respondAlert(w, "invalid parameters", "", conf.SignupTemplate, http.StatusBadRequest) return } _, created, err := h.userSrvc.CreateOrGet(&signup) if err != nil { - respondAlert(w, "failed to create new user", "", "signup.tpl.html", http.StatusInternalServerError) + respondAlert(w, "failed to create new user", "", conf.SignupTemplate, http.StatusInternalServerError) return } if !created { - respondAlert(w, "user already existing", "", "signup.tpl.html", http.StatusConflict) + respondAlert(w, "user already existing", "", conf.SignupTemplate, http.StatusConflict) return } diff --git a/routes/routes.go b/routes/routes.go index 6005caa..f94333a 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -59,7 +59,7 @@ func loadTemplates() { func respondAlert(w http.ResponseWriter, error, success, tplName string, status int) { w.WriteHeader(status) if tplName == "" { - tplName = "index.tpl.html" + tplName = config.IndexTemplate } templates[tplName].Execute(w, struct { Error string diff --git a/routes/settings.go b/routes/settings.go index 89bdf1a..bc7bfb8 100644 --- a/routes/settings.go +++ b/routes/settings.go @@ -3,7 +3,7 @@ package routes import ( "fmt" "github.com/gorilla/schema" - config2 "github.com/muety/wakapi/config" + conf "github.com/muety/wakapi/config" "github.com/muety/wakapi/models" "github.com/muety/wakapi/services" "github.com/muety/wakapi/utils" @@ -12,7 +12,7 @@ import ( ) type SettingsHandler struct { - config *config2.Config + config *conf.Config userSrvc *services.UserService } @@ -20,7 +20,7 @@ var credentialsDecoder = schema.NewDecoder() func NewSettingsHandler(userService *services.UserService) *SettingsHandler { return &SettingsHandler{ - config: config2.Get(), + config: conf.Get(), userSrvc: userService, } } @@ -36,10 +36,10 @@ func (h *SettingsHandler) GetIndex(w http.ResponseWriter, r *http.Request) { } // TODO: when alerts are present, other data will not be passed to the template - if handleAlerts(w, r, "settings.tpl.html") { + if handleAlerts(w, r, conf.SettingsTemplate) { return } - templates["settings.tpl.html"].Execute(w, data) + templates[conf.SettingsTemplate].Execute(w, data) } func (h *SettingsHandler) PostCredentials(w http.ResponseWriter, r *http.Request) { @@ -51,32 +51,32 @@ func (h *SettingsHandler) PostCredentials(w http.ResponseWriter, r *http.Request var credentials models.CredentialsReset if err := r.ParseForm(); err != nil { - respondAlert(w, "missing parameters", "", "settings.tpl.html", http.StatusBadRequest) + respondAlert(w, "missing parameters", "", conf.SettingsTemplate, http.StatusBadRequest) return } if err := credentialsDecoder.Decode(&credentials, r.PostForm); err != nil { - respondAlert(w, "missing parameters", "", "settings.tpl.html", http.StatusBadRequest) + respondAlert(w, "missing parameters", "", conf.SettingsTemplate, http.StatusBadRequest) return } if !utils.CheckPasswordBcrypt(user, credentials.PasswordOld, h.config.Security.PasswordSalt) { - respondAlert(w, "invalid credentials", "", "settings.tpl.html", http.StatusUnauthorized) + respondAlert(w, "invalid credentials", "", conf.SettingsTemplate, http.StatusUnauthorized) return } if !credentials.IsValid() { - respondAlert(w, "invalid parameters", "", "settings.tpl.html", http.StatusBadRequest) + respondAlert(w, "invalid parameters", "", conf.SettingsTemplate, http.StatusBadRequest) return } user.Password = credentials.PasswordNew if err := utils.HashPassword(user, h.config.Security.PasswordSalt); err != nil { - respondAlert(w, "internal server error", "", "settings.tpl.html", http.StatusInternalServerError) + respondAlert(w, "internal server error", "", conf.SettingsTemplate, http.StatusInternalServerError) return } if _, err := h.userSrvc.Update(user); err != nil { - respondAlert(w, "internal server error", "", "settings.tpl.html", http.StatusInternalServerError) + respondAlert(w, "internal server error", "", conf.SettingsTemplate, http.StatusInternalServerError) return } @@ -86,7 +86,7 @@ func (h *SettingsHandler) PostCredentials(w http.ResponseWriter, r *http.Request } encoded, err := h.config.Security.SecureCookie.Encode(models.AuthCookieKey, login) if err != nil { - respondAlert(w, "internal server error", "", "settings.tpl.html", http.StatusInternalServerError) + respondAlert(w, "internal server error", "", conf.SettingsTemplate, http.StatusInternalServerError) return } @@ -110,7 +110,7 @@ func (h *SettingsHandler) PostResetApiKey(w http.ResponseWriter, r *http.Request user := r.Context().Value(models.UserKey).(*models.User) if _, err := h.userSrvc.ResetApiKey(user); err != nil { - respondAlert(w, "internal server error", "", "settings.tpl.html", http.StatusInternalServerError) + respondAlert(w, "internal server error", "", conf.SettingsTemplate, http.StatusInternalServerError) return } @@ -126,7 +126,7 @@ func (h *SettingsHandler) PostToggleBadges(w http.ResponseWriter, r *http.Reques user := r.Context().Value(models.UserKey).(*models.User) if _, err := h.userSrvc.ToggleBadges(user); err != nil { - respondAlert(w, "internal server error", "", "settings.tpl.html", http.StatusInternalServerError) + respondAlert(w, "internal server error", "", conf.SettingsTemplate, http.StatusInternalServerError) return } diff --git a/routes/summary.go b/routes/summary.go index 4dd57a3..92fe2d8 100644 --- a/routes/summary.go +++ b/routes/summary.go @@ -1,7 +1,7 @@ package routes import ( - config2 "github.com/muety/wakapi/config" + conf "github.com/muety/wakapi/config" "github.com/muety/wakapi/models" "github.com/muety/wakapi/services" "github.com/muety/wakapi/utils" @@ -10,13 +10,13 @@ import ( type SummaryHandler struct { summarySrvc *services.SummaryService - config *config2.Config + config *conf.Config } func NewSummaryHandler(summaryService *services.SummaryService) *SummaryHandler { return &SummaryHandler{ summarySrvc: summaryService, - config: config2.Get(), + config: conf.Get(), } } @@ -44,13 +44,13 @@ func (h *SummaryHandler) GetIndex(w http.ResponseWriter, r *http.Request) { summary, err, status := h.loadUserSummary(r) if err != nil { - respondAlert(w, err.Error(), "", "summary.tpl.html", status) + respondAlert(w, err.Error(), "", conf.SummaryTemplate, status) return } user := r.Context().Value(models.UserKey).(*models.User) if user == nil { - respondAlert(w, "unauthorized", "", "summary.tpl.html", http.StatusUnauthorized) + respondAlert(w, "unauthorized", "", conf.SummaryTemplate, http.StatusUnauthorized) return } @@ -60,7 +60,7 @@ func (h *SummaryHandler) GetIndex(w http.ResponseWriter, r *http.Request) { ApiKey: user.ApiKey, } - templates["summary.tpl.html"].Execute(w, vm) + templates[conf.SummaryTemplate].Execute(w, vm) } func (h *SummaryHandler) loadUserSummary(r *http.Request) (*models.Summary, error, int) { diff --git a/scripts/push_sample_data.py b/scripts/push_sample_data.py index 5674219..fa5f22c 100644 --- a/scripts/push_sample_data.py +++ b/scripts/push_sample_data.py @@ -3,7 +3,7 @@ import random import string import sys from datetime import datetime, timedelta -from typing import List +from typing import List, NoneType import requests @@ -36,7 +36,7 @@ class Heartbeat: self.is_write: bool = is_write self.branch: str = branch self.type: str = type - self.category: str = None + self.category: str | NoneType = None def generate_data(n: int) -> List[Heartbeat]: @@ -45,7 +45,7 @@ def generate_data(n: int) -> List[Heartbeat]: projects: List[str] = [randomword(random.randint(5, 10)) for _ in range(5)] languages: List[str] = list(LANGUAGES.keys()) - for i in range(n): + for _ in range(n): p: str = random.choice(projects) l: str = random.choice(languages) f: str = randomword(random.randint(2, 8)) @@ -77,7 +77,7 @@ def post_data_sync(data: List[Heartbeat], url: str): def randomword(length: int) -> str: letters = string.ascii_lowercase - return ''.join(random.choice(letters) for i in range(length)) + return ''.join(random.choice(letters) for _ in range(length)) if __name__ == '__main__': diff --git a/services/aggregation.go b/services/aggregation.go index 406afa9..af28edd 100644 --- a/services/aggregation.go +++ b/services/aggregation.go @@ -12,7 +12,7 @@ import ( ) const ( - aggregateIntervalDays int = 1 // TODO: Make configurable + aggregateIntervalDays int = 1 ) type AggregationService struct { diff --git a/services/summary.go b/services/summary.go index ce8919b..42dde30 100644 --- a/services/summary.go +++ b/services/summary.go @@ -37,6 +37,7 @@ type Interval struct { End time.Time } +// TODO: simplify! func (srv *SummaryService) Construct(from, to time.Time, user *models.User, recompute bool) (*models.Summary, error) { var existingSummaries []*models.Summary var cacheKey string diff --git a/static/assets/app.js b/static/assets/app.js index 2d06ef2..1fd2931 100644 --- a/static/assets/app.js +++ b/static/assets/app.js @@ -242,8 +242,8 @@ function equalizeHeights() { }) } -function getTotal(data) { - let total = data.reduce((acc, d) => acc + d.total, 0) +function getTotal(items) { + let total = items.reduce((acc, d) => acc + d.total, 0) document.getElementById('total-span').innerText = total.toString().toHHMMSS() } diff --git a/version.txt b/version.txt index 69669de..c56eaaa 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.12.2 \ No newline at end of file +1.12.3 \ No newline at end of file diff --git a/views/imprint.tpl.html b/views/imprint.tpl.html index 81e116e..fa251dc 100644 --- a/views/imprint.tpl.html +++ b/views/imprint.tpl.html @@ -1,4 +1,5 @@ - + + {{ template "head.tpl.html" . }} diff --git a/views/index.tpl.html b/views/index.tpl.html index 1de7d9d..d1e6d30 100644 --- a/views/index.tpl.html +++ b/views/index.tpl.html @@ -1,4 +1,5 @@ - + + {{ template "head.tpl.html" . }} diff --git a/views/settings.tpl.html b/views/settings.tpl.html index 901d412..869c793 100644 --- a/views/settings.tpl.html +++ b/views/settings.tpl.html @@ -1,4 +1,5 @@ - + + {{ template "head.tpl.html" . }} @@ -86,7 +87,7 @@
- + Shields.io badge
https://img.shields.io/endpoint?url=%s/api/compat/shields/v1/{{ .User.ID }}/interval:today&style=flat-square&color=blue&label=today @@ -94,7 +95,7 @@
- + Shields.io badge
https://img.shields.io/endpoint?url=%s/api/compat/shields/v1/{{ .User.ID }}/interval:30_days&style=flat-square&color=blue&label=last 30d @@ -104,7 +105,7 @@

You can also add /project:your-cool-project to the URL to filter by project.

{{ else }} -

You have the ability to create badges from your coding statistics using Shields.io. To do so, you need to grant public, unauthorized access to the respective endpoint.

+

You have the ability to create badges from your coding statistics using Shields.io. To do so, you need to grant public, unauthorized access to the respective endpoint.

GET /api/compat/shields/v1
@@ -82,7 +83,7 @@
@@ -95,7 +96,7 @@ @@ -108,7 +109,7 @@ @@ -121,7 +122,7 @@