worklog/internal/api/server.go
2023-01-27 17:11:22 +01:00

161 lines
4.9 KiB
Go

package api
import (
"net/http"
"net/url"
"strconv"
"strings"
"time"
"velvettear/worklog/internal/config"
"velvettear/worklog/internal/database"
"velvettear/worklog/internal/log"
"velvettear/worklog/internal/workday"
)
// exported function(s)
func Run() {
serverAddress := config.ServerListen() + ":" + strconv.Itoa(config.ServerPort())
http.HandleFunc("/", handleRequests)
log.Info("starting server '" + serverAddress + "'...")
err := http.ListenAndServe(serverAddress, nil)
if err != nil {
log.Fatal("encountered an error starting the server", err.Error())
}
}
// unexported function(s)
func handleRequests(writer http.ResponseWriter, request *http.Request) {
requestPath := request.URL.Path
requestMethod := strings.ToLower(request.Method)
user, authorized := isAuthorized(request)
if !authorized {
log.Debug("denying unauthorized '" + requestMethod + "' request for path '" + requestPath + "'")
writer.WriteHeader(404)
writer.Write([]byte("error: basic authorization failed\n"))
return
}
handled := false
switch requestMethod {
case "get":
log.Debug("handling '" + requestMethod + "' request for path '" + requestPath + "'...")
handled = handleGet(user, writer, request)
case "post":
log.Debug("handling '" + requestMethod + "' request for path '" + requestPath + "'...")
handled = handlePost(user, writer, request)
}
if handled {
return
}
log.Debug("ignoring '" + requestMethod + "' request for path '" + requestPath + "'\n")
writer.WriteHeader(501)
writer.Write([]byte("error: endpoint '" + requestPath + "' not implemented\n"))
}
func isAuthorized(request *http.Request) (string, bool) {
username, password, ok := request.BasicAuth()
if !ok {
return username, false
}
return username, password == config.GetString("users."+username+".password")
}
func handleGet(user string, writer http.ResponseWriter, request *http.Request) bool {
handled := true
switch request.URL.Path {
case "/today":
workday, error := workday.GetToday(user)
if error != nil {
writer.WriteHeader(404)
break
}
json, error := workday.ToJSON(user)
if error != nil {
msg := "encountered an error generating json output"
log.Error(msg, error.Error())
writer.WriteHeader(500)
writer.Write([]byte(msg + "\n"))
break
}
writer.WriteHeader(200)
writer.Write([]byte(json + "\n"))
case "/json":
from, to := getTimespan(request.URL.Query())
json, error := workday.ToJSON(from, to, user)
if error != nil {
msg := "encountered an error generating json output"
log.Error(msg, error.Error())
writer.WriteHeader(500)
writer.Write([]byte(msg + "\n"))
break
}
writer.WriteHeader(200)
writer.Write([]byte(json + "\n"))
case "/csv":
from, to := getTimespan(request.URL.Query())
result := workday.ToCSV(from, to, user)
writer.WriteHeader(200)
writer.Write([]byte(result + "\n"))
default:
handled = false
}
return handled
}
func handlePost(user string, writer http.ResponseWriter, request *http.Request) bool {
handled := true
switch request.URL.Path {
case "/start":
success, workday := database.StartTimestamp(user)
if !success {
if workday.ID > 0 {
writer.WriteHeader(400)
writer.Write([]byte("workday for today has already been started at " + strconv.Itoa(workday.Start.Hour()) + ":" + strconv.Itoa(workday.Start.Minute()) + ":" + strconv.Itoa(workday.Start.Second()) + "\n"))
} else {
writer.WriteHeader(500)
writer.Write([]byte("encountered an error starting a new workday\n"))
}
break
}
writer.WriteHeader(200)
writer.Write([]byte("started new workday for user '" + workday.User + "' at " + strconv.Itoa(workday.Start.Hour()) + ":" + strconv.Itoa(workday.Start.Minute()) + ":" + strconv.Itoa(workday.Start.Second()) + "\n"))
case "/stop":
success, workday := database.StopTimestamp()
if !success {
if workday.ID > 0 {
writer.WriteHeader(500)
writer.Write([]byte("encountered an error stopping workday for user '" + workday.User + "'\n"))
} else {
writer.WriteHeader(400)
writer.Write([]byte("there is no open workday to stop\n"))
}
break
}
writer.WriteHeader(200)
writer.Write([]byte("stopped workday for user '" + workday.User + "' started at " + strconv.Itoa(workday.Start.Hour()) + ":" + strconv.Itoa(workday.Start.Minute()) + ":" + strconv.Itoa(workday.Start.Second()) + "\n"))
default:
handled = false
}
return handled
}
func getTimespan(values url.Values) (time.Time, time.Time) {
from := time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC)
to := time.Now()
layout := "02.01.2006"
if values.Has("from") {
tmp, error := time.Parse(layout, values.Get("from"))
if error != nil {
log.Error("error parsing date '"+values.Get("from"), error.Error())
}
from = tmp
}
if values.Has("to") {
tmp, error := time.Parse(layout, values.Get("to"))
if error != nil {
log.Error("error parsing date '"+values.Get("from"), error.Error())
}
to = tmp
to = to.Add(time.Hour * 23).Add(time.Minute * 59).Add(time.Second * 59)
}
return from, to
}