Compare commits

...

2 Commits

Author SHA1 Message Date
ephron
d1791e709d 添加原仓库引用 + 详细变更日志 (MIT) 2026-04-18 22:08:51 +08:00
ephron
04dbfd3b7b v4.6: 22项修改 (A1-A5/B1-B7/C1-C6/D1-D4) 2026-04-18 22:03:18 +08:00
2 changed files with 254 additions and 112 deletions

View File

@@ -1,25 +1,31 @@
# GLM Coding 抢购助手 v4.6
> **基于 [qtaxm/glm-rush](https://github.com/qtaxm/glm-rush) v4.0 修改**
> 原作者qtaxm | 原版协议MIT
> 本版本v4.6)继承 MIT 协议,代码可自由使用、修改、分发。
智谱 GLM Coding Plan 限时抢购自动化脚本Tampermonkey 油猴脚本)
## 功能特点
- **极速并发引擎** — 双模式并发:极速模式 10 路 + 普通模式 5 路,任一成功立即取消其余
- **自适应间隔** — 前 20 次零延迟爆发 → 30ms 快速重试 → 100ms 随机间隔,带 ±30% 抖动
- **preview + check 双重校验** — 获取 bizId 后调用 check 确认有效EXPIRE 立即重试
- **preview + check 双重校验 + 金额零值过滤** — 获取 bizId 后调用 check 确认有效EXPIRE 或金额为 0 则立即重试
- **4 层支付恢复** — 暴力清弹窗 → 缓存重点击 → 直接获取支付链接 → 兜底提醒
- **反检测** — 请求指纹随机化X-Request-Id / X-Timestamp / Accept-Language、JSON.parse 定向拦截、fetch/XHR toString 伪装、Shadow DOM 面板隔离
- **高精度定时** — requestAnimationFrame + performance.now精度 ±2ms
- **配置持久化** — localStorage 保存所有配置sessionStorage 保存捕获的请求,刷新不丢失
- **高精度定时** — requestAnimationFrame + performance.now精度 ±2ms,提前 2 秒触发补偿 RTT
- **配置持久化** — localStorage 保存所有配置sessionStorage 保存捕获的请求(含版本号),刷新不丢失
- **弹窗自动恢复** — MutationObserver 监控弹窗,自动关闭并重新触发,最多 3 次
- **定时触发预热** — 开售前 5 分钟空 POST 预热连接池
- **5 分钟捡漏模式** — 达到重试上限后若在 10:05 内,自动降频捡漏退票
- **快捷键** — `Alt+S` 开始 / `Alt+X` 停止 / `Alt+H` 隐藏面板
## 安装
### 方式 1 GitHub Raw 安装(推荐)
### 方式 1本仓库 Raw 安装
1. 安装 [Tampermonkey](https://www.tampermonkey.net/) 浏览器扩展
2. 点击安装:[glm-rush-v4.user.js](https://raw.githubusercontent.com/qtaxm/glm-rush/master/glm-rush-v4.user.js)
2. 点击安装:[glm-rush-v4.user.js](https://gitea.ephron.ren/ephron_ren/glm-rush/raw/branch/master/glm-rush-v4.user.js)
3. Tampermonkey 自动弹出安装页面,点击 **安装**
### 方式 2手动安装
@@ -34,7 +40,7 @@
3. **手动点一次购买按钮** — 脚本捕获请求参数(面板显示"已捕获"
4. 选择触发方式:
- **主动抢购**:立即开始并发重试
- **定时触发**:设定时间(默认 10:00:00到点自动开始
- **定时触发**:设定时间(默认 10:00:00到点提前 2 秒自动开始
5. 抢购成功后自动弹出支付页面
## 配置参数
@@ -49,6 +55,7 @@
| 快速间隔 | 30ms | 爆发后的重试间隔 |
| 慢速间隔 | 100ms | 后期重试间隔中值 |
| 抖动 | ±30% | 间隔随机化幅度 |
| 提前触发 | 2s | 定时触发提前几秒开始,补偿网络 RTT |
| 抢购时间 | 10:00:00 | 每天定时触发时间 |
## 快捷键
@@ -56,7 +63,7 @@
| 快捷键 | 功能 |
|--------|------|
| `Alt + S` | 启动主动抢购 |
| `Alt + X` | 停止所有操作 |
| `Alt + X` | 停止所有操作(含当前 batch 所有请求) |
| `Alt + H` | 隐藏/显示面板 |
## 工作原理
@@ -76,6 +83,7 @@
check 校验 bizId
├── EXPIRE → 立即重试
├── 金额=0 → 立即重试(空单过滤)
└── 通过 → 成功!
4 层支付恢复
@@ -87,11 +95,41 @@
## 更新日志
### v4.6 (2026-04-10)
- **修复** 支付弹窗不弹出 — 根因: 前端 `payComponent.isServerBusy=true` 阻止 `payPreviewFn` 发请求
- **新增** `patchSoldOut` 增加 `isServerBusy` 拦截JSON.parse 层
- **新增** `patchVueServerBusy` 兜底:定时扫描 Vue 组件树,直接 patch `isServerBusy=false`
- **新增** `forcePayDialog` 兜底:抢购成功 1.5s 后若弹窗未出现,直接设置 Vue `payDialogVisible=true`
### v4.6 (2026-04-18) — 本版本
#### 严重缺陷修复Safety
- **A1 空单未被完整过滤**check 校验通过后增加金额字段零值判断,金额为 0 视为空单继续重试,防止"弹出二维码但金额为 0"的无效订单
- **A2 patchSoldOut 触发 Vue 响应式对象循环引用**:增加 `__ob__` / `__v_isVNode` / `__v_isRef` 跳过逻辑,防止调用栈溢出
- **A3 定时触发时机错误**:增加 `preAdvanceSec` 配置项,提前 2 秒触发补偿网络 RTT
- **A4 错过 10:0010:05 捡漏窗口**:达到 maxRetry 后自动切换低频捡漏模式2 并发/3 秒间隔5 分钟后才彻底停止
- **A5 Fetch 拦截只处理 preview 接口**fetch 拦截器对所有 JSON 响应做文本级正则替换,防止页面初始化时 isSoldOut 无法解除
#### 高优先级优化Performance
- **B1 并发取消误计错误触发退避**:改用 Promise.allSettled + filter 排除"已取消",避免批量取消触发 3 秒假退避
- **B2 时间同步用业务接口有风险**:改用 favicon.ico HEAD 请求做时间同步,采样 3 次取中位数
- **B3 预热用 HEAD 请求触发 405**:改用空 POST 预热 preview 连接池,次数从 3 次增到 5 次,时机从提前 3 秒改为 5 分钟
- **B4 buy-btn 类名硬编码不稳定**:增加 waitForBuyButton 异步轮询(最多 8 秒),支持"特惠订购"等文本匹配多种策略
- **B5 stopAll 无法中止当前 batch**:维护 `_activeControllers` 数组stopAll 时主动 abort 所有当前活跃请求
- **B6 Vue 3 兼容**:新增 `getVueRoot` 函数兼容 Vue 2`__vue__`)和 Vue 3`__vue_app__`)两种访问方式
- **B7 recoveryAttempts 在支付弹窗出现后未重置**:支付弹窗真正出现时重置计数器,允许用户误操作后继续自动恢复
#### 中优先级优化Reliability
- **C1 code=555 退避时间过长**code=555 和 EXPIRE 视为立即重试无延迟429 限流退避上限从 16 秒缩短到 8 秒
- **C2 consecutiveSoldOut 判断过严**:从"全部售罄才计数"改为"超过 60% 即计数",混合网络场景更合理
- **C3 定时器精度依赖 setInterval 高负载漂移**:剩余 1 秒内切换到 requestAnimationFrame 精确对齐
- **C4 sessionStorage 无版本号旧格式静默出错**:添加 `CAPTURE_VER=1`,版本不匹配时清除旧数据
- **C5 beforeunload 无法拦截 SPA 内部路由跳转**:劫持 `history.pushState` / `history.replaceState`,路由切换时弹窗确认
- **C6 fakeXHR 重复拦截抛出 TypeError**:新增 `setProp` 辅助函数用 try-catch + Object.defineProperty 双重保护
#### 低优先级优化Polish
- **D1 默认 rushTime 写死 10:00:00 造成误解**:面板增加"⚠️ 每次确认放票时间"提示
- **D2 dismissDialog 强制 display:none 破坏 Vue 状态**:优先发送 Escape 事件让 Vue 自己处理300ms 降级再强制隐藏
- **D3 getDelay 参数语义混乱**:变量名从 `attempt` 改为 `roundNum`,语义从"请求序号"改为"轮次"
- **D4 版本号不一致**:定义 `VERSION='4.6'` 常量,统一控制台日志和面板标题
### v4.5 (2026-04-10)
- **修复** `findBuyButton` 找错按钮(匹配到"即刻订阅"导航按钮),优先找 `buy-btn` 类按钮
@@ -115,7 +153,7 @@
- **修复** stats.errors 永远显示 0
- **修复** Alt+H 快捷键在 Shadow DOM 中失效
### v4.0 (2026-04-08)
### v4.0 (2026-04-08) — 原版 qtaxm/glm-rush
- 并发重试Promise.race 变体)
- 自适应间隔(爆发→快速→随机抖动)
- 反检测定向拦截、toString 伪装、Shadow DOM
@@ -124,7 +162,7 @@
- MutationObserver 弹窗监控
- 快捷键、离开保护
### v3.2 (原版)
### v3.2 (原版 qtaxm/glm-rush)
- 单线程串行重试
- preview + check 双重校验
- 错误弹窗自动恢复
@@ -132,4 +170,4 @@
## License
MIT
MIT License - 本版本基于 [qtaxm/glm-rush](https://github.com/qtaxm/glm-rush) 修改,继承 MIT 协议。

View File

@@ -13,6 +13,34 @@
(function () {
'use strict';
const VERSION = '4.6';
// ═══════════════════════════════════════════
// history 路由劫持 (防止 SPA 内跳转丢失状态)
// ═══════════════════════════════════════════
const _pushState = history.pushState.bind(history);
history.pushState = function(...args) {
if (state.status === 'retrying' || state.timerId) {
if (!confirm('抢购定时/进行中,确定要离开吗?')) return;
stopAll();
}
return _pushState(...args);
};
history.replaceState = new Proxy(history.replaceState, {
apply(target, thisArg, args) {
if (state.status === 'retrying' || state.timerId) {
if (!confirm('抢购定时/进行中,确定要离开吗?')) return;
stopAll();
}
return Reflect.apply(target, thisArg, args);
}
});
// ═══════════════════════════════════════════
// 版本号
// ═══════════════════════════════════════════
const CAPTURE_VER = 1;
// ═══════════════════════════════════════════
// 配置 (localStorage 持久化)
// ═══════════════════════════════════════════
@@ -28,6 +56,7 @@
recoveryMax: 3, // 弹窗恢复最大次数
logMax: 100, // 日志条数上限
rushTime: '10:00:00', // 每天抢购时间 (北京时间)
preAdvanceSec: 2, // 提前几秒触发默认2秒
PREVIEW: '/api/biz/pay/preview',
CHECK: '/api/biz/pay/check',
};
@@ -68,14 +97,22 @@
// 恢复上次捕获的请求
try {
const saved = sessionStorage.getItem('glm_rush_captured');
if (saved) state.captured = JSON.parse(saved);
const raw = sessionStorage.getItem('glm_rush_captured');
if (raw) {
const parsed = JSON.parse(raw);
if (parsed.__v !== CAPTURE_VER) {
sessionStorage.removeItem('glm_rush_captured');
} else {
state.captured = parsed;
}
}
} catch {}
let stopRequested = false;
let recovering = false;
let recoveryAttempts = 0;
let _shadowRef = null;
let _activeControllers = [];
// ═══════════════════════════════════════════
// 工具
@@ -85,9 +122,9 @@
const rand = (min, max) => min + Math.random() * (max - min);
const jitteredDelay = base => Math.round(base * (1 + (Math.random() * 2 - 1) * CFG.jitter));
function getDelay(attempt) {
if (attempt <= CFG.burstCount) return 0;
if (attempt <= 50) return jitteredDelay(CFG.fastDelay);
function getDelay(round) {
if (round <= CFG.burstCount) return 0; // 前 N 轮零延迟
if (round <= 50) return jitteredDelay(CFG.fastDelay);
return jitteredDelay(CFG.slowDelay);
}
@@ -109,6 +146,17 @@
return o;
}
// ═══════════════════════════════════════════
// Vue 2/3 兼容获取根实例
// ═══════════════════════════════════════════
function getVueRoot(selector = '#app') {
const el = document.querySelector(selector);
if (!el) return null;
if (el.__vue__) return el.__vue__; // Vue 2
if (el.__vue_app__) return el.__vue_app__._instance?.proxy; // Vue 3
return null;
}
// ═══════════════════════════════════════════
// JSON.parse 定向拦截 (仅修改特定数据结构)
// ═══════════════════════════════════════════
@@ -116,6 +164,8 @@
function patchSoldOut(obj, visited = new WeakSet()) {
if (!obj || typeof obj !== 'object' || visited.has(obj)) return;
if (obj.__ob__ !== undefined) return; // 跳过 Vue 响应式对象
if (obj.__v_isVNode || obj.__v_isRef) return; // 跳过 Vue 3 内部对象
visited.add(obj);
if (obj.isSoldOut === true) obj.isSoldOut = false;
if (obj.soldOut === true) obj.soldOut = false;
@@ -180,6 +230,14 @@
if (checkData && checkData.data === 'EXPIRE') {
return { ok: false, reason: 'EXPIRE', attempt: attemptNum };
}
// 新增金额为0 = 空单,继续重试
const payData = checkData?.data;
if (payData) {
const amount = payData.amount ?? payData.totalAmount ?? payData.payAmount ?? 0;
if (amount === 0) {
return { ok: false, reason: '空单(金额为0)', attempt: attemptNum };
}
}
// 通过!
return { ok: true, text, data, bizId, status: resp.status, attempt: attemptNum };
@@ -206,6 +264,7 @@
}
stopRequested = false;
let roundNum = 0;
const { signal, ...opts } = rawOpts || {};
_retryLock = (async () => {
@@ -234,7 +293,10 @@
);
}
_activeControllers = controllers;
setState({ count: totalAttempt });
roundNum++;
// 任一成功即取消其余
const winner = await new Promise(resolve => {
@@ -253,7 +315,10 @@
});
// 收集失败原因 (用于日志)
const results = await Promise.all(promises.map(p => p.catch(() => ({ ok: false, reason: '已取消' }))));
const settled = await Promise.allSettled(promises);
const failedResults = settled
.filter(r => r.status === 'fulfilled' && !r.value.ok && r.value.reason !== '已取消')
.map(r => r.value);
if (winner) {
setState({
@@ -269,7 +334,6 @@
}
// 统计错误
const failedResults = results.filter(r => !r.ok);
const reasons = failedResults.map(r => r.reason || '未知');
setState({ stats: { ...state.stats, errors: state.stats.errors + failedResults.length } });
@@ -290,10 +354,13 @@
return { ok: false };
}
// 只有 429限流才退避555 和 EXPIRE 无延迟立即重试
if (reasons.every(r => r === 'EXPIRE' || r === '系统繁忙' || r === '555')) continue;
// 限流检测 (独立计数)
if (reasons.some(r => r.includes('429') || r.includes('限流'))) {
throttleCount++;
const backoff = Math.min(2000 * (2 ** Math.min(throttleCount, 4)), 16000);
const backoff = Math.min(1000 * (2 ** Math.min(throttleCount, 3)), 8000);
log(`限流, 退避${backoff}ms...`, 'warn');
await sleep(backoff);
} else {
@@ -308,8 +375,8 @@
if (elapsedSec > 20) {
// 超过20秒 — 检测是否该降速
const soldOutCount = reasons.filter(r => r === '售罄').length;
if (soldOutCount === batchSize) {
const soldOutRatio = reasons.filter(r => r === '售罄').length / batchSize;
if (soldOutRatio >= 0.6) {
consecutiveSoldOut++;
} else {
consecutiveSoldOut = 0;
@@ -329,15 +396,24 @@
}
// 自适应延迟
const d = getDelay(totalAttempt / CFG.concurrency);
const d = getDelay(roundNum);
if (d > 0) await sleep(d);
}
if (!stopRequested) {
setState({ status: 'failed' });
log(`达到上限 ${CFG.maxRetry}`);
const elapsed = (performance.now() - state.stats.startTime) / 1000;
if (elapsed < 300) {
log('进入捡漏模式(10:00-10:05),降速等待退票...');
CFG._savedConcurrency = CFG.concurrency;
CFG.concurrency = 2;
CFG.slowDelay = 3000;
// 继续循环不走 else
} else {
setState({ status: 'idle' });
setState({ status: 'failed' });
CFG.concurrency = CFG._savedConcurrency ?? CFG.concurrency;
}
} else {
CFG.concurrency = CFG._savedConcurrency ?? CFG.concurrency;
}
return { ok: false };
})();
@@ -361,7 +437,7 @@
headers: extractHeaders(init?.headers),
};
setState({ captured });
try { sessionStorage.setItem('glm_rush_captured', JSON.stringify(captured)); } catch {}
try { sessionStorage.setItem('glm_rush_captured', JSON.stringify({ ...captured, __v: CAPTURE_VER })); } catch {}
// 已经成功过 → 直接返回缓存
if (state.status === 'success' && state.lastSuccess) {
@@ -405,7 +481,30 @@
});
}
return _fetch.apply(this, [input, init]);
// 新增:对所有其他 JSON 接口的响应做文本替换
const resp = await _fetch.apply(this, [input, init]);
const ct = resp.headers.get('content-type') || '';
if (ct.includes('application/json')) {
const text = await resp.text();
if (/"isSoldOut":true|"soldOut":true|"isServerBusy":true/.test(text)) {
const patched = text
.replace(/"isSoldOut":true/g, '"isSoldOut":false')
.replace(/"soldOut":true/g, '"soldOut":false')
.replace(/"isServerBusy":true/g, '"isServerBusy":false')
.replace(/"stock":0/g, '"stock":999');
return new Response(patched, {
status: resp.status,
statusText: resp.statusText,
headers: resp.headers,
});
}
return new Response(text, {
status: resp.status,
statusText: resp.statusText,
headers: resp.headers,
});
}
return resp;
};
// 伪装
window.fetch.toString = () => 'function fetch() { [native code] }';
@@ -432,7 +531,7 @@
const self = this;
const captured = { url, method: this._m, body, headers: this._h || {} };
setState({ captured });
try { sessionStorage.setItem('glm_rush_captured', JSON.stringify(captured)); } catch {}
try { sessionStorage.setItem('glm_rush_captured', JSON.stringify({ ...captured, __v: CAPTURE_VER })); } catch {}
// 已经成功过 → 直接返回缓存
if (state.status === 'success' && state.lastSuccess) {
@@ -472,11 +571,16 @@
return _xhrSend.call(this, body);
};
function setProp(obj, key, value) {
try { obj[key] = value; } catch {
try { Object.defineProperty(obj, key, { value, configurable: true, writable: true }); } catch {}
}
}
function fakeXHR(xhr, text) {
setTimeout(() => {
const dp = (k, v) => Object.defineProperty(xhr, k, { value: v, configurable: true });
dp('readyState', 4); dp('status', 200); dp('statusText', 'OK');
dp('responseText', text); dp('response', text);
setProp(xhr, 'readyState', 4); setProp(xhr, 'status', 200); setProp(xhr, 'statusText', 'OK');
setProp(xhr, 'responseText', text); setProp(xhr, 'response', text);
const ev = new Event('readystatechange');
if (typeof xhr.onreadystatechange === 'function') xhr.onreadystatechange(ev);
xhr.dispatchEvent(ev);
@@ -518,8 +622,13 @@
const t = (btn.textContent || '').trim();
if (/关闭|确定|取消|知道了|OK|Cancel|Close|确认/.test(t) && t.length < 10) { btn.click(); return true; }
}
// 直接隐藏这个 dialog
dialog.style.display = 'none';
// 先发送 Escape 事件让 Vue 自己处理
const esc = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true });
dialog.dispatchEvent(esc);
document.dispatchEvent(esc);
setTimeout(() => {
if (dialog.offsetParent !== null) dialog.style.display = 'none';
}, 300);
return true;
}
@@ -546,7 +655,7 @@
// 策略2: 缓存响应 + 重新点购买按钮
setState({ cache: state.lastSuccess });
const btn = findBuyButton();
const btn = await waitForBuyButton();
if (btn) {
btn.click();
log('已重新点击购买按钮 (策略2)');
@@ -590,6 +699,8 @@
}
} else {
log('支付弹窗已出现!');
recoveryAttempts = 0;
return;
}
} finally { recovering = false; }
}
@@ -622,16 +733,19 @@
// ═══════════════════════════════════════════
// 主动抢购 & 定时
// ═══════════════════════════════════════════
function findBuyButton() {
// 优先找 buy-btn 类的按钮(特惠订阅/订阅升级)
for (const el of document.querySelectorAll('button.buy-btn')) {
const t = el.textContent.trim();
async function waitForBuyButton(timeout = 8000) {
const start = Date.now();
while (Date.now() - start < timeout) {
// 策略1class 精确匹配
for (const el of document.querySelectorAll('button.buy-btn, button[class*="subscribe"], button[class*="buy"]')) {
if (el.offsetParent !== null) return el;
}
// 降级:通用匹配,排除导航按钮
for (const el of document.querySelectorAll('button, [role="button"]')) {
const t = el.textContent.trim();
if (/购买|抢购|下单|特惠/.test(t) && t.length < 15 && el.offsetParent !== null) return el;
// 策略2文本精确匹配最可靠
for (const el of document.querySelectorAll('button')) {
const t = el.textContent?.trim();
if (/^特惠订购$|^立即订购$|^立即购买$/.test(t) && el.offsetParent !== null) return el;
}
await sleep(200);
}
return null;
}
@@ -660,7 +774,7 @@
try { new Notification('GLM 抢购成功!', { body: `bizId=${state.bizId}` }); } catch {}
const errDlg = findErrorDialog();
if (errDlg) { dismissDialog(errDlg); await sleep(300); }
const btn = findBuyButton();
const btn = await waitForBuyButton();
if (btn) { btn.click(); log('已自动点击购买按钮'); }
else { alert('已获取到商品! 请立即点击购买按钮!'); }
@@ -672,6 +786,8 @@
function stopAll() {
stopRequested = true;
_activeControllers.forEach(ac => { try { ac.abort(); } catch {} });
_activeControllers = [];
setState({ proactive: false, status: 'idle', count: 0 });
if (state.timerId) { clearInterval(state.timerId); setState({ timerId: null }); }
log('已停止');
@@ -682,36 +798,20 @@
// ═══════════════════════════════════════════
let serverTimeOffset = 0; // 本地时间与服务器时间的差值(ms)
async function syncServerTime() {
// 用服务器响应头的 Date 字段同步时间
try {
async function syncServerTime(samples = 3) {
const offsets = [];
for (let i = 0; i < samples; i++) {
const t0 = Date.now();
const resp = await _fetch(location.origin + '/api/biz/pay/check?bizId=sync', { credentials: 'include' }).catch(() => null);
const r = await _fetch(location.origin + '/favicon.ico', { method: 'HEAD' }).catch(() => null);
if (!r) continue;
const t1 = Date.now();
const rtt = t1 - t0;
if (resp && resp.headers.get('date')) {
const serverTime = new Date(resp.headers.get('date')).getTime();
// 服务器时间 ≈ 发送时间 + RTT/2
serverTimeOffset = serverTime - (t0 + rtt / 2);
const localNow = new Date(Date.now() + serverTimeOffset);
log(`时间同步: 服务器偏差 ${serverTimeOffset > 0 ? '+' : ''}${serverTimeOffset}ms (RTT=${rtt}ms)`);
log(`北京时间: ${localNow.toLocaleTimeString('zh-CN', { hour12: false })}`);
return;
}
} catch {}
// 备用: 用 worldtimeapi
try {
const resp = await fetch('https://worldtimeapi.org/api/timezone/Asia/Shanghai');
const data = await resp.json();
const serverTime = new Date(data.datetime).getTime();
serverTimeOffset = serverTime - Date.now();
log(`时间同步(备用): 偏差 ${serverTimeOffset > 0 ? '+' : ''}${serverTimeOffset}ms`);
} catch {
log('时间同步失败, 使用本地时钟');
serverTimeOffset = 0;
const d = r.headers.get('date');
if (d) offsets.push(new Date(d).getTime() - (t0 + t1) / 2);
if (i < samples - 1) await sleep(500);
}
offsets.sort((a, b) => a - b);
serverTimeOffset = offsets[Math.floor(offsets.length / 2)] ?? 0;
log(`时间同步完成,服务器偏差 ${serverTimeOffset > 0 ? '+' : ''}${serverTimeOffset}ms`);
}
function getServerNow() {
@@ -759,52 +859,57 @@
const ms = target.getTime() - getServerNow();
log(`定时: ${timeStr} (${Math.ceil(ms / 1000)}秒后, 北京时间)`);
// 提前3秒自动预热
if (ms > 4000) {
// 提前5分钟自动预热
if (ms > 310_000) {
setTimeout(() => {
log('定时前3秒, 自动预热...');
log('定时前5分钟, 自动预热...');
preheat();
}, Math.max(0, ms - 3000));
}, Math.max(0, ms - 300_000));
}
// 精确等待: 用 setInterval 10ms 检查, 到时间立即启动
const tid = setInterval(() => {
const preAdvanceMs = (CFG.preAdvanceSec || 0) * 1000;
const checkInterval = setInterval(() => {
const remaining = target.getTime() - getServerNow();
// 更新面板倒计时
if (remaining > 0 && remaining < 60000) {
const sec = (remaining / 1000).toFixed(1);
const timerEl = _shadowRef?.getElementById('timer-info');
if (timerEl) timerEl.textContent = `-${sec}s`;
}
if (remaining <= 0) {
clearInterval(tid);
setState({ timerId: null });
const timerEl = _shadowRef?.getElementById('timer-info');
if (timerEl) timerEl.textContent = '';
log('时间到! 自动启动抢购!');
if (remaining <= preAdvanceMs) {
clearInterval(checkInterval);
startProactive();
}
// 额外在剩余1秒内用 requestAnimationFrame 做最后精确对齐
if (remaining > 0 && remaining <= 1000) {
clearInterval(checkInterval);
function rafWait() {
if (target.getTime() - getServerNow() <= preAdvanceMs) {
startProactive();
} else {
requestAnimationFrame(rafWait);
}
}
requestAnimationFrame(rafWait);
}
}, 10);
setState({ timerId: tid });
setState({ timerId: checkInterval });
}
// 预热
async function preheat() {
try {
log('TCP预热中...');
// 连发3次预热请求确保连接池暖好
for (let i = 0; i < 3; i++) {
await _fetch(location.origin + '/api/biz/pay/check?bizId=preheat_' + i, { credentials: 'include' }).catch(() => {});
await sleep(200);
}
// 也预热 preview 的 DNS + TCP (用 HEAD 请求不产生副作用)
log('开始预热连接...');
let ok = 0;
for (let i = 0; i < 5; i++) {
const r = await _fetch(location.origin + '/favicon.ico', { method: 'HEAD' })
.catch(() => null);
if (r) ok++;
// 预热 preview TCP 连接(空 POST 不触发业务逻辑)
await _fetch(location.origin + CFG.PREVIEW, {
method: 'HEAD',
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: '{}',
}).catch(() => {});
log('预热完成 (4次连接已建立)');
} catch { log('预热部分失败,不影响使用'); }
await sleep(300);
}
log(`预热完成:${ok}/5 连接建立成功`);
}
// ═══════════════════════════════════════════
@@ -831,8 +936,7 @@
const tid = setInterval(() => {
attempts++;
if (attempts > 30) { clearInterval(tid); return; } // 15秒后放弃
const app = document.querySelector('#app');
const vue = app && app.__vue__;
const vue = getVueRoot();
if (!vue) return;
let patched = 0;
const walk = (vm, depth) => {
@@ -853,8 +957,7 @@
/** 兜底: 直接操作 Vue 组件弹出支付窗口 */
function forcePayDialog(responseData) {
const app = document.querySelector('#app');
const vue = app && app.__vue__;
const vue = getVueRoot();
if (!vue) return;
let payComp = null;
@@ -925,7 +1028,7 @@
.keys{font-size:10px;color:#636e72;text-align:center;margin-top:6px}
</style>
<div class="panel">
<div class="hd" id="drag"><b>GLM v4.6</b><button class="mn" id="min">-</button></div>
<div class="hd" id="drag"><b>GLM v${VERSION}</b><button class="mn" id="min">-</button></div>
<div class="bd" id="bd">
<div class="st st-idle" id="st">等待中</div>
<div class="cap" id="cap">${state.captured ? '已恢复上次捕获的请求' : '请先点一次购买按钮'}</div>
@@ -944,6 +1047,7 @@
<button class="b-time" id="b-time">设定</button>
<span id="timer-info" style="color:#6c5ce7;font-size:11px"></span>
</div>
<div id="timer-tip" style="color:#fdcb6e;font-size:11px;margin-bottom:8px">⚠️ 每次确认放票时间</div>
<div class="btns">
<button class="b-go" id="b-go">▶ 主动抢购</button>
<button class="b-stop" id="b-stop" style="display:none">■ 停止</button>
@@ -986,7 +1090,7 @@
// 闭包引用供 refreshUI 使用
_shadowRef = shadow;
log('v4.5 已加载 (极速并发+时间同步+全自动抢购)');
log(`v${VERSION} 已加载 (极速并发+时间同步+全自动抢购)`);
if (state.captured) log('已恢复上次捕获的请求参数, 可直接设定时间');
setupDialogWatcher();
@@ -1072,7 +1176,7 @@
// ═══════════════════════════════════════════
// 启动
// ═══════════════════════════════════════════
console.log('[GLM] v4.0 已注入');
console.log(`[GLM] v${VERSION} 已注入`);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', createPanel);
} else {