重构: 活动热切换并发安全 + 代码清理优化

- 活动切换并发安全:App/Scheduler 增加 client/cfg 读写锁与快照访问,
  支持运行中热替换客户端,切换活动不再静默覆盖用户自定义 timeApiUrl
- 启动失败时写入崩溃日志文件便于事后排查
- 前端类型声明从 Wails 自动生成的绑定派生,避免手写契约漂移
- 提取 parseAccountFile 消除 ExportAccounts/OrganizeAccounts 重复解析逻辑
- 删除 utils 中未使用的 ReadJSON/WriteJSON/WriteError 及空目录 internal/app
- gofmt 统一格式化(activity/types/scheduler 字段对齐)
- 新增 logger/seckill/utils 单元测试
- 清理 git 中遗留产物(frontend/app.js、yml.txt、其他日志/)并补全 .gitignore
This commit is contained in:
yml2213
2026-07-29 12:33:16 +08:00
parent ed3fd5f09e
commit 3ae9cb4a42
20 changed files with 574 additions and 20390 deletions
+8 -2
View File
@@ -5,17 +5,24 @@ logs/
success_images/ success_images/
build/ build/
config.json config.json
frontend/dist frontend/dist/
frontend/node_modules frontend/node_modules
# Wails 自动生成的前端绑定 # Wails 自动生成的前端绑定
frontend/wailsjs/ frontend/wailsjs/
# 遗留构建产物
frontend/app.js
# 本地账号、Cookie 与抓包资料 # 本地账号、Cookie 与抓包资料
data/user.txt data/user.txt
ck 对比.md ck 对比.md
软软马卡龙.txt 软软马卡龙.txt
# 本地笔记与运行日志
yml.txt
其他日志/
# 本地字体文件 # 本地字体文件
*.ttf *.ttf
@@ -23,5 +30,4 @@ ck 对比.md
*.exe *.exe
*.app *.app
.DS_Store .DS_Store
frontend/dist/
.workbuddy .workbuddy
+112 -116
View File
@@ -22,19 +22,23 @@ import (
"douyu_go/internal/seckill" "douyu_go/internal/seckill"
"douyu_go/internal/trace" "douyu_go/internal/trace"
"douyu_go/internal/types" "douyu_go/internal/types"
"douyu_go/internal/utils"
) )
// App 应用主结构体,所有导出方法可被前端通过 Wails 绑定调用。 // App 应用主结构体,所有导出方法可被前端通过 Wails 绑定调用。
type App struct { type App struct {
ctx context.Context ctx context.Context
clientMu sync.RWMutex
client *client.DouyuClient client *client.DouyuClient
scheduler *seckill.Scheduler scheduler *seckill.Scheduler
logStore *logger.MemoryLogStore logStore *logger.MemoryLogStore
trace *trace.Recorder trace *trace.Recorder
paths types.AppPaths paths types.AppPaths
font *truetype.Font font *truetype.Font
cfg types.Config
cfgMu sync.RWMutex
cfg types.Config
productsMu sync.RWMutex productsMu sync.RWMutex
products []types.Product products []types.Product
@@ -46,6 +50,44 @@ type App struct {
const exchangeLookupConcurrency = 8 const exchangeLookupConcurrency = 8
// getClient 返回当前 client 指针快照(读锁保护)。
func (a *App) getClient() *client.DouyuClient {
a.clientMu.RLock()
defer a.clientMu.RUnlock()
return a.client
}
// getCfg 返回当前配置的深拷贝(读锁保护)。
func (a *App) getCfg() types.Config {
a.cfgMu.RLock()
defer a.cfgMu.RUnlock()
return cloneConfig(a.cfg)
}
// setClient 替换 client(写锁保护)。
func (a *App) setClient(c *client.DouyuClient) {
a.clientMu.Lock()
a.client = c
a.clientMu.Unlock()
}
// setCfg 替换配置(写锁保护)。
func (a *App) setCfg(c types.Config) {
a.cfgMu.Lock()
a.cfg = c
a.cfgMu.Unlock()
}
// cloneConfig 深拷贝配置,避免 RetryStages 切片共享引用。
func cloneConfig(c types.Config) types.Config {
cp := c
if c.RetryStages != nil {
cp.RetryStages = make([]types.RetryStage, len(c.RetryStages))
copy(cp.RetryStages, c.RetryStages)
}
return cp
}
type exchangeLookupResult struct { type exchangeLookupResult struct {
Account types.Account Account types.Account
Records []client.ExchangeRecord Records []client.ExchangeRecord
@@ -121,7 +163,7 @@ func (a *App) shutdown(ctx context.Context) {
// LoadProducts 刷新商品列表。refresh=true 时从斗鱼实时拉取。 // LoadProducts 刷新商品列表。refresh=true 时从斗鱼实时拉取。
func (a *App) LoadProducts(refresh bool) types.ProductPayload { func (a *App) LoadProducts(refresh bool) types.ProductPayload {
if refresh { if refresh {
products, err := a.client.Products() products, err := a.getClient().Products()
if err != nil { if err != nil {
logger.LogEvent("商品", "error", "商品刷新失败: %v", err) logger.LogEvent("商品", "error", "商品刷新失败: %v", err)
return types.ProductPayload{Success: false} return types.ProductPayload{Success: false}
@@ -142,7 +184,7 @@ func (a *App) GetAccounts() []types.AccountView {
list = append(list, types.AccountView{ list = append(list, types.AccountView{
Index: i, Index: i,
Name: account.Name, Name: account.Name,
Cookie: maskCookie(account.Cookie), Cookie: utils.MaskCookie(account.Cookie),
}) })
} }
return list return list
@@ -162,7 +204,7 @@ func (a *App) StartSeckill(accountProducts map[string]string) map[string]any {
if !a.scheduler.TryStartRun() { if !a.scheduler.TryStartRun() {
return map[string]any{"success": false, "error": "抢购任务正在运行,请勿重复提交"} return map[string]any{"success": false, "error": "抢购任务正在运行,请勿重复提交"}
} }
go a.scheduler.RunNow(cloneMap(accountProducts)) go a.scheduler.RunNow(utils.CloneStringMap(accountProducts))
return map[string]any{"success": true, "msg": "抢购已启动"} return map[string]any{"success": true, "msg": "抢购已启动"}
} }
@@ -199,7 +241,7 @@ func (a *App) GetLogs(since int64) map[string]any {
// GetTime 返回服务端时间和本地时间。 // GetTime 返回服务端时间和本地时间。
func (a *App) GetTime() map[string]any { func (a *App) GetTime() map[string]any {
serverTime, err := a.client.ServerTime() serverTime, err := a.getClient().ServerTime()
source := "currentTime" source := "currentTime"
if err != nil { if err != nil {
source = "localFallback" source = "localFallback"
@@ -227,7 +269,7 @@ func (a *App) QueryScore(accountName string) map[string]any {
if !ok || cookie == "" { if !ok || cookie == "" {
return map[string]any{"score": fmt.Sprintf("账号不存在或 Cookie 为空: %s", accountName)} return map[string]any{"score": fmt.Sprintf("账号不存在或 Cookie 为空: %s", accountName)}
} }
score, err := a.client.Score(cookie) score, err := a.getClient().Score(cookie)
if err != nil { if err != nil {
return map[string]any{"score": "查询失败: " + err.Error()} return map[string]any{"score": "查询失败: " + err.Error()}
} }
@@ -244,7 +286,7 @@ func (a *App) VerifyExchange(accountName string) map[string]any {
return map[string]any{"success": false, "error": fmt.Sprintf("账号不存在或 Cookie 为空: %s", accountName)} return map[string]any{"success": false, "error": fmt.Sprintf("账号不存在或 Cookie 为空: %s", accountName)}
} }
records, err := a.client.ExchangeList(cookie) records, err := a.getClient().ExchangeList(cookie)
if err != nil { if err != nil {
return map[string]any{"success": false, "error": "查询失败: " + err.Error()} return map[string]any{"success": false, "error": "查询失败: " + err.Error()}
} }
@@ -372,7 +414,7 @@ func (a *App) lookupExchangeRecords(category string, accounts []types.Account) [
results[idx] = lookup results[idx] = lookup
continue continue
} }
records, err := a.client.ExchangeList(account.Cookie) records, err := a.getClient().ExchangeList(account.Cookie)
lookup.Records = records lookup.Records = records
lookup.Err = err lookup.Err = err
results[idx] = lookup results[idx] = lookup
@@ -440,39 +482,61 @@ func hasCommodityRecord(records []client.ExchangeRecord, commodityID string, sta
return false return false
} }
// accountLine 账号文件的一行解析结果。
type accountLine struct {
Raw string // 原始行文本
Name string // 解析出的账号名(注释/空行为空)
Comment bool // 是否为注释或空行
}
// parseAccountFile 读取账号文件并按行解析账号名。
func parseAccountFile(path string) ([]accountLine, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var lines []accountLine
scanner := bufio.NewScanner(strings.NewReader(string(data)))
for scanner.Scan() {
raw := scanner.Text()
trimmed := strings.TrimSpace(raw)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
lines = append(lines, accountLine{Raw: raw, Comment: true})
continue
}
name := ""
if parts := strings.SplitN(trimmed, "----", 3); len(parts) >= 1 {
name = strings.TrimSpace(parts[0])
}
lines = append(lines, accountLine{Raw: raw, Name: name})
}
return lines, scanner.Err()
}
// ExportAccounts 导出指定账号到文件。 // ExportAccounts 导出指定账号到文件。
func (a *App) ExportAccounts(accountNames []string, filename string) map[string]any { func (a *App) ExportAccounts(accountNames []string, filename string) map[string]any {
if len(accountNames) == 0 { if len(accountNames) == 0 {
return map[string]any{"success": false, "error": "没有要导出的账号"} return map[string]any{"success": false, "error": "没有要导出的账号"}
} }
// 读取原账号文件
accountFile := a.scheduler.AccountFilePath() accountFile := a.scheduler.AccountFilePath()
lines, err := os.ReadFile(accountFile) lines, err := parseAccountFile(accountFile)
if err != nil { if err != nil {
return map[string]any{"success": false, "error": "读取账号文件失败: " + err.Error()} return map[string]any{"success": false, "error": "读取账号文件失败: " + err.Error()}
} }
// 解析账号行
nameSet := make(map[string]bool) nameSet := make(map[string]bool)
for _, name := range accountNames { for _, name := range accountNames {
nameSet[name] = true nameSet[name] = true
} }
var matchedLines []string var matchedLines []string
scanner := bufio.NewScanner(strings.NewReader(string(lines))) for _, line := range lines {
for scanner.Scan() { if line.Comment {
line := scanner.Text()
trimmed := strings.TrimSpace(line)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue continue
} }
parts := strings.SplitN(trimmed, "----", 3) if nameSet[line.Name] {
if len(parts) >= 1 { matchedLines = append(matchedLines, line.Raw)
name := strings.TrimSpace(parts[0])
if nameSet[name] {
matchedLines = append(matchedLines, line)
}
} }
} }
@@ -502,16 +566,8 @@ func (a *App) ExportAccountsWithProduct(accountNames []string, commodityID, comm
// 生成文件名: user_已抢到_商品中文名_20260626_150405.txt // 生成文件名: user_已抢到_商品中文名_20260626_150405.txt
now := time.Now() now := time.Now()
timestamp := now.Format("20060102_150405") timestamp := now.Format("20060102_150405")
// 清理商品名中的特殊字符 // 清理商品名中的特殊字符(复用 utils.SafeFilename,避免与 utils 包重复实现)
safeName := strings.ReplaceAll(commodityName, "/", "_") safeName := utils.SafeFilename(commodityName)
safeName = strings.ReplaceAll(safeName, "\\", "_")
safeName = strings.ReplaceAll(safeName, ":", "_")
safeName = strings.ReplaceAll(safeName, "*", "_")
safeName = strings.ReplaceAll(safeName, "?", "_")
safeName = strings.ReplaceAll(safeName, "\"", "_")
safeName = strings.ReplaceAll(safeName, "<", "_")
safeName = strings.ReplaceAll(safeName, ">", "_")
safeName = strings.ReplaceAll(safeName, "|", "_")
filename := fmt.Sprintf("user_已抢到_%s_%s.txt", safeName, timestamp) filename := fmt.Sprintf("user_已抢到_%s_%s.txt", safeName, timestamp)
return a.ExportAccounts(accountNames, filename) return a.ExportAccounts(accountNames, filename)
@@ -545,7 +601,7 @@ func (a *App) OrganizeAccounts(commodityID, commodityName string, startTime, end
// 更新原文件,只保留未抢到的 // 更新原文件,只保留未抢到的
accountFile := a.scheduler.AccountFilePath() accountFile := a.scheduler.AccountFilePath()
lines, err := os.ReadFile(accountFile) lines, err := parseAccountFile(accountFile)
if err != nil { if err != nil {
return map[string]any{"success": false, "error": "读取账号文件失败: " + err.Error()} return map[string]any{"success": false, "error": "读取账号文件失败: " + err.Error()}
} }
@@ -556,20 +612,13 @@ func (a *App) OrganizeAccounts(commodityID, commodityName string, startTime, end
} }
var keepLines []string var keepLines []string
scanner := bufio.NewScanner(strings.NewReader(string(lines))) for _, line := range lines {
for scanner.Scan() { if line.Comment {
line := scanner.Text() keepLines = append(keepLines, line.Raw)
trimmed := strings.TrimSpace(line)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
keepLines = append(keepLines, line)
continue continue
} }
parts := strings.SplitN(trimmed, "----", 3) if missSet[line.Name] {
if len(parts) >= 1 { keepLines = append(keepLines, line.Raw)
name := strings.TrimSpace(parts[0])
if missSet[name] {
keepLines = append(keepLines, line)
}
} }
} }
@@ -614,7 +663,8 @@ func (a *App) GetActivities() []types.ActivityInfo {
// GetCurrentActivity 返回当前生效的活动。 // GetCurrentActivity 返回当前生效的活动。
func (a *App) GetCurrentActivity() types.ActivityInfo { func (a *App) GetCurrentActivity() types.ActivityInfo {
act := a.client.Activity cli := a.getClient()
act := cli.Activity
return types.ActivityInfo{ID: act.ID, DisplayName: act.DisplayName} return types.ActivityInfo{ID: act.ID, DisplayName: act.DisplayName}
} }
@@ -624,14 +674,23 @@ func (a *App) SwitchActivity(id string) map[string]any {
if act == nil { if act == nil {
return map[string]any{"success": false, "error": "未知活动: " + id} return map[string]any{"success": false, "error": "未知活动: " + id}
} }
a.cfg.Activity = act.ID cfg := a.getCfg()
a.cfg.TimeAPIURL = constants.DefaultTimeAPI cfg.Activity = act.ID
if err := config.SaveConfig(a.paths.ConfigFile, a.cfg); err != nil { // 仅当用户未自定义时间校准接口时才回退默认值,避免切换活动静默覆盖用户在设置里填的 timeApiUrl。
if cfg.TimeAPIURL == "" {
cfg.TimeAPIURL = constants.DefaultTimeAPI
}
if err := config.SaveConfig(a.paths.ConfigFile, cfg); err != nil {
logger.LogEvent("活动", "error", "切换活动配置保存失败: %v", err) logger.LogEvent("活动", "error", "切换活动配置保存失败: %v", err)
return map[string]any{"success": false, "error": "配置保存失败: " + err.Error()} return map[string]any{"success": false, "error": "配置保存失败: " + err.Error()}
} }
a.client = client.New(act, a.cfg.TimeAPIURL, a.trace) a.setCfg(cfg)
if sample, err := a.client.ServerTimeSample(); err == nil { newClient := client.New(act, cfg.TimeAPIURL, a.trace)
a.setClient(newClient)
if !a.scheduler.UpdateClient(newClient) {
logger.LogEvent("活动", "warn", "抢购任务正在运行,调度器客户端将在下次抢购时生效")
}
if sample, err := newClient.ServerTimeSample(); err == nil {
logger.SetDouyuOffset(sample.Offset) logger.SetDouyuOffset(sample.Offset)
} }
logger.LogEvent("活动", "success", "已切换到活动: %s", act.DisplayName) logger.LogEvent("活动", "success", "已切换到活动: %s", act.DisplayName)
@@ -640,7 +699,7 @@ func (a *App) SwitchActivity(id string) map[string]any {
// GetSettings 返回当前配置。 // GetSettings 返回当前配置。
func (a *App) GetSettings() types.Config { func (a *App) GetSettings() types.Config {
return a.cfg return a.getCfg()
} }
// SaveSettings 保存配置并运行时生效。 // SaveSettings 保存配置并运行时生效。
@@ -663,7 +722,7 @@ func (a *App) SaveSettings(cfg types.Config) map[string]any {
} }
// 运行时生效 // 运行时生效
a.cfg = cfg a.setCfg(cfg)
logger.SetMinLevel(cfg.LogLevel) logger.SetMinLevel(cfg.LogLevel)
a.scheduler.UpdateSettings(cfg.Concurrency, cfg.Attempts, cfg.RetryStages, cfg.SeckillMode) a.scheduler.UpdateSettings(cfg.Concurrency, cfg.Attempts, cfg.RetryStages, cfg.SeckillMode)
@@ -707,66 +766,3 @@ func (a *App) productPayload(source string) types.ProductPayload {
} }
return payload return payload
} }
func cloneMap(in map[string]string) map[string]string {
out := make(map[string]string, len(in))
for k, v := range in {
out[k] = v
}
return out
}
func maskCookie(cookie string) string {
pairs := splitCookie(cookie)
masked := make([]string, 0, 3)
total := 0
for _, pair := range pairs {
key, value := splitCookiePair(pair)
if key == "" {
continue
}
total++
if len(masked) >= 3 {
continue
}
masked = append(masked, key+"="+maskValue(value))
}
if total == 0 {
return ""
}
if total > len(masked) {
masked = append(masked, fmt.Sprintf("...共%d项", total))
}
return strings.Join(masked, "; ")
}
func splitCookie(cookie string) []string {
var result []string
for _, part := range strings.Split(cookie, ";") {
trimmed := strings.TrimSpace(part)
if trimmed != "" {
result = append(result, trimmed)
}
}
return result
}
func splitCookiePair(pair string) (string, string) {
idx := strings.Index(pair, "=")
if idx < 0 {
return strings.TrimSpace(pair), ""
}
return strings.TrimSpace(pair[:idx]), pair[idx+1:]
}
func maskValue(value string) string {
value = strings.TrimSpace(value)
if value == "" {
return "****"
}
runes := []rune(value)
if len(runes) <= 8 {
return "****"
}
return string(runes[:4]) + "****" + string(runes[len(runes)-4:])
}
-723
View File
@@ -1,723 +0,0 @@
let accounts=[], products=[], productInfo=null, selProdId=null, selProdName='', selAccs=new Set();
let productSearch='';
let scheduleActive=false, countdownTimer=null, lastResults={};
let lastLogId=0;
let statusMap={}; // ← 加这行
// applyTheme 应用亮色/暗色主题,并把选择保存到本地。
function applyTheme(theme) {
let nextTheme = theme === 'light' ? 'light' : 'dark';
document.body.dataset.theme = nextTheme;
localStorage.setItem('uiTheme', nextTheme);
let btn = document.getElementById('btnTheme');
if (btn) {
btn.textContent = nextTheme === 'light' ? '☀' : '☾';
btn.title = nextTheme === 'light' ? '切换到暗色' : '切换到亮色';
btn.setAttribute('aria-label', btn.title);
}
}
// toggleTheme 在亮色和暗色之间切换。
function toggleTheme() {
applyTheme(document.body.dataset.theme === 'light' ? 'dark' : 'light');
}
// init 初始化页面状态:恢复本地缓存、加载账号和商品、启动时间与结果轮询。
async function init(){
let savedTheme=localStorage.getItem('uiTheme') || (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
applyTheme(savedTheme);
// 恢复缓存的选择
let savedAccs=localStorage.getItem('selAccs');
let savedProd=localStorage.getItem('selProd');
let savedProdName=localStorage.getItem('selProdName');
let savedTime=localStorage.getItem('targetTime');
let savedAdv=localStorage.getItem('advance');
let savedStatus=localStorage.getItem('statusMap'); // ← 提前读取
let savedProductSearch=localStorage.getItem('productSearch');
clearLegacyProductBindings();
if(savedAccs) selAccs=new Set(JSON.parse(savedAccs));
if(savedProd){ selProdId=savedProd; selProdName=savedProdName||''; }
if(savedTime) document.getElementById('targetTime').value=savedTime;
if(savedAdv) document.getElementById('advance').value=savedAdv;
if(savedStatus) statusMap=JSON.parse(savedStatus); // ← 提前恢复
if(savedProductSearch) {
productSearch=savedProductSearch;
document.getElementById('productSearch').value=productSearch;
}
updateSelectedProductCard();
updateDashboardStats();
await loadAccounts();
await loadProducts(false);
updateTime();
clearLog(); // ← 加这行,启动时清空日志区
//localStorage.removeItem('statusMap'); // ← 加这行
// statusMap={}; // ← 加这行 这两行删除就保存成功失败得状态
// 清空后端旧结果
await App.ClearResults();
App.GetVersion().then(v => { document.getElementById('versionTag').textContent = 'v' + v; }).catch(()=>{});
setInterval(updateTime,1000);
setInterval(checkResults,2000);
setInterval(fetchServerLogs,2000);
fetchServerLogs();
}
// setProductSearch 更新商品搜索词,并即时过滤左侧商品列表。
function setProductSearch(value) {
productSearch = String(value || '').trim();
if (productSearch) localStorage.setItem('productSearch', productSearch);
else localStorage.removeItem('productSearch');
renderProducts();
renderProductMeta();
}
// clearProductSearch 清空商品搜索词。
function clearProductSearch() {
productSearch = '';
localStorage.removeItem('productSearch');
document.getElementById('productSearch').value = '';
renderProducts();
renderProductMeta();
}
// filteredProducts 根据搜索词过滤商品,支持名称、ID、积分和库存。
function filteredProducts() {
let keyword = productSearch.toLowerCase();
if (!keyword) return products;
return products.filter(p => [
p.commodityName,
p.commodityId,
p.score,
p.count
].some(v => String(v ?? '').toLowerCase().includes(keyword)));
}
// updateTime 从后端获取斗鱼服务端时间,并刷新顶部时间展示。
function updateTime(){
App.GetTime().then(d=>{
document.getElementById('svrTime').textContent=d.serverTime||'--';
}).catch(()=>{});
}
// apiJSON 统一处理 Wails 绑定调用,失败时抛出后端返回的错误文案。
async function apiJSON(fn) {
let data = await fn();
if (data && data.success === false && data.error) {
throw new Error(data.error);
}
return data;
}
// Wails 绑定快捷引用
const App = window.go.main.App;
// reloadAccounts 通知后端重新读取 user.txt,然后刷新前端账号表格。
async function reloadAccounts(){
let d=await App.ReloadAccounts();
await loadAccounts();
toast('账号已刷新',`共 ${d.count} 个账号`,'success');
}
// queryAllScore 并发查询所有账号积分,并把积分按账号名缓存到 localStorage。
async function queryAllScore() {
addLog('正在并发查询积分...', 'i');
let tasks = [];
for (let i = 0; i < accounts.length; i++) {
tasks.push((async (idx) => {
let a = accounts[idx];
try {
let d = await App.QueryScore(a.name);
let score = (d.score !== undefined && d.score !== null && d.score !== '') ? d.score : 'N/A';
localStorage.setItem('accScore_' + a.name, score);
let el = document.getElementById('score_' + idx);
if (el) el.textContent = score;
} catch (e) { }
})(i));
}
await Promise.all(tasks);
addLog('积分查询完成', 's');
toast('积分查询完成', '', 'success');
}
// ==================== Toast提示 ====================
// toast 创建右侧滑入提示,按类型控制颜色,并在指定时间后自动移除。
function toast(title, body, type, duration){
type=type||'info'; duration=duration||4000;
let container=document.getElementById('toastContainer');
let div=document.createElement('div');
div.className='toast toast-'+type;
div.innerHTML=`<div class="toast-title">${title}</div><div class="toast-body">${body}</div>`;
container.appendChild(div);
// 短延迟回调用于触发 CSS 过渡,让提示从右侧滑入。
setTimeout(()=>container.classList.add('show'),10);
// 外层回调控制停留时长,内层回调等待淡出动画结束后移除节点。
setTimeout(()=>{
div.style.opacity='0';
div.style.transition='opacity .3s';
setTimeout(()=>{div.remove();if(container.children.length===0)container.classList.remove('show');},300);
},duration);
}
// ==================== 商品 ====================
// loadProducts 从后端实时刷新斗鱼商品;失败时不读取旧缓存,避免库存误判。
async function loadProducts(showToast = true){
let btn = document.getElementById('btnLoadProducts');
let meta = document.getElementById('productMeta');
btn.disabled = true;
btn.textContent = '刷新中...';
meta.className = 'product-meta';
meta.textContent = '正在请求斗鱼商品接口';
addLog('正在实时刷新商品...','i');
try{
let d = await App.LoadProducts(true);
products = Array.isArray(d.products) ? d.products : [];
productInfo = d;
if (selProdId && !products.some(p => p.commodityId === selProdId)) {
clearSelectedProduct();
}
renderProducts();
renderProductMeta();
renderAccounts();
addLog(`商品刷新完成,共 ${products.length} 个,库存时间 ${d.fetchedAt || '--'}`,'s');
if (showToast) toast('商品已刷新',`共 ${products.length} 个,库存时间 ${d.fetchedAt || '--'}`,'success');
}catch(e){
products = [];
productInfo = null;
clearSelectedProduct();
renderProducts();
renderProductMeta(e.message);
addLog('商品刷新失败: ' + e.message,'e');
toast('商品刷新失败', e.message || '请检查网络连接','error');
}finally{
btn.disabled = false;
btn.textContent = '刷新商品';
}
}
// renderProducts 根据当前商品数组绘制左侧商品列表,并标记已选商品。
function renderProducts(){
let h='';
let list = filteredProducts();
document.getElementById('btnClearProductSearch').style.display = productSearch ? 'block' : 'none';
// 遍历商品缓存,生成每个商品的点击项和库存、积分信息。
list.forEach(p=>{
h+=`<div class="prod-item${selProdId==p.commodityId?' active':''}" onclick="selProduct('${jsAttr(p.commodityId)}','${jsAttr(p.commodityName)}')">
<img src="${p.pic}" onerror="this.style.display='none'">
<div class="pinfo"><div class="pname">${escHtml(p.commodityName)}</div>
<div class="pmeta"><span class="chip chip-score">${p.score} 积分</span><span class="chip chip-stock${p.count<500?' low':''}">库存 ${p.count}</span></div></div>
</div>`;
});
let emptyText = productSearch ? `没有匹配“${escHtml(productSearch)}”的商品` : '暂无实时商品数据';
document.getElementById('prodList').innerHTML=h||`<div class="empty-state">${emptyText}</div>`;
updateSelectedProductCard();
}
// renderProductMeta 显示库存来源和刷新时间,避免把旧库存当实时库存。
function renderProductMeta(errorMsg) {
let meta = document.getElementById('productMeta');
if (errorMsg) {
meta.className = 'product-meta warn';
meta.textContent = '刷新失败,未使用旧库存';
return;
}
if (!productInfo || !productInfo.fetchedAt) {
meta.className = 'product-meta';
meta.textContent = '库存未刷新';
return;
}
meta.className = 'product-meta ' + (productInfo.stale ? 'warn' : 'good');
if (productSearch) {
meta.textContent = `实时库存 ${filteredProducts().length}/${productInfo.count} 个,刷新于 ${productInfo.fetchedAt}`;
} else {
meta.textContent = `实时库存 ${productInfo.count} 个,刷新于 ${productInfo.fetchedAt}`;
}
}
// selProduct 记录当前选择的商品,提交时会应用到所有已勾选账号。
function selProduct(id, name) {
selProdId = id;
selProdName = name;
localStorage.setItem('selProd', id);
localStorage.setItem('selProdName', name);
renderProducts();
renderAccounts();
updateSelectedProductCard();
updateDashboardStats();
}
// clearSelectedProduct 清理已经不存在的商品选择。
function clearSelectedProduct() {
selProdId = null;
selProdName = '';
localStorage.removeItem('selProd');
localStorage.removeItem('selProdName');
updateSelectedProductCard();
updateDashboardStats();
}
// ==================== 账号 ====================
// loadAccounts 从后端获取账号列表,清理无效本地缓存后重新渲染账号表格。
async function loadAccounts() {
accounts = await App.GetAccounts();
selAccs = new Set([...selAccs].filter(i => i >= 0 && i < accounts.length));
localStorage.setItem('selAccs', JSON.stringify([...selAccs]));
// map 回调抽取账号名,用于判断 localStorage 中的旧积分缓存是否仍然有效。
let validNames = new Set(accounts.map(a => a.name));
for (let key in localStorage) {
// 只清理积分缓存,商品选择改为全局当前商品。
if (key.startsWith('accScore_')) {
let name = key.substring(key.indexOf('_') + 1);
if (!validNames.has(name)) {
localStorage.removeItem(key);
}
}
}
renderAccounts();
}
// renderAccounts 根据账号、选择状态、商品绑定、积分和抢购结果绘制账号表格。
function renderAccounts() {
document.getElementById('accCnt').textContent = accounts.length;
document.getElementById('selectedCnt').textContent = selAccs.size;
document.getElementById('accountPanelSub').textContent = `${accounts.length} 个账号,已选 ${selAccs.size} 个`;
let chkAll = document.getElementById('chkAll');
if (chkAll) chkAll.checked = accounts.length > 0 && selAccs.size === accounts.length;
// 将账号数组映射为表格行 HTML,行内状态从 localStorage 和 statusMap 读取。
let h = accounts.map((a, i) => {
let isSel = selAccs.has(i);
// 商品列展示当前选中商品,提交时会应用到所有勾选账号。
let prodTag = selProdName ? `<span class="prod-tag">${escHtml(selProdName)}</span>` : '-';
let scoreVal = localStorage.getItem('accScore_' + a.name) || '-'; // ← 改成 a.name
let st = statusMap[a.name]; // ← 已经是 a.name,保持
let status = statusInfo(st, isSel);
let credential = a.cookie ? '<span class="status-badge status-success">已加载</span>' : '<span class="status-badge status-fail">缺失</span>';
let lastMessage = resultMessage(st);
return `<tr>
<td>
<label class="account-check" onclick="togAcc(${i})">
<div class="check-box${isSel ? ' checked' : ''}">
${isSel ? '<span>✓</span>' : ''}
</div>
</label>
</td>
<td><div class="account-name">${escHtml(a.name)}</div><div class="account-sub">${isSel ? '已加入任务' : '未选择'}</div></td>
<td>${credential}</td>
<td>${prodTag}</td>
<td id="score_${i}">${scoreVal}</td>
<td class="status-td" id="st_${i}"><span class="status-badge ${status.cls}">${status.text}</span></td>
<td>${lastMessage}</td>
</tr>`;
});
document.getElementById('accTable').innerHTML = h.join('');
updateDashboardStats();
}
// toggleAll 根据表头复选框批量选择或取消所有账号,并持久化选择结果。
function toggleAll(){
let ck=document.getElementById('chkAll').checked;
// 批量选择时的回调把每个账号下标加入选择集合。
if(ck) accounts.forEach((_,i)=>selAccs.add(i));
else selAccs.clear();
localStorage.setItem('selAccs',JSON.stringify([...selAccs]));
renderAccounts();
updateDashboardStats();
}
// togAcc 切换单个账号的选择状态,并同步更新 localStorage。
function togAcc(i){
if(selAccs.has(i)) selAccs.delete(i); else selAccs.add(i);
localStorage.setItem('selAccs',JSON.stringify([...selAccs]));
renderAccounts();
updateDashboardStats();
}
// ==================== 立即抢购(不弹窗) ====================
// startNow 构建账号商品映射后,调用后端立即启动抢购。
async function startNow(){
let ap=buildAP();
if(!ap) return;
resetRunResults();
setRunState('立即抢购已提交');
addLog(`立即抢购: ${Object.keys(ap).length}个账号 → ${selProdName}`,'i');
toast('抢购中',`${Object.keys(ap).length} 个账号正在抢购 ${selProdName}`,'info',3000);
try {
let d=await App.StartSeckill(ap);
addLog(d.msg||'已提交','i');
} catch(e) {
setRunState('提交失败');
addLog('提交失败: '+e.message,'e');
toast('提交失败',e.message,'error');
}
}
// ==================== 定时抢购 ====================
// startSchedule 构建定时参数并提交给后端,由后端按服务端时间安排抢购。
async function startSchedule(){
let ap=buildAP();
if(!ap) return;
resetRunResults();
let timeStr=document.getElementById('targetTime').value.trim();
if(!timeStr){ toast('提示','请选择目标时间','warn'); return; }
if(timeStr.split(':').length===2) timeStr+=':00';
let today=new Intl.DateTimeFormat('zh-CN',{year:'numeric',month:'2-digit',day:'2-digit'})
.format(new Date()).replace(/\//g,'-');
let fullTime=today+' '+timeStr;
let adv=parseInt(document.getElementById('advance').value)||300;
setRunState('定时配置中');
addLog(`设置定时: ${fullTime}, 提前=${adv}ms`,'i');
try {
let d=await App.SetSchedule({accountProducts:ap,targetTime:fullTime,advance:adv});
scheduleActive=true;
// 保存定时信息
localStorage.setItem('targetTime',timeStr);
localStorage.setItem('advance',adv);
// 锁定:关闭自动,固定当前值
document.getElementById('btnSchedule').style.display='none';
document.getElementById('btnCancel').style.display='inline-block';
setRunState(`定时已开启,触发 ${d.triggerTime}`);
addLog(`定时已开启: 触发 ${d.triggerTime},剩余 ${d.remainSecond} 秒`,'s');
toast('定时已开启',`触发时刻: ${d.triggerTime}<br>剩余时间: <b>${formatRemain(d.remainSecond)}</b><br>商品: ${selProdName}<br>账号: ${Object.keys(ap).length} 个`,'success',5000);
startCountdown(d.remainSecond);
} catch(e) {
setRunState('定时设置失败');
addLog('设置失败: '+e.message,'e');
toast('定时失败',e.message,'error');
}
}
// cancelSchedule 调用后端取消尚未触发的定时任务,并恢复前端按钮状态。
async function cancelSchedule(){
try{
await App.CancelSchedule();
}catch(e){}
scheduleActive=false;
// 清除缓存的定时
localStorage.removeItem('targetTime');
localStorage.removeItem('advance');
// 恢复自动
document.getElementById('btnSchedule').style.display='inline-block';
document.getElementById('btnCancel').style.display='none';
stopCountdown();
setRunState('定时已停止');
addLog('定时已手动停止','w');
toast('定时已停止','抢购任务已取消','warn');
}
// startCountdown 启动前端倒计时徽标,用后端返回的剩余秒数做展示。
function startCountdown(sec) {
stopCountdown();
let badge = document.getElementById('cdBadge');
badge.style.display = 'inline-block';
let startTime = Date.now();
let endTime = startTime + sec * 1000;
// 每 500ms 刷新一次显示,确保用户能看到接近触发时的状态变化。
countdownTimer = setInterval(() => {
let now = Date.now();
let remain = Math.max(0, Math.ceil((endTime - now) / 1000));
if (remain <= 0) {
badge.textContent = '触发中';
clearInterval(countdownTimer);
countdownTimer = null;
scheduleActive = false;
document.getElementById('btnSchedule').style.display = 'inline-block';
document.getElementById('btnCancel').style.display = 'none';
setRunState('定时已触发');
// 延迟回调让“触发中”状态短暂停留,避免用户看不到最终状态。
setTimeout(() => badge.style.display = 'none', 5000);
} else {
badge.textContent = formatRemain(remain);
}
}, 500);
}
// stopCountdown 停止倒计时定时器,并隐藏倒计时徽标。
function stopCountdown(){
clearInterval(countdownTimer);
document.getElementById('cdBadge').style.display='none';
}
// formatRemain 把秒数格式化为 h:mm:ss,供定时提示和倒计时徽标使用。
function formatRemain(sec){
let h=Math.floor(sec/3600),m=Math.floor((sec%3600)/60),s=sec%60;
return `${h}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
}
// setRunState 更新顶部运行状态。
function setRunState(text) {
let el = document.getElementById('runStateText');
if (el) el.textContent = text || '等待操作';
}
// switchLogTab 切换右侧日志/结果/统计面板。
function switchLogTab(id) {
document.querySelectorAll('.log-tab').forEach(btn => btn.classList.toggle('active', btn.dataset.logTab === id));
document.querySelectorAll('.log-panel').forEach(panel => panel.classList.toggle('active', panel.id === id));
}
// updateSelectedProductCard 刷新左侧当前商品卡片。
function updateSelectedProductCard() {
let card = document.getElementById('selectedProductCard');
let nameEl = document.getElementById('selectedProductName');
let metaEl = document.getElementById('selectedProductMeta');
if (!nameEl || !metaEl) return;
let product = products.find(p => p.commodityId === selProdId);
nameEl.textContent = selProdName || '未选';
if (card) card.classList.toggle('has-product', !!selProdId);
if (!product) {
metaEl.innerHTML = selProdId ? '<span class="chip">等待刷新</span>' : '<span class="chip">未绑定任务</span>';
return;
}
metaEl.innerHTML = `<span class="chip chip-score">${product.score} 积分</span><span class="chip chip-stock${product.count<500?' low':''}">库存 ${product.count}</span>`;
}
// statusInfo 将后端结果转换为账号状态标签。
function statusInfo(st, selected) {
if (st === true) return {text:'成功', cls:'status-success'};
if (st === false) return {text:'失败', cls:'status-fail'};
if (st && typeof st === 'object') {
if (st.ok) return {text:'成功', cls:'status-success'};
let msg = String(st.message || '');
if (msg.includes('库存已耗完')) return {text:'库存耗尽', cls:'status-warn'};
if (msg.includes('兑换上限')) return {text:'已达上限', cls:'status-warn'};
if (msg.includes('未绑定')) return {text:'未绑定', cls:'status-fail'};
if (msg.includes('精英手册')) return {text:'资格不足', cls:'status-fail'};
return {text:selected ? '未命中' : '失败', cls:selected ? 'status-warn' : 'status-fail'};
}
return selected ? {text:'待命', cls:'status-ready'} : {text:'未选择', cls:'status-idle'};
}
// resultMessage 返回账号最后一次结果摘要。
function resultMessage(st) {
let msg = '';
if (st && typeof st === 'object') msg = st.message || '';
else if (st === true) msg = '成功';
else if (st === false) msg = '失败';
if (!msg) return '<span class="account-sub">-</span>';
let short = msg.length > 46 ? msg.slice(0, 46) + '...' : msg;
return `<span class="account-sub" title="${escHtml(msg)}">${escHtml(short)}</span>`;
}
// updateDashboardStats 刷新顶部统计指标。
function updateDashboardStats() {
let selectedNames = new Set([...selAccs].map(i => accounts[i]?.name).filter(Boolean));
let success = 0, fail = 0;
for (let name of selectedNames) {
let st = statusMap[name];
if (st === true || (st && typeof st === 'object' && st.ok)) success++;
else if (st === false || (st && typeof st === 'object' && st.message)) fail++;
}
let pending = Math.max(0, selectedNames.size - success - fail);
setText('selectedCnt', selectedNames.size);
setText('successCnt', success);
setText('failCnt', fail);
setText('pendingCnt', pending);
let stats = document.getElementById('statsBody');
if (stats) {
stats.innerHTML = `<div class="log-result log-s">成功账号: ${success}</div>
<div class="log-result log-e">异常账号: ${fail}</div>
<div class="log-result log-i">待处理账号: ${pending}</div>
<div class="log-result">已选账号: ${selectedNames.size} / 总账号: ${accounts.length}</div>`;
}
}
function setText(id, value) {
let el = document.getElementById(id);
if (el) el.textContent = value;
}
// resetRunResults 清理上一轮前端结果,避免新任务被旧状态干扰。
function resetRunResults() {
lastResults = {};
statusMap = {};
localStorage.removeItem('statusMap');
let resultEl = document.getElementById('resultBody');
if (resultEl) resultEl.innerHTML = '<div class="result-empty">暂无抢购结果</div>';
renderAccounts();
updateDashboardStats();
}
// ==================== 结果刷新 ====================
// checkResults 轮询后端抢购结果,更新日志区、账号状态和本地状态缓存。
async function checkResults() {
try {
let d = await App.GetResults();
if (JSON.stringify(d) !== JSON.stringify(lastResults) && Object.keys(d).length > 0) {
lastResults = d;
let newStatusMap = {};
let h = '<div class="log-i">=== 最新结果 ===</div>';
for (let [k, v] of Object.entries(d)) {
let cls = v.includes('成功') ? 'log-s' : 'log-e';
h += `<div class="log-result ${cls}"><b>${k}</b>: ${v}</div>`;
let name = k.split('_')[0];
if (!(name in newStatusMap)) newStatusMap[name] = {ok:false,message:v};
if (v.includes('成功')) newStatusMap[name] = {ok:true,message:v};
}
statusMap = newStatusMap;
localStorage.setItem('statusMap', JSON.stringify(statusMap));
renderAccounts();
let resultEl = document.getElementById('resultBody');
resultEl.innerHTML = h;
resultEl.scrollTop = resultEl.scrollHeight;
updateDashboardStats();
}
} catch (e) { }
}
// fetchServerLogs 增量拉取后端日志,把真实接口链路日志显示到前端日志区。
async function fetchServerLogs() {
try {
let d = await App.GetLogs(lastLogId);
if (!d.success || !Array.isArray(d.logs) || d.logs.length === 0) return;
d.logs.forEach(item => {
lastLogId = Math.max(lastLogId, item.id || 0);
let type = 'i';
if (item.level === 'success') type = 's';
else if (item.level === 'error') type = 'e';
else if (item.level === 'warn') type = 'w';
else if (item.level === 'debug') type = 'd';
addServerLog(item.message, type, item.category);
});
} catch (e) { }
}
// addServerLog 追加一条后端日志,和本地操作日志共用同一个日志区域。
function addServerLog(msg, type = 'i', category = '') {
let el = document.getElementById('logBody');
let cat = category ? `<span class="log-cat">${escHtml(category)}</span>` : '';
el.innerHTML += `<div class="log-${type}">[后端] ${cat}${escHtml(cleanServerLogMessage(msg))}</div>`;
el.scrollTop = el.scrollHeight;
}
// cleanServerLogMessage 去掉后端结构化日志前缀,分类由单独标签展示。
function cleanServerLogMessage(msg) {
return String(msg ?? '').replace(/\[[^\]]+\]\[(info|success|warn|error)\]\s*/i, '');
}
// ==================== 设置 ====================
// openSettings 打开设置弹窗,从后端读取当前配置填充表单。
async function openSettings() {
try {
let cfg = await App.GetSettings();
document.getElementById('setTraceEnabled').checked = !!cfg.traceEnabled;
document.getElementById('setTraceMaxBody').value = cfg.traceMaxBody || 0;
document.getElementById('setLogLevel').value = cfg.logLevel || 'info';
document.getElementById('setConcurrency').value = cfg.concurrency || 80;
document.getElementById('setAttempts').value = cfg.attempts || 1;
} catch(e) {
toast('读取设置失败', e.message, 'error');
}
document.getElementById('settingsModal').classList.add('show');
}
// closeSettings 关闭设置弹窗。
function closeSettings() {
document.getElementById('settingsModal').classList.remove('show');
}
// saveSettings 收集表单数据,提交给后端保存。
async function saveSettings() {
let cfg = {
traceEnabled: document.getElementById('setTraceEnabled').checked,
traceMaxBody: parseInt(document.getElementById('setTraceMaxBody').value) || 0,
logLevel: document.getElementById('setLogLevel').value,
concurrency: parseInt(document.getElementById('setConcurrency').value) || 80,
attempts: parseInt(document.getElementById('setAttempts').value) || 1,
seckillMode: 1,
};
try {
let d = await App.SaveSettings(cfg);
if (d.success) {
toast('设置已保存', '配置已生效', 'success');
closeSettings();
} else {
toast('保存失败', d.error || '', 'error');
}
} catch(e) {
toast('保存失败', e.message, 'error');
}
}
// buildAP 根据已勾选账号和账号绑定商品,生成后端需要的账号到商品 ID 映射。
function buildAP() {
if (selAccs.size === 0) {
toast('提示', '请勾选要抢购的账号', 'warn');
return null;
}
if (!selProdId) {
toast('提示', '请先选择商品', 'warn');
return null;
}
if (!productInfo || !products.some(p => p.commodityId === selProdId)) {
toast('提示', '请先刷新商品,确认库存是实时数据', 'warn');
return null;
}
let ap = {};
// 遍历已选账号,把当前选中商品应用到每个账号。
selAccs.forEach(i => {
let account = accounts[i];
if (account) {
ap[account.name] = selProdId;
}
});
if (Object.keys(ap).length === 0) {
toast('提示', '没有有效账号可提交', 'warn');
return null;
}
return ap;
}
// clearLegacyProductBindings 删除旧版按账号保存商品的缓存,避免残留旧商品误导界面。
function clearLegacyProductBindings() {
for (let key in localStorage) {
if (key.startsWith('accProd_') || key.startsWith('accProdName_')) {
localStorage.removeItem(key);
}
}
}
// addLog 向底部日志区追加一条带毫秒时间戳的运行日志。
function addLog(msg, type = 'i') {
let el = document.getElementById('logBody');
let now = new Date();
let timeStr = now.toLocaleTimeString() + '.' + String(now.getMilliseconds()).padStart(3, '0');
el.innerHTML += `<div class="log-${type}">[${timeStr}] ${msg}</div>`;
el.scrollTop = el.scrollHeight;
}
// clearLog 清空前端日志显示,并重置最近一次结果快照。
function clearLog(){
document.getElementById('logBody').innerHTML='<div class="log-i">[系统] 就绪,等待操作...</div>';
document.getElementById('resultBody').innerHTML='<div class="result-empty">暂无抢购结果</div>';
lastResults={};
setRunState('等待操作');
updateDashboardStats();
}
// escHtml 转义 HTML 特殊字符,避免接口数据破坏页面结构。
function escHtml(s){ return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;'); }
// jsAttr 转义写入 onclick 字符串参数的数据。
function jsAttr(s){ return escHtml(String(s ?? '').replace(/\\/g,'\\\\').replace(/'/g,"\\'").replace(/\n/g,' ')); }
init();
+11 -28
View File
@@ -6,34 +6,17 @@ declare module '*.vue' {
export default component export default component
} }
// Wails Go 绑定类型声明 // 统一从 Wails 自动生成的强类型绑定派生 window.go.main.App 的类型声明,
interface Window { // 避免手写声明与后端契约漂移。后端方法签名变更后重新运行 `wails generate`
go: { // 会更新 wailsjs/go/main/App.d.ts,此处类型随之更新;若前端引用了已删除或
main: { // 已重命名的方法,TypeScript 编译(vue-tsc)会直接报错。
App: { import type * as GoApp from './wailsjs/go/main/App'
LoadProducts: (refresh: boolean) => Promise<any>
GetAccounts: () => Promise<any[]> declare global {
ReloadAccounts: () => Promise<any> interface Window {
StartSeckill: (accountProducts: Record<string, string>) => Promise<any> go: {
SetSchedule: (req: any) => Promise<any> main: {
CancelSchedule: () => Promise<any> App: typeof GoApp
GetResults: () => Promise<Record<string, string>>
GetLogs: (since: number) => Promise<any>
GetTime: () => Promise<any>
ClearResults: () => Promise<any>
QueryScore: (accountName: string) => Promise<any>
GetVersion: () => Promise<string>
GetSettings: () => Promise<any>
SaveSettings: (cfg: any) => Promise<any>
VerifyExchange: (accountName: string) => Promise<any>
VerifyAllExchange: () => Promise<any>
VerifyAndExport: (commodityID: string) => Promise<any>
ExportAccounts: (accountNames: string[], filename: string) => Promise<any>
ExportAccountsWithProduct: (accountNames: string[], commodityID: string, commodityName: string) => Promise<any>
OrganizeAccounts: (commodityID: string, commodityName: string, startTime: number, endTime: number) => Promise<any>
GetActivities: () => Promise<Array<{ id: string; displayName: string }>>
GetCurrentActivity: () => Promise<{ id: string; displayName: string }>
SwitchActivity: (id: string) => Promise<{ success: boolean; activity?: string; displayName?: string; error?: string }>
} }
} }
} }
+17 -17
View File
@@ -46,15 +46,15 @@ const douyuBase = constants.BaseURL
// peace 精英手册(旧活动,ActAlias=20260120QYOOB)。 // peace 精英手册(旧活动,ActAlias=20260120QYOOB)。
var peace = &Activity{ var peace = &Activity{
ID: "peace", ID: "peace",
DisplayName: "精英手册", DisplayName: "精英手册",
ManualID: "G4KA4Qnz4LDp7", ManualID: "G4KA4Qnz4LDp7",
RoomID: "9263298", RoomID: "9263298",
ActAlias: "20260120QYOOB", ActAlias: "20260120QYOOB",
BaseURL: douyuBase, BaseURL: douyuBase,
ShopReferer: douyuBase + "/pages/live-peace-handbook/web/shop?ditchname=pass0&roomId=9263298", ShopReferer: douyuBase + "/pages/live-peace-handbook/web/shop?ditchname=pass0&roomId=9263298",
StoreHomeURL: douyuBase + "/wgapi/ordnc/activity/peace/storehome?manualID=G4KA4Qnz4LDp7&rid=9263298", StoreHomeURL: douyuBase + "/wgapi/ordnc/activity/peace/storehome?manualID=G4KA4Qnz4LDp7&rid=9263298",
CSRFURL: douyuBase + "/japi/carnival/nc/common/generateCsrf", CSRFURL: douyuBase + "/japi/carnival/nc/common/generateCsrf",
BatchLimitURL: douyuBase + "/wgapi/ordnc/activity/peace/batchExchangeLimit", BatchLimitURL: douyuBase + "/wgapi/ordnc/activity/peace/batchExchangeLimit",
PreExchangeURL: douyuBase + "/wgapi/ordnc/activity/peace/preExchange", PreExchangeURL: douyuBase + "/wgapi/ordnc/activity/peace/preExchange",
ExchangeURL: douyuBase + "/wgapi/ordnc/activity/peace/exchange", ExchangeURL: douyuBase + "/wgapi/ordnc/activity/peace/exchange",
@@ -68,13 +68,13 @@ var peace = &Activity{
// peacematch 电竞手册(新活动,ActAlias=20260226ZMGDG)。 // peacematch 电竞手册(新活动,ActAlias=20260226ZMGDG)。
// 数据来源:/Users/yml/Desktop/抓包/douyu/7.29/电竞手册-基础信息.har 及 7.28 系列抓包。 // 数据来源:/Users/yml/Desktop/抓包/douyu/7.29/电竞手册-基础信息.har 及 7.28 系列抓包。
var peacematch = &Activity{ var peacematch = &Activity{
ID: "peacematch", ID: "peacematch",
DisplayName: "电竞手册", DisplayName: "电竞手册",
ManualID: "1W0yGkOdDbAXb", ManualID: "1W0yGkOdDbAXb",
RoomID: "9263298", RoomID: "9263298",
ActAlias: "20260226ZMGDG", ActAlias: "20260226ZMGDG",
BaseURL: douyuBase, BaseURL: douyuBase,
ShopReferer: douyuBase + "/pages/live-peace-pel/web/shop?roomId=9263298&isAnchorSide=0", ShopReferer: douyuBase + "/pages/live-peace-pel/web/shop?roomId=9263298&isAnchorSide=0",
StoreHomeURL: douyuBase + "/wgapi/ordnc/activity/peacematch/storehome?manualID=1W0yGkOdDbAXb&rid=9263298", StoreHomeURL: douyuBase + "/wgapi/ordnc/activity/peacematch/storehome?manualID=1W0yGkOdDbAXb&rid=9263298",
// generateCsrf 为嘉年华平台级接口,抓包未单独出现,沿用 peace 同款端点。 // generateCsrf 为嘉年华平台级接口,抓包未单独出现,沿用 peace 同款端点。
CSRFURL: douyuBase + "/japi/carnival/nc/common/generateCsrf", CSRFURL: douyuBase + "/japi/carnival/nc/common/generateCsrf",
@@ -91,7 +91,7 @@ var peacematch = &Activity{
} }
var registry = map[string]*Activity{ var registry = map[string]*Activity{
peace.ID: peace, peace.ID: peace,
peacematch.ID: peacematch, peacematch.ID: peacematch,
} }
+81
View File
@@ -0,0 +1,81 @@
package logger
import (
"testing"
)
func TestIsLogLevel(t *testing.T) {
valid := []string{"success", "error", "warn", "info", "debug", "SUCCESS", "Warn"}
for _, l := range valid {
if !IsLogLevel(l) {
t.Errorf("IsLogLevel(%q) = false, want true", l)
}
}
invalid := []string{"fatal", "trace", "", "warning"}
for _, l := range invalid {
if IsLogLevel(l) {
t.Errorf("IsLogLevel(%q) = true, want false", l)
}
}
}
func TestDetectLogLevel(t *testing.T) {
cases := []struct {
line string
want string
}{
{"[2026/01/01 00:00:00.000][网络][debug] 调试", "debug"},
{"[2026/01/01 00:00:00.000][抢购][success] 兑换成功", "success"},
{"[2026/01/01 00:00:00.000][系统][error] 失败", "error"},
{"[2026/01/01 00:00:00.000][系统][warn] 跳过", "warn"},
{"[2026/01/01 00:00:00.000][系统][info] 信息", "info"},
{"兑换成功完成", "success"},
{"网络请求失败 error 发生", "error"},
{"配置降级处理 warn", "warn"},
{"普通信息日志", "info"},
}
for _, c := range cases {
if got := DetectLogLevel(c.line); got != c.want {
t.Errorf("DetectLogLevel(%q) = %q, want %q", c.line, got, c.want)
}
}
}
func TestParseLogLine(t *testing.T) {
line := "2026/01/01 12:00:00.123 [抢购][success] 账号:testuser 兑换成功"
meta := ParseLogLine(line)
if meta.Time != "2026-01-01 12:00:00.123" {
t.Errorf("ParseLogLine Time = %q, want '2026-01-01 12:00:00.123'", meta.Time)
}
if meta.Category != "抢购" {
t.Errorf("ParseLogLine Category = %q, want '抢购'", meta.Category)
}
if meta.Level != "success" {
t.Errorf("ParseLogLine Level = %q, want 'success'", meta.Level)
}
if meta.Account != "testuser" {
t.Errorf("ParseLogLine Account = %q, want 'testuser'", meta.Account)
}
}
func TestParseLogLineShort(t *testing.T) {
// 不含时间的行,ParseLogLine 不应 panic,Time 应为空
line := "[系统][info] 配置已加载"
meta := ParseLogLine(line)
if meta.Category != "系统" {
t.Errorf("ParseLogLine Category = %q, want '系统'", meta.Category)
}
if meta.Level != "info" {
t.Errorf("ParseLogLine Level = %q, want 'info'", meta.Level)
}
if meta.Time != "" {
t.Errorf("ParseLogLine Time = %q, want empty", meta.Time)
}
}
func TestParseLogMeta(t *testing.T) {
cat, lvl := ParseLogMeta("[网络][warn] 降级")
if cat != "网络" || lvl != "warn" {
t.Errorf("ParseLogMeta = (%q, %q), want ('网络', 'warn')", cat, lvl)
}
}
+53 -15
View File
@@ -54,9 +54,10 @@ type runSettings struct {
// Scheduler 抢购调度器。 // Scheduler 抢购调度器。
type Scheduler struct { type Scheduler struct {
client *client.DouyuClient clientMu sync.RWMutex
paths types.AppPaths client *client.DouyuClient
font *truetype.Font paths types.AppPaths
font *truetype.Font
successImages *image.SuccessImageSaver successImages *image.SuccessImageSaver
@@ -82,8 +83,8 @@ type Scheduler struct {
resyncSchedule *time.Timer resyncSchedule *time.Timer
warmupGen int64 warmupGen int64
warmupsMu sync.RWMutex warmupsMu sync.RWMutex
warmups map[string]types.WarmupData warmups map[string]types.WarmupData
warmupRunMu sync.Mutex warmupRunMu sync.Mutex
attemptCacheMu sync.RWMutex attemptCacheMu sync.RWMutex
@@ -128,6 +129,33 @@ func (s *Scheduler) Close() {
} }
} }
// clientSnapshot 返回当前 client 的指针快照(读锁保护,用于执行期间持有一个稳定引用)。
func (s *Scheduler) clientSnapshot() *client.DouyuClient {
s.clientMu.RLock()
defer s.clientMu.RUnlock()
return s.client
}
// UpdateClient 热替换底层 HTTP 客户端(用于活动切换)。
// 若有抢购任务正在运行则拒绝替换,返回 false。
func (s *Scheduler) UpdateClient(newClient *client.DouyuClient) bool {
s.runMu.Lock()
if s.running {
s.runMu.Unlock()
return false
}
s.runMu.Unlock()
s.clientMu.Lock()
defer s.clientMu.Unlock()
old := s.client
s.client = newClient
if old != nil && old.HTTPClient != nil {
old.HTTPClient.CloseIdleConnections()
}
return true
}
// UpdateProducts 更新商品缓存,抢购成功图片会优先使用中文商品名。 // UpdateProducts 更新商品缓存,抢购成功图片会优先使用中文商品名。
func (s *Scheduler) UpdateProducts(products []types.Product) { func (s *Scheduler) UpdateProducts(products []types.Product) {
next := make(map[string]types.Product, len(products)) next := make(map[string]types.Product, len(products))
@@ -817,6 +845,7 @@ func (s *Scheduler) warmupAttempts(attempts []types.ExchangeAttempt) {
logger.LogEvent("预热", "info", "开始预热: %d 个请求", len(attempts)) logger.LogEvent("预热", "info", "开始预热: %d 个请求", len(attempts))
settings := s.settingsSnapshot() settings := s.settingsSnapshot()
cli := s.clientSnapshot()
limit := make(chan struct{}, settings.concurrency) limit := make(chan struct{}, settings.concurrency)
var wg sync.WaitGroup var wg sync.WaitGroup
for _, attempt := range attempts { for _, attempt := range attempts {
@@ -827,12 +856,12 @@ func (s *Scheduler) warmupAttempts(attempts []types.ExchangeAttempt) {
defer func() { <-limit }() defer func() { <-limit }()
start := time.Now() start := time.Now()
csrf, err := s.client.GenerateCSRF(attempt.Account.Cookie) csrf, err := cli.GenerateCSRF(attempt.Account.Cookie)
if err != nil { if err != nil {
logger.LogAccountEvent("预热", "warn", attempt.Account.Name, "CSRF预热失败: 账号=%s 商品=%s err=%v", attempt.Account.Name, attempt.Product.CommodityName, err) logger.LogAccountEvent("预热", "warn", attempt.Account.Name, "CSRF预热失败: 账号=%s 商品=%s err=%v", attempt.Account.Name, attempt.Product.CommodityName, err)
return return
} }
roleName, err := s.client.RoleName(attempt.Account.Cookie) roleName, err := cli.RoleName(attempt.Account.Cookie)
if err != nil { if err != nil {
logger.LogAccountEvent("预热", "warn", attempt.Account.Name, "角色预热失败: 账号=%s err=%v", attempt.Account.Name, err) logger.LogAccountEvent("预热", "warn", attempt.Account.Name, "角色预热失败: 账号=%s err=%v", attempt.Account.Name, err)
} }
@@ -867,7 +896,8 @@ func uniqueWarmupAttempts(attempts []types.ExchangeAttempt) []types.ExchangeAtte
} }
func (s *Scheduler) calibrateDouyuTime(label string) types.TimeCalibration { func (s *Scheduler) calibrateDouyuTime(label string) types.TimeCalibration {
calibration, err := s.client.BestServerTimeCalibration(timeCalibrateRounds, timeCalibrateWait) cli := s.clientSnapshot()
calibration, err := cli.BestServerTimeCalibration(timeCalibrateRounds, timeCalibrateWait)
if err != nil { if err != nil {
logger.LogEvent("时间", "warn", "%s校准降级: %v", label, err) logger.LogEvent("时间", "warn", "%s校准降级: %v", label, err)
} }
@@ -906,6 +936,7 @@ func (s *Scheduler) stopSchedulesLocked() {
} }
func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResult { func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResult {
cli := s.clientSnapshot()
result := types.ExchangeResult{ result := types.ExchangeResult{
Account: attempt.Account.Name, Account: attempt.Account.Name,
Product: attempt.Product.CommodityName, Product: attempt.Product.CommodityName,
@@ -922,7 +953,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
} }
if csrf == "" { if csrf == "" {
var err error var err error
csrf, err = s.client.GenerateCSRF(attempt.Account.Cookie) csrf, err = cli.GenerateCSRF(attempt.Account.Cookie)
if err != nil { if err != nil {
result.Message = "失败|生成CSRF失败: " + err.Error() result.Message = "失败|生成CSRF失败: " + err.Error()
return result return result
@@ -930,7 +961,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "CSRF已生成,本次兑换链路复用同一个 token: 账号=%s 商品=%s", attempt.Account.Name, attempt.Product.CommodityName) logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "CSRF已生成,本次兑换链路复用同一个 token: 账号=%s 商品=%s", attempt.Account.Name, attempt.Product.CommodityName)
} }
limit, err := s.client.BatchExchangeLimit(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf) limit, err := cli.BatchExchangeLimit(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
if err != nil { if err != nil {
result.Message = "失败|批量限制检查失败: " + err.Error() result.Message = "失败|批量限制检查失败: " + err.Error()
return result return result
@@ -941,7 +972,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
} }
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "批量限制通过: 账号=%s 商品=%s limit=%d", attempt.Account.Name, attempt.Product.CommodityName, limit) logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "批量限制通过: 账号=%s 商品=%s limit=%d", attempt.Account.Name, attempt.Product.CommodityName, limit)
if err := s.client.PreExchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf); err != nil { if err := cli.PreExchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf); err != nil {
result.Message = "失败|预兑换失败: " + err.Error() result.Message = "失败|预兑换失败: " + err.Error()
return result return result
} }
@@ -953,7 +984,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
}) })
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "资格预检通过: 账号=%s 商品=%s,后续可直兑", attempt.Account.Name, attempt.Product.CommodityName) logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "资格预检通过: 账号=%s 商品=%s,后续可直兑", attempt.Account.Name, attempt.Product.CommodityName)
exchangeInfo, err := s.client.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf) exchangeInfo, err := cli.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
if err != nil { if err != nil {
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{ s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
CSRF: csrf, CSRF: csrf,
@@ -967,7 +998,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
} }
if roleName == "" { if roleName == "" {
roleName, err = s.client.RoleName(attempt.Account.Cookie) roleName, err = cli.RoleName(attempt.Account.Cookie)
if err != nil { if err != nil {
logger.LogAccountEvent("抢购", "warn", attempt.Account.Name, "角色名查询失败: 账号=%s err=%v", attempt.Account.Name, err) logger.LogAccountEvent("抢购", "warn", attempt.Account.Name, "角色名查询失败: 账号=%s err=%v", attempt.Account.Name, err)
} }
@@ -994,6 +1025,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
// runAttemptFast 激进模式的兑换逻辑,复用缓存的 CSRF,跳过 BatchExchangeLimit 和 PreExchange。 // runAttemptFast 激进模式的兑换逻辑,复用缓存的 CSRF,跳过 BatchExchangeLimit 和 PreExchange。
func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.ExchangeResult { func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.ExchangeResult {
cli := s.clientSnapshot()
result := types.ExchangeResult{ result := types.ExchangeResult{
Account: attempt.Account.Name, Account: attempt.Account.Name,
Product: attempt.Product.CommodityName, Product: attempt.Product.CommodityName,
@@ -1014,7 +1046,7 @@ func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.Exchange
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "激进模式直兑: 账号=%s 商品=%s 第%d包", attempt.Account.Name, attempt.Product.CommodityName, attempt.Index) logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "激进模式直兑: 账号=%s 商品=%s 第%d包", attempt.Account.Name, attempt.Product.CommodityName, attempt.Index)
// 直接调用 Exchange // 直接调用 Exchange
exchangeInfo, err := s.client.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf) exchangeInfo, err := cli.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
if err != nil { if err != nil {
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{ s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
CSRF: csrf, CSRF: csrf,
@@ -1040,7 +1072,7 @@ func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.Exchange
} }
if roleName == "" { if roleName == "" {
var err error var err error
roleName, err = s.client.RoleName(attempt.Account.Cookie) roleName, err = cli.RoleName(attempt.Account.Cookie)
if err != nil { if err != nil {
logger.LogAccountEvent("抢购", "warn", attempt.Account.Name, "角色名查询失败: 账号=%s err=%v", attempt.Account.Name, err) logger.LogAccountEvent("抢购", "warn", attempt.Account.Name, "角色名查询失败: 账号=%s err=%v", attempt.Account.Name, err)
} }
@@ -1143,10 +1175,16 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (map[string]any, error
time.Now().Add(resyncRemain).In(constants.CST).Format("15:04:05.000"), time.Now().Add(resyncRemain).In(constants.CST).Format("15:04:05.000"),
) )
remainSecond := int(triggerTime.Sub(serverTime).Seconds())
if remainSecond < 0 {
remainSecond = 0
}
return map[string]any{ return map[string]any{
"success": true, "success": true,
"targetTime": targetTime.In(constants.CST).Format("2006-01-02 15:04:05"), "targetTime": targetTime.In(constants.CST).Format("2006-01-02 15:04:05"),
"triggerTime": triggerTime.In(constants.CST).Format("2006-01-02 15:04:05"), "triggerTime": triggerTime.In(constants.CST).Format("2006-01-02 15:04:05"),
"remainSecond": remainSecond,
"offsetMs": calibration.Offset.Milliseconds(), "offsetMs": calibration.Offset.Milliseconds(),
"errorBoundMs": calibration.ErrorBound.Milliseconds(), "errorBoundMs": calibration.ErrorBound.Milliseconds(),
"rttMs": calibration.RTT.Milliseconds(), "rttMs": calibration.RTT.Milliseconds(),
+162
View File
@@ -0,0 +1,162 @@
package seckill
import (
"testing"
"time"
"douyu_go/internal/types"
)
func makeAttempts(names ...string) []types.ExchangeAttempt {
out := make([]types.ExchangeAttempt, 0, len(names))
for i, n := range names {
out = append(out, types.ExchangeAttempt{
Account: types.Account{Name: n},
Index: i + 1,
})
}
return out
}
func TestRetryIntervalFor(t *testing.T) {
stages := []types.RetryStage{
{MaxElapsed: 4, Interval: 120},
{MaxElapsed: 12, Interval: 200},
{MaxElapsed: 30, Interval: 500},
{MaxElapsed: 75, Interval: 1000},
}
cases := []struct {
elapsed time.Duration
want time.Duration
}{
{1 * time.Second, 120 * time.Millisecond},
{5 * time.Second, 200 * time.Millisecond},
{13 * time.Second, 500 * time.Millisecond},
{31 * time.Second, 1000 * time.Millisecond},
{100 * time.Second, 900 * time.Millisecond}, // 超出所有阶段,用默认值
}
for _, c := range cases {
if got := retryIntervalFor(stages, c.elapsed); got != c.want {
t.Errorf("retryIntervalFor(%v) = %v, want %v", c.elapsed, got, c.want)
}
}
}
func TestRetryIntervalForEmpty(t *testing.T) {
// 空阶段或无效阶段都回退到默认 900ms
if got := retryIntervalFor(nil, 1*time.Second); got != 900*time.Millisecond {
t.Errorf("retryIntervalFor(nil) = %v, want 900ms", got)
}
if got := retryIntervalFor([]types.RetryStage{{MaxElapsed: 0, Interval: 0}}, 1*time.Second); got != 900*time.Millisecond {
t.Errorf("retryIntervalFor(invalid) = %v, want 900ms", got)
}
}
func TestRetryCooldownDuration(t *testing.T) {
cases := []struct {
msg string
want time.Duration
}{
{"用户行为异常,请稍后再试", behaviorCooldown},
{"点击太快了", clickFastCooldown},
{"操作频繁请稍后", behaviorCooldown},
{"请求过多", behaviorCooldown},
{"请求太频繁", behaviorCooldown},
{"兑换成功", 0},
{"库存不足", 0},
}
for _, c := range cases {
if got := retryCooldownDuration(c.msg); got != c.want {
t.Errorf("retryCooldownDuration(%q) = %v, want %v", c.msg, got, c.want)
}
}
}
func TestClassifyRetryStop(t *testing.T) {
acc, prod, reason := classifyRetryStop("您已达本次活动兑换上限")
if !acc || prod || reason != "已达兑换上限" {
t.Errorf("classifyRetryStop(兑换上限) = (%v,%v,%q), want (true,false,'已达兑换上限')", acc, prod, reason)
}
acc, prod, reason = classifyRetryStop("未绑定账号")
if !acc || prod || reason != "账号未绑定角色" {
t.Errorf("classifyRetryStop(未绑定) = (%v,%v,%q), want (true,false,'账号未绑定角色')", acc, prod, reason)
}
acc, prod, reason = classifyRetryStop("需要开通精英手册")
if !acc || prod || reason != "账号不满足精英手册条件" {
t.Errorf("classifyRetryStop(精英手册) = (%v,%v,%q), want (true,false,'账号不满足精英手册条件')", acc, prod, reason)
}
// 库存耗尽不停止
acc, prod, reason = classifyRetryStop("商品本次活动库存已耗完")
if acc || prod || reason != "" {
t.Errorf("classifyRetryStop(库存耗完) = (%v,%v,%q), want (false,false,'')", acc, prod, reason)
}
// 普通错误不停止
acc, prod, reason = classifyRetryStop("网络超时")
if acc || prod || reason != "" {
t.Errorf("classifyRetryStop(普通错误) = (%v,%v,%q), want (false,false,'')", acc, prod, reason)
}
}
func TestFilterCooldownAttempts(t *testing.T) {
attempts := makeAttempts("a", "b", "c")
now := time.Now()
cooldown := map[string]time.Time{
"a": now.Add(5 * time.Second), // 仍在冷却
"b": now.Add(-5 * time.Second), // 已过期
}
out, nextReady := filterCooldownAttempts(attempts, cooldown, now)
if len(out) != 2 {
t.Fatalf("filterCooldownAttempts out length = %d, want 2", len(out))
}
for _, a := range out {
if a.Account.Name == "a" {
t.Errorf("account 'a' should be filtered out")
}
}
if nextReady.IsZero() {
t.Errorf("nextReady should not be zero")
}
if !nextReady.After(now) {
t.Errorf("nextReady should be after now")
}
}
func TestPickRoundAttempts(t *testing.T) {
// 账号 A 有 3 个包,账号 B 有 3 个包
attempts := []types.ExchangeAttempt{
{Account: types.Account{Name: "A"}, Index: 1},
{Account: types.Account{Name: "A"}, Index: 2},
{Account: types.Account{Name: "A"}, Index: 3},
{Account: types.Account{Name: "B"}, Index: 1},
{Account: types.Account{Name: "B"}, Index: 2},
{Account: types.Account{Name: "B"}, Index: 3},
}
// 第 1 轮每账号选第 1 包
out := pickRoundAttempts(attempts, 1, 3)
if len(out) != 2 {
t.Fatalf("pickRoundAttempts round1 length = %d, want 2", len(out))
}
for _, a := range out {
if a.Index != 1 {
t.Errorf("round1 should pick index 1, got %d for %s", a.Index, a.Account.Name)
}
}
// 第 2 轮每账号选第 2 包
out = pickRoundAttempts(attempts, 2, 3)
for _, a := range out {
if a.Index != 2 {
t.Errorf("round2 should pick index 2, got %d for %s", a.Index, a.Account.Name)
}
}
// attemptsPerAccount=0 时回退取各自首个
out = pickRoundAttempts(attempts, 1, 0)
for _, a := range out {
if a.Index != 1 {
t.Errorf("round with 0 perAccount should pick index 1, got %d", a.Index)
}
}
// 空输入
if out := pickRoundAttempts(nil, 1, 3); out != nil {
t.Errorf("pickRoundAttempts(nil) = %v, want nil", out)
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ import (
// Config 应用配置。 // Config 应用配置。
type Config struct { type Config struct {
TimeAPIURL string `json:"timeApiUrl"` TimeAPIURL string `json:"timeApiUrl"`
Activity string `json:"activity"` // 当前活动 ID,见 internal/activity Activity string `json:"activity"` // 当前活动 ID,见 internal/activity
TraceEnabled bool `json:"traceEnabled"` TraceEnabled bool `json:"traceEnabled"`
TraceMaxBody int `json:"traceMaxBody"` TraceMaxBody int `json:"traceMaxBody"`
LogLevel string `json:"logLevel"` // debug / info / warn / error LogLevel string `json:"logLevel"` // debug / info / warn / error
-24
View File
@@ -1,9 +1,7 @@
package utils package utils
import ( import (
"encoding/json"
"fmt" "fmt"
"net/http"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -116,25 +114,3 @@ func MaskValue(value string) string {
func RoundDuration(d time.Duration) time.Duration { func RoundDuration(d time.Duration) time.Duration {
return d.Round(time.Millisecond) return d.Round(time.Millisecond)
} }
// ReadJSON 读取请求 JSON。
func ReadJSON(r *http.Request, out any) error {
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(out)
}
// WriteJSON 写出 JSON 响应。
func WriteJSON(w http.ResponseWriter, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(value)
}
// WriteError 写出统一错误 JSON,同时设置 HTTP 状态码。
func WriteError(w http.ResponseWriter, status int, err error) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]any{
"success": false,
"error": err.Error(),
})
}
+117
View File
@@ -0,0 +1,117 @@
package utils
import (
"strings"
"testing"
)
func TestMaskValue(t *testing.T) {
cases := []struct {
in string
want string
}{
{"", "****"},
{"abc", "****"},
{"12345678", "****"},
{"abcdefghij", "abcd****ghij"}, // 10 runes => 前4+****+后4
}
for _, c := range cases {
got := MaskValue(c.in)
if got != c.want {
t.Errorf("MaskValue(%q) = %q, want %q", c.in, got, c.want)
}
}
}
func TestMaskCookie(t *testing.T) {
// 空
if got := MaskCookie(""); got != "" {
t.Errorf("MaskCookie(empty) = %q, want empty", got)
}
// 单条
got := MaskCookie("acf_ccn=abcdefghij")
if !strings.Contains(got, "acf_ccn=abcd****ghij") {
t.Errorf("MaskCookie single = %q, want masked acf_ccn", got)
}
// 多条只显示前 3 条并标注总数
got = MaskCookie("a=abcdefghij; b=abcdefghij; c=abcdefghij; d=abcdefghij")
if !strings.Contains(got, "共4项") {
t.Errorf("MaskCookie multi = %q, want '共4项'", got)
}
if strings.Count(got, "; ") > 3 {
t.Errorf("MaskCookie multi shows too many pairs: %q", got)
}
// 缺失 = 号的段被跳过
got = MaskCookie("broken; valid=12345678")
if strings.Contains(got, "broken") {
t.Errorf("MaskCookie should skip pair without '=': %q", got)
}
}
func TestMergeCookie(t *testing.T) {
// 覆盖已有
got := MergeCookie("a=1; b=2; c=3", "b", "20")
if got != "a=1; b=20; c=3" {
t.Errorf("MergeCookie overwrite = %q, want 'a=1; b=20; c=3'", got)
}
// 追加新字段
got = MergeCookie("a=1", "b", "2")
if got != "a=1; b=2" {
t.Errorf("MergeCookie append = %q, want 'a=1; b=2'", got)
}
// 空值不追加
got = MergeCookie("a=1", "b", "")
if got != "a=1" {
t.Errorf("MergeCookie empty value = %q, want 'a=1'", got)
}
// 空值覆盖已有:当前实现对空值仍保留 name= 形式(生产调用均传非空值)
got = MergeCookie("a=1; b=2", "a", "")
if got != "a=; b=2" {
t.Errorf("MergeCookie empty overwrite = %q, want 'a=; b=2'", got)
}
}
func TestSafeFilename(t *testing.T) {
got := SafeFilename("a/b:c*d?e\"f<g>h|i")
want := "a_b_c_d_e_f_g_h_i"
if got != want {
t.Errorf("SafeFilename = %q, want %q", got, want)
}
}
func TestCloneStringMap(t *testing.T) {
in := map[string]string{"a": "1", "b": "2"}
out := CloneStringMap(in)
out["a"] = "changed"
if in["a"] != "1" {
t.Errorf("CloneStringMap should be independent, original mutated")
}
if len(out) != 2 {
t.Errorf("CloneStringMap length = %d, want 2", len(out))
}
}
func TestTrimForLog(t *testing.T) {
if got := TrimForLog("hello", 10); got != "hello" {
t.Errorf("TrimForLog short = %q, want 'hello'", got)
}
got := TrimForLog("abcdefghij", 5)
if got != "abcde..." {
t.Errorf("TrimForLog long = %q, want 'abcde...'", got)
}
if got := TrimForLog(" spaced ", 10); got != "spaced" {
t.Errorf("TrimForLog trim = %q, want 'spaced'", got)
}
}
func TestEmptyDefault(t *testing.T) {
if got := EmptyDefault("", "fb"); got != "fb" {
t.Errorf("EmptyDefault empty = %q, want 'fb'", got)
}
if got := EmptyDefault("x", "fb"); got != "x" {
t.Errorf("EmptyDefault non-empty = %q, want 'x'", got)
}
if got := EmptyDefault(" ", "fb"); got != "fb" {
t.Errorf("EmptyDefault whitespace = %q, want 'fb'", got)
}
}
+11 -1
View File
@@ -2,6 +2,9 @@ package main
import ( import (
"embed" "embed"
"log"
"os"
"path/filepath"
"github.com/wailsapp/wails/v2" "github.com/wailsapp/wails/v2"
"github.com/wailsapp/wails/v2/pkg/options" "github.com/wailsapp/wails/v2/pkg/options"
@@ -30,6 +33,13 @@ func main() {
}, },
}) })
if err != nil { if err != nil {
println("Error:", err.Error()) log.Printf("启动失败: %v", err)
// GUI 应用无控制台,把启动错误写入崩溃日志文件,便于用户事后排查。
if dir, derr := os.UserCacheDir(); derr == nil {
path := filepath.Join(dir, "douyu-go", "startup_error.log")
_ = os.MkdirAll(filepath.Dir(path), 0o755)
_ = os.WriteFile(path, []byte("斗鱼抢购系统启动失败:\n"+err.Error()+"\n"), 0o644)
}
os.Exit(1)
} }
} }
-1
View File
@@ -1 +0,0 @@
测试1----pwd123456----dy_did=944d384a673e7ea5b66faf9a00081701; Hm_lvt_e99aee90ec1b2106afe7ec3b199020a7=1781834308; HMACCOUNT=5476EE8F6942A0B2; PHPSESSID=9nhg0uqbl25pdfmg1hsan2krd2; acf_auth=0703%2FCjm7ZivfSUpfXtIwfOxTFX0yh3JCy2vnhET8ltFovlK9a3ddS%2Bz%2FVVueiEw86b66k%2FY45iw9fJpa2gSmfjPO%2FhUo8jLudd8nxl%2BIYq%2FzEzDm7As09k; acf_jwt_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJtZDUifQ.eyJ1aWQiOjEwMDAxMTkwMywiY3QiOjAsInN1YiI6InN0IiwiYXVkIjpbImR5Iiwibm9uZSJdLCJiaXoiOjEsImx0a2lkIjo1OTQ3ODQ0NCwic3RrIjoiNzUxODgzOWIwODMyZDBkYiIsImV4cCI6MTc4MjQzOTExNywiaWF0IjoxNzgxODM0MzE3LCJrZXkiOiJkeS1qd3QtbWQ1In0.NWJkOTk1NmY1ZTFkMjY4MjI1YjA2OTllZWE3Yjg4MDc; acf_dmjwt_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJtZDUifQ.eyJ1aWQiOjEwMDAxMTkwMywiY3QiOjAsInN1YiI6InN0IiwiYXVkIjpbImRtIiwibm9uZSJdLCJiaXoiOjEsImx0a2lkIjo1OTQ3ODQ0NCwic3RrIjoiNzUxODgzOWIwODMyZDBkYiIsImV4cCI6MTc4MjQzOTExNywiaWF0IjoxNzgxODM0MzE3LCJrZXkiOiJkeS1qd3QtbWQ1In0.ODBlYzhjZjQyMjA5YWZlZmFiODM4Y2Y1MTY3MmM4YmM; dy_auth=3730Bv0NTC35FhSBwq4Dgbv9HQHiFW%2FMgNQ4nFYsWOKnkxK0nD05KbTdELoCwTMwDByVcKQuQMTf1y54fFo9wff5OYaKrXZpRxu85hICUrG65S1g2DgOpAc; wan_auth37wan=188025b16b88OdcbZFsJpwoT6D60nMeXnM27aYMOolAFceHZgxmONVYYDUoNNu2cDhQ00YrHcBm7q9fYncX%2BsiwRuUQz5Yxdw1co%2B7lr3Hr6J99qqfQ; acf_uid=100011903; acf_username=100011903; acf_nickname=%E6%9D%A8%E5%8D%8A%E4%BB%99z; acf_own_room=0; acf_groupid=1; acf_phonestatus=1; acf_avatar=https%3A%2F%2Fapic.douyucdn.cn%2Fupload%2Favanew%2Fface%2F201701%2F04%2F02%2F497692b08166ab43377dcfb97f418bc8_; acf_ct=0; acf_ltkid=59478444; acf_biz=1; acf_stk=7518839b0832d0db; mantine-color-scheme-value=light; dy_did=944d384a673e7ea5b66faf9a00081701; dy_teen_mode=%7B%22uid%22%3A%22100011903%22%2C%22status%22%3A0%2C%22birthday%22%3A%22%22%2C%22password%22%3A%22%22%7D; acf_ssid=1729388853998258962; acf_web_id=7652920204304914958; acf_ab_pmt=20100212%23webnewhome%23B%2C20100395%23webslidetag%23B%2C20100249%23webTagRank%23B%2C20100248%23webTagHover%23B%2C20100254%23WebTool0703%23new%2C20100272%23all_lists_sort%23c; acf_ab_ver_all=20100212%2C20100395%2C20100249%2C20100248%2C20100254%2C20100272; acf_ab_vs=webnewhome%3DB%2Cwebslidetag%3DB%2CwebTagRank%3DB%2CwebTagHover%3DB%2CWebTool0703%3Dnew%2Call_lists_sort%3Dc; acf_ccn=5ee6ac7651f3dc89abd571425e2c4f4f; acf_did=944d384a673e7ea5b66faf9a00081701; Hm_lpvt_e99aee90ec1b2106afe7ec3b199020a7=1781834382; post-csrfToken=1useglzm5he; game_did=zUF63jQB0AWN2AOylrwecMiLNA3-qnj54sW; huya_ua=outer_pc&0.0.1&websocket&&h5_/9263298; _ga=GA1.1.421749312.1781834386; _ga_5JKQ7DTEXC=GS2.1.s1781834386$o1$g0$t1781834386$j60$l0$h1960451153; guid=0a7d931b92a2346a260165196619e916
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,8 +0,0 @@
2026/06/27 18:21:44.590 [日志][success] 日志文件已启用: C:\Users\Administrator\Desktop\新建文件夹\logs\douyu_20260627_182144.log
2026/06/27 18:21:44.590 [配置][success] 配置加载完成: C:\Users\Administrator\Desktop\新建文件夹\config.json
2026/06/27 18:21:44.602 [字体][success] 字体加载完成: C:\Windows\Fonts\msyh.ttc
2026/06/27 18:21:44.603 [账号][success] 账号加载完成: 29 个,来源=C:\Users\Administrator\Desktop\新建文件夹\data\user.txt
2026/06/27 18:21:44.723 [时间][success] 服务端时间获取成功: 2026-06-27 18:21:44.723
2026/06/27 18:21:44.723 [系统][success] 应用启动完成 | 账号: 29
2026/06/27 18:21:45.107 [网络][info] 请求完成: 商品列表 GET /wgapi/ordnc/activity/peace/storehome 耗时=291ms
2026/06/27 18:21:45.107 [商品][success] 商品刷新完成: 69 个,刷新时间=18:21:45.107