优化抢购成功图片生成逻辑
This commit is contained in:
@@ -97,6 +97,9 @@ func (a *App) startup(ctx context.Context) {
|
||||
|
||||
// shutdown Wails 应用关闭时调用。
|
||||
func (a *App) shutdown(ctx context.Context) {
|
||||
if a.scheduler != nil {
|
||||
a.scheduler.Close()
|
||||
}
|
||||
if a.closeTrace != nil {
|
||||
a.closeTrace()
|
||||
}
|
||||
@@ -629,9 +632,12 @@ func (a *App) SaveSettings(cfg types.Config) map[string]any {
|
||||
|
||||
func (a *App) setProducts(products []types.Product, fetchedAt time.Time) {
|
||||
a.productsMu.Lock()
|
||||
defer a.productsMu.Unlock()
|
||||
a.products = products
|
||||
a.productsAt = fetchedAt
|
||||
a.productsMu.Unlock()
|
||||
if a.scheduler != nil {
|
||||
a.scheduler.UpdateProducts(products)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) productPayload(source string) types.ProductPayload {
|
||||
|
||||
+11
-2
@@ -23,11 +23,19 @@ func SaveSuccessImage(account types.Account, product types.Product, roleName str
|
||||
if font == nil {
|
||||
return
|
||||
}
|
||||
if successDir == "" {
|
||||
successDir = constants.DefaultSuccessDir
|
||||
}
|
||||
if err := os.MkdirAll(successDir, 0755); err != nil {
|
||||
logger.LogEvent("图片", "error", "成功图片目录创建失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
productName := product.CommodityName
|
||||
if productName == "" {
|
||||
productName = product.CommodityID
|
||||
}
|
||||
now := time.Now().In(constants.CST)
|
||||
|
||||
width, height := 600, 280
|
||||
img := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
@@ -59,7 +67,7 @@ func SaveSuccessImage(account types.Account, product types.Product, roleName str
|
||||
Color color.Color
|
||||
}{
|
||||
{productName, 20, 25, 42, white},
|
||||
{"兑换时间:" + time.Now().In(constants.CST).Format("2006年01月02日 15:04:05"), 16, 25, 110, black},
|
||||
{"兑换时间:" + now.Format("2006年01月02日 15:04:05"), 16, 25, 110, black},
|
||||
{"游戏昵称:" + utils.EmptyDefault(roleName, "未知"), 16, 25, 150, black},
|
||||
{"兑换账号:" + account.Name, 16, 25, 190, black},
|
||||
}
|
||||
@@ -69,7 +77,8 @@ func SaveSuccessImage(account types.Account, product types.Product, roleName str
|
||||
_, _ = ctx.DrawString(line.Text, freetype.Pt(line.X, line.Y))
|
||||
}
|
||||
|
||||
name := utils.SafeFilename(fmt.Sprintf("%s_%s_%d.png", account.Name, productName, time.Now().Unix()))
|
||||
ownerName := utils.EmptyDefault(roleName, account.Name)
|
||||
name := utils.SafeFilename(fmt.Sprintf("%s_%s_%s.png", ownerName, productName, now.Format("20060102_150405.000")))
|
||||
path := filepath.Join(successDir, name)
|
||||
file, err := os.Create(path)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package image
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/golang/freetype/truetype"
|
||||
|
||||
"douyu_go/internal/logger"
|
||||
"douyu_go/internal/types"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultSuccessImageWorkers = 1
|
||||
defaultSuccessImageQueue = 256
|
||||
)
|
||||
|
||||
type successImageJob struct {
|
||||
Account types.Account
|
||||
Product types.Product
|
||||
RoleName string
|
||||
}
|
||||
|
||||
// SuccessImageSaver 用后台队列生成成功图片,避免图片编码和磁盘写入占用抢购链路。
|
||||
type SuccessImageSaver struct {
|
||||
font *truetype.Font
|
||||
successDir string
|
||||
ch chan successImageJob
|
||||
wg sync.WaitGroup
|
||||
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
}
|
||||
|
||||
// NewSuccessImageSaver 创建成功图片后台保存器。
|
||||
func NewSuccessImageSaver(font *truetype.Font, successDir string, workers, queueSize int) *SuccessImageSaver {
|
||||
if font == nil {
|
||||
return nil
|
||||
}
|
||||
if workers <= 0 {
|
||||
workers = defaultSuccessImageWorkers
|
||||
}
|
||||
if queueSize <= 0 {
|
||||
queueSize = defaultSuccessImageQueue
|
||||
}
|
||||
saver := &SuccessImageSaver{
|
||||
font: font,
|
||||
successDir: successDir,
|
||||
ch: make(chan successImageJob, queueSize),
|
||||
}
|
||||
for i := 0; i < workers; i++ {
|
||||
saver.wg.Add(1)
|
||||
go saver.run()
|
||||
}
|
||||
return saver
|
||||
}
|
||||
|
||||
// Enqueue 投递成功图片任务;队列满时丢弃图片任务,优先保护抢购请求。
|
||||
func (s *SuccessImageSaver) Enqueue(account types.Account, product types.Product, roleName string) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
job := successImageJob{
|
||||
Account: account,
|
||||
Product: product,
|
||||
RoleName: roleName,
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case s.ch <- job:
|
||||
default:
|
||||
logger.LogEvent("图片", "warn", "成功图片队列已满,已跳过: 账号=%s 商品=%s", account.Name, product.CommodityID)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SuccessImageSaver) run() {
|
||||
defer s.wg.Done()
|
||||
for job := range s.ch {
|
||||
SaveSuccessImage(job.Account, job.Product, job.RoleName, s.font, s.successDir)
|
||||
}
|
||||
}
|
||||
|
||||
// Close 关闭后台队列并等待已投递图片保存完成。
|
||||
func (s *SuccessImageSaver) Close() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
if s.closed {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.closed = true
|
||||
close(s.ch)
|
||||
s.mu.Unlock()
|
||||
s.wg.Wait()
|
||||
}
|
||||
@@ -48,6 +48,8 @@ type Scheduler struct {
|
||||
paths types.AppPaths
|
||||
font *truetype.Font
|
||||
|
||||
successImages *image.SuccessImageSaver
|
||||
|
||||
concurrency int // 抢购并发数
|
||||
attempts int // 单号重试次数
|
||||
|
||||
@@ -73,6 +75,9 @@ type Scheduler struct {
|
||||
|
||||
attemptCacheMu sync.RWMutex
|
||||
attemptCache map[string]*types.AttemptCache // 激进模式缓存
|
||||
|
||||
productsMu sync.RWMutex
|
||||
products map[string]types.Product
|
||||
}
|
||||
|
||||
// New 创建抢购调度器。
|
||||
@@ -84,18 +89,49 @@ func New(cli *client.DouyuClient, paths types.AppPaths, font *truetype.Font, con
|
||||
attempts = constants.DefaultAttempts
|
||||
}
|
||||
return &Scheduler{
|
||||
client: cli,
|
||||
paths: paths,
|
||||
font: font,
|
||||
client: cli,
|
||||
paths: paths,
|
||||
font: font,
|
||||
successImages: image.NewSuccessImageSaver(
|
||||
font,
|
||||
paths.SuccessDir,
|
||||
1,
|
||||
256,
|
||||
),
|
||||
concurrency: concurrency,
|
||||
attempts: attempts,
|
||||
retryStages: retryStages,
|
||||
seckillMode: seckillMode,
|
||||
results: make(map[string]string),
|
||||
attemptCache: make(map[string]*types.AttemptCache),
|
||||
products: make(map[string]types.Product),
|
||||
}
|
||||
}
|
||||
|
||||
// Close 关闭调度器的后台资源。
|
||||
func (s *Scheduler) Close() {
|
||||
if s.successImages != nil {
|
||||
s.successImages.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateProducts 更新商品缓存,抢购成功图片会优先使用中文商品名。
|
||||
func (s *Scheduler) UpdateProducts(products []types.Product) {
|
||||
next := make(map[string]types.Product, len(products))
|
||||
for _, product := range products {
|
||||
if product.CommodityID == "" {
|
||||
continue
|
||||
}
|
||||
if product.CommodityName == "" {
|
||||
product.CommodityName = product.CommodityID
|
||||
}
|
||||
next[product.CommodityID] = product
|
||||
}
|
||||
s.productsMu.Lock()
|
||||
s.products = next
|
||||
s.productsMu.Unlock()
|
||||
}
|
||||
|
||||
// UpdateSettings 运行时更新并发数、重试次数、重试间隔和抢购模式。
|
||||
func (s *Scheduler) UpdateSettings(concurrency, attempts int, retryStages []types.RetryStage, seckillMode types.SeckillMode) {
|
||||
if concurrency > 0 {
|
||||
@@ -502,7 +538,7 @@ func (s *Scheduler) executeRound(attempts []types.ExchangeAttempt) roundOutcome
|
||||
|
||||
if result.OK {
|
||||
logger.LogAccountEvent("抢购", "success", result.Account, "成功: 账号=%s 商品=%s 第%d包 %s", result.Account, result.Product, result.Attempt, result.Message)
|
||||
go image.SaveSuccessImage(attempt.Account, attempt.Product, result.RoleName, s.font, s.paths.SuccessDir)
|
||||
s.enqueueSuccessImage(attempt.Account, attempt.Product, result.RoleName)
|
||||
|
||||
mu.Lock()
|
||||
outcome.successAccounts[attempt.Account.Name] = true
|
||||
@@ -514,7 +550,7 @@ func (s *Scheduler) executeRound(attempts []types.ExchangeAttempt) roundOutcome
|
||||
outcome.cooldownAccounts[attempt.Account.Name] = time.Now().Add(jitterDuration(cooldown))
|
||||
mu.Unlock()
|
||||
}
|
||||
terminalAccount, terminalProduct, isSuccess, reason := classifyRetryStop(result.Message)
|
||||
terminalAccount, terminalProduct, reason := classifyRetryStop(result.Message)
|
||||
if terminalAccount || terminalProduct {
|
||||
mu.Lock()
|
||||
if terminalAccount {
|
||||
@@ -523,12 +559,6 @@ func (s *Scheduler) executeRound(attempts []types.ExchangeAttempt) roundOutcome
|
||||
if terminalProduct {
|
||||
outcome.stoppedProducts[attempt.Product.CommodityID] = reason
|
||||
}
|
||||
// 兑换上限也算成功
|
||||
if isSuccess {
|
||||
outcome.successAccounts[attempt.Account.Name] = true
|
||||
logger.LogAccountEvent("抢购", "success", result.Account, "成功(兑换上限): 账号=%s 商品=%s 第%d包", result.Account, result.Product, result.Attempt)
|
||||
go image.SaveSuccessImage(attempt.Account, attempt.Product, result.RoleName, s.font, s.paths.SuccessDir)
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}
|
||||
@@ -582,19 +612,19 @@ func retryCooldownDuration(message string) time.Duration {
|
||||
}
|
||||
}
|
||||
|
||||
func classifyRetryStop(message string) (account bool, product bool, success bool, reason string) {
|
||||
func classifyRetryStop(message string) (account bool, product bool, reason string) {
|
||||
switch {
|
||||
case strings.Contains(message, "商品本次活动库存已耗完"):
|
||||
// 库存耗尽不停止,继续重试(斗鱼可能会补货)
|
||||
return false, false, false, ""
|
||||
return false, false, ""
|
||||
case strings.Contains(message, "您已达本次活动兑换上限"):
|
||||
return true, false, true, "已抢到(兑换上限)"
|
||||
return true, false, "已达兑换上限"
|
||||
case strings.Contains(message, "未绑定账号"):
|
||||
return true, false, false, "账号未绑定角色"
|
||||
return true, false, "账号未绑定角色"
|
||||
case strings.Contains(message, "需要开通精英手册"):
|
||||
return true, false, false, "账号不满足精英手册条件"
|
||||
return true, false, "账号不满足精英手册条件"
|
||||
default:
|
||||
return false, false, false, ""
|
||||
return false, false, ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -614,7 +644,7 @@ func (s *Scheduler) buildAttempts(accountProducts map[string]string) []types.Exc
|
||||
if commodityID == "" {
|
||||
continue
|
||||
}
|
||||
product := types.Product{CommodityID: commodityID, CommodityName: commodityID}
|
||||
product := s.productForCommodityID(commodityID)
|
||||
for i := 1; i <= s.attempts; i++ {
|
||||
attempts = append(attempts, types.ExchangeAttempt{
|
||||
Account: account,
|
||||
@@ -626,6 +656,26 @@ func (s *Scheduler) buildAttempts(accountProducts map[string]string) []types.Exc
|
||||
return attempts
|
||||
}
|
||||
|
||||
func (s *Scheduler) productForCommodityID(commodityID string) types.Product {
|
||||
s.productsMu.RLock()
|
||||
product, ok := s.products[commodityID]
|
||||
s.productsMu.RUnlock()
|
||||
if ok {
|
||||
if product.CommodityName == "" {
|
||||
product.CommodityName = commodityID
|
||||
}
|
||||
return product
|
||||
}
|
||||
return types.Product{CommodityID: commodityID, CommodityName: commodityID}
|
||||
}
|
||||
|
||||
func (s *Scheduler) enqueueSuccessImage(account types.Account, product types.Product, roleName string) {
|
||||
if s.successImages == nil {
|
||||
return
|
||||
}
|
||||
s.successImages.Enqueue(account, product, roleName)
|
||||
}
|
||||
|
||||
func warmupKey(attempt types.ExchangeAttempt) string {
|
||||
return fmt.Sprintf("%s|%s|%d", attempt.Account.Name, attempt.Product.CommodityID, attempt.Index)
|
||||
}
|
||||
@@ -826,6 +876,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
|
||||
Qualified: true,
|
||||
LastCheck: time.Now(),
|
||||
})
|
||||
result.RoleName = roleName
|
||||
result.Message = "失败|" + err.Error()
|
||||
return result
|
||||
}
|
||||
@@ -886,6 +937,7 @@ func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.Exchange
|
||||
Qualified: true,
|
||||
LastCheck: time.Now(),
|
||||
})
|
||||
result.RoleName = cache.RoleName
|
||||
errMsg := err.Error()
|
||||
// 检查是否是 CSRF 相关错误,如果是则回退到标准模式
|
||||
if strings.Contains(errMsg, "csrf") || strings.Contains(errMsg, "CSRF") || strings.Contains(errMsg, "token") {
|
||||
|
||||
Reference in New Issue
Block a user