84 lines
1.8 KiB
Go
84 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
// External
|
|
werr "git.gibonuddevalla.se/go/wrappederror"
|
|
|
|
// Standard
|
|
"database/sql"
|
|
"time"
|
|
)
|
|
|
|
type Configuration struct {
|
|
timezoneLocation *time.Location
|
|
Settings map[string]string
|
|
}
|
|
|
|
var smonConfig Configuration
|
|
|
|
func SmonConfigInit() (cfg Configuration, err error) {
|
|
cfg.Settings = make(map[string]string, 8)
|
|
|
|
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
|
|
}
|
|
|
|
err = cfg.LoadTimezone()
|
|
return
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
func (cfg *Configuration) LoadTimezone() (err error) {
|
|
cfg.timezoneLocation, err = time.LoadLocation(cfg.Settings["TIMEZONE"])
|
|
return
|
|
}
|
|
|
|
func (cfg *Configuration) Timezone() *time.Location {
|
|
return cfg.timezoneLocation
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
func (cfg *Configuration) SetTimezone(tz string) (err error) {
|
|
cfg.Settings["TIMEZONE"] = tz
|
|
err = cfg.LoadTimezone()
|
|
if err != nil {
|
|
return werr.Wrap(err).WithData(tz)
|
|
}
|
|
|
|
_, err = service.Db.Conn.Exec(`UPDATE public.configuration SET value=$1 WHERE setting='TIMEZONE'`, tz)
|
|
if err != nil {
|
|
return werr.Wrap(err).WithData(tz)
|
|
}
|
|
|
|
return
|
|
}
|