config.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "os"
  6. "path/filepath"
  7. )
  8. const appDirName = "deepseek-tray"
  9. // Config 托盘程序配置,存于 %APPDATA%\deepseek-tray\config.json。
  10. type Config struct {
  11. WebPort int `json:"webPort"` // dsh web 监听端口(默认 3080)
  12. WebHost string `json:"webHost"` // 绑定地址(默认 127.0.0.1)
  13. NodePath string `json:"nodePath"` // node 可执行路径(留空自动探测)
  14. DshBinJS string `json:"dshBinJs"` // dsh 入口 JS(留空自动探测)
  15. AutoStart bool `json:"autoStart"` // 开机自启(注册表 Run 键)
  16. AutoUpdate bool `json:"autoUpdate"` // 定期后台更新
  17. UpdateIntervalH int `json:"updateIntervalHours"` // 定期更新间隔(小时)
  18. RestartDelaySec int `json:"restartDelaySeconds"` // 异常退出后重启延迟(秒)
  19. }
  20. func defaultConfig() *Config {
  21. return &Config{
  22. WebPort: 3080,
  23. WebHost: "127.0.0.1",
  24. AutoStart: false,
  25. AutoUpdate: false,
  26. UpdateIntervalH: 24,
  27. RestartDelaySec: 5,
  28. }
  29. }
  30. // appDataDir 返回配置与日志目录(不存在时创建)。
  31. func appDataDir() string {
  32. base := os.Getenv("APPDATA")
  33. if base == "" {
  34. if home, err := os.UserHomeDir(); err == nil {
  35. base = home
  36. } else {
  37. base = "."
  38. }
  39. }
  40. dir := filepath.Join(base, appDirName)
  41. _ = os.MkdirAll(dir, 0o755)
  42. return dir
  43. }
  44. func configPath() string {
  45. return filepath.Join(appDataDir(), "config.json")
  46. }
  47. func loadConfig() *Config {
  48. cfg := defaultConfig()
  49. data, err := os.ReadFile(configPath())
  50. if err != nil {
  51. _ = saveConfig(cfg)
  52. return cfg
  53. }
  54. // 容忍 UTF-8 BOM(Windows 记事本等编辑器写入的配置会带 BOM)
  55. data = bytes.TrimPrefix(data, []byte{0xEF, 0xBB, 0xBF})
  56. if err := json.Unmarshal(data, cfg); err != nil {
  57. return defaultConfig()
  58. }
  59. if cfg.WebPort <= 0 {
  60. cfg.WebPort = 3080
  61. }
  62. if cfg.WebHost == "" {
  63. cfg.WebHost = "127.0.0.1"
  64. }
  65. if cfg.UpdateIntervalH <= 0 {
  66. cfg.UpdateIntervalH = 24
  67. }
  68. if cfg.RestartDelaySec <= 0 {
  69. cfg.RestartDelaySec = 5
  70. }
  71. return cfg
  72. }
  73. func saveConfig(cfg *Config) error {
  74. data, err := json.MarshalIndent(cfg, "", " ")
  75. if err != nil {
  76. return err
  77. }
  78. return os.WriteFile(configPath(), data, 0o644)
  79. }