nezha/model/config.go

91 lines
1.7 KiB
Go
Raw Normal View History

2019-12-08 16:59:58 +08:00
package model
import (
2020-12-09 19:05:40 +08:00
"io/ioutil"
"os"
"strconv"
"strings"
2019-12-20 23:58:09 +08:00
2019-12-08 16:59:58 +08:00
"github.com/spf13/viper"
2020-12-09 19:05:40 +08:00
"gopkg.in/yaml.v2"
2019-12-08 16:59:58 +08:00
)
const (
ConfigTypeGitHub = "github"
ConfigTypeGitee = "gitee"
)
2021-06-22 14:05:36 +08:00
const (
ConfigCoverAll = iota
ConfigCoverIgnoreAll
)
2019-12-08 16:59:58 +08:00
type Config struct {
Debug bool
Site struct {
Brand string // 站点名称
CookieName string // 浏览器 Cookie 名称
Theme string
CustomCode string
ViewPassword string // 前台查看密码
2019-12-08 16:59:58 +08:00
}
Oauth2 struct {
Type string
Admin string // 管理员用户名列表
2019-12-08 16:59:58 +08:00
ClientID string
ClientSecret string
}
HTTPPort uint
GRPCPort uint
2021-08-10 14:04:21 +08:00
GRPCHost string
EnableIPChangeNotification bool
2021-06-22 14:05:36 +08:00
// IP变更提醒
Cover uint8 // 覆盖范围
IgnoredIPNotification string // 特定服务器
2019-12-20 23:58:09 +08:00
v *viper.Viper
2021-06-22 14:05:36 +08:00
IgnoredIPNotificationServerIDs map[uint64]bool
2019-12-08 16:59:58 +08:00
}
2019-12-20 23:58:09 +08:00
func (c *Config) Read(path string) error {
c.v = viper.New()
c.v.SetConfigFile(path)
err := c.v.ReadInConfig()
2019-12-08 16:59:58 +08:00
if err != nil {
2019-12-20 23:58:09 +08:00
return err
2019-12-08 16:59:58 +08:00
}
2019-12-20 23:58:09 +08:00
err = c.v.Unmarshal(c)
2019-12-08 16:59:58 +08:00
if err != nil {
2019-12-20 23:58:09 +08:00
return err
2019-12-08 16:59:58 +08:00
}
2020-12-09 19:05:40 +08:00
if c.Site.Theme == "" {
c.Site.Theme = "default"
}
c.updateIgnoredIPNotificationID()
2019-12-20 23:58:09 +08:00
return nil
2019-12-08 16:59:58 +08:00
}
2020-12-09 19:05:40 +08:00
func (c *Config) updateIgnoredIPNotificationID() {
2021-06-22 14:05:36 +08:00
c.IgnoredIPNotificationServerIDs = make(map[uint64]bool)
splitedIDs := strings.Split(c.IgnoredIPNotification, ",")
for i := 0; i < len(splitedIDs); i++ {
id, _ := strconv.ParseUint(splitedIDs[i], 10, 64)
if id > 0 {
2021-06-22 14:05:36 +08:00
c.IgnoredIPNotificationServerIDs[id] = true
}
}
}
2020-12-09 19:05:40 +08:00
func (c *Config) Save() error {
c.updateIgnoredIPNotificationID()
2020-12-09 19:05:40 +08:00
data, err := yaml.Marshal(c)
if err != nil {
return err
}
return ioutil.WriteFile(c.v.ConfigFileUsed(), data, os.ModePerm)
}