gottdad/config.go
2021-12-05 16:44:10 +08:00

130 lines
2.6 KiB
Go

package main
import (
_ "embed"
"encoding/json"
"io/ioutil"
"log"
"time"
"github.com/tidwall/pretty"
)
//go:embed config.sample.json
var cfgSample []byte
type ServerConfig struct {
Addr string `json:"addr"`
Passwd string `json:"passwd"`
}
type TelegramConfig struct {
AdminID int64 `json:"admin_id"`
ChatID int64 `json:"chat_id"`
URL string `json:"url"`
Token string `json:"token"`
}
type GameConfig struct {
TimeZone string `json:"timezone"`
DailyAllotment time.Duration `json:"daily_allotment"`
StartingAllotment time.Duration `json:"starting_allotment"`
Threshold time.Duration `json:"threshold"`
StartDate time.Time `json:"start_date"`
Started bool `json:"started"`
}
type ClientConfig struct {
UserID int `json:"user_id"`
Username string `json:"username"`
Passwd string `json:"passwd"`
Online bool `json:"online"`
TimeLeft time.Duration `json:"time_left"`
CompanyID uint8 `json:"company_id`
Ready bool `json:"ready"`
}
type Config struct {
Server *ServerConfig `json:"server"`
Telegram *TelegramConfig `json:"telegram"`
Game *GameConfig `json:"game"`
Clients map[int]*ClientConfig `json:"clients"`
Stats map[uint8]map[string]*Stat `json:"stats"`
}
// Init values for a config based on package defaults
func (c *Config) Init() error {
err := json.Unmarshal(cfgSample, &c)
c.Clients = make(map[int]*ClientConfig)
c.Stats = make(map[uint8]map[string]*Stat)
if err != nil {
return err
}
return nil
}
// Load config values from a given file
func (c *Config) Load(path string) error {
err := c.Init()
if err != nil {
return err
}
b, err := ioutil.ReadFile(path)
if err != nil {
return c.Save(path)
}
err = json.Unmarshal(b, &c)
if err != nil {
return err
}
log.Printf("Stats : %d", len(c.Stats))
return c.Save(path)
}
// Save config values to a given file
func (c *Config) Save(path string) error {
b, err := c.Export()
if err != nil {
return nil
}
err = ioutil.WriteFile(path, b, 0644)
return err
}
// Export config values as a bytestream
func (c *Config) Export() ([]byte, error) {
b, err := json.Marshal(c)
if err != nil {
return b, err
}
return pretty.Pretty(b), nil
}
func (c *Config) CompanyIsRegistered(id uint8) bool {
if id == 255 {
return false
}
for _, cc := range c.Clients {
if cc.CompanyID == id {
return true
}
}
return false
}
func (c *Config) GetCompanyClient(id uint8) *ClientConfig {
for _, cc := range c.Clients {
if cc.CompanyID == id {
return cc
}
}
return nil
}