smon/configuration.go

84 lines
1.8 KiB
Go
Raw Normal View History

2024-06-25 08:59:07 +02:00
package main
import (
// External
werr "git.gibonuddevalla.se/go/wrappederror"
// Standard
"database/sql"
2024-06-27 13:14:37 +02:00
"time"
2024-06-25 08:59:07 +02:00
)
type Configuration struct {
2024-06-27 13:14:37 +02:00
timezoneLocation *time.Location
2024-06-25 08:59:07 +02:00
Settings map[string]string
}
var smonConfig Configuration
func SmonConfigInit() (cfg Configuration, err error) {
cfg.Settings = make(map[string]string, 8)
2024-06-25 08:59:07 +02:00
var rows *sql.Rows
rows, err = service.Db.Conn.Query(`SELECT * FROM public.configuration`)
if err != nil {
err = werr.Wrap(err)
return
}
defer rows.Close()
for rows.Next() {
var setting, value string
err = rows.Scan(&setting, &value)
if err != nil {
err = werr.Wrap(err)
return
}
cfg.Settings[setting] = value
2024-06-25 08:59:07 +02:00
}
2024-06-27 13:14:37 +02:00
err = cfg.LoadTimezone()
2024-06-25 08:59:07 +02:00
return
}
2024-06-25 09:18:15 +02:00
func (cfg *Configuration) Validate() (err error) {
mandatorySettings := []string{"THEME", "TIMEZONE"}
for _, settingsKey := range mandatorySettings {
if _, found := cfg.Settings[settingsKey]; !found {
return werr.New("Configuration missing setting '%s' in database", settingsKey)
}
}
return
}
2024-06-27 13:14:37 +02:00
func (cfg *Configuration) LoadTimezone() (err error) {
cfg.timezoneLocation, err = time.LoadLocation(cfg.Settings["TIMEZONE"])
return
}
func (cfg *Configuration) Timezone() *time.Location {
return cfg.timezoneLocation
}
2024-06-25 09:18:15 +02:00
func (cfg *Configuration) SetTheme(theme string) (err error) {
cfg.Settings["THEME"] = theme
_, err = service.Db.Conn.Exec(`UPDATE public.configuration SET value=$1 WHERE setting='THEME'`, theme)
return
}
2024-06-27 10:02:11 +02:00
func (cfg *Configuration) SetTimezone(tz string) (err error) {
cfg.Settings["TIMEZONE"] = tz
2024-06-27 13:14:37 +02:00
err = cfg.LoadTimezone()
if err != nil {
return werr.Wrap(err).WithData(tz)
}
2024-06-27 10:02:11 +02:00
_, err = service.Db.Conn.Exec(`UPDATE public.configuration SET value=$1 WHERE setting='TIMEZONE'`, tz)
2024-06-27 13:14:37 +02:00
if err != nil {
return werr.Wrap(err).WithData(tz)
}
2024-06-27 10:02:11 +02:00
return
}