feat: 完善代理池与抢购链路,发布 0.5.0

This commit is contained in:
yml
2026-11-20 00:48:21 +08:00
parent 2f087ac7f1
commit 98b3dc4b16
28 changed files with 1522 additions and 204 deletions
@@ -6,6 +6,7 @@ import { useProducts } from '@/composables/useProducts'
import type { Product } from '@/composables/useProducts'
import { useActivity } from '@/composables/useActivity'
import { useToast } from '@/composables/useToast'
import { formatExchangeTime, formatShortExchangeTime } from '@/utils/formatTime'
import {
ExportLatestXiaodianReport,
QueryExchangeRecords,
@@ -242,23 +243,10 @@ const recordSummary = (accountName: string) => {
if (!records.length) return ''
const latest = records[0]
const name = latest.commodityName || latest.commodityId || '-'
const time = formatShortTime(latest.time || latest.buyTime || '')
const time = formatShortExchangeTime(latest.time || latest.buyTime || '')
return time ? `${name} · ${time}` : name
}
const formatShortTime = (value: string) => {
if (!value) return ''
const text = String(value)
const match = text.match(/(\d{2})[-/](\d{2})\s+(\d{2}:\d{2})/)
if (match) return `${match[1]}-${match[2]} ${match[3]}`
const numeric = Number(text)
if (Number.isFinite(numeric) && numeric > 0) {
const date = new Date(numeric < 10_000_000_000 ? numeric * 1000 : numeric)
return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}
return text.replace('T', ' ').slice(0, 16)
}
const getLookupResult = (accountName: string) => exchangeLookup.value?.results[accountName]
const getMatchedRecord = (accountName: string) => {
@@ -304,8 +292,6 @@ const getResultMessage = (name: string) => {
return msg.length > 46 ? msg.slice(0, 46) + '...' : msg
}
const formatTime = (value: string) => value ? value.replace('T', ' ') : '-'
const orderStatus = (status: string) => {
const labels: Record<string, { text: string; cls: string }> = {
'0': { text: '待支付', cls: 'order-pending' },
@@ -619,7 +605,7 @@ const closeExchangeRecords = () => {
<div v-if="record.showName" class="account-sub">{{ record.showName }}</div>
</td>
<td>×{{ record.exchangeNum || 1 }}</td>
<td>{{ formatTime(record.time) }}</td>
<td>{{ formatExchangeTime(record.time) }}</td>
<td>{{ record.score || '-' }}</td>
<td>{{ record.nickName || '-' }}</td>
</tr>
@@ -632,8 +618,8 @@ const closeExchangeRecords = () => {
<tbody>
<tr v-for="(record, index) in recordsModal.records" :key="`${record.commodityId}-${record.buyTime}-${index}`">
<td><div class="record-product">{{ record.commodityName || record.commodityId }}</div><div v-if="record.quantity > 1" class="account-sub">数量 ×{{ record.quantity }}</div></td>
<td>{{ formatTime(record.buyTime) }}</td>
<td>{{ formatTime(record.payTime) }}</td>
<td>{{ formatExchangeTime(record.buyTime) }}</td>
<td>{{ formatExchangeTime(record.payTime) }}</td>
<td>{{ record.price }}</td>
<td><span class="order-status" :class="orderStatus(record.status).cls">{{ orderStatus(record.status).text }}</span></td>
<td>{{ record.roleName || '-' }}</td>
@@ -400,7 +400,7 @@ onUnmounted(() => {
<button v-if="isXiaodian" class="btn btn-primary" @click="openBindQRCode">获取绑定二维码</button>
<button v-if="isXiaodian" class="btn btn-fixed" @click="startFixedBuy">固定抢购</button>
</div>
<div class="schedule-item target-item">
<div v-if="isXiaodian" class="schedule-item target-item">
<label>目标</label>
<input v-model="targetTime" type="time" step="1">
</div>
@@ -469,8 +469,8 @@ onUnmounted(() => {
</div>
</div>
<!-- 非和平小店仅显示目标时间,保持原有定时布局。 -->
<div v-else class="schedule-bar">
<!-- 非和平小店只保留一处目标时间。 -->
<div v-if="!isXiaodian" class="schedule-bar">
<div class="schedule-item">
<label>目标</label>
<input
@@ -4,6 +4,7 @@ import { useProducts } from '@/composables/useProducts'
import { useAccounts } from '@/composables/useAccounts'
import { useActivity } from '@/composables/useActivity'
import { useToast } from '@/composables/useToast'
import { formatExchangeTime } from '@/utils/formatTime'
import { QueryXiaodianExchangeRecords } from '@wails/go/app/App'
const { selectedProductId, selectedProductName } = useProducts()
@@ -56,15 +57,6 @@ const queryRecords = async () => {
}
}
const formatTime = (value: string) => {
if (!value) return '-'
const numeric = Number(value)
if (Number.isFinite(numeric) && numeric > 0) {
return new Date(numeric < 10_000_000_000 ? numeric * 1000 : numeric).toLocaleString('zh-CN')
}
return value.replace('T', ' ')
}
watch(selectedProductId, () => {
queryResult.value = null
})
@@ -133,7 +125,7 @@ watch(selectedProductId, () => {
<div v-for="(record, index) in row.records" :key="`${row.name}-${index}`" class="record-detail">
<span class="detail-name">{{ record.commodityName || record.commodityId }}</span>
<span class="detail-quantity">×{{ record.quantity || 1 }}</span>
<span class="detail-time">{{ formatTime(record.buyTime) }}</span>
<span class="detail-time">{{ formatExchangeTime(record.buyTime) }}</span>
<span class="detail-status">状态 {{ record.status || '-' }}</span>
</div>
</div>
+101 -4
View File
@@ -1,7 +1,8 @@
<script setup lang="ts">
import { ref } from 'vue'
import { computed, onMounted, ref } from 'vue'
import { useTheme } from '@/composables/useTheme'
import { useScheduler } from '@/composables/useScheduler'
import { useSettings } from '@/composables/useSettings'
import StatusGrid from '@/components/console/StatusGrid.vue'
import ControlStrip from '@/components/console/ControlStrip.vue'
import AccountTable from '@/components/account/AccountTable.vue'
@@ -16,13 +17,44 @@ defineProps<{
const { theme, toggleTheme } = useTheme()
const { runState, countdownSeconds, formatRemain } = useScheduler()
const { settings, loadSettings } = useSettings()
const settingsModalRef = ref<InstanceType<typeof SettingsModal> | null>(null)
const currentPage = ref<'console' | 'ck' | 'exchange'>('console')
const openSettings = () => {
settingsModalRef.value?.open()
const proxyAutoFetchReady = computed(() => (
settings.value.proxyEnabled
&& settings.value.autoFetchProxyOnSchedule
&& !!settings.value.proxyApi.trim()
))
const proxyNeedsApi = computed(() => (
settings.value.proxyEnabled
&& settings.value.autoFetchProxyOnSchedule
&& !settings.value.proxyApi.trim()
))
const proxySummary = computed(() => {
if (!settings.value.proxyEnabled) return '代理未启用'
const size = settings.value.accountsPerProxy || 5
const spare = settings.value.proxySparePercent || 25
if (!settings.value.autoFetchProxyOnSchedule) return `代理 · ${size}号/组 · 备用${spare}%`
if (!settings.value.proxyApi.trim()) return `代理 · ${size}号/组 · 缺少 API`
return `代理 · ${size}号/组 · 备用${spare}% · 预取`
})
const proxyTitle = computed(() => {
if (!settings.value.proxyEnabled) return '代理尚未启用,点击配置'
if (proxyNeedsApi.value) return '已开启定时预取,但缺少代理提取 API;点击配置'
if (proxyAutoFetchReady.value) return '定时抢购触发前 30 秒自动提取并校验代理;点击查看设置'
return '代理已启用,点击打开代理设置'
})
const openSettings = (section = '') => {
settingsModalRef.value?.open(section)
}
onMounted(loadSettings)
</script>
<template>
@@ -38,7 +70,22 @@ const openSettings = () => {
<span v-if="countdownSeconds > 0 && currentPage === 'console'" class="countdown-badge">{{ formatRemain(countdownSeconds) }}</span>
</div>
<div class="top-actions">
<button class="btn btn-ghost icon-btn" title="设置" aria-label="设置" @click="openSettings">⚙</button>
<button
class="proxy-quick"
:class="{
active: settings.proxyEnabled,
scheduled: proxyAutoFetchReady,
warning: proxyNeedsApi
}"
:title="proxyTitle"
@click="openSettings('proxy')"
>
{{ proxySummary }}
</button>
<button class="btn btn-ghost settings-button" title="设置" aria-label="设置" @click="openSettings()">
<span aria-hidden="true">⚙</span>
<span>设置</span>
</button>
<button class="btn btn-ghost icon-btn theme-toggle" :title="theme === 'light' ? '切换到暗色' : '切换到亮色'" :aria-label="theme === 'light' ? '切换到暗色' : '切换到亮色'" @click="toggleTheme">{{ theme === 'light' ? '☀' : '☾' }}</button>
</div>
</header>
@@ -88,6 +135,50 @@ const openSettings = () => {
.top-actions { gap: 6px; }
.nav-tabs { gap: 4px; }
.proxy-quick {
height: 30px;
padding: 0 10px;
border: 1px solid var(--line);
border-radius: 999px;
background: var(--surface-2);
color: var(--muted);
cursor: pointer;
font-size: 11px;
white-space: nowrap;
}
.proxy-quick:hover {
border-color: var(--accent-border);
color: var(--text-strong);
}
.proxy-quick.active {
color: var(--success);
border-color: var(--success);
background: var(--success-soft);
}
.proxy-quick.scheduled {
color: var(--accent);
border-color: var(--accent-border);
background: var(--accent-soft);
}
.proxy-quick.warning {
color: var(--warning);
border-color: var(--warning);
background: var(--warning-soft);
}
.settings-button {
display: inline-flex;
align-items: center;
gap: 6px;
height: 30px;
padding: 0 10px;
font-size: 12px;
}
.nav-tab {
height: 28px;
padding: 0 12px;
@@ -129,4 +220,10 @@ const openSettings = () => {
.right { overflow: visible; min-height: auto; }
.console-workspace { min-height: 520px; padding: 14px; }
}
@media (max-width: 900px) {
.console-head { flex-wrap: wrap; }
.top-actions { width: 100%; justify-content: flex-end; }
.proxy-quick { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
}
</style>
+173 -30
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref } from 'vue'
import { computed, nextTick, ref } from 'vue'
import { useSettings, type RetryStage } from '@/composables/useSettings'
import { useToast } from '@/composables/useToast'
import { TestProxy, FetchProxy } from '@wails/go/app/App'
@@ -8,6 +8,7 @@ const { settings, loadSettings, saveSettings } = useSettings()
const { showToast } = useToast()
const visible = ref(false)
const proxySectionRef = ref<HTMLElement | null>(null)
const formData = ref({
timeApiUrl: '',
activity: '',
@@ -22,8 +23,10 @@ const formData = ref({
proxyEnabled: false,
proxyUrl: '',
proxyApi: '',
proxyExpiresAt: 0,
autoFetchProxyOnSchedule: false,
accountsPerProxy: 5,
proxySparePercent: 25,
proxyAutoWhitelist: false,
proxyWhitelistReplace: true,
proxyWhitelistPassword: '',
@@ -34,6 +37,31 @@ const testingProxy = ref(false)
const testProxyResult = ref<{ success?: boolean; text?: string; error?: string } | null>(null)
const fetchingProxy = ref(false)
const proxyOverviewTitle = computed(() => (
formData.value.proxyEnabled ? '代理已启用' : '代理未启用'
))
const proxyOverviewDetail = computed(() => {
if (!formData.value.proxyEnabled) return '启用后可配置账号分组、提取 API 和自动预取'
const size = formData.value.accountsPerProxy || 5
const spare = formData.value.proxySparePercent || 25
if (!formData.value.autoFetchProxyOnSchedule) return `当前每 ${size} 个账号一个代理,备用 ${spare}%`
if (!formData.value.proxyApi.trim()) return '已开启自动预取,但尚未填写代理提取 API'
return `每 ${size} 个账号一组,备用 ${spare}%;定时抢购触发前 30 秒自动预取`
})
const proxyAutoFetchReady = computed(() => (
formData.value.proxyEnabled
&& formData.value.autoFetchProxyOnSchedule
&& !!formData.value.proxyApi.trim()
))
const proxyAutoFetchMissingAPI = computed(() => (
formData.value.proxyEnabled
&& formData.value.autoFetchProxyOnSchedule
&& !formData.value.proxyApi.trim()
))
const handleTestProxy = async () => {
const target = formData.value.proxyUrl.trim()
if (!target) {
@@ -77,6 +105,7 @@ const handleFetchProxy = async () => {
const res = await FetchProxy(api)
if (res.success && res.proxyUrl) {
formData.value.proxyUrl = res.proxyUrl
formData.value.proxyExpiresAt = res.expiresAt || 0
formData.value.proxyEnabled = true
const expires = res.expiresAt
? new Date(res.expiresAt).toLocaleString()
@@ -98,7 +127,7 @@ const handleFetchProxy = async () => {
}
}
const open = async () => {
const open = async (section = '') => {
await loadSettings()
formData.value = {
...settings.value,
@@ -106,6 +135,10 @@ const open = async () => {
}
testProxyResult.value = null
visible.value = true
if (section === 'proxy') {
await nextTick()
proxySectionRef.value?.scrollIntoView({ block: 'start', behavior: 'smooth' })
}
}
const close = () => {
@@ -146,21 +179,32 @@ defineExpose({ open, close })
<button class="modal-close" @click="close">×</button>
</div>
<div class="modal-body">
<!-- 时间 API -->
<div class="form-group">
<label class="form-label">时间 API 地址</label>
<input
v-model="formData.timeApiUrl"
class="form-input"
type="text"
placeholder="留空使用默认地址"
>
<div class="form-hint">用于获取斗鱼服务端时间,一般不需要修改</div>
</div>
<!-- 实例独立代理设置 (防多开 IP 限流/风控) -->
<div class="form-section">
<div class="form-section-title">🌐 实例独立代理设置 (防多开 IP 限流)</div>
<div ref="proxySectionRef" class="form-section proxy-section">
<div class="form-section-title">🌐 代理设置(品赞 / 通用)</div>
<div
class="proxy-overview"
:class="{
enabled: formData.proxyEnabled,
active: proxyAutoFetchReady,
warning: proxyAutoFetchMissingAPI
}"
>
<div class="proxy-overview-main">
<span class="proxy-status-dot"></span>
<strong>{{ proxyOverviewTitle }}</strong>
<span>{{ proxyOverviewDetail }}</span>
</div>
<button
v-if="!formData.proxyEnabled"
type="button"
class="btn btn-ghost btn-sm"
@click="formData.proxyEnabled = true"
>
立即启用
</button>
</div>
<div class="form-group">
<div class="toggle-row">
@@ -176,18 +220,34 @@ defineExpose({ open, close })
</div>
<div v-if="formData.proxyEnabled" class="proxy-config-area">
<div class="form-group">
<label class="form-label">每个代理账号数</label>
<input
v-model.number="formData.accountsPerProxy"
class="form-input"
type="number"
min="1"
max="100"
step="1"
>
<div class="form-hint">
例如填 5:30 个账号会稳定分成 6 组,每组使用独立代理连接池;定时抢购会按组分别提取并校验代理。
<div class="form-row">
<div class="form-group">
<label class="form-label">每个代理账号数</label>
<input
v-model.number="formData.accountsPerProxy"
class="form-input"
type="number"
min="1"
max="100"
step="1"
>
<div class="form-hint">
30 个账号填 5 会分成 6 个活动代理组,每组使用独立连接池。
</div>
</div>
<div class="form-group">
<label class="form-label">备用代理比例 (%)</label>
<input
v-model.number="formData.proxySparePercent"
class="form-input"
type="number"
min="1"
max="100"
step="1"
>
<div class="form-hint">
默认 25%,至少备用 1 个;6 个活动组会额外提取 2 个备用代理。
</div>
</div>
</div>
@@ -200,6 +260,7 @@ defineExpose({ open, close })
class="form-input"
type="text"
placeholder="例: http://115.230.134.174:40014 或 socks5://127.0.0.1:1080"
@input="formData.proxyExpiresAt = 0"
>
<button
type="button"
@@ -248,10 +309,10 @@ defineExpose({ open, close })
<div class="form-group">
<label class="checkbox-row">
<input v-model="formData.autoFetchProxyOnSchedule" type="checkbox">
<span class="checkbox-text">定时任务触发前 30 秒自动提取并校验分组 IP</span>
<span class="checkbox-text">定时抢购触发前 30 秒自动预取并校验代理</span>
</label>
<div class="form-hint">
按“每组账号数”提取对应数量的代理,先测斗鱼时间接口再启用;建议使用 10 分钟以上时长,覆盖抢购与最长 180 秒支付。
仅对定时抢购生效。按“每组账号数”提取对应数量,先测斗鱼时间接口再启用;立即抢购会在开始前同步准备代理。建议使用 10 分钟以上时长,覆盖抢购与最长 180 秒支付。
</div>
</div>
@@ -297,6 +358,18 @@ defineExpose({ open, close })
</div>
</div>
<!-- 时间 API -->
<div class="form-group">
<label class="form-label">时间 API 地址</label>
<input
v-model="formData.timeApiUrl"
class="form-input"
type="text"
placeholder="留空使用默认地址"
>
<div class="form-hint">用于获取斗鱼服务端时间,一般不需要修改</div>
</div>
<!-- 和平小店参数 -->
<div class="form-section">
<div class="form-section-title">和平小店商品列表</div>
@@ -562,6 +635,76 @@ defineExpose({ open, close })
border-top: 1px solid var(--line);
}
.proxy-section {
scroll-margin-top: 16px;
}
.proxy-overview {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 12px;
margin-bottom: 16px;
border: 1px solid var(--line);
border-radius: var(--radius-sm);
background: var(--surface-2);
color: var(--muted);
font-size: 12px;
}
.proxy-overview-main {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
flex-wrap: wrap;
}
.proxy-overview strong {
color: var(--text-strong);
font-weight: 600;
white-space: nowrap;
}
.proxy-status-dot {
width: 8px;
height: 8px;
flex-shrink: 0;
border-radius: 50%;
background: var(--muted);
}
.proxy-overview.enabled {
color: var(--success);
border-color: var(--success);
background: var(--success-soft);
}
.proxy-overview.enabled .proxy-status-dot {
background: var(--success);
}
.proxy-overview.active {
color: var(--accent);
border-color: var(--accent-border);
background: var(--accent-soft);
}
.proxy-overview.active .proxy-status-dot {
background: var(--accent);
}
.proxy-overview.warning {
color: var(--warning);
border-color: var(--warning);
background: var(--warning-soft);
}
.proxy-overview.warning .proxy-status-dot {
background: var(--warning);
}
.form-section-title {
font-size: 13px;
font-weight: 600;
+6
View File
@@ -22,8 +22,10 @@ export interface Settings {
proxyEnabled: boolean
proxyUrl: string
proxyApi: string
proxyExpiresAt: number
autoFetchProxyOnSchedule: boolean
accountsPerProxy: number
proxySparePercent: number
proxyAutoWhitelist: boolean
proxyWhitelistReplace: boolean
proxyWhitelistPassword: string
@@ -51,8 +53,10 @@ const settings = ref<Settings>({
proxyEnabled: false,
proxyUrl: '',
proxyApi: '',
proxyExpiresAt: 0,
autoFetchProxyOnSchedule: false,
accountsPerProxy: 5,
proxySparePercent: 25,
proxyAutoWhitelist: false,
proxyWhitelistReplace: true,
proxyWhitelistPassword: '',
@@ -81,8 +85,10 @@ export function useSettings() {
proxyEnabled: !!cfg.proxyEnabled,
proxyUrl: cfg.proxyUrl || '',
proxyApi: cfg.proxyApi || '',
proxyExpiresAt: cfg.proxyExpiresAt || 0,
autoFetchProxyOnSchedule: !!cfg.autoFetchProxyOnSchedule,
accountsPerProxy: cfg.accountsPerProxy || 5,
proxySparePercent: cfg.proxySparePercent || 25,
proxyAutoWhitelist: !!cfg.proxyAutoWhitelist,
proxyWhitelistReplace: !!cfg.proxyWhitelistReplace,
proxyWhitelistPassword: cfg.proxyWhitelistPassword || '',
+36
View File
@@ -0,0 +1,36 @@
const pad = (value: number) => String(value).padStart(2, '0')
const parseTimeValue = (value: unknown): Date | null => {
const text = String(value ?? '').trim()
if (!text) return null
if (/^\d+$/.test(text)) {
const numeric = Number(text)
if (!Number.isFinite(numeric) || numeric <= 0) return null
const milliseconds = numeric < 10_000_000_000 ? numeric * 1000 : numeric
const date = new Date(milliseconds)
return Number.isNaN(date.getTime()) ? null : date
}
if (/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/.test(text)) {
const date = new Date(text.replace(' ', 'T'))
return Number.isNaN(date.getTime()) ? null : date
}
return null
}
export const formatExchangeTime = (value: unknown): string => {
const text = String(value ?? '').trim()
if (!text) return '-'
const date = parseTimeValue(text)
if (!date) return text.replace('T', ' ')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
export const formatShortExchangeTime = (value: unknown): string => {
const text = String(value ?? '').trim()
if (!text) return ''
const date = parseTimeValue(text)
if (!date) return text.replace('T', ' ').slice(0, 16)
return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}
+100 -27
View File
@@ -26,10 +26,11 @@ import (
type App struct {
ctx context.Context
clientMu sync.RWMutex
client *client.DouyuClient
scheduler *seckill.Scheduler
logStore *logger.MemoryLogStore
clientMu sync.RWMutex
client *client.DouyuClient
schedulerMu sync.RWMutex
scheduler *seckill.Scheduler
logStore *logger.MemoryLogStore
traceMu sync.RWMutex
trace *trace.Recorder
@@ -81,6 +82,18 @@ func (a *App) setClient(c *client.DouyuClient) {
a.clientMu.Unlock()
}
func (a *App) getScheduler() *seckill.Scheduler {
a.schedulerMu.RLock()
defer a.schedulerMu.RUnlock()
return a.scheduler
}
func (a *App) setScheduler(s *seckill.Scheduler) {
a.schedulerMu.Lock()
a.scheduler = s
a.schedulerMu.Unlock()
}
// setCfg 替换配置(写锁保护)。
func (a *App) setCfg(c types.Config) {
a.cfgMu.Lock()
@@ -167,53 +180,113 @@ func (a *App) Startup(ctx context.Context) {
logger.LogEvent("配置", "success", "已迁移旧配置到应用内部目录: %s", a.paths.ConfigFile)
}
// 加载配置并应用运行时设置
a.cfg = config.LoadConfig(a.paths.ConfigFile)
logger.SetMinLevel(a.cfg.LogLevel)
// 优先初始化调度器和账号库,避免前端首屏请求早于启动网络探测时读到 nil。
cfg := config.LoadConfig(a.paths.ConfigFile)
a.setCfg(cfg)
logger.SetMinLevel(cfg.LogLevel)
a.replaceTrace(cfg)
a.replaceTrace(a.cfg)
// 解析当前活动:配置中的 activity ID 决定使用哪套接口参数
act := activity.Get(a.cfg.Activity)
act := activity.Get(cfg.Activity)
if act == nil {
act = activity.Default()
logger.LogEvent("活动", "warn", "配置中的活动 %q 未识别,已回退到默认活动 %s", a.cfg.Activity, act.DisplayName)
logger.LogEvent("活动", "warn", "配置中的活动 %q 未识别,已回退到默认活动 %s", cfg.Activity, act.DisplayName)
}
proxyURL := a.effectiveProxyURL(a.cfg)
a.client, _ = client.NewWithProxy(act, a.cfg.TimeAPIURL, a.getTrace(), proxyURL)
if a.client == nil {
proxyURL := a.effectiveProxyURL(cfg)
initialClient, _ := client.NewWithProxy(act, cfg.TimeAPIURL, a.getTrace(), proxyURL)
if initialClient == nil {
logger.LogEvent("代理", "error", "启动时代理配置无效,已回退直连: %s", client.MaskProxyURL(proxyURL))
a.client, _ = client.NewWithProxy(act, a.cfg.TimeAPIURL, a.getTrace(), "")
initialClient, _ = client.NewWithProxy(act, cfg.TimeAPIURL, a.getTrace(), "")
}
a.setClient(initialClient)
if proxyURL != "" {
logger.LogEvent("代理", "info", "已启用代理: %s", client.MaskProxyURL(proxyURL))
}
a.font = imgpkg.LoadFont(a.paths.FontFiles)
a.scheduler = seckill.New(a.client, a.paths, a.font, a.cfg.Concurrency, a.cfg.Attempts, a.cfg.RetryStages, a.cfg.SeckillMode)
a.scheduler.UpdateProxySettings(a.cfg)
a.scheduler.SetStateChangeCallback(func(state string) {
scheduler := seckill.New(initialClient, a.paths, a.font, cfg.Concurrency, cfg.Attempts, cfg.RetryStages, cfg.SeckillMode)
a.setScheduler(scheduler)
scheduler.UpdateProxySettings(cfg)
scheduler.SetStateChangeCallback(func(state string) {
runtime.EventsEmit(a.ctx, seckillStateEvent, state)
})
a.scheduler.LoadAccounts()
scheduler.LoadAccounts()
startupRefreshTried := false
tryRefreshStartupProxy := func(reason string) bool {
if startupRefreshTried {
return false
}
startupRefreshTried = true
currentCfg := a.getCfg()
refreshedCfg := currentCfg
if err := a.refreshStartupProxy(&refreshedCfg, reason); err != nil {
logger.LogEvent("代理", "warn", "启动自动刷新代理失败: %v", err)
return false
}
candidate, err := client.NewWithProxy(act, refreshedCfg.TimeAPIURL, a.getTrace(), a.effectiveProxyURL(refreshedCfg))
if err != nil {
logger.LogEvent("代理", "warn", "启动自动刷新代理地址无效: %v", err)
return false
}
oldClient := a.getClient()
a.setClient(candidate)
a.setCfg(refreshedCfg)
scheduler.UpdateClient(candidate)
scheduler.UpdateProxySettings(refreshedCfg)
if oldClient != nil && oldClient.HTTPClient != nil {
oldClient.HTTPClient.CloseIdleConnections()
}
if oldClient != nil && oldClient.TimeHTTPClient != nil {
oldClient.TimeHTTPClient.CloseIdleConnections()
}
if err := config.SaveConfig(a.paths.ConfigFile, refreshedCfg); err != nil {
logger.LogEvent("代理", "warn", "启动自动刷新代理已生效,但配置保存失败: %v", err)
}
logger.LogEvent("代理", "success", "启动自动刷新代理已生效: %s",
client.MaskProxyURL(a.effectiveProxyURL(refreshedCfg)))
return true
}
if proxyNeedsStartupRefresh(a.getCfg(), time.Now()) {
tryRefreshStartupProxy("当前代理已过期")
}
proxyURL = a.effectiveProxyURL(a.getCfg())
if proxyURL != "" {
if _, err := a.getClient().ProbeServerTime(); err != nil {
logger.LogEvent("代理", "warn", "启动代理探测失败: %v", err)
currentCfg := a.getCfg()
if currentCfg.ProxyEnabled &&
strings.TrimSpace(currentCfg.ProxyAPI) != "" &&
isStartupProxyFailure(err) {
tryRefreshStartupProxy("当前代理连接失败")
}
}
}
startupSample, startupErr := a.getClient().ServerTimeSample()
if err := os.MkdirAll(a.paths.SuccessDir, 0755); err != nil {
logger.LogEvent("图片", "warn", "成功图片目录创建失败,图片保存功能可能不可用: %v", err)
}
if sample, err := a.client.ServerTimeSample(); err == nil {
logger.SetDouyuOffset(sample.Offset)
logger.LogEvent("时间", "success", "服务端时间获取成功: %s", sample.EstimatedServerNow().In(constants.CST).Format("2006-01-02 15:04:05.000"))
if startupErr == nil {
logger.SetDouyuOffset(startupSample.Offset)
logger.LogEvent("时间", "success", "服务端时间获取成功: %s", startupSample.EstimatedServerNow().In(constants.CST).Format("2006-01-02 15:04:05.000"))
} else {
logger.LogEvent("时间", "error", "服务端时间获取失败: %v", err)
logger.LogEvent("时间", "error", "服务端时间获取失败: %v", startupErr)
}
logger.LogEvent("系统", "success", "应用启动完成 | 账号: %d", a.scheduler.AccountCount())
logger.LogEvent("系统", "success", "应用启动完成 | 账号: %d", scheduler.AccountCount())
}
// Shutdown Wails 应用关闭时调用。
func (a *App) Shutdown(ctx context.Context) {
if a.scheduler != nil {
a.scheduler.Close()
if scheduler := a.getScheduler(); scheduler != nil {
scheduler.Close()
}
a.traceMu.Lock()
closeTrace := a.closeTrace
+6
View File
@@ -105,6 +105,12 @@ func (a *App) SaveSettings(cfg types.Config) types.ErrorResult {
if cfg.AccountsPerProxy > constants.MaxAccountsPerProxy {
cfg.AccountsPerProxy = constants.MaxAccountsPerProxy
}
if cfg.ProxySparePercent <= 0 {
cfg.ProxySparePercent = constants.DefaultProxySparePercent
}
if cfg.ProxySparePercent > constants.MaxProxySparePercent {
cfg.ProxySparePercent = constants.MaxProxySparePercent
}
if cfg.Attempts <= 0 {
cfg.Attempts = constants.DefaultAttempts
}
+12 -4
View File
@@ -29,7 +29,11 @@ func (a *App) loadProducts(refresh bool, accountNames []string) types.ProductPay
options := types.XiaodianProductListOptions{PageSize: cfg.XiaodianPageSize}
var products []types.Product
err := fmt.Errorf("没有可用账号 Cookie")
accounts := productRefreshAccounts(a.scheduler.AccountSnapshot(), accountNames)
scheduler := a.getScheduler()
if scheduler == nil {
return types.ProductPayload{Success: false}
}
accounts := productRefreshAccounts(scheduler.AccountSnapshot(), accountNames)
for _, account := range accounts {
products, err = a.getClient().Products(account.Cookie, options)
if err == nil {
@@ -75,7 +79,11 @@ func productRefreshAccounts(accounts []types.Account, preferredNames []string) [
// GetAccounts 返回账号列表。
func (a *App) GetAccounts() []types.AccountView {
accounts := a.scheduler.AccountSnapshot()
scheduler := a.getScheduler()
if scheduler == nil {
return []types.AccountView{}
}
accounts := scheduler.AccountSnapshot()
list := make([]types.AccountView, 0, len(accounts))
for i, account := range accounts {
list = append(list, types.AccountView{
@@ -100,8 +108,8 @@ func (a *App) setProducts(products []types.Product, fetchedAt time.Time) {
a.products = products
a.productsAt = fetchedAt
a.productsMu.Unlock()
if a.scheduler != nil {
a.scheduler.UpdateProducts(products)
if scheduler := a.getScheduler(); scheduler != nil {
scheduler.UpdateProducts(products)
}
}
+73 -16
View File
@@ -2,6 +2,8 @@ package app
import (
"context"
"fmt"
"strings"
"time"
"douyu_go/internal/client"
@@ -24,27 +26,12 @@ func (a *App) TestProxy(proxyURL string) types.ProxyTestResult {
// FetchProxy 从指定 API 提取一个代理 IP。
func (a *App) FetchProxy(apiURL string) types.ProxyFetchResult {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
service := proxyprovider.NewService()
cfg := a.getCfg()
endpoints, err := service.ExtractWithWhitelist(ctx, apiURL, 1, proxyprovider.WhitelistConfig{
APIURL: apiURL,
LoginPassword: cfg.ProxyWhitelistPassword,
SignKey: cfg.ProxyWhitelistSignKey,
ReplaceOldest: cfg.ProxyWhitelistReplace,
AutoWhitelist: cfg.ProxyAutoWhitelist,
})
endpoints, err := extractProxyEndpoints(cfg, apiURL, 1)
if err != nil {
logger.LogEvent("代理", "warn", "代理提取失败: %v", err)
return types.ProxyFetchResult{Error: err.Error()}
}
if len(endpoints) == 0 {
return types.ProxyFetchResult{
Success: false,
Error: "代理 API 未返回有效地址",
}
}
endpoint := endpoints[0]
expiresAt := int64(0)
if !endpoint.ExpiresAt.IsZero() {
@@ -67,3 +54,73 @@ func (a *App) FetchProxy(apiURL string) types.ProxyFetchResult {
ExpiresAt: expiresAt,
}
}
func extractProxyEndpoints(cfg types.Config, apiURL string, count int) ([]proxyprovider.Endpoint, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
service := proxyprovider.NewService()
endpoints, err := service.ExtractWithWhitelist(ctx, apiURL, count, proxyprovider.WhitelistConfig{
APIURL: apiURL,
LoginPassword: cfg.ProxyWhitelistPassword,
SignKey: cfg.ProxyWhitelistSignKey,
ReplaceOldest: cfg.ProxyWhitelistReplace,
AutoWhitelist: cfg.ProxyAutoWhitelist,
})
if err != nil {
return nil, err
}
if len(endpoints) == 0 {
return nil, fmt.Errorf("代理 API 未返回有效地址")
}
return endpoints, nil
}
func proxyNeedsStartupRefresh(cfg types.Config, now time.Time) bool {
return cfg.ProxyEnabled &&
strings.TrimSpace(cfg.ProxyAPI) != "" &&
cfg.ProxyExpiresAt > 0 &&
now.Add(30*time.Second).UnixMilli() >= cfg.ProxyExpiresAt
}
func isStartupProxyFailure(err error) bool {
if err == nil {
return false
}
message := strings.ToLower(err.Error())
for _, hint := range []string{
"407", "proxy authentication required", "proxyconnect", "connection refused",
"connection reset", "unexpected eof", "context deadline exceeded", "timeout",
"can't assign requested address",
} {
if strings.Contains(message, hint) {
return true
}
}
return false
}
func (a *App) refreshStartupProxy(cfg *types.Config, reason string) error {
if !cfg.ProxyEnabled || strings.TrimSpace(cfg.ProxyAPI) == "" {
return fmt.Errorf("代理提取 API 未配置")
}
endpoints, err := extractProxyEndpoints(*cfg, cfg.ProxyAPI, 1)
if err != nil {
return err
}
endpoint := endpoints[0]
if probe := client.TestProxyConnection(endpoint.URL); !probe.Success {
return fmt.Errorf("新代理连通性校验失败: %s", probe.Error)
}
cfg.ProxyURL = endpoint.URL
cfg.ProxyExpiresAt = 0
if !endpoint.ExpiresAt.IsZero() {
cfg.ProxyExpiresAt = endpoint.ExpiresAt.UnixMilli()
}
expiresLabel := "未知"
if !endpoint.ExpiresAt.IsZero() {
expiresLabel = endpoint.ExpiresAt.In(constants.CST).Format("2006-01-02 15:04:05")
}
logger.LogEvent("代理", "success", "启动时检测到%s,已提取并校验新代理: %s,过期=%s",
reason, client.MaskProxyURL(cfg.ProxyURL), expiresLabel)
return nil
}
+79
View File
@@ -0,0 +1,79 @@
package app
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"douyu_go/internal/types"
)
func TestProxyNeedsStartupRefresh(t *testing.T) {
now := time.Date(2026, 11, 20, 0, 30, 0, 0, time.Local)
base := types.Config{
ProxyEnabled: true,
ProxyAPI: "https://service.ipzan.com/core-extract",
ProxyExpiresAt: now.Add(10 * time.Minute).UnixMilli(),
}
if proxyNeedsStartupRefresh(base, now) {
t.Fatal("未过期代理不应在启动时刷新")
}
base.ProxyExpiresAt = now.Add(20 * time.Second).UnixMilli()
if !proxyNeedsStartupRefresh(base, now) {
t.Fatal("距离过期不足30秒时应提前刷新")
}
base.ProxyEnabled = false
if proxyNeedsStartupRefresh(base, now) {
t.Fatal("代理未启用时不应刷新")
}
}
func TestIsStartupProxyFailure(t *testing.T) {
cases := []struct {
err error
want bool
}{
{err: errors.New(`Get "https://www.douyu.com": Proxy Authentication Required`), want: true},
{err: errors.New("proxyconnect tcp: connection refused"), want: true},
{err: errors.New("Get https://www.douyu.com: unexpected EOF"), want: true},
{err: errors.New("context deadline exceeded"), want: true},
{err: errors.New("业务接口返回库存不足"), want: false},
{err: nil, want: false},
}
for _, tc := range cases {
if got := isStartupProxyFailure(tc.err); got != tc.want {
t.Errorf("isStartupProxyFailure(%v)=%v, want %v", tc.err, got, tc.want)
}
}
}
func TestRefreshStartupProxyValidatesAndUpdatesConfig(t *testing.T) {
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Host == "myip.ipip.net" {
fmt.Fprint(w, "当前 IP:127.0.0.1 来自于:中国 测试")
return
}
http.Error(w, "unexpected request", http.StatusBadGateway)
}))
defer proxyServer.Close()
apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, proxyServer.URL)
}))
defer apiServer.Close()
cfg := types.Config{
ProxyEnabled: true,
ProxyAPI: apiServer.URL,
}
app := &App{}
if err := app.refreshStartupProxy(&cfg, "测试"); err != nil {
t.Fatalf("refreshStartupProxy() error = %v", err)
}
if cfg.ProxyURL != proxyServer.URL {
t.Fatalf("ProxyURL=%q, want %q", cfg.ProxyURL, proxyServer.URL)
}
}
+15 -2
View File
@@ -50,7 +50,11 @@ func (a *App) StopSeckill() types.MessageResult {
// GetSeckillStatus 返回当前抢购运行状态。
func (a *App) GetSeckillStatus() types.SimpleResult {
return types.SimpleResult{Success: a.scheduler.IsRunning()}
scheduler := a.getScheduler()
if scheduler == nil {
return types.SimpleResult{Success: false}
}
return types.SimpleResult{Success: scheduler.IsRunning()}
}
// StartFixedSeckill 启动和平小店固定次数/间隔抢购。
@@ -117,7 +121,16 @@ func (a *App) GetLogs(since int64) types.LogsResult {
// GetTime 返回服务端时间和本地时间。
func (a *App) GetTime() types.TimeResult {
serverTime, err := a.getClient().ServerTime()
cli := a.getClient()
if cli == nil {
now := time.Now()
return types.TimeResult{
ServerTime: now.In(constants.CST).Format("2006-01-02 15:04:05.000"),
LocalTime: now.In(constants.CST).Format("2006-01-02 15:04:05.000"),
Source: "localFallback",
}
}
serverTime, err := cli.ServerTime()
source := "currentTime"
if err != nil {
source = "localFallback"
+16
View File
@@ -0,0 +1,16 @@
package app
import "testing"
func TestEarlyFrontendCallsAreSafeBeforeSchedulerReady(t *testing.T) {
app := &App{}
if got := app.GetAccounts(); len(got) != 0 {
t.Fatalf("GetAccounts()=%v, want empty before scheduler init", got)
}
if got := app.GetSeckillStatus(); got.Success {
t.Fatal("GetSeckillStatus() should report not running before scheduler init")
}
if got := app.GetTime(); got.Source != "localFallback" {
t.Fatalf("GetTime().Source=%q, want localFallback", got.Source)
}
}
+82 -16
View File
@@ -25,11 +25,12 @@ import (
// DouyuClient 斗鱼接口客户端。
type DouyuClient struct {
HTTPClient *http.Client
Activity *activity.Activity
TimeAPIURL string
Trace *trace.Recorder
ProxyURL string
HTTPClient *http.Client
TimeHTTPClient *http.Client
Activity *activity.Activity
TimeAPIURL string
Trace *trace.Recorder
ProxyURL string
xiaodianEmbedMu sync.Mutex
xiaodianEmbedCache map[string]xiaodianEmbedCacheItem
@@ -92,6 +93,7 @@ func NewWithProxy(act *activity.Activity, timeAPIURL string, tr *trace.Recorder,
TimeAPIURL: timeAPIURL,
Trace: tr,
ProxyURL: effectiveProxy,
TimeHTTPClient: newDirectHTTPClient(),
xiaodianEmbedCache: make(map[string]xiaodianEmbedCacheItem),
HTTPClient: &http.Client{
Timeout: 8 * time.Second,
@@ -100,6 +102,14 @@ func NewWithProxy(act *activity.Activity, timeAPIURL string, tr *trace.Recorder,
}, nil
}
func newDirectHTTPClient() *http.Client {
trsp, _ := newHTTPTransport("")
return &http.Client{
Timeout: 8 * time.Second,
Transport: trsp,
}
}
func newHTTPTransport(proxyURL string) (*http.Transport, error) {
trsp := &http.Transport{
MaxConnsPerHost: 120,
@@ -146,6 +156,12 @@ func (c *DouyuClient) ServerTime() (time.Time, error) {
return sample.EstimatedServerNow(), err
}
// ProbeServerTime 使用业务代理客户端访问时间接口,仅用于探测代理连通性。
// 正常时间同步走 TimeHTTPClient 直连,不受代理失效影响。
func (c *DouyuClient) ProbeServerTime() (types.TimeSample, error) {
return c.fetchServerTimeOnceWithClient(c.HTTPClient, "代理探测")
}
// ServerTimeSample 从斗鱼秒级 currentTime 估算毫秒级服务端时间。
func (c *DouyuClient) ServerTimeSample() (types.TimeSample, error) {
var lastErr error
@@ -264,23 +280,32 @@ func betterTimeSample(candidate, current types.TimeSample) bool {
}
func (c *DouyuClient) fetchServerTimeOnce() (types.TimeSample, error) {
return c.fetchServerTimeOnceWithClient(c.timeHTTPClient(), "服务时间")
}
func (c *DouyuClient) timeHTTPClient() *http.Client {
if c.TimeHTTPClient != nil {
return c.TimeHTTPClient
}
return c.HTTPClient
}
func (c *DouyuClient) fetchServerTimeOnceWithClient(httpClient *http.Client, label string) (types.TimeSample, error) {
url := utils.AppendCacheBuster(c.TimeAPIURL)
var result struct {
types.APIResponse
Data struct {
PreExchange struct {
CurrentTime string `json:"currentTime"`
} `json:"preExchange"`
} `json:"data"`
}
start := time.Now()
if err := c.getJSON(url, "", "服务时间", &result); err != nil {
if err := c.getJSONWithClient(url, "", label, &result, httpClient); err != nil {
return types.TimeSample{}, err
}
end := time.Now()
ts, err := strconv.ParseInt(result.Data.PreExchange.CurrentTime, 10, 64)
if err != nil || ts <= 0 {
return types.TimeSample{}, fmt.Errorf("currentTime 无效: %q", result.Data.PreExchange.CurrentTime)
if result.Error != 0 {
return types.TimeSample{}, fmt.Errorf("服务时间接口失败: %s", result.Msg)
}
ts, err := parseServerTimestamp(result.Data)
if err != nil {
return types.TimeSample{}, err
}
rtt := end.Sub(start)
@@ -295,6 +320,36 @@ func (c *DouyuClient) fetchServerTimeOnce() (types.TimeSample, error) {
}, nil
}
func parseServerTimestamp(raw json.RawMessage) (int64, error) {
raw = bytesTrimJSON(raw)
if len(raw) == 0 || string(raw) == "null" {
return 0, errors.New("服务时间响应缺少 data")
}
var timestamp int64
if err := json.Unmarshal(raw, &timestamp); err == nil && timestamp > 0 {
return timestamp, nil
}
var timestampText string
if err := json.Unmarshal(raw, &timestampText); err == nil {
timestamp, err = strconv.ParseInt(strings.TrimSpace(timestampText), 10, 64)
if err == nil && timestamp > 0 {
return timestamp, nil
}
}
var detail struct {
PreExchange struct {
CurrentTime string `json:"currentTime"`
} `json:"preExchange"`
}
if err := json.Unmarshal(raw, &detail); err == nil {
timestamp, err = strconv.ParseInt(strings.TrimSpace(detail.PreExchange.CurrentTime), 10, 64)
if err == nil && timestamp > 0 {
return timestamp, nil
}
}
return 0, fmt.Errorf("服务时间响应中没有有效的 Unix 秒时间戳: %s", utils.TrimForLog(string(raw), 120))
}
// Products 拉取当前活动的商品列表。
func (c *DouyuClient) Products(cookie string, xiaodianOptions types.XiaodianProductListOptions) ([]types.Product, error) {
if c.Activity.IsXiaodian {
@@ -1717,12 +1772,16 @@ func (c *DouyuClient) ExchangeList(cookie string) ([]types.ExchangeRecord, error
}
func (c *DouyuClient) getJSON(url, cookie, label string, out any) error {
return c.getJSONWithClient(url, cookie, label, out, c.HTTPClient)
}
func (c *DouyuClient) getJSONWithClient(url, cookie, label string, out any, httpClient *http.Client) error {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
c.setBrowserHeaders(req, cookie)
_, err = c.doJSON(req, out, label)
_, err = c.doJSONWithClient(req, out, label, httpClient)
return err
}
@@ -1783,9 +1842,16 @@ func (c *DouyuClient) postMultipart(url, cookie string, csrf *string, label stri
}
func (c *DouyuClient) doJSON(req *http.Request, out any, label string) (*http.Response, error) {
return c.doJSONWithClient(req, out, label, c.HTTPClient)
}
func (c *DouyuClient) doJSONWithClient(req *http.Request, out any, label string, httpClient *http.Client) (*http.Response, error) {
start := time.Now()
reqBody := c.Trace.RequestBody(req)
resp, err := c.HTTPClient.Do(req)
if httpClient == nil {
httpClient = c.HTTPClient
}
resp, err := httpClient.Do(req)
if err != nil {
c.Trace.Record(label, req, 0, time.Since(start), reqBody, nil, err.Error(), 0, "")
c.logNetworkError(label, req, time.Since(start), err)
+56
View File
@@ -2,6 +2,7 @@ package client
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"net/url"
@@ -36,6 +37,61 @@ func TestGenerateCSRFUseCTNReusesCookie(t *testing.T) {
}
}
func TestServerTimeSampleBypassesProxyClient(t *testing.T) {
timeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"error":0,"data":1795103912}`))
}))
defer timeServer.Close()
act := *activity.Get("peace")
cli := &DouyuClient{
HTTPClient: &http.Client{
Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return nil, errors.New("Proxy Authentication Required")
}),
},
TimeHTTPClient: timeServer.Client(),
Activity: &act,
TimeAPIURL: timeServer.URL,
Trace: &trace.Recorder{},
}
sample, err := cli.ServerTimeSample()
if err != nil {
t.Fatalf("ServerTimeSample() error = %v", err)
}
if sample.RawCurrentTime != 1795103912 {
t.Fatalf("RawCurrentTime=%d, want 1795103912", sample.RawCurrentTime)
}
if _, err := cli.ProbeServerTime(); err == nil {
t.Fatal("ProbeServerTime() should use the proxied business client")
}
}
func TestParseServerTimestamp(t *testing.T) {
cases := []struct {
name string
raw string
want int64
}{
{name: "timestamp number", raw: `1795103912`, want: 1795103912},
{name: "timestamp string", raw: `"1795103912"`, want: 1795103912},
{name: "storedetail compatibility", raw: `{"preExchange":{"currentTime":"1795103912"}}`, want: 1795103912},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, err := parseServerTimestamp(json.RawMessage(tc.raw))
if err != nil {
t.Fatalf("parseServerTimestamp() error = %v", err)
}
if got != tc.want {
t.Fatalf("parseServerTimestamp() = %d, want %d", got, tc.want)
}
})
}
}
func TestPostMultipartUseCTNPreservesCSRFCookie(t *testing.T) {
var gotCookie string
var gotContentType string
+81
View File
@@ -0,0 +1,81 @@
package client
import (
"context"
"errors"
"io"
"net/http"
"sync"
)
// MonitorProxyHealth 为代理客户端安装传输层健康回调。
// 回调参数为 nil 表示一次完整传输成功;非 nil 表示连接、超时或响应体读取失败。
func MonitorProxyHealth(c *DouyuClient, handler func(error)) {
if c == nil || c.HTTPClient == nil || handler == nil {
return
}
if _, ok := c.HTTPClient.Transport.(*proxyHealthTransport); ok {
return
}
base := c.HTTPClient.Transport
if base == nil {
base = http.DefaultTransport
}
c.HTTPClient.Transport = &proxyHealthTransport{
base: base,
handler: handler,
}
}
// IsProxyTransportFailure 区分真实网络故障与主动取消。
func IsProxyTransportFailure(err error) bool {
if err == nil {
return false
}
return !errors.Is(err, context.Canceled)
}
type proxyHealthTransport struct {
base http.RoundTripper
handler func(error)
}
func (t *proxyHealthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := t.base.RoundTrip(req)
if err != nil {
if IsProxyTransportFailure(err) {
t.handler(err)
}
return nil, err
}
t.handler(nil)
if resp != nil && resp.Body != nil {
resp.Body = &proxyHealthBody{
ReadCloser: resp.Body,
handler: t.handler,
}
}
return resp, nil
}
func (t *proxyHealthTransport) CloseIdleConnections() {
if closer, ok := t.base.(interface{ CloseIdleConnections() }); ok {
closer.CloseIdleConnections()
}
}
type proxyHealthBody struct {
io.ReadCloser
once sync.Once
handler func(error)
}
func (b *proxyHealthBody) Read(p []byte) (int, error) {
n, err := b.ReadCloser.Read(p)
if err != nil && !errors.Is(err, io.EOF) && IsProxyTransportFailure(err) {
b.once.Do(func() {
b.handler(err)
})
}
return n, err
}
+52
View File
@@ -0,0 +1,52 @@
package client
import (
"context"
"errors"
"net/http"
"testing"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
func TestIsProxyTransportFailure(t *testing.T) {
if IsProxyTransportFailure(nil) {
t.Fatal("nil error should not be treated as proxy failure")
}
if IsProxyTransportFailure(context.Canceled) {
t.Fatal("context cancellation should not trigger proxy failover")
}
if !IsProxyTransportFailure(errors.New("connection reset by peer")) {
t.Fatal("transport error should trigger proxy failover")
}
}
func TestMonitorProxyHealthReportsRoundTripFailure(t *testing.T) {
wantErr := errors.New("proxy connection refused")
cli := &DouyuClient{
HTTPClient: &http.Client{
Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return nil, wantErr
}),
},
}
var gotErr error
MonitorProxyHealth(cli, func(err error) {
gotErr = err
})
req, err := http.NewRequest(http.MethodGet, "https://example.test", nil)
if err != nil {
t.Fatal(err)
}
if _, err := cli.HTTPClient.Do(req); !errors.Is(err, wantErr) {
t.Fatalf("HTTPClient.Do() error=%v, want %v", err, wantErr)
}
if !errors.Is(gotErr, wantErr) {
t.Fatalf("health handler error=%v, want %v", gotErr, wantErr)
}
}
+19 -12
View File
@@ -164,17 +164,18 @@ func envInt(key string, fallback int) int {
// defaultConfig 返回内置默认配置。
func defaultConfig() types.Config {
return types.Config{
Activity: activity.DefaultActivityID,
TimeAPIURL: constants.DefaultTimeAPI,
TraceEnabled: false,
TraceMaxBody: 0,
LogLevel: "info",
Concurrency: constants.DefaultConcurrency,
Attempts: constants.DefaultAttempts,
RetryStages: defaultRetryStages(),
SeckillMode: types.SeckillModeAggressive,
XiaodianPageSize: 200,
AccountsPerProxy: constants.DefaultAccountsPerProxy,
Activity: activity.DefaultActivityID,
TimeAPIURL: constants.DefaultTimeAPI,
TraceEnabled: false,
TraceMaxBody: 0,
LogLevel: "info",
Concurrency: constants.DefaultConcurrency,
Attempts: constants.DefaultAttempts,
RetryStages: defaultRetryStages(),
SeckillMode: types.SeckillModeAggressive,
XiaodianPageSize: 200,
AccountsPerProxy: constants.DefaultAccountsPerProxy,
ProxySparePercent: constants.DefaultProxySparePercent,
}
}
@@ -214,7 +215,7 @@ func LoadConfig(path string) types.Config {
if cfg.Activity == "" {
cfg.Activity = activity.DefaultActivityID
}
if cfg.TimeAPIURL == "" {
if cfg.TimeAPIURL == "" || cfg.TimeAPIURL == constants.LegacyDefaultTimeAPI {
cfg.TimeAPIURL = constants.DefaultTimeAPI
}
if cfg.Concurrency <= 0 {
@@ -242,6 +243,12 @@ func normalizeProxyConfig(cfg *types.Config) {
if cfg.AccountsPerProxy > constants.MaxAccountsPerProxy {
cfg.AccountsPerProxy = constants.MaxAccountsPerProxy
}
if cfg.ProxySparePercent <= 0 {
cfg.ProxySparePercent = constants.DefaultProxySparePercent
}
if cfg.ProxySparePercent > constants.MaxProxySparePercent {
cfg.ProxySparePercent = constants.MaxProxySparePercent
}
}
// normalizeXiaodianConfig 约束和平小店分页参数,接口单页最大为 200。
+27
View File
@@ -128,3 +128,30 @@ func TestLoadConfigNormalizesAccountsPerProxy(t *testing.T) {
t.Fatalf("AccountsPerProxy=%d, want %d", got, constants.MaxAccountsPerProxy)
}
}
func TestLoadConfigNormalizesProxySparePercent(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.json")
if err := os.WriteFile(path, []byte(`{"proxySparePercent":0}`), 0600); err != nil {
t.Fatal(err)
}
if got := LoadConfig(path).ProxySparePercent; got != constants.DefaultProxySparePercent {
t.Fatalf("ProxySparePercent=%d, want %d", got, constants.DefaultProxySparePercent)
}
if err := os.WriteFile(path, []byte(`{"proxySparePercent":999}`), 0600); err != nil {
t.Fatal(err)
}
if got := LoadConfig(path).ProxySparePercent; got != constants.MaxProxySparePercent {
t.Fatalf("ProxySparePercent=%d, want %d", got, constants.MaxProxySparePercent)
}
}
func TestLoadConfigMigratesLegacyTimeAPI(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.json")
content := []byte(`{"timeApiUrl":"` + constants.LegacyDefaultTimeAPI + `"}`)
if err := os.WriteFile(path, content, 0600); err != nil {
t.Fatal(err)
}
if got := LoadConfig(path).TimeAPIURL; got != constants.DefaultTimeAPI {
t.Fatalf("TimeAPIURL=%q, want %q", got, constants.DefaultTimeAPI)
}
}
+15 -11
View File
@@ -3,19 +3,21 @@ package constants
import "time"
// Version 应用版本号,与 wails.json version 同步。
const Version = "0.4.0"
const Version = "0.5.0"
// BuildTime 构建时间,由编译时 ldflags 注入。
var BuildTime = "unknown"
const (
BaseURL = "https://www.douyu.com"
UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36"
DefaultAttempts = 2
DefaultConcurrency = 150
DefaultAccountsPerProxy = 5
MaxAccountsPerProxy = 100
ProductCacheTTL = 30 * time.Second
BaseURL = "https://www.douyu.com"
UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/157.0.0.0 Safari/537.36"
DefaultAttempts = 2
DefaultConcurrency = 150
DefaultAccountsPerProxy = 5
MaxAccountsPerProxy = 100
DefaultProxySparePercent = 25
MaxProxySparePercent = 100
ProductCacheTTL = 30 * time.Second
DefaultAppDataDirName = "douyu-go"
DefaultConfigFile = "config.json"
@@ -28,9 +30,11 @@ const (
LegacyDefaultAccountFile = "data/user.txt"
// DefaultTimeAPI 服务端时间校准接口。
// 斗鱼服务器时间与活动无关,统一用精英手册的 storedetail(能稳定返回
// data.preExchange.currentTime),所有活动共用。
DefaultTimeAPI = BaseURL + "/wgapi/ordnc/activity/peace/storedetail?manualID=G4KA4Qnz4LDp7&commodityID=20260120QYOOB_bag274&rid=9263298"
// 斗鱼服务器时间与活动无关,优先使用轻量级 data=Unix秒 接口;
// 客户端同时兼容旧配置中的 storedetail data.preExchange.currentTime。
DefaultTimeAPI = BaseURL + "/api/v1/timestamp"
// LegacyDefaultTimeAPI 用于迁移曾保存到 config.json 的旧默认时间接口。
LegacyDefaultTimeAPI = BaseURL + "/wgapi/ordnc/activity/peace/storedetail?manualID=G4KA4Qnz4LDp7&commodityID=20260120QYOOB_bag274&rid=9263298"
)
// CST 中国标准时间 UTC+8。
+6 -6
View File
@@ -58,12 +58,12 @@ var (
var (
// 锁单成功后到第一次支付的等待。斗鱼对"锁单→支付"有最短间隔:
// 2026-10-03 19:38 的模拟里,+0.50s/+0.60s/+1.37s/+1.68s 发起的支付一律被
// "您点击太快,请稍等再试"拒绝,而 +2.56s/+3.30s 发起的都成功;19:20 那次
// 在 +2.1s~+3.9s 发起的 6 笔全部一次通过。阈值落在 (1.68s, 2.1s] 之间,
// 这里取 2.3-3.0 秒留出余量:抢在 2 秒前支付只会白挨拒绝、多花时间。
peaceLockPayMin = 2500 * time.Millisecond
peaceLockPayMax = 3500 * time.Millisecond
// 2026-10-03 的模拟里,+0.50s/+0.60s/+1.37s/+1.68s 发起的支付一律被
// "您点击太快,请稍等再试"拒绝,而 +2.1s 以上发起的全部通过。
// 2026-11-19 网页实测在锁单响应后 3.26 秒支付一次成功。
// 这里取 3.0-4.0 秒:锁单已占库存,支付稍晚没有损失,但能减少频控。
peaceLockPayMin = 3000 * time.Millisecond
peaceLockPayMax = 4000 * time.Millisecond
)
// 斗鱼订单接口错误码。
+486 -31
View File
@@ -20,6 +20,7 @@ import (
const (
proxyFetchRounds = 3
proxyFetchMaxRounds = 20
proxyFetchRetryWait = 300 * time.Millisecond
proxyRequestTimeout = 15 * time.Second
proxyValidationTimeout = 3 * time.Second
@@ -33,6 +34,7 @@ type proxySettingsSnapshot struct {
proxyAPI string
autoFetchOnTimer bool
accountsPerProxy int
sparePercent int
autoWhitelist bool
whitelistReplace bool
whitelistPassword string
@@ -49,6 +51,34 @@ type validatedProxy struct {
expiresAt time.Time
}
type proxyRuntimeGroup struct {
accountNames []string
activeURL string
consecutiveFailures int
failed bool
}
type preparedProxyPool struct {
accountClients map[string]*client.DouyuClient
activeClients []*client.DouyuClient
groups map[*client.DouyuClient]*proxyRuntimeGroup
standbys []validatedProxy
allClients []*client.DouyuClient
excludedURLs map[string]struct{}
standbyTarget int
expiresAt time.Time
}
type proxySwitchEvent struct {
accountNames []string
fromURL string
toURL string
toIP string
toRegion string
toRTT time.Duration
toSource string
}
// UpdateProxySettings 运行时更新代理配置。
func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
enabled := cfg.ProxyEnabled
@@ -56,12 +86,19 @@ func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
proxyAPI := cfg.ProxyAPI
autoFetch := cfg.AutoFetchProxyOnSchedule
accountsPerProxy := cfg.AccountsPerProxy
sparePercent := cfg.ProxySparePercent
if accountsPerProxy <= 0 {
accountsPerProxy = constants.DefaultAccountsPerProxy
}
if accountsPerProxy > constants.MaxAccountsPerProxy {
accountsPerProxy = constants.MaxAccountsPerProxy
}
if sparePercent <= 0 {
sparePercent = constants.DefaultProxySparePercent
}
if sparePercent > constants.MaxProxySparePercent {
sparePercent = constants.MaxProxySparePercent
}
proxyURL = strings.TrimSpace(proxyURL)
proxyAPI = strings.TrimSpace(proxyAPI)
whitelistPassword := strings.TrimSpace(cfg.ProxyWhitelistPassword)
@@ -72,6 +109,7 @@ func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
s.proxyAPI != proxyAPI ||
s.autoFetchProxyOnSchedule != autoFetch ||
s.accountsPerProxy != accountsPerProxy ||
s.proxySparePercent != sparePercent ||
s.autoWhitelist != cfg.ProxyAutoWhitelist ||
s.whitelistReplace != cfg.ProxyWhitelistReplace ||
s.whitelistPassword != whitelistPassword ||
@@ -81,6 +119,7 @@ func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
s.proxyAPI = proxyAPI
s.autoFetchProxyOnSchedule = autoFetch
s.accountsPerProxy = accountsPerProxy
s.proxySparePercent = sparePercent
s.autoWhitelist = cfg.ProxyAutoWhitelist
s.whitelistReplace = cfg.ProxyWhitelistReplace
s.whitelistPassword = whitelistPassword
@@ -105,12 +144,20 @@ func (s *Scheduler) proxySettings() proxySettingsSnapshot {
if size > constants.MaxAccountsPerProxy {
size = constants.MaxAccountsPerProxy
}
sparePercent := s.proxySparePercent
if sparePercent <= 0 {
sparePercent = constants.DefaultProxySparePercent
}
if sparePercent > constants.MaxProxySparePercent {
sparePercent = constants.MaxProxySparePercent
}
return proxySettingsSnapshot{
enabled: s.proxyEnabled,
proxyURL: s.proxyURL,
proxyAPI: s.proxyAPI,
autoFetchOnTimer: s.autoFetchProxyOnSchedule,
accountsPerProxy: size,
sparePercent: sparePercent,
autoWhitelist: s.autoWhitelist,
whitelistReplace: s.whitelistReplace,
whitelistPassword: s.whitelistPassword,
@@ -120,27 +167,64 @@ func (s *Scheduler) proxySettings() proxySettingsSnapshot {
func (s *Scheduler) closeAccountClients() {
s.clientMu.Lock()
old := s.accountClients
oldClients := append([]*client.DouyuClient(nil), s.proxyClientPool...)
for _, cli := range s.accountClients {
oldClients = append(oldClients, cli)
}
s.accountClients = make(map[string]*client.DouyuClient)
s.accountClientOrder = nil
s.accountClientsDirty = true
s.accountClientsExpireAt = time.Time{}
s.proxyGroups = make(map[*client.DouyuClient]*proxyRuntimeGroup)
s.proxyStandbys = nil
s.proxyClientPool = nil
s.proxyExcludedURLs = make(map[string]struct{})
s.proxyStandbyTarget = 0
s.proxyPoolGeneration++
s.proxyRefillInFlight = false
s.clientMu.Unlock()
closeDouyuClients(old)
closeDouyuClientList(oldClients)
}
func (s *Scheduler) replaceAccountClients(accountClients map[string]*client.DouyuClient, order []*client.DouyuClient, expiresAt time.Time) {
func (s *Scheduler) replaceAccountClients(pool preparedProxyPool) {
if pool.accountClients == nil {
pool.accountClients = make(map[string]*client.DouyuClient)
}
if pool.groups == nil {
pool.groups = make(map[*client.DouyuClient]*proxyRuntimeGroup)
}
if pool.excludedURLs == nil {
pool.excludedURLs = make(map[string]struct{})
}
s.clientMu.Lock()
old := s.accountClients
s.accountClients = accountClients
s.accountClientOrder = order
oldClients := append([]*client.DouyuClient(nil), s.proxyClientPool...)
for _, cli := range s.accountClients {
oldClients = append(oldClients, cli)
}
s.accountClients = pool.accountClients
s.accountClientOrder = pool.activeClients
s.accountClientsDirty = false
s.accountClientsExpireAt = expiresAt
s.accountClientsExpireAt = pool.expiresAt
s.proxyGroups = pool.groups
s.proxyStandbys = pool.standbys
s.proxyClientPool = pool.allClients
s.proxyExcludedURLs = pool.excludedURLs
s.proxyStandbyTarget = pool.standbyTarget
s.proxyPoolGeneration++
s.proxyRefillInFlight = false
s.clientMu.Unlock()
closeDouyuClients(old)
closeDouyuClientList(oldClients)
}
func closeDouyuClients(clients map[string]*client.DouyuClient) {
items := make([]*client.DouyuClient, 0, len(clients))
for _, cli := range clients {
items = append(items, cli)
}
closeDouyuClientList(items)
}
func closeDouyuClientList(clients []*client.DouyuClient) {
seen := make(map[*client.DouyuClient]struct{}, len(clients))
for _, cli := range clients {
if cli == nil {
@@ -153,6 +237,9 @@ func closeDouyuClients(clients map[string]*client.DouyuClient) {
if cli.HTTPClient != nil {
cli.HTTPClient.CloseIdleConnections()
}
if cli.TimeHTTPClient != nil {
cli.TimeHTTPClient.CloseIdleConnections()
}
}
}
@@ -168,6 +255,9 @@ func (s *Scheduler) accountClientsCover(accountNames []string) bool {
if s.accountClientsDirty {
return false
}
if len(s.proxyStandbys) < s.proxyStandbyTarget {
return false
}
if !s.accountClientsExpireAt.IsZero() && !time.Now().Before(s.accountClientsExpireAt.Add(-30*time.Second)) {
return false
}
@@ -213,6 +303,9 @@ func (s *Scheduler) allClients() []*client.DouyuClient {
// prepareProxyGroups 将本次参与抢购的账号按固定顺序分组,并为每组准备独立客户端。
// forceRefresh=true 用于定时任务启动前主动刷新短效代理。
func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceRefresh bool) error {
s.proxyPrepareMu.Lock()
defer s.proxyPrepareMu.Unlock()
cfg := s.proxySettings()
names := selectedAccountNames(accountProducts)
if len(names) == 0 {
@@ -227,25 +320,36 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
}
groups := chunkAccountNames(names, cfg.accountsPerProxy)
activeCount := len(groups)
standbyTarget := proxyStandbyCount(activeCount, cfg.sparePercent)
base := s.clientSnapshot()
if base == nil {
return errors.New("基础客户端未初始化")
}
poolStartedAt := time.Now()
proxies, err := s.buildProxyPool(base, cfg, len(groups))
proxies, err := s.buildProxyPool(base, cfg, activeCount, activeCount+standbyTarget, nil)
if err != nil {
return err
}
if len(proxies) < len(groups) {
return fmt.Errorf("代理数量不足: 需要%d组,实际%d组", len(groups), len(proxies))
if len(proxies) < activeCount {
return fmt.Errorf("代理数量不足: 需要%d个活动代理,实际%d个", activeCount, len(proxies))
}
if len(proxies) < activeCount+standbyTarget {
logger.LogEvent("代理", "warn", "备用代理不足: 目标%d个,实际%d个;活动代理不受影响",
standbyTarget, len(proxies)-activeCount)
}
accountClients := make(map[string]*client.DouyuClient, len(names))
clientOrder := make([]*client.DouyuClient, 0, len(groups))
clientOrder := make([]*client.DouyuClient, 0, activeCount)
runtimeGroups := make(map[*client.DouyuClient]*proxyRuntimeGroup, activeCount)
for i, group := range groups {
proxy := proxies[i]
clientOrder = append(clientOrder, proxy.client)
runtimeGroups[proxy.client] = &proxyRuntimeGroup{
accountNames: append([]string(nil), group...),
activeURL: proxy.url,
}
for _, name := range group {
accountClients[name] = proxy.client
}
@@ -253,6 +357,17 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
i+1, len(group), client.MaskProxyURL(proxy.url), proxy.ip, proxy.region,
proxy.rtt.Round(time.Millisecond), proxy.source)
}
standbys := append([]validatedProxy(nil), proxies[activeCount:]...)
allClients := make([]*client.DouyuClient, 0, len(proxies))
excludedURLs := make(map[string]struct{}, len(proxies))
for _, proxy := range proxies {
allClients = append(allClients, proxy.client)
excludedURLs[proxy.url] = struct{}{}
proxyClient := proxy.client
client.MonitorProxyHealth(proxyClient, func(err error) {
s.recordProxyResult(proxyClient, err)
})
}
expiresAt := time.Time{}
if cfg.proxyAPI != "" {
expiresAt = proxyPoolExpiresAt(cfg.proxyAPI, poolStartedAt)
@@ -265,12 +380,28 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
expiresAt = proxy.expiresAt
}
}
s.replaceAccountClients(accountClients, clientOrder, expiresAt)
logger.LogEvent("代理", "success", "代理分组完成: 账号=%d,每组=%d,代理组=%d",
len(names), cfg.accountsPerProxy, len(groups))
s.replaceAccountClients(preparedProxyPool{
accountClients: accountClients,
activeClients: clientOrder,
groups: runtimeGroups,
standbys: standbys,
allClients: allClients,
excludedURLs: excludedURLs,
standbyTarget: effectiveProxyStandbyTarget(cfg, standbyTarget, len(standbys)),
expiresAt: expiresAt,
})
logger.LogEvent("代理", "success", "代理池准备完成: 账号=%d,每组=%d,活动代理=%d,备用代理=%d/%d",
len(names), cfg.accountsPerProxy, activeCount, len(standbys), standbyTarget)
return nil
}
func effectiveProxyStandbyTarget(cfg proxySettingsSnapshot, target, actual int) int {
if cfg.proxyAPI == "" {
return actual
}
return target
}
// PrepareProxyGroups 供立即抢购入口在启动前同步准备代理,便于把错误直接返回给界面。
func (s *Scheduler) PrepareProxyGroups(accountProducts map[string]string) error {
return s.prepareProxyGroups(accountProducts, false)
@@ -307,39 +438,124 @@ func chunkAccountNames(names []string, size int) [][]string {
return groups
}
func (s *Scheduler) buildProxyPool(base *client.DouyuClient, cfg proxySettingsSnapshot, count int) ([]validatedProxy, error) {
if count <= 0 {
func proxyStandbyCount(activeCount, sparePercent int) int {
if activeCount <= 0 {
return 0
}
if sparePercent <= 0 {
sparePercent = constants.DefaultProxySparePercent
}
if sparePercent > constants.MaxProxySparePercent {
sparePercent = constants.MaxProxySparePercent
}
count := (activeCount*sparePercent + 99) / 100
if count < 1 {
count = 1
}
return count
}
func (s *Scheduler) buildProxyPool(base *client.DouyuClient, cfg proxySettingsSnapshot, required, desired int, excludedURLs map[string]struct{}) ([]validatedProxy, error) {
if desired < required {
desired = required
}
if required <= 0 {
return nil, nil
}
if cfg.proxyAPI != "" {
proxies, err := s.fetchAndValidateProxyPool(base, cfg, count)
if err == nil && len(proxies) >= count {
proxies, err := s.fetchAndValidateProxyPool(base, cfg, desired, excludedURLs)
if len(proxies) >= required {
if len(proxies) < desired {
logger.LogEvent("代理", "warn", "动态代理备用数量不足: 目标%d个,实际%d个", desired, len(proxies))
}
return proxies, nil
}
closeValidatedProxies(proxies)
if err != nil {
logger.LogEvent("代理", "warn", "动态代理提取未完全成功: %v", err)
}
}
staticURLs := splitProxyURLs(cfg.proxyURL)
staticURLs := uniqueStrings(splitProxyURLs(cfg.proxyURL))
if len(staticURLs) == 0 {
return nil, errors.New("代理已启用,但没有可用的提取 API 或静态代理")
}
if len(staticURLs) == 1 {
logger.LogEvent("代理", "warn", "当前只有一个静态代理,%d 个账号组将共享该出口", count)
logger.LogEvent("代理", "warn", "当前只有一个静态代理,%d 个账号组将共享该出口且没有可用备用代理", required)
}
proxies := make([]validatedProxy, 0, count)
for i := 0; i < count; i++ {
rawURL := staticURLs[i%len(staticURLs)]
validateCount := len(staticURLs)
if validateCount > desired {
validateCount = desired
}
templates := make([]validatedProxy, 0, validateCount)
for _, rawURL := range staticURLs[:validateCount] {
proxy, err := s.validateProxy(base, rawURL, "静态")
if err != nil {
return nil, fmt.Errorf("静态代理组%d不可用: %w", i+1, err)
closeValidatedProxies(templates)
return nil, fmt.Errorf("静态代理不可用: %w", err)
}
templates = append(templates, proxy)
}
total := required
if len(templates) > required {
total += len(templates) - required
if total > desired {
total = desired
}
}
proxies := make([]validatedProxy, 0, total)
var cloneErr error
for i := 0; i < total; i++ {
template := templates[i%len(templates)]
proxy := template
if i >= len(templates) {
proxy, cloneErr = cloneValidatedProxy(base, template)
if cloneErr != nil {
closeValidatedProxies(proxies)
closeValidatedProxies(templates)
return nil, fmt.Errorf("创建共享静态代理连接失败: %w", cloneErr)
}
}
proxies = append(proxies, proxy)
}
if total < len(templates) {
closeValidatedProxies(templates[total:])
}
return proxies, nil
}
func uniqueStrings(items []string) []string {
seen := make(map[string]struct{}, len(items))
out := make([]string, 0, len(items))
for _, item := range items {
if _, ok := seen[item]; ok {
continue
}
seen[item] = struct{}{}
out = append(out, item)
}
return out
}
func cloneValidatedProxy(base *client.DouyuClient, template validatedProxy) (validatedProxy, error) {
cli, err := client.NewWithProxy(base.Activity, base.TimeAPIURL, base.Trace, template.url)
if err != nil {
return validatedProxy{}, err
}
template.client = cli
return template, nil
}
func closeValidatedProxies(proxies []validatedProxy) {
clients := make([]*client.DouyuClient, 0, len(proxies))
for _, proxy := range proxies {
clients = append(clients, proxy.client)
}
closeDouyuClientList(clients)
}
func splitProxyURLs(raw string) []string {
parts := strings.FieldsFunc(raw, func(r rune) bool {
return r == '\n' || r == '\r' || r == ';' || r == ','
@@ -354,7 +570,7 @@ func splitProxyURLs(raw string) []string {
return out
}
func (s *Scheduler) fetchAndValidateProxyPool(base *client.DouyuClient, cfg proxySettingsSnapshot, count int) ([]validatedProxy, error) {
func (s *Scheduler) fetchAndValidateProxyPool(base *client.DouyuClient, cfg proxySettingsSnapshot, count int, excludedURLs map[string]struct{}) ([]validatedProxy, error) {
service := s.proxyService
if service == nil {
service = proxyprovider.NewService()
@@ -362,10 +578,20 @@ func (s *Scheduler) fetchAndValidateProxyPool(base *client.DouyuClient, cfg prox
}
proxies := make([]validatedProxy, 0, count)
seen := make(map[string]struct{}, count)
seen := make(map[string]struct{}, count+len(excludedURLs))
for rawURL := range excludedURLs {
seen[rawURL] = struct{}{}
}
var lastErr error
for round := 0; round < proxyFetchRounds; round++ {
rounds := proxyFetchRounds
if count > rounds {
rounds = count
}
if rounds > proxyFetchMaxRounds {
rounds = proxyFetchMaxRounds
}
for round := 0; round < rounds; round++ {
need := count - len(proxies)
if need <= 0 {
break
@@ -394,9 +620,11 @@ func (s *Scheduler) fetchAndValidateProxyPool(base *client.DouyuClient, cfg prox
}
if !item.endpoint.ExpiresAt.IsZero() && !time.Now().Before(item.endpoint.ExpiresAt) {
lastErr = fmt.Errorf("代理 %s 已过期", item.endpoint.IP)
closeDouyuClientList([]*client.DouyuClient{item.proxy.client})
continue
}
if _, exists := seen[item.endpoint.URL]; exists {
closeDouyuClientList([]*client.DouyuClient{item.proxy.client})
continue
}
seen[item.endpoint.URL] = struct{}{}
@@ -412,7 +640,7 @@ func (s *Scheduler) fetchAndValidateProxyPool(base *client.DouyuClient, cfg prox
}
}
if round < proxyFetchRounds-1 {
if round < rounds-1 {
time.Sleep(proxyFetchRetryWait)
}
}
@@ -426,6 +654,233 @@ func (s *Scheduler) fetchAndValidateProxyPool(base *client.DouyuClient, cfg prox
return proxies, nil
}
func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error) {
if proxyClient == nil {
return
}
s.clientMu.Lock()
group := s.proxyGroups[proxyClient]
if group == nil {
s.clientMu.Unlock()
return
}
if err == nil {
group.consecutiveFailures = 0
s.clientMu.Unlock()
return
}
if !client.IsProxyTransportFailure(err) || group.failed {
s.clientMu.Unlock()
return
}
group.consecutiveFailures++
if group.consecutiveFailures < 2 {
failures := group.consecutiveFailures
activeURL := group.activeURL
s.clientMu.Unlock()
logger.LogEvent("代理", "debug", "代理网络异常计数: %s 连续失败=%d", client.MaskProxyURL(activeURL), failures)
return
}
event, expiredClients, switched := s.switchGroupToStandbyLocked(proxyClient, group)
needRefill := false
failedAccounts := 0
failedURL := ""
if switched {
needRefill = len(s.proxyStandbys) < s.proxyStandbyTarget && !s.proxyRefillInFlight
} else {
group.failed = true
failedAccounts = len(group.accountNames)
failedURL = group.activeURL
needRefill = !s.proxyRefillInFlight
}
s.clientMu.Unlock()
closeDouyuClientList(expiredClients)
if switched {
logProxySwitch("代理故障切换", event)
} else {
logger.LogEvent("代理", "warn", "代理组连续失败且暂无备用: 账号=%d 出口=%s,正在尝试补提取",
failedAccounts, client.MaskProxyURL(failedURL))
}
if needRefill {
s.startProxyRefill()
}
}
func (s *Scheduler) switchGroupToStandbyLocked(oldClient *client.DouyuClient, group *proxyRuntimeGroup) (proxySwitchEvent, []*client.DouyuClient, bool) {
expiredClients := make([]*client.DouyuClient, 0, 1)
for len(s.proxyStandbys) > 0 {
standby := s.proxyStandbys[0]
s.proxyStandbys = s.proxyStandbys[1:]
if !standby.expiresAt.IsZero() && !time.Now().Before(standby.expiresAt) {
expiredClients = append(expiredClients, standby.client)
continue
}
event := proxySwitchEvent{
accountNames: append([]string(nil), group.accountNames...),
fromURL: group.activeURL,
toURL: standby.url,
toIP: standby.ip,
toRegion: standby.region,
toRTT: standby.rtt,
toSource: standby.source,
}
group.activeURL = standby.url
group.consecutiveFailures = 0
group.failed = false
for _, accountName := range group.accountNames {
s.accountClients[accountName] = standby.client
}
delete(s.proxyGroups, oldClient)
s.proxyGroups[standby.client] = group
replaceClientInOrder(s.accountClientOrder, oldClient, standby.client)
return event, expiredClients, true
}
return proxySwitchEvent{}, expiredClients, false
}
func replaceClientInOrder(order []*client.DouyuClient, oldClient, newClient *client.DouyuClient) {
for i, cli := range order {
if cli == oldClient {
order[i] = newClient
return
}
}
}
func (s *Scheduler) startProxyRefill() {
cfg := s.proxySettings()
if !cfg.enabled || cfg.proxyAPI == "" {
return
}
base := s.clientSnapshot()
if base == nil {
return
}
s.clientMu.Lock()
need := s.proxyStandbyTarget - len(s.proxyStandbys)
if need <= 0 || s.proxyRefillInFlight {
s.clientMu.Unlock()
return
}
s.proxyRefillInFlight = true
generation := s.proxyPoolGeneration
excludedURLs := copyStringSet(s.proxyExcludedURLs)
s.clientMu.Unlock()
go s.refillProxyStandbys(base, cfg, generation, need, excludedURLs)
}
func (s *Scheduler) refillProxyStandbys(base *client.DouyuClient, cfg proxySettingsSnapshot, generation uint64, need int, excludedURLs map[string]struct{}) {
proxies, err := s.fetchAndValidateProxyPool(base, cfg, need, excludedURLs)
if err != nil {
logger.LogEvent("代理", "warn", "备用代理补提取未完全成功: %v", err)
}
var extras []*client.DouyuClient
var switches []proxySwitchEvent
var expiredClients []*client.DouyuClient
s.clientMu.Lock()
if generation != s.proxyPoolGeneration {
s.clientMu.Unlock()
closeValidatedProxies(proxies)
return
}
currentNeed := s.proxyStandbyTarget - len(s.proxyStandbys)
if currentNeed < 0 {
currentNeed = 0
}
if len(proxies) > currentNeed {
for _, proxy := range proxies[currentNeed:] {
extras = append(extras, proxy.client)
}
proxies = proxies[:currentNeed]
}
for _, proxy := range proxies {
proxyClient := proxy.client
client.MonitorProxyHealth(proxyClient, func(err error) {
s.recordProxyResult(proxyClient, err)
})
s.proxyStandbys = append(s.proxyStandbys, proxy)
s.proxyClientPool = append(s.proxyClientPool, proxy.client)
s.proxyExcludedURLs[proxy.url] = struct{}{}
}
for {
pendingClient, pendingGroup := findFailedProxyGroup(s.proxyGroups)
if pendingClient == nil {
break
}
event, expired, switched := s.switchGroupToStandbyLocked(pendingClient, pendingGroup)
expiredClients = append(expiredClients, expired...)
if !switched {
break
}
switches = append(switches, event)
}
s.proxyRefillInFlight = false
remainingFailed := countFailedProxyGroups(s.proxyGroups)
standbyCount := len(s.proxyStandbys)
standbyTarget := s.proxyStandbyTarget
s.clientMu.Unlock()
closeDouyuClientList(extras)
closeDouyuClientList(expiredClients)
for _, event := range switches {
logProxySwitch("备用代理补提取成功", event)
}
if len(proxies) > 0 {
logger.LogEvent("代理", "success", "备用代理已补充: 新增=%d,剩余=%d,目标=%d",
len(proxies), standbyCount, standbyTarget)
}
if remainingFailed > 0 {
logger.LogEvent("代理", "warn", "仍有%d个代理组等待备用代理,请检查提取 API 配额与白名单", remainingFailed)
}
if standbyCount < standbyTarget && len(proxies) > 0 {
s.startProxyRefill()
}
}
func findFailedProxyGroup(groups map[*client.DouyuClient]*proxyRuntimeGroup) (*client.DouyuClient, *proxyRuntimeGroup) {
for cli, group := range groups {
if group != nil && group.failed {
return cli, group
}
}
return nil, nil
}
func countFailedProxyGroups(groups map[*client.DouyuClient]*proxyRuntimeGroup) int {
count := 0
for _, group := range groups {
if group != nil && group.failed {
count++
}
}
return count
}
func copyStringSet(source map[string]struct{}) map[string]struct{} {
out := make(map[string]struct{}, len(source))
for value := range source {
out[value] = struct{}{}
}
return out
}
func logProxySwitch(label string, event proxySwitchEvent) {
logger.LogEvent("代理", "warn", "%s: 账号=%d %s -> %s IP=%s 归属=%s RTT=%s 来源=%s",
label, len(event.accountNames), client.MaskProxyURL(event.fromURL), client.MaskProxyURL(event.toURL),
event.toIP, event.toRegion, event.toRTT.Round(time.Millisecond), event.toSource)
}
func proxyPoolExpiresAt(apiURL string, now time.Time) time.Time {
minutes := 10
if u, err := url.Parse(strings.TrimSpace(apiURL)); err == nil {
@@ -451,8 +906,8 @@ func (s *Scheduler) validateProxy(base *client.DouyuClient, proxyURL, source str
}
var lastErr error
for attempt := 0; attempt < proxyValidateAttempts; attempt++ {
sample, sampleErr := cli.ServerTimeSample()
if sampleErr == nil && !sample.Fallback {
sample, sampleErr := cli.ProbeServerTime()
if sampleErr == nil {
return validatedProxy{
url: proxyURL,
client: cli,
+50 -7
View File
@@ -1,6 +1,7 @@
package seckill
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -41,17 +42,35 @@ func TestProxyPoolExpiresAtUsesMinuteParameter(t *testing.T) {
}
}
func TestProxyStandbyCount(t *testing.T) {
cases := []struct {
active int
percent int
want int
}{
{active: 1, percent: 25, want: 1},
{active: 6, percent: 25, want: 2},
{active: 10, percent: 25, want: 3},
{active: 6, percent: 1, want: 1},
}
for _, tc := range cases {
if got := proxyStandbyCount(tc.active, tc.percent); got != tc.want {
t.Errorf("proxyStandbyCount(%d, %d)=%d, want %d", tc.active, tc.percent, got, tc.want)
}
}
}
func TestAccountClientsRespectExpiryAndSettingsRevision(t *testing.T) {
scheduler := &Scheduler{
client: &client.DouyuClient{},
accountClients: make(map[string]*client.DouyuClient),
}
groupClient := &client.DouyuClient{}
scheduler.replaceAccountClients(
map[string]*client.DouyuClient{"a": groupClient},
[]*client.DouyuClient{groupClient},
time.Now().Add(time.Minute),
)
scheduler.replaceAccountClients(preparedProxyPool{
accountClients: map[string]*client.DouyuClient{"a": groupClient},
activeClients: []*client.DouyuClient{groupClient},
expiresAt: time.Now().Add(time.Minute),
})
if !scheduler.accountClientsCover([]string{"a"}) {
t.Fatal("未过期代理组应可复用")
}
@@ -67,8 +86,8 @@ func TestAccountClientsRespectExpiryAndSettingsRevision(t *testing.T) {
func TestPrepareProxyGroupsRoutesAccountsToDistinctClients(t *testing.T) {
timeAPIURL := "http://douyu.test/time"
proxyServers := make([]*httptest.Server, 0, 3)
for i := 0; i < 3; i++ {
proxyServers := make([]*httptest.Server, 0, 5)
for i := 0; i < 5; i++ {
proxyServers = append(proxyServers, newTimeProxyServer(t))
}
var next int32
@@ -86,6 +105,7 @@ func TestPrepareProxyGroupsRoutesAccountsToDistinctClients(t *testing.T) {
ProxyAPI: apiServer.URL,
AutoFetchProxyOnSchedule: true,
AccountsPerProxy: 2,
ProxySparePercent: 25,
})
accountProducts := make(map[string]string)
@@ -108,6 +128,29 @@ func TestPrepareProxyGroupsRoutesAccountsToDistinctClients(t *testing.T) {
if scheduler.clientForAccount("e") == scheduler.clientForAccount("a") {
t.Fatal("e 应使用独立代理客户端")
}
if len(scheduler.proxyStandbys) != 1 {
t.Fatalf("备用代理=%d, want 1", len(scheduler.proxyStandbys))
}
standbyClient := scheduler.proxyStandbys[0].client
scheduler.UpdateProxySettings(types.Config{
ProxyEnabled: true,
ProxyURL: "http://127.0.0.1:1",
AccountsPerProxy: 2,
ProxySparePercent: 25,
})
proxyErr := errors.New("read tcp: connection reset by peer")
scheduler.recordProxyResult(scheduler.clientForAccount("a"), proxyErr)
if scheduler.clientForAccount("a") == standbyClient {
t.Fatal("单次网络异常不应立即切换备用代理")
}
scheduler.recordProxyResult(scheduler.clientForAccount("a"), proxyErr)
if scheduler.clientForAccount("a") != standbyClient || scheduler.clientForAccount("b") != standbyClient {
t.Fatal("连续网络异常后整组账号应切换到备用代理")
}
if scheduler.clientForAccount("c") == standbyClient {
t.Fatal("其他代理组不应被错误切换")
}
}
func newTimeProxyServer(t *testing.T) *httptest.Server {
+11 -2
View File
@@ -58,13 +58,21 @@ type runSettings struct {
// 具体职责拆分到同包文件:attempt.go(兑换执行)、warmup.go(预热)、
// schedule_timer.go(定时抢购)、account_store.go(账号管理)。
type Scheduler struct {
clientMu sync.RWMutex
client *client.DouyuClient
clientMu sync.RWMutex
proxyPrepareMu sync.Mutex
client *client.DouyuClient
// accountClients 按账号名路由到独立的代理客户端;未命中的账号使用 client。
accountClients map[string]*client.DouyuClient
accountClientOrder []*client.DouyuClient
accountClientsDirty bool
accountClientsExpireAt time.Time
proxyGroups map[*client.DouyuClient]*proxyRuntimeGroup
proxyStandbys []validatedProxy
proxyClientPool []*client.DouyuClient
proxyExcludedURLs map[string]struct{}
proxyStandbyTarget int
proxyPoolGeneration uint64
proxyRefillInFlight bool
paths types.AppPaths
font *truetype.Font
@@ -109,6 +117,7 @@ type Scheduler struct {
proxyAPI string
autoFetchProxyOnSchedule bool
accountsPerProxy int
proxySparePercent int
autoWhitelist bool
whitelistReplace bool
whitelistPassword string
+6 -2
View File
@@ -173,13 +173,17 @@ func TestPayRetryDelayStaysShort(t *testing.T) {
// TestFirstPayDelayStaysAboveServerMinimum 守住"锁单优先、支付从容"这条设计前提。
//
// 实测(2026-10-03 两次模拟):锁单后 +0.50s/+0.60s/+1.37s/+1.68s 发起的支付
// 一律被"您点击太快,请稍等再试"拒绝,+2.1s 以上发起的全部一次通过。
// 一律被"您点击太快,请稍等再试"拒绝,+2.1s 以上发起的全部一次通过;
// 2026-11-19 网页在锁单响应后 3.26s 支付一次成功。
// 0.3.1 曾把等待压到 0.3-0.7 秒,结果 6 个号各白挨两次拒绝、反而多花 2.7 秒。
func TestFirstPayDelayStaysAboveServerMinimum(t *testing.T) {
const measuredMinimum = 2 * time.Second
const measuredMinimum = 3 * time.Second
if peaceLockPayMin < measuredMinimum {
t.Fatalf("首次支付等待下限 = %v,必须不低于实测阈值 %v", peaceLockPayMin, measuredMinimum)
}
if peaceLockPayMax > 4*time.Second {
t.Fatalf("首次支付等待上限 = %v,超过设计上限 4s", peaceLockPayMax)
}
if peaceLockPayMax < peaceLockPayMin {
t.Fatalf("支付等待区间非法: [%v, %v]", peaceLockPayMin, peaceLockPayMax)
}
+2
View File
@@ -20,8 +20,10 @@ type Config struct {
ProxyEnabled bool `json:"proxyEnabled"` // 是否启用代理
ProxyURL string `json:"proxyUrl"` // 代理地址,支持 http://, https://, socks5://
ProxyAPI string `json:"proxyApi"` // 代理提取 API 地址,支持品赞与通用格式
ProxyExpiresAt int64 `json:"proxyExpiresAt,omitempty"` // 当前静态代理的过期时间(Unix 毫秒),0 表示未知
AutoFetchProxyOnSchedule bool `json:"autoFetchProxyOnSchedule"` // 定时抢购触发前自动从 API 提取最新代理
AccountsPerProxy int `json:"accountsPerProxy"` // 每个独立代理承载的账号数
ProxySparePercent int `json:"proxySparePercent"` // 额外提取的备用代理比例,至少预留一个
ProxyAutoWhitelist bool `json:"proxyAutoWhitelist"` // 提取前自动添加本机公网 IP 白名单
ProxyWhitelistReplace bool `json:"proxyWhitelistReplace"` // 白名单已满时替换最早 IP
ProxyWhitelistPassword string `json:"proxyWhitelistPassword"` // 白名单签名使用的登录密码
+2 -2
View File
@@ -2,7 +2,7 @@
"$schema": "https://wails.io/schemas/config.v2.json",
"name": "douyu_go",
"outputfilename": "douyu_go",
"version": "0.4.0",
"version": "0.5.0",
"frontend:dir": "frontend",
"frontend:install": "npm install",
"frontend:build": "npm run build",
@@ -15,6 +15,6 @@
"email": "yml@example.com"
},
"info": {
"productVersion": "0.4.0"
"productVersion": "0.5.0"
}
}