重构: 账号管理抽离、强类型返回、消除反射、删除死字段

- 抽离账号管理为独立 AccountStore,Scheduler 只持有引用,
  职责单一化(scheduler.go 减少 ~110 行)
- Wails 绑定方法返回结构体替代 map[string]any(新增 responses.go),
  前端获得强类型,字段名保持兼容无需改前端
- ExchangeRecord 移至 types 包,消除 types↔client 循环依赖
- extractAPIStatus 用 apiResponder 接口替代 reflect 逐字段查找,
  types.APIResponse 与 ExchangeListResponse 实现 APIStatus 方法
- 删除 types.Account.Password 死字段(鉴权仅用 Cookie)
- 重新生成 Wails 绑定,前端 vue-tsc 类型检查通过
This commit is contained in:
yml2213
2026-07-29 12:47:01 +08:00
parent 3ae9cb4a42
commit 7c2c5a61a6
7 changed files with 450 additions and 287 deletions
+89 -107
View File
@@ -90,7 +90,7 @@ func cloneConfig(c types.Config) types.Config {
type exchangeLookupResult struct {
Account types.Account
Records []client.ExchangeRecord
Records []types.ExchangeRecord
Err error
EmptyCookie bool
}
@@ -191,32 +191,32 @@ func (a *App) GetAccounts() []types.AccountView {
}
// ReloadAccounts 重新加载账号文件。
func (a *App) ReloadAccounts() map[string]any {
func (a *App) ReloadAccounts() types.ReloadAccountsResult {
a.scheduler.LoadAccounts()
return map[string]any{"success": true, "count": a.scheduler.AccountCount()}
return types.ReloadAccountsResult{Success: true, Count: a.scheduler.AccountCount()}
}
// StartSeckill 立即启动抢购。
func (a *App) StartSeckill(accountProducts map[string]string) map[string]any {
func (a *App) StartSeckill(accountProducts map[string]string) types.MessageResult {
if len(accountProducts) == 0 {
return map[string]any{"success": false, "error": "请选择账号和商品"}
return types.MessageResult{Error: "请选择账号和商品"}
}
if !a.scheduler.TryStartRun() {
return map[string]any{"success": false, "error": "抢购任务正在运行,请勿重复提交"}
return types.MessageResult{Error: "抢购任务正在运行,请勿重复提交"}
}
go a.scheduler.RunNow(utils.CloneStringMap(accountProducts))
return map[string]any{"success": true, "msg": "抢购已启动"}
return types.MessageResult{Success: true, Msg: "抢购已启动"}
}
// SetSchedule 设置定时抢购。
func (a *App) SetSchedule(req types.SeckillRequest) (map[string]any, error) {
func (a *App) SetSchedule(req types.SeckillRequest) (types.ScheduleResult, error) {
return a.scheduler.ScheduleRun(req)
}
// CancelSchedule 取消未触发的定时抢购。
func (a *App) CancelSchedule() map[string]any {
func (a *App) CancelSchedule() types.CancelScheduleResult {
stopped := a.scheduler.CancelSchedule()
return map[string]any{"success": true, "stopped": stopped}
return types.CancelScheduleResult{Success: true, Stopped: stopped}
}
// GetResults 返回当前抢购结果。
@@ -225,118 +225,112 @@ func (a *App) GetResults() map[string]string {
}
// GetLogs 返回后端内存日志,支持增量获取。
func (a *App) GetLogs(since int64) map[string]any {
func (a *App) GetLogs(since int64) types.LogsResult {
entries := a.logStore.Since(since)
nextSince := since
if len(entries) > 0 {
nextSince = entries[len(entries)-1].ID
}
return map[string]any{
"success": true,
"logs": entries,
"since": nextSince,
"file": a.logStore.FilePath(),
return types.LogsResult{
Success: true,
Logs: entries,
Since: nextSince,
File: a.logStore.FilePath(),
}
}
// GetTime 返回服务端时间和本地时间。
func (a *App) GetTime() map[string]any {
func (a *App) GetTime() types.TimeResult {
serverTime, err := a.getClient().ServerTime()
source := "currentTime"
if err != nil {
source = "localFallback"
logger.LogEvent("时间", "warn", "时间接口降级: %v", err)
}
return map[string]any{
"serverTime": serverTime.In(constants.CST).Format("2006-01-02 15:04:05.000"),
"localTime": time.Now().In(constants.CST).Format("2006-01-02 15:04:05.000"),
"source": source,
return types.TimeResult{
ServerTime: serverTime.In(constants.CST).Format("2006-01-02 15:04:05.000"),
LocalTime: time.Now().In(constants.CST).Format("2006-01-02 15:04:05.000"),
Source: source,
}
}
// ClearResults 清空抢购结果。
func (a *App) ClearResults() map[string]any {
func (a *App) ClearResults() types.SimpleResult {
a.scheduler.ClearResults()
return map[string]any{"success": true}
return types.SimpleResult{Success: true}
}
// QueryScore 查询单个账号的积分。
func (a *App) QueryScore(accountName string) map[string]any {
func (a *App) QueryScore(accountName string) types.ScoreResult {
if accountName == "" {
return map[string]any{"score": "缺少账号名"}
return types.ScoreResult{Score: "缺少账号名"}
}
cookie, ok := a.scheduler.AccountCookieByName(accountName)
if !ok || cookie == "" {
return map[string]any{"score": fmt.Sprintf("账号不存在或 Cookie 为空: %s", accountName)}
return types.ScoreResult{Score: fmt.Sprintf("账号不存在或 Cookie 为空: %s", accountName)}
}
score, err := a.getClient().Score(cookie)
if err != nil {
return map[string]any{"score": "查询失败: " + err.Error()}
return types.ScoreResult{Score: "查询失败: " + err.Error()}
}
return map[string]any{"score": score}
return types.ScoreResult{Score: strconv.Itoa(score)}
}
// VerifyExchange 查询兑换记录,用于复验抢购结果。
func (a *App) VerifyExchange(accountName string) map[string]any {
func (a *App) VerifyExchange(accountName string) types.ExchangeRecordsResult {
if accountName == "" {
return map[string]any{"success": false, "error": "缺少账号名"}
return types.ExchangeRecordsResult{Error: "缺少账号名"}
}
cookie, ok := a.scheduler.AccountCookieByName(accountName)
if !ok || cookie == "" {
return map[string]any{"success": false, "error": fmt.Sprintf("账号不存在或 Cookie 为空: %s", accountName)}
return types.ExchangeRecordsResult{Error: fmt.Sprintf("账号不存在或 Cookie 为空: %s", accountName)}
}
records, err := a.getClient().ExchangeList(cookie)
if err != nil {
return map[string]any{"success": false, "error": "查询失败: " + err.Error()}
return types.ExchangeRecordsResult{Error: "查询失败: " + err.Error()}
}
matched := filterExchangeRecords(records)
return map[string]any{
"success": true,
"records": matched,
"count": len(matched),
return types.ExchangeRecordsResult{
Success: true,
Records: matched,
Count: len(matched),
}
}
// VerifyAllExchange 批量查询兑换记录,使用有限并发减少等待时间。
func (a *App) VerifyAllExchange() map[string]any {
func (a *App) VerifyAllExchange() types.VerifyAllExchangeResult {
accounts := a.scheduler.AccountSnapshot()
results := make(map[string]any)
results := make(map[string]types.AccountExchangeResult)
lookups := a.lookupExchangeRecords("复验", accounts)
for _, lookup := range lookups {
if lookup.EmptyCookie {
results[lookup.Account.Name] = map[string]any{
"success": false,
"error": "Cookie 为空",
}
results[lookup.Account.Name] = types.AccountExchangeResult{Error: "Cookie 为空"}
continue
}
if lookup.Err != nil {
results[lookup.Account.Name] = map[string]any{
"success": false,
"error": "查询失败: " + lookup.Err.Error(),
}
results[lookup.Account.Name] = types.AccountExchangeResult{Error: "查询失败: " + lookup.Err.Error()}
continue
}
matched := filterExchangeRecords(lookup.Records)
results[lookup.Account.Name] = map[string]any{
"success": true,
"records": matched,
"count": len(matched),
results[lookup.Account.Name] = types.AccountExchangeResult{
Success: true,
Records: matched,
Count: len(matched),
}
}
return results
return types.VerifyAllExchangeResult{Results: results}
}
// VerifyAndExport 复验并导出结果。
func (a *App) VerifyAndExport(commodityID string) map[string]any {
func (a *App) VerifyAndExport(commodityID string) types.VerifyAndExportResult {
accounts := a.scheduler.AccountSnapshot()
results := make(map[string]any)
results := make(map[string]types.AccountHitResult)
hitAccounts := make([]string, 0)
missAccounts := make([]string, 0)
lookups := a.lookupExchangeRecords("复验", accounts)
@@ -344,19 +338,13 @@ func (a *App) VerifyAndExport(commodityID string) map[string]any {
for _, lookup := range lookups {
if lookup.EmptyCookie {
missAccounts = append(missAccounts, lookup.Account.Name)
results[lookup.Account.Name] = map[string]any{
"success": false,
"error": "Cookie 为空",
}
results[lookup.Account.Name] = types.AccountHitResult{Error: "Cookie 为空"}
continue
}
if lookup.Err != nil {
missAccounts = append(missAccounts, lookup.Account.Name)
results[lookup.Account.Name] = map[string]any{
"success": false,
"error": "查询失败: " + lookup.Err.Error(),
}
results[lookup.Account.Name] = types.AccountHitResult{Error: "查询失败: " + lookup.Err.Error()}
continue
}
@@ -364,26 +352,20 @@ func (a *App) VerifyAndExport(commodityID string) map[string]any {
hit := hasCommodityRecord(lookup.Records, commodityID, 0, 0)
if hit {
hitAccounts = append(hitAccounts, lookup.Account.Name)
results[lookup.Account.Name] = map[string]any{
"success": true,
"hit": true,
}
results[lookup.Account.Name] = types.AccountHitResult{Success: true, Hit: true}
} else {
missAccounts = append(missAccounts, lookup.Account.Name)
results[lookup.Account.Name] = map[string]any{
"success": true,
"hit": false,
}
results[lookup.Account.Name] = types.AccountHitResult{Success: true}
}
}
return map[string]any{
"success": true,
"hitCount": len(hitAccounts),
"missCount": len(missAccounts),
"hitAccounts": hitAccounts,
"missAccounts": missAccounts,
"details": results,
return types.VerifyAndExportResult{
Success: true,
HitCount: len(hitAccounts),
MissCount: len(missAccounts),
HitAccounts: hitAccounts,
MissAccounts: missAccounts,
Details: results,
}
}
@@ -446,8 +428,8 @@ func (a *App) lookupExchangeRecords(category string, accounts []types.Account) [
return results
}
func filterExchangeRecords(records []client.ExchangeRecord) []client.ExchangeRecord {
matched := make([]client.ExchangeRecord, 0, len(records))
func filterExchangeRecords(records []types.ExchangeRecord) []types.ExchangeRecord {
matched := make([]types.ExchangeRecord, 0, len(records))
for _, r := range records {
if r.CommodityID != "" {
matched = append(matched, r)
@@ -456,7 +438,7 @@ func filterExchangeRecords(records []client.ExchangeRecord) []client.ExchangeRec
return matched
}
func hasCommodityRecord(records []client.ExchangeRecord, commodityID string, startTime, endTime int64) bool {
func hasCommodityRecord(records []types.ExchangeRecord, commodityID string, startTime, endTime int64) bool {
if commodityID == "" {
return false
}
@@ -514,15 +496,15 @@ func parseAccountFile(path string) ([]accountLine, error) {
}
// ExportAccounts 导出指定账号到文件。
func (a *App) ExportAccounts(accountNames []string, filename string) map[string]any {
func (a *App) ExportAccounts(accountNames []string, filename string) types.ExportAccountsResult {
if len(accountNames) == 0 {
return map[string]any{"success": false, "error": "没有要导出的账号"}
return types.ExportAccountsResult{Error: "没有要导出的账号"}
}
accountFile := a.scheduler.AccountFilePath()
lines, err := parseAccountFile(accountFile)
if err != nil {
return map[string]any{"success": false, "error": "读取账号文件失败: " + err.Error()}
return types.ExportAccountsResult{Error: "读取账号文件失败: " + err.Error()}
}
nameSet := make(map[string]bool)
@@ -541,7 +523,7 @@ func (a *App) ExportAccounts(accountNames []string, filename string) map[string]
}
if len(matchedLines) == 0 {
return map[string]any{"success": false, "error": "没有找到匹配的账号行"}
return types.ExportAccountsResult{Error: "没有找到匹配的账号行"}
}
// 生成导出文件路径
@@ -549,20 +531,20 @@ func (a *App) ExportAccounts(accountNames []string, filename string) map[string]
content := strings.Join(matchedLines, "\n") + "\n"
if err := os.WriteFile(exportPath, []byte(content), 0644); err != nil {
return map[string]any{"success": false, "error": "写入文件失败: " + err.Error()}
return types.ExportAccountsResult{Error: "写入文件失败: " + err.Error()}
}
logger.LogEvent("导出", "success", "已导出 %d 个账号到: %s", len(matchedLines), exportPath)
return map[string]any{
"success": true,
"count": len(matchedLines),
"filePath": exportPath,
return types.ExportAccountsResult{
Success: true,
Count: len(matchedLines),
FilePath: exportPath,
}
}
// ExportAccountsWithProduct 导出指定账号到文件,自动使用中文商品名和时间戳命名。
func (a *App) ExportAccountsWithProduct(accountNames []string, commodityID, commodityName string) map[string]any {
func (a *App) ExportAccountsWithProduct(accountNames []string, commodityID, commodityName string) types.ExportAccountsResult {
// 生成文件名: user_已抢到_商品中文名_20260626_150405.txt
now := time.Now()
timestamp := now.Format("20060102_150405")
@@ -574,7 +556,7 @@ func (a *App) ExportAccountsWithProduct(accountNames []string, commodityID, comm
}
// OrganizeAccounts 整理账号,把已抢到指定商品的账号分离出来。
func (a *App) OrganizeAccounts(commodityID, commodityName string, startTime, endTime int64) map[string]any {
func (a *App) OrganizeAccounts(commodityID, commodityName string, startTime, endTime int64) types.OrganizeAccountsResult {
accounts := a.scheduler.AccountSnapshot()
hitAccounts := make([]string, 0)
missAccounts := make([]string, 0)
@@ -594,7 +576,7 @@ func (a *App) OrganizeAccounts(commodityID, commodityName string, startTime, end
}
// 导出已抢到的账号
var exportResult map[string]any
var exportResult types.ExportAccountsResult
if len(hitAccounts) > 0 {
exportResult = a.ExportAccountsWithProduct(hitAccounts, commodityID, commodityName)
}
@@ -603,7 +585,7 @@ func (a *App) OrganizeAccounts(commodityID, commodityName string, startTime, end
accountFile := a.scheduler.AccountFilePath()
lines, err := parseAccountFile(accountFile)
if err != nil {
return map[string]any{"success": false, "error": "读取账号文件失败: " + err.Error()}
return types.OrganizeAccountsResult{Error: "读取账号文件失败: " + err.Error()}
}
missSet := make(map[string]bool)
@@ -625,7 +607,7 @@ func (a *App) OrganizeAccounts(commodityID, commodityName string, startTime, end
// 写回原文件
newContent := strings.Join(keepLines, "\n") + "\n"
if err := os.WriteFile(accountFile, []byte(newContent), 0644); err != nil {
return map[string]any{"success": false, "error": "更新账号文件失败: " + err.Error()}
return types.OrganizeAccountsResult{Error: "更新账号文件失败: " + err.Error()}
}
// 重新加载账号
@@ -633,13 +615,13 @@ func (a *App) OrganizeAccounts(commodityID, commodityName string, startTime, end
logger.LogEvent("整理", "success", "整理完成: 已抢到=%d, 未抢到=%d", len(hitAccounts), len(missAccounts))
return map[string]any{
"success": true,
"hitCount": len(hitAccounts),
"missCount": len(missAccounts),
"hitAccounts": hitAccounts,
"missAccounts": missAccounts,
"exportResult": exportResult,
return types.OrganizeAccountsResult{
Success: true,
HitCount: len(hitAccounts),
MissCount: len(missAccounts),
HitAccounts: hitAccounts,
MissAccounts: missAccounts,
ExportResult: exportResult,
}
}
@@ -669,10 +651,10 @@ func (a *App) GetCurrentActivity() types.ActivityInfo {
}
// SwitchActivity 切换当前活动并持久化到配置;切换后重建客户端与时间基准。
func (a *App) SwitchActivity(id string) map[string]any {
func (a *App) SwitchActivity(id string) types.SwitchActivityResult {
act := activity.Get(id)
if act == nil {
return map[string]any{"success": false, "error": "未知活动: " + id}
return types.SwitchActivityResult{Error: "未知活动: " + id}
}
cfg := a.getCfg()
cfg.Activity = act.ID
@@ -682,7 +664,7 @@ func (a *App) SwitchActivity(id string) map[string]any {
}
if err := config.SaveConfig(a.paths.ConfigFile, cfg); err != nil {
logger.LogEvent("活动", "error", "切换活动配置保存失败: %v", err)
return map[string]any{"success": false, "error": "配置保存失败: " + err.Error()}
return types.SwitchActivityResult{Error: "配置保存失败: " + err.Error()}
}
a.setCfg(cfg)
newClient := client.New(act, cfg.TimeAPIURL, a.trace)
@@ -694,7 +676,7 @@ func (a *App) SwitchActivity(id string) map[string]any {
logger.SetDouyuOffset(sample.Offset)
}
logger.LogEvent("活动", "success", "已切换到活动: %s", act.DisplayName)
return map[string]any{"success": true, "activity": act.ID, "displayName": act.DisplayName}
return types.SwitchActivityResult{Success: true, Activity: act.ID, DisplayName: act.DisplayName}
}
// GetSettings 返回当前配置。
@@ -703,7 +685,7 @@ func (a *App) GetSettings() types.Config {
}
// SaveSettings 保存配置并运行时生效。
func (a *App) SaveSettings(cfg types.Config) map[string]any {
func (a *App) SaveSettings(cfg types.Config) types.SimpleResult {
// 校验
if cfg.Concurrency <= 0 {
cfg.Concurrency = constants.DefaultConcurrency
@@ -718,7 +700,7 @@ func (a *App) SaveSettings(cfg types.Config) map[string]any {
// 写入文件
if err := config.SaveConfig(a.paths.ConfigFile, cfg); err != nil {
logger.LogEvent("配置", "error", "配置保存失败: %v", err)
return map[string]any{"success": false, "error": err.Error()}
return types.SimpleResult{}
}
// 运行时生效
@@ -728,7 +710,7 @@ func (a *App) SaveSettings(cfg types.Config) map[string]any {
logger.LogEvent("配置", "success", "配置已保存并生效: 日志等级=%s 并发=%d 重试=%d 重试阶段=%d 模式=%d trace=%v",
cfg.LogLevel, cfg.Concurrency, cfg.Attempts, len(cfg.RetryStages), cfg.SeckillMode, cfg.TraceEnabled)
return map[string]any{"success": true}
return types.SimpleResult{Success: true}
}
// ==================== 内部辅助方法 ====================