feat(config): 支持共享代理配置文件,发布 0.5.2

This commit is contained in:
yml
2026-11-20 13:20:12 +08:00
parent 635d80e63e
commit f4b3cfa486
13 changed files with 595 additions and 6 deletions
+18
View File
@@ -183,6 +183,24 @@ func (a *App) Startup(ctx context.Context) {
// 优先初始化调度器和账号库,避免前端首屏请求早于启动网络探测时读到 nil。
cfg := config.LoadConfig(a.paths.ConfigFile)
sharedPath := strings.TrimSpace(cfg.SharedProxyConfigFile)
if sharedPath == "" {
if inheritedPath, err := config.LoadSharedProxyConfigPointer(); err != nil {
logger.LogEvent("配置", "warn", "读取本机共享代理配置路径失败: %v", err)
} else {
sharedPath = strings.TrimSpace(inheritedPath)
}
}
if sharedPath != "" {
cfg.SharedProxyConfigFile = sharedPath
shared, err := config.LoadSharedProxyConfig(sharedPath)
if err != nil {
logger.LogEvent("配置", "warn", "启动加载共享代理配置失败,继续使用本机配置: %v", err)
} else {
config.ApplySharedProxyConfig(&cfg, shared)
logger.LogEvent("配置", "success", "已加载共享代理配置: %s", sharedPath)
}
}
a.setCfg(cfg)
logger.SetMinLevel(cfg.LogLevel)
a.replaceTrace(cfg)
+5
View File
@@ -143,6 +143,11 @@ func (a *App) SaveSettings(cfg types.Config) types.ErrorResult {
logger.LogEvent("配置", "error", "配置保存失败: %v", err)
return types.ErrorResult{Error: "配置保存失败: " + err.Error()}
}
if cfg.SharedProxyConfigFile != oldCfg.SharedProxyConfigFile && strings.TrimSpace(cfg.SharedProxyConfigFile) != "" {
if err := config.SaveSharedProxyConfigPointer(cfg.SharedProxyConfigFile); err != nil {
logger.LogEvent("配置", "warn", "保存共享代理配置路径失败: %v", err)
}
}
traceChanged := cfg.TraceEnabled != oldCfg.TraceEnabled || cfg.TraceMaxBody != oldCfg.TraceMaxBody
proxyChanged := cfg.ProxyEnabled != oldCfg.ProxyEnabled || cfg.ProxyURL != oldCfg.ProxyURL
+101
View File
@@ -0,0 +1,101 @@
package app
import (
"os"
"path/filepath"
"strings"
"github.com/wailsapp/wails/v2/pkg/runtime"
"douyu_go/internal/config"
"douyu_go/internal/logger"
"douyu_go/internal/types"
)
// LoadSharedProxyConfig 从指定文件读取代理配置并立即应用到当前实例。
func (a *App) LoadSharedProxyConfig(path string) types.ErrorResult {
path = strings.TrimSpace(path)
if path == "" {
path = strings.TrimSpace(a.getCfg().SharedProxyConfigFile)
}
shared, err := config.LoadSharedProxyConfig(path)
if err != nil {
logger.LogEvent("配置", "warn", "加载共享代理配置失败: %v", err)
return types.ErrorResult{Error: err.Error()}
}
cfg := a.getCfg()
cfg.SharedProxyConfigFile = path
config.ApplySharedProxyConfig(&cfg, shared)
if err := config.SaveSharedProxyConfigPointer(path); err != nil {
logger.LogEvent("配置", "warn", "保存共享代理配置路径失败: %v", err)
}
result := a.SaveSettings(cfg)
if result.Success {
logger.LogEvent("配置", "success", "共享代理配置已加载并应用: %s", path)
}
return result
}
// SaveSharedProxyConfig 将当前实例的代理配置写入共享文件。
func (a *App) SaveSharedProxyConfig(path string) types.ErrorResult {
path = strings.TrimSpace(path)
if path == "" {
path = strings.TrimSpace(a.getCfg().SharedProxyConfigFile)
}
if path == "" {
return types.ErrorResult{Error: "请先选择共享代理配置文件"}
}
cfg := a.getCfg()
if err := config.SaveSharedProxyConfig(path, cfg); err != nil {
logger.LogEvent("配置", "error", "保存共享代理配置失败: %v", err)
return types.ErrorResult{Error: err.Error()}
}
cfg.SharedProxyConfigFile = path
if err := config.SaveSharedProxyConfigPointer(path); err != nil {
logger.LogEvent("配置", "warn", "保存共享代理配置路径失败: %v", err)
}
result := a.SaveSettings(cfg)
if result.Success {
logger.LogEvent("配置", "success", "共享代理配置已保存: %s", path)
}
return result
}
// SelectSharedProxyConfigFile 打开系统文件选择器,供前端选择共享代理配置。
func (a *App) SelectSharedProxyConfigFile(save bool) types.FileDialogResult {
cfg := a.getCfg()
defaultDir := strings.TrimSpace(filepath.Dir(cfg.SharedProxyConfigFile))
if defaultDir == "." || defaultDir == "" {
defaultDir = a.paths.DataDir
}
if info, err := os.Stat(defaultDir); err != nil || !info.IsDir() {
defaultDir = a.paths.DataDir
}
filter := runtime.FileFilter{DisplayName: "JSON 配置 (*.json)", Pattern: "*.json"}
var (
path string
err error
)
if save {
path, err = runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
DefaultDirectory: defaultDir,
DefaultFilename: "douyu-proxy-config.json",
Title: "保存共享代理配置",
Filters: []runtime.FileFilter{filter},
})
} else {
path, err = runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
DefaultDirectory: defaultDir,
Title: "选择共享代理配置",
Filters: []runtime.FileFilter{filter},
})
}
if err != nil {
return types.FileDialogResult{Error: err.Error()}
}
path = strings.TrimSpace(path)
if path != "" && !strings.EqualFold(filepath.Ext(path), ".json") {
path += ".json"
}
return types.FileDialogResult{Success: true, Path: path}
}
+184
View File
@@ -0,0 +1,184 @@
package config
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"douyu_go/internal/types"
)
const SharedProxyConfigSchemaVersion = 1
const sharedProxyConfigPointerFile = "shared-proxy-config-path.txt"
// DefaultSharedProxyConfigPointerPath 返回所有本机实例共享的配置路径指针。
func DefaultSharedProxyConfigPointerPath() string {
return filepath.Join(defaultDataDir(), sharedProxyConfigPointerFile)
}
// LoadSharedProxyConfigPointer 读取本机默认共享配置路径。
func LoadSharedProxyConfigPointer() (string, error) {
data, err := os.ReadFile(DefaultSharedProxyConfigPointerPath())
if errors.Is(err, os.ErrNotExist) {
return "", nil
}
if err != nil {
return "", err
}
return strings.TrimSpace(string(data)), nil
}
// SaveSharedProxyConfigPointer 保存本机默认共享配置路径,供新实例自动继承。
func SaveSharedProxyConfigPointer(path string) error {
path = strings.TrimSpace(path)
if path == "" {
return nil
}
pointerPath := DefaultSharedProxyConfigPointerPath()
if err := os.MkdirAll(filepath.Dir(pointerPath), 0700); err != nil {
return err
}
return os.WriteFile(pointerPath, []byte(path), 0600)
}
// LoadSharedProxyConfig 读取并校验共享代理配置。
func LoadSharedProxyConfig(path string) (types.SharedProxyConfig, error) {
path = strings.TrimSpace(path)
if path == "" {
return types.SharedProxyConfig{}, errors.New("共享代理配置路径为空")
}
data, err := os.ReadFile(path)
if err != nil {
return types.SharedProxyConfig{}, fmt.Errorf("读取共享代理配置失败: %w", err)
}
var shared types.SharedProxyConfig
if err := json.Unmarshal(data, &shared); err != nil {
return types.SharedProxyConfig{}, fmt.Errorf("解析共享代理配置失败: %w", err)
}
if shared.SchemaVersion != SharedProxyConfigSchemaVersion {
return types.SharedProxyConfig{}, fmt.Errorf(
"不支持的共享代理配置版本 %d,当前仅支持 %d",
shared.SchemaVersion, SharedProxyConfigSchemaVersion,
)
}
if !hasSharedProxySettings(shared.Proxy) {
return types.SharedProxyConfig{}, errors.New("共享代理配置中没有 proxy 设置")
}
return shared, nil
}
// ApplySharedProxyConfig 将共享代理字段叠加到实例配置,未提供的字段保持不变。
func ApplySharedProxyConfig(cfg *types.Config, shared types.SharedProxyConfig) {
if cfg == nil {
return
}
proxy := shared.Proxy
if proxy.Enabled != nil {
cfg.ProxyEnabled = *proxy.Enabled
}
if proxy.API != nil {
cfg.ProxyAPI = strings.TrimSpace(*proxy.API)
}
if proxy.AccountsPerProxy != nil {
cfg.AccountsPerProxy = *proxy.AccountsPerProxy
}
if proxy.SparePercent != nil {
cfg.ProxySparePercent = *proxy.SparePercent
}
if proxy.AutoFetchOnSchedule != nil {
cfg.AutoFetchProxyOnSchedule = *proxy.AutoFetchOnSchedule
}
if proxy.AutoWhitelist != nil {
cfg.ProxyAutoWhitelist = *proxy.AutoWhitelist
}
if proxy.WhitelistReplace != nil {
cfg.ProxyWhitelistReplace = *proxy.WhitelistReplace
}
if proxy.WhitelistPassword != nil {
cfg.ProxyWhitelistPassword = strings.TrimSpace(*proxy.WhitelistPassword)
}
if proxy.WhitelistSignKey != nil {
cfg.ProxyWhitelistSignKey = strings.TrimSpace(*proxy.WhitelistSignKey)
}
normalizeProxyConfig(cfg)
}
// SaveSharedProxyConfig 将当前代理配置写入共享文件,不包含实例代理 URL 或账号数据。
func SaveSharedProxyConfig(path string, cfg types.Config) error {
path = strings.TrimSpace(path)
if path == "" {
return errors.New("共享代理配置路径为空")
}
shared := types.SharedProxyConfig{
SchemaVersion: SharedProxyConfigSchemaVersion,
UpdatedAt: time.Now().Format(time.RFC3339),
Proxy: types.SharedProxySettings{
Enabled: boolPointer(cfg.ProxyEnabled),
API: stringPointer(cfg.ProxyAPI),
AccountsPerProxy: intPointer(cfg.AccountsPerProxy),
SparePercent: intPointer(cfg.ProxySparePercent),
AutoFetchOnSchedule: boolPointer(cfg.AutoFetchProxyOnSchedule),
AutoWhitelist: boolPointer(cfg.ProxyAutoWhitelist),
WhitelistReplace: boolPointer(cfg.ProxyWhitelistReplace),
WhitelistPassword: stringPointer(cfg.ProxyWhitelistPassword),
WhitelistSignKey: stringPointer(cfg.ProxyWhitelistSignKey),
},
}
data, err := json.MarshalIndent(shared, "", " ")
if err != nil {
return fmt.Errorf("生成共享代理配置失败: %w", err)
}
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return fmt.Errorf("创建共享配置目录失败: %w", err)
}
temp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*.tmp")
if err != nil {
return fmt.Errorf("创建共享配置临时文件失败: %w", err)
}
tempPath := temp.Name()
defer func() {
if tempPath != "" {
_ = os.Remove(tempPath)
}
}()
if err := temp.Chmod(0600); err != nil {
_ = temp.Close()
return err
}
if _, err := temp.Write(data); err != nil {
_ = temp.Close()
return err
}
if err := temp.Sync(); err != nil {
_ = temp.Close()
return err
}
if err := temp.Close(); err != nil {
return err
}
if err := replaceSharedProxyConfigFile(tempPath, path); err != nil {
return fmt.Errorf("替换共享代理配置失败: %w", err)
}
tempPath = ""
return nil
}
func hasSharedProxySettings(proxy types.SharedProxySettings) bool {
return proxy.Enabled != nil ||
proxy.API != nil ||
proxy.AccountsPerProxy != nil ||
proxy.SparePercent != nil ||
proxy.AutoFetchOnSchedule != nil ||
proxy.AutoWhitelist != nil ||
proxy.WhitelistReplace != nil ||
proxy.WhitelistPassword != nil ||
proxy.WhitelistSignKey != nil
}
func boolPointer(value bool) *bool { return &value }
func intPointer(value int) *int { return &value }
func stringPointer(value string) *string { return &value }
@@ -0,0 +1,9 @@
//go:build !windows
package config
import "os"
func replaceSharedProxyConfigFile(tempPath, targetPath string) error {
return os.Rename(tempPath, targetPath)
}
@@ -0,0 +1,18 @@
//go:build windows
package config
import (
"errors"
"os"
)
func replaceSharedProxyConfigFile(tempPath, targetPath string) error {
if err := os.Rename(tempPath, targetPath); err == nil {
return nil
}
if err := os.Remove(targetPath); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return os.Rename(tempPath, targetPath)
}
@@ -0,0 +1,98 @@
package config
import (
"os"
"path/filepath"
"strings"
"testing"
"douyu_go/internal/types"
)
func TestSharedProxyConfigRoundTripExcludesRuntimeProxy(t *testing.T) {
path := filepath.Join(t.TempDir(), "shared-proxy.json")
cfg := types.Config{
ProxyEnabled: true,
ProxyURL: "http://user:pass@127.0.0.1:9000",
ProxyAPI: "https://service.ipzan.com/core-extract?mode=auth",
AccountsPerProxy: 5,
ProxySparePercent: 25,
AutoFetchProxyOnSchedule: true,
ProxyAutoWhitelist: true,
ProxyWhitelistReplace: true,
ProxyWhitelistPassword: "login-pass",
ProxyWhitelistSignKey: "0123456789abcdef",
}
if err := SaveSharedProxyConfig(path, cfg); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(data), "proxyUrl") || strings.Contains(string(data), "127.0.0.1:9000") {
t.Fatalf("shared config leaked runtime proxy URL: %s", data)
}
shared, err := LoadSharedProxyConfig(path)
if err != nil {
t.Fatal(err)
}
local := types.Config{
ProxyURL: "http://runtime-only:8000",
}
ApplySharedProxyConfig(&local, shared)
if local.ProxyURL != "http://runtime-only:8000" {
t.Fatalf("ProxyURL=%q, runtime URL should remain local", local.ProxyURL)
}
if !local.ProxyEnabled || local.ProxyAPI != cfg.ProxyAPI || local.AccountsPerProxy != 5 {
t.Fatalf("unexpected merged config: %+v", local)
}
}
func TestApplySharedProxyConfigSupportsPartialOverrides(t *testing.T) {
enabled := false
shared := types.SharedProxyConfig{
SchemaVersion: SharedProxyConfigSchemaVersion,
Proxy: types.SharedProxySettings{
Enabled: &enabled,
},
}
cfg := types.Config{
ProxyEnabled: true,
ProxyAPI: "keep-api",
AccountsPerProxy: 7,
}
ApplySharedProxyConfig(&cfg, shared)
if cfg.ProxyEnabled {
t.Fatal("shared enabled=false should override local value")
}
if cfg.ProxyAPI != "keep-api" || cfg.AccountsPerProxy != 7 {
t.Fatalf("unspecified fields should remain unchanged: %+v", cfg)
}
}
func TestLoadSharedProxyConfigRejectsUnsupportedVersion(t *testing.T) {
path := filepath.Join(t.TempDir(), "shared-proxy.json")
if err := os.WriteFile(path, []byte(`{"schemaVersion":2,"proxy":{"enabled":true}}`), 0600); err != nil {
t.Fatal(err)
}
if _, err := LoadSharedProxyConfig(path); err == nil {
t.Fatal("expected unsupported schema error")
}
}
func TestSharedProxyConfigPointerIsSharedAcrossInstances(t *testing.T) {
t.Setenv("DOUYU_DATA_DIR", t.TempDir())
want := filepath.Join(t.TempDir(), "common-proxy.json")
if err := SaveSharedProxyConfigPointer(want); err != nil {
t.Fatal(err)
}
got, err := LoadSharedProxyConfigPointer()
if err != nil {
t.Fatal(err)
}
if got != want {
t.Fatalf("LoadSharedProxyConfigPointer()=%q, want %q", got, want)
}
}
+1 -1
View File
@@ -3,7 +3,7 @@ package constants
import "time"
// Version 应用版本号,与 wails.json version 同步。
const Version = "0.5.1"
const Version = "0.5.2"
// BuildTime 构建时间,由编译时 ldflags 注入。
var BuildTime = "unknown"
+29
View File
@@ -0,0 +1,29 @@
package types
// SharedProxyConfig 是跨实例、跨电脑同步的代理配置。
// 该文件不包含代理 URL、代理过期时间、账号或 Cookie。
type SharedProxyConfig struct {
SchemaVersion int `json:"schemaVersion"`
UpdatedAt string `json:"updatedAt,omitempty"`
Proxy SharedProxySettings `json:"proxy"`
}
// SharedProxySettings 使用指针区分“未提供”与显式零值,支持部分配置覆盖。
type SharedProxySettings struct {
Enabled *bool `json:"enabled,omitempty"`
API *string `json:"api,omitempty"`
AccountsPerProxy *int `json:"accountsPerProxy,omitempty"`
SparePercent *int `json:"sparePercent,omitempty"`
AutoFetchOnSchedule *bool `json:"autoFetchOnSchedule,omitempty"`
AutoWhitelist *bool `json:"autoWhitelist,omitempty"`
WhitelistReplace *bool `json:"whitelistReplace,omitempty"`
WhitelistPassword *string `json:"whitelistPassword,omitempty"`
WhitelistSignKey *string `json:"whitelistSignKey,omitempty"`
}
// FileDialogResult 返回通过系统文件选择器选中的路径。
type FileDialogResult struct {
Success bool `json:"success"`
Path string `json:"path,omitempty"`
Error string `json:"error,omitempty"`
}
+1
View File
@@ -20,6 +20,7 @@ type Config struct {
ProxyEnabled bool `json:"proxyEnabled"` // 是否启用代理
ProxyURL string `json:"proxyUrl"` // 代理地址,支持 http://, https://, socks5://
ProxyAPI string `json:"proxyApi"` // 代理提取 API 地址,支持品赞与通用格式
SharedProxyConfigFile string `json:"sharedProxyConfigFile"` // 本机保存的共享代理配置路径
ProxyExpiresAt int64 `json:"proxyExpiresAt,omitempty"` // 当前静态代理的过期时间(Unix 毫秒),0 表示未知
AutoFetchProxyOnSchedule bool `json:"autoFetchProxyOnSchedule"` // 定时抢购触发前自动从 API 提取最新代理
AccountsPerProxy int `json:"accountsPerProxy"` // 每个独立代理承载的账号数