Files
yml2213 5da35ab65e 抢购后自动核对积分余额(基线在导入账号时获取),发布0.3.5
兑换成功会扣积分,所以"余额确实少了多少"是一个独立于接口返回的确认证据——
2026-09-30 出现过订单实际已支付、程序却报成失败的情况,只看接口返回不够。

基线的获取时机刻意放在抢购链路之外:轮次/预热期间任何额外请求都会挤占锁单,
账号越多越明显。基线只在三个时机更新:
- 导入账号后自动查一次(后台执行,不阻塞导入返回)
- 用户手动点"查询积分"时
- 每次抢购核对之后把最新余额存回,下一次抢购的基线就是上一次的终值,差值才准
账号被编辑(改名/换 Cookie)时清掉旧基线,删除账号时一并清理。

- 新增 ScoreBaselineStore(scores.json,与账号库同目录,原子写盘):
  记录每个账号上次已知的积分余额与时间;账号库路径为空时退化为纯内存,不写工作目录
- 核对输出示例:
  "积分已扣减,兑换确认: 账号=a 抢购前=1000 抢购后=800 扣减=200"
  并把"|积分-200"附到结果集,账号表里也能直接看到确认信息
- 没有基线时只记录余额并提示"下次抢购即可比对",不会误报"未扣分";
  积分接口失败只记警告,不改变"抢到"这个结论
- 抢购进行中调用导入不会去查询积分(避免与锁单抢连接),提示稍后手动查询
- 预热日志措辞修正:"开始预热: N 个请求" → "N 个账号"(每账号实际不止一个请求)
- 新增测试:TestVerifyRunResultsConfirmsScoreDeduction、TestVerifyRunResultsWithoutBaseline、
  TestVerifyRunResultsIgnoresScoreFailure、TestScoreBaselineStorePersists、
  TestFetchScoreBaselinesRecordsValues
2026-10-03 19:57:13 +08:00

250 lines
8.2 KiB
Go

