增加设置界面、debug日志等级、版本号展示、构建脚本

- 新增设置弹窗: trace开关/正文上限、日志等级(debug/info/warn/error)、并发数、重试次数
- 配置运行时生效,持久化到 config.json
- 日志系统支持 debug 级别过滤
- 工具栏展示版本号(v0.0.2),来源 wails.json + constants.go
- 抢购并发数和重试次数改为读取配置,不再写死常量
- 新增 build.sh 构建脚本,Windows exe 文件名带版本号
- config.json 加入 .gitignore
This commit is contained in:
yml2213
2026-06-24 20:18:33 +08:00
parent 154e55d484
commit 8790c4ca33
10 changed files with 365 additions and 21 deletions
+51 -6
View File
@@ -14,16 +14,28 @@ import (
)
// DefaultAppPaths 收集运行时路径,支持环境变量覆盖。
// 所有相对路径会基于当前工作目录解析为绝对路径,避免打包后工作目录不同导致路径错位。
func DefaultAppPaths() types.AppPaths {
return types.AppPaths{
ConfigFile: envOrDefault("DOUYU_CONFIG", constants.DefaultConfigFile),
AccountFile: envOrDefault("DOUYU_USERS", constants.DefaultAccountFile),
LogDir: envOrDefault("DOUYU_LOG_DIR", constants.DefaultLogDir),
SuccessDir: envOrDefault("DOUYU_SUCCESS_DIR", constants.DefaultSuccessDir),
ConfigFile: resolvePath(envOrDefault("DOUYU_CONFIG", constants.DefaultConfigFile)),
AccountFile: resolvePath(envOrDefault("DOUYU_USERS", constants.DefaultAccountFile)),
LogDir: resolvePath(envOrDefault("DOUYU_LOG_DIR", constants.DefaultLogDir)),
SuccessDir: resolvePath(envOrDefault("DOUYU_SUCCESS_DIR", constants.DefaultSuccessDir)),
FontFiles: CollectFontCandidates(),
}
}
// resolvePath 将相对路径解析为绝对路径。
func resolvePath(path string) string {
if filepath.IsAbs(path) {
return path
}
if abs, err := filepath.Abs(path); err == nil {
return abs
}
return path
}
func envOrDefault(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return filepath.Clean(value)
@@ -60,9 +72,21 @@ func envInt(key string, fallback int) int {
return value
}
// defaultConfig 返回内置默认配置。
func defaultConfig() types.Config {
return types.Config{
TimeAPIURL: constants.DefaultTimeAPI,
TraceEnabled: false,
TraceMaxBody: 0,
LogLevel: "info",
Concurrency: constants.DefaultConcurrency,
Attempts: constants.DefaultAttempts,
}
}
// LoadConfig 读取配置文件;缺失时安静使用内置默认配置。
func LoadConfig(path string) types.Config {
cfg := types.Config{TimeAPIURL: constants.DefaultTimeAPI}
cfg := defaultConfig()
if path == "" {
path = constants.DefaultConfigFile
}
@@ -80,15 +104,36 @@ func LoadConfig(path string) types.Config {
if err := json.NewDecoder(f).Decode(&cfg); err != nil {
logger.LogEvent("配置", "warn", "解析 %s 失败,使用内置默认配置: %v", path, err)
return types.Config{TimeAPIURL: constants.DefaultTimeAPI}
return defaultConfig()
}
if cfg.TimeAPIURL == "" {
cfg.TimeAPIURL = constants.DefaultTimeAPI
}
if cfg.Concurrency <= 0 {
cfg.Concurrency = constants.DefaultConcurrency
}
if cfg.Attempts <= 0 {
cfg.Attempts = constants.DefaultAttempts
}
if cfg.LogLevel == "" {
cfg.LogLevel = "info"
}
logger.LogEvent("配置", "success", "配置加载完成: %s", path)
return cfg
}
// SaveConfig 将配置写入文件。
func SaveConfig(path string, cfg types.Config) error {
if path == "" {
path = constants.DefaultConfigFile
}
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0644)
}
// CollectFontCandidates 收集常见中文字体路径,允许用 DOUYU_FONT 指定自定义字体。
func CollectFontCandidates() []string {
candidates := []string{}
+3
View File
@@ -2,6 +2,9 @@ package constants
import "time"
// Version 应用版本号,与 wails.json version 同步。
const Version = "0.0.2"
const (
ManualID = "G4KA4Qnz4LDp7"
RoomID = "9263298"
+56 -2
View File
@@ -14,6 +14,29 @@ import (
"douyu_go/internal/constants"
)
// minLevel 日志最低等级,低于此等级的日志不输出。0=info, 1=warn, 2=error。
var minLevel atomic.Int32
// SetMinLevel 设置日志最低显示等级。
func SetMinLevel(level string) {
minLevel.Store(int32(levelPriority(level)))
}
func levelPriority(level string) int {
switch strings.ToLower(level) {
case "debug":
return -1
case "info":
return 0
case "warn":
return 1
case "error":
return 2
default:
return 0
}
}
// AsyncLogWriter 异步日志写入器,队列满时丢弃日志以保护主链路。
type AsyncLogWriter struct {
dst io.Writer
@@ -82,6 +105,10 @@ func InitLogging(store *MemoryLogStore, logDir string) func() {
if logDir == "" {
logDir = constants.DefaultLogDir
}
// 解析为绝对路径,避免打包后工作目录不同导致日志写到意外位置
logDir = resolveAbsolutePath(logDir)
if err := os.MkdirAll(logDir, 0755); err != nil {
async := NewAsyncLogWriter(io.MultiWriter(os.Stdout, store), 2048)
log.SetOutput(async)
@@ -108,7 +135,7 @@ func InitLogging(store *MemoryLogStore, logDir string) func() {
}
}
// LogEvent 输出带分类和级别的结构化文本日志。
// LogEvent 输出带分类和级别的结构化文本日志。低于当前最低等级的日志会被丢弃。
func LogEvent(category, level, format string, args ...any) {
if category == "" {
category = "系统"
@@ -116,6 +143,9 @@ func LogEvent(category, level, format string, args ...any) {
if level == "" {
level = "info"
}
if levelPriority(level) < int(minLevel.Load()) {
return
}
log.Printf("[%s][%s] %s", category, level, fmt.Sprintf(format, args...))
}
@@ -150,17 +180,41 @@ func cutBracket(s string) (string, string, bool) {
// IsLogLevel 判断是否为有效日志级别。
func IsLogLevel(level string) bool {
switch strings.ToLower(level) {
case "success", "error", "warn", "info":
case "success", "error", "warn", "info", "debug":
return true
default:
return false
}
}
// LogDebug 输出 debug 级别日志,仅在日志等级设为 debug 时可见。
func LogDebug(category, format string, args ...any) {
LogEvent(category, "debug", format, args...)
}
// resolveAbsolutePath 将相对路径解析为绝对路径。
// 如果路径已经是绝对路径则直接返回;否则基于可执行文件所在目录解析。
func resolveAbsolutePath(path string) string {
if filepath.IsAbs(path) {
return path
}
// 先尝试基于当前工作目录解析
if abs, err := filepath.Abs(path); err == nil {
return abs
}
// 兜底:基于可执行文件所在目录
if exe, err := os.Executable(); err == nil {
return filepath.Join(filepath.Dir(exe), path)
}
return path
}
// DetectLogLevel 根据日志文本粗略分类,方便前端染色。
func DetectLogLevel(line string) string {
lower := strings.ToLower(line)
switch {
case strings.Contains(lower, "[debug]"):
return "debug"
case strings.Contains(lower, "[success]"):
return "success"
case strings.Contains(lower, "[error]"):
+46 -8
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
@@ -33,6 +34,9 @@ type Scheduler struct {
paths types.AppPaths
font *truetype.Font
concurrency int // 抢购并发数
attempts int // 单号重试次数
accountsMu sync.RWMutex
accounts []types.Account
@@ -52,12 +56,30 @@ type Scheduler struct {
}
// New 创建抢购调度器。
func New(cli *client.DouyuClient, paths types.AppPaths, font *truetype.Font) *Scheduler {
func New(cli *client.DouyuClient, paths types.AppPaths, font *truetype.Font, concurrency, attempts int) *Scheduler {
if concurrency <= 0 {
concurrency = constants.DefaultConcurrency
}
if attempts <= 0 {
attempts = constants.DefaultAttempts
}
return &Scheduler{
client: cli,
paths: paths,
font: font,
results: make(map[string]string),
client: cli,
paths: paths,
font: font,
concurrency: concurrency,
attempts: attempts,
results: make(map[string]string),
}
}
// UpdateSettings 运行时更新并发数和重试次数。
func (s *Scheduler) UpdateSettings(concurrency, attempts int) {
if concurrency > 0 {
s.concurrency = concurrency
}
if attempts > 0 {
s.attempts = attempts
}
}
@@ -67,6 +89,22 @@ func (s *Scheduler) LoadAccounts() {
if path == "" {
path = constants.DefaultAccountFile
}
// 文件不存在时自动创建目录和空文件,方便用户直接粘贴 Cookie
if _, err := os.Stat(path); os.IsNotExist(err) {
if dir := filepath.Dir(path); dir != "" && dir != "." {
if mkErr := os.MkdirAll(dir, 0755); mkErr != nil {
logger.LogEvent("账号", "warn", "账号目录创建失败: %s: %v", dir, mkErr)
}
}
hint := "# 格式: 账号名----密码----Cookie\n# 每行一个账号,粘贴后保存即可\n"
if wrErr := os.WriteFile(path, []byte(hint), 0644); wrErr != nil {
logger.LogEvent("账号", "warn", "账号文件创建失败: %s: %v", path, wrErr)
} else {
logger.LogEvent("账号", "info", "已创建空账号文件: %s,请粘贴 Cookie 后重新加载", path)
}
}
f, err := os.Open(path)
if err != nil {
logger.LogEvent("账号", "error", "读取账号文件失败: %s: %v", path, err)
@@ -186,7 +224,7 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
}
logger.LogEvent("抢购", "info", "开始抢购: %d 个请求", len(attempts))
limit := make(chan struct{}, constants.DefaultConcurrency)
limit := make(chan struct{}, s.concurrency)
var wg sync.WaitGroup
for _, attempt := range attempts {
wg.Add(1)
@@ -219,7 +257,7 @@ func (s *Scheduler) buildAttempts(accountProducts map[string]string) []types.Exc
continue
}
product := types.Product{CommodityID: commodityID, CommodityName: commodityID}
for i := 1; i <= constants.DefaultAttempts; i++ {
for i := 1; i <= s.attempts; i++ {
attempts = append(attempts, types.ExchangeAttempt{
Account: account,
Product: product,
@@ -266,7 +304,7 @@ func (s *Scheduler) warmupAttempts(attempts []types.ExchangeAttempt) {
s.clearWarmups()
logger.LogEvent("预热", "info", "开始预热: %d 个请求", len(attempts))
limit := make(chan struct{}, constants.DefaultConcurrency)
limit := make(chan struct{}, s.concurrency)
var wg sync.WaitGroup
for _, attempt := range attempts {
wg.Add(1)
+6 -1
View File
@@ -7,7 +7,12 @@ import (
// Config 应用配置。
type Config struct {
TimeAPIURL string `json:"timeApiUrl"`
TimeAPIURL string `json:"timeApiUrl"`
TraceEnabled bool `json:"traceEnabled"`
TraceMaxBody int `json:"traceMaxBody"`
LogLevel string `json:"logLevel"` // debug / info / warn / error
Concurrency int `json:"concurrency"` // 抢购并发数
Attempts int `json:"attempts"` // 单号重试次数
}
// AppPaths 运行时路径。