1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00
wakapi/routes/home.go

72 lines
1.8 KiB
Go
Raw Permalink Normal View History

package routes
import (
2020-05-24 17:34:32 +03:00
"fmt"
"github.com/gorilla/mux"
"github.com/gorilla/schema"
2020-10-09 22:37:16 +03:00
conf "github.com/muety/wakapi/config"
"github.com/muety/wakapi/models"
2020-11-06 23:19:54 +03:00
"github.com/muety/wakapi/models/view"
"github.com/muety/wakapi/services"
"net/http"
"strconv"
"time"
)
2020-11-06 23:19:54 +03:00
type HomeHandler struct {
config *conf.Config
keyValueSrvc services.IKeyValueService
}
var loginDecoder = schema.NewDecoder()
2020-05-24 17:34:32 +03:00
var signupDecoder = schema.NewDecoder()
2021-04-05 23:57:57 +03:00
var resetPasswordDecoder = schema.NewDecoder()
func NewHomeHandler(keyValueService services.IKeyValueService) *HomeHandler {
2020-11-06 23:19:54 +03:00
return &HomeHandler{
config: conf.Get(),
keyValueSrvc: keyValueService,
}
}
func (h *HomeHandler) RegisterRoutes(router *mux.Router) {
router.Path("/").Methods(http.MethodGet).HandlerFunc(h.GetIndex)
}
2020-11-06 23:19:54 +03:00
func (h *HomeHandler) GetIndex(w http.ResponseWriter, r *http.Request) {
if h.config.IsDev() {
loadTemplates()
}
if cookie, err := r.Cookie(models.AuthCookieKey); err == nil && cookie.Value != "" {
http.Redirect(w, r, fmt.Sprintf("%s/summary", h.config.Server.BasePath), http.StatusFound)
return
}
2020-11-06 23:19:54 +03:00
templates[conf.IndexTemplate].Execute(w, h.buildViewModel(r))
}
2020-11-06 23:19:54 +03:00
func (h *HomeHandler) buildViewModel(r *http.Request) *view.HomeViewModel {
var totalHours int
var totalUsers int
if t, err := h.keyValueSrvc.GetString(conf.KeyLatestTotalTime); err == nil && t != nil && t.Value != "" {
if d, err := time.ParseDuration(t.Value); err == nil {
totalHours = int(d.Hours())
}
}
if t, err := h.keyValueSrvc.GetString(conf.KeyLatestTotalUsers); err == nil && t != nil && t.Value != "" {
if d, err := strconv.Atoi(t.Value); err == nil {
totalUsers = d
}
}
2020-11-06 23:19:54 +03:00
return &view.HomeViewModel{
Success: r.URL.Query().Get("success"),
Error: r.URL.Query().Get("error"),
TotalHours: totalHours,
TotalUsers: totalUsers,
2020-11-06 23:19:54 +03:00
}
}