package app
import (
"fmt"
"strings"
"douyu_go/internal/logger"
"douyu_go/internal/types"
)
// ImportAccounts 将剪贴板中的账号行追加到内部账号库。每行格式必须为
// 账号名----密码----Cookie,账号名不能与已有账号重复。
func (a *App) ImportAccounts(content string) types.AccountMutationResult {
entries, err := parseAccountImport(content)
if err != nil {
return types.AccountMutationResult{Error: err.Error()}
}
a.accountsMu.Lock()
defer a.accountsMu.Unlock()
accountFile := a.scheduler.AccountFilePath()
lines, err := parseAccountFile(accountFile)
if err != nil {
return types.AccountMutationResult{Error: "读取内部账号库失败: " + err.Error()}
}
existingNames := make(map[string]struct{}, len(lines))
for _, line := range lines {
if line.Name != "" {
existingNames[line.Name] = struct{}{}
}
}
for _, entry := range entries {
if _, exists := existingNames[entry.Name]; exists {
return types.AccountMutationResult{Error: fmt.Sprintf("账号 %q 已存在", entry.Name)}
}
existingNames[entry.Name] = struct{}{}
lines = append(lines, entry)
}
if err := a.saveAccountLines(accountFile, lines); err != nil {
return types.AccountMutationResult{Error: err.Error()}
}
logger.LogEvent("账号", "success", "已从剪贴板导入 %d 个账号", len(entries))
// 导入完顺手记一次积分余额作为基线。刻意放在这里而不是预热/抢购链路里:
// 账号多的时候,抢购期的任何额外请求都会挤占锁单。后台执行,不阻塞导入返回。
a.fetchScoreBaselinesAsync(scoreAccountsFromLines(entries), "导入账号")
return types.AccountMutationResult{Success: true, Count: len(entries)}
}
// UpdateAccount 更新账号名或 Cookie。newCookie 留空时保留内部账号库中的原 Cookie。
func (a *App) UpdateAccount(originalName, newName, newCookie string) types.AccountMutationResult {
originalName = strings.TrimSpace(originalName)
newName = strings.TrimSpace(newName)
newCookie = strings.TrimSpace(newCookie)
if originalName == "" || newName == "" {
return types.AccountMutationResult{Error: "账号名不能为空"}
}
if invalidAccountField(newName) || strings.ContainsAny(newCookie, "\r\n") {
return types.AccountMutationResult{Error: "账号名或 Cookie 包含无效字符"}
}
a.accountsMu.Lock()
defer a.accountsMu.Unlock()
accountFile := a.scheduler.AccountFilePath()
lines, err := parseAccountFile(accountFile)
if err != nil {
return types.AccountMutationResult{Error: "读取内部账号库失败: " + err.Error()}
}
targetIndex := -1
nameCount := 0
for i, line := range lines {
if line.Name == originalName {
targetIndex = i
nameCount++
}
if line.Name == newName && newName != originalName {
return types.AccountMutationResult{Error: fmt.Sprintf("账号 %q 已存在", newName)}
}
}
if targetIndex < 0 {
return types.AccountMutationResult{Error: "未找到要编辑的账号"}
}
if nameCount > 1 {
return types.AccountMutationResult{Error: "账号名重复,请先删除重复账号后再编辑"}
}
parts := strings.SplitN(strings.TrimSpace(lines[targetIndex].Raw), "----", 3)
if len(parts) != 3 {
return types.AccountMutationResult{Error: "原账号格式不正确,无法保留密码段"}
}
oldCookie := strings.TrimSpace(parts[2])
if newCookie == "" {
newCookie = oldCookie
}
if newCookie == "" {
return types.AccountMutationResult{Error: "Cookie 不能为空"}
}
lines[targetIndex] = accountLine{
Raw: newName + "----" + strings.TrimSpace(parts[1]) + "----" + newCookie,
Name: newName,
}
if err := a.saveAccountLines(accountFile, lines); err != nil {
return types.AccountMutationResult{Error: err.Error()}
}
logger.LogEvent("账号", "success", "账号已更新: %s", newName)
// 改过名或换过 Cookie,旧基线都不再适用:改名先删旧键,再按新 Cookie 取一次。
if newName != originalName {
a.scheduler.ForgetScoreBaselines([]string{originalName})
}
a.fetchScoreBaselinesAsync([]types.Account{{Name: newName, Cookie: newCookie}}, "更新账号")
return types.AccountMutationResult{Success: true, Count: 1}
}
// DeleteAccounts 从内部账号库中删除指定账号,可一次删除多个账号。
func (a *App) DeleteAccounts(accountNames []string) types.AccountMutationResult {
nameSet := make(map[string]struct{}, len(accountNames))
for _, name := range accountNames {
if trimmed := strings.TrimSpace(name); trimmed != "" {
nameSet[trimmed] = struct{}{}
}
}
if len(nameSet) == 0 {
return types.AccountMutationResult{Error: "请选择要删除的账号"}
}
a.accountsMu.Lock()
defer a.accountsMu.Unlock()
accountFile := a.scheduler.AccountFilePath()
lines, err := parseAccountFile(accountFile)
if err != nil {
return types.AccountMutationResult{Error: "读取内部账号库失败: " + err.Error()}
}
kept := make([]accountLine, 0, len(lines))
deleted := 0
for _, line := range lines {
if _, remove := nameSet[line.Name]; remove && !line.Comment {
deleted++
continue
}
kept = append(kept, line)
}
if deleted == 0 {
return types.AccountMutationResult{Error: "未找到要删除的账号"}
}
if err := a.saveAccountLines(accountFile, kept); err != nil {
return types.AccountMutationResult{Error: err.Error()}
}
deletedNames := make([]string, 0, deleted)
for name := range nameSet {
deletedNames = append(deletedNames, name)
}
a.scheduler.ForgetScoreBaselines(deletedNames)
logger.LogEvent("账号", "success", "已删除 %d 个账号", deleted)
return types.AccountMutationResult{Success: true, Count: deleted}
}
func parseAccountImport(content string) ([]accountLine, error) {
content = strings.ReplaceAll(content, "\r\n", "\n")
content = strings.ReplaceAll(content, "\r", "\n")
entries := make([]accountLine, 0)
names := make(map[string]struct{})
for index, raw := range strings.Split(content, "\n") {
trimmed := strings.TrimSpace(raw)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue
}
parts := strings.SplitN(trimmed, "----", 3)
if len(parts) != 3 {
return nil, fmt.Errorf("第 %d 行格式不正确,应为 账号名----密码----Cookie", index+1)
}
name := strings.TrimSpace(parts[0])
password := strings.TrimSpace(parts[1])
cookie := strings.TrimSpace(parts[2])
if name == "" || cookie == "" || invalidAccountField(name) || strings.ContainsAny(cookie, "\r\n") {
return nil, fmt.Errorf("第 %d 行账号名或 Cookie 无效", index+1)
}
if _, exists := names[name]; exists {
return nil, fmt.Errorf("剪贴板中账号 %q 重复", name)
}
names[name] = struct{}{}
entries = append(entries, accountLine{Raw: name + "----" + password + "----" + cookie, Name: name})
}
if len(entries) == 0 {
return nil, fmt.Errorf("未识别到可导入的账号")
}
return entries, nil
}
func invalidAccountField(value string) bool {
return strings.ContainsAny(value, "\r\n") || strings.Contains(value, "----")
}
func (a *App) saveAccountLines(accountFile string, lines []accountLine) error {
rawLines := make([]string, 0, len(lines))
for _, line := range lines {
rawLines = append(rawLines, line.Raw)
}
content := strings.Join(rawLines, "\r\n")
if content != "" {
content += "\r\n"
}
if _, err := writeFileWithBackup(accountFile, []byte(content)); err != nil {
return fmt.Errorf("更新内部账号库失败: %w", err)
}
a.scheduler.LoadAccounts()
return nil
}
// scoreAccountsFromLines 从账号行里取出"账号名 + Cookie",用于积分基线查询。
func scoreAccountsFromLines(lines []accountLine) []types.Account {
out := make([]types.Account, 0, len(lines))
for _, line := range lines {
if line.Comment || line.Name == "" {
continue
}
parts := strings.SplitN(strings.TrimSpace(line.Raw), "----", 3)
if len(parts) != 3 {
continue
}
cookie := strings.TrimSpace(parts[2])
if cookie == "" {
continue
}
out = append(out, types.Account{Name: line.Name, Cookie: cookie})
}
return out
}
// fetchScoreBaselinesAsync 后台查询积分基线,不阻塞调用方。
func (a *App) fetchScoreBaselinesAsync(accounts []types.Account, label string) {
if len(accounts) == 0 {
return
}
go func() {
defer func() {
if r := recover(); r != nil {
logger.LogEvent("账号", "warn", "%s后查询积分基线异常: %v", label, r)
}
}()
a.scheduler.FetchScoreBaselines(accounts)
}()
}