// ==UserScript== // @name 乐斗辅助 // @namespace http://tampermonkey.net/ // @version 1.10.3 // @description 提供系统繁忙监控、定时刷新、碎片监控、侠客岛任务、自动抢地盘、武器血量高亮、黄历、购物道具仓库余量显示、方向键控制、可扩展定时任务(每日/指定日期 · 访问链接/开启功能开关)、文字游戏、战报多页合并、QQ Cookie持久化登录 // @author xiong1136108122 // @match https://dld.qzapp.z.qq.com/* // @match https://graph.qq.com/* // @grant GM_xmlhttpRequest // @grant GM_setValue // @grant GM_getValue // @grant GM_addStyle // @grant GM_cookie // @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js // @connect qzapp.z.qq.com // @connect fight.pet.qq.com // @connect dld.qzapp.z.qq.com // @connect graph.qq.com // ==/UserScript== (function() { 'use strict'; // ========== 页面类型判断 ========== const IS_GAME_PAGE = location.href.includes('dld.qzapp.z.qq.com'); const IS_LOGIN_PAGE = location.href.includes('graph.qq.com') && (location.href.includes('oauth2.0/show') || location.href.includes('which=Login')) && (location.href.includes('client_id=102067279') || location.href.includes('redirect_uri') && location.href.includes('dld.qzapp.z.qq.com')); // 默认高亮关键字 const DEFAULT_HIGHLIGHT_KEYWORDS = [ '帮派商会', '帮派祭坛', '全民乱斗', '华山论剑', '竞技场', '吉利兑', '飞升大作战', '群侠', '祝福宝库', '远方祝福', '大侠回归三重好礼', '侠客岛', '任务', '九宫宝库', '符石宝箱', '年兽大作战', '喜从天降', '春联大赛', '新元婴神器', '徽章优惠', '乐斗驿站', '乐斗游记' ]; // 默认武器高亮关键词 const DEFAULT_WEAPON_KEYWORDS = [ '神·霸皇', '盘古开天斧', '神·大力神杯', '神·雷神之锤', '神·炼狱加特林', '加特林', '神·死寂', '死神之镰', '神·无限板砖', '神·埃辛诺斯战刃', '神·命运之枪', '神·龙雀', '神·马格南左轮', '神·月光炮', '神·电饭煲', '神·星之杖', '神·死亡笔记', '生死簿', '神·冈格尼尔', '神·可乐切割枪', '神·无敌飞鞋', '神·花仙子' ]; // 获取高亮关键字,确保有默认值 function getHighlightKeywords() { let keywords = GM_getValue('highlightKeywords', null); if (keywords === null || keywords === undefined || (Array.isArray(keywords) && keywords.length === 0)) { keywords = [...DEFAULT_HIGHLIGHT_KEYWORDS]; GM_setValue('highlightKeywords', keywords); } return keywords; } // 获取武器高亮关键字 function getWeaponHighlightKeywords() { let keywords = GM_getValue('weaponHighlightKeywords', null); if (keywords === null || keywords === undefined || (Array.isArray(keywords) && keywords.length === 0)) { keywords = [...DEFAULT_WEAPON_KEYWORDS]; GM_setValue('weaponHighlightKeywords', keywords); } return keywords; } // 配置存储 const CONFIG = { systemBusy: { enabled: GM_getValue('systemBusyEnabled', true), targetText: GM_getValue('systemBusyTargetText', '系统繁忙'), checkInterval: GM_getValue('systemBusyCheckInterval', 100), refreshCooldown: GM_getValue('systemBusyRefreshCooldown', 2000) }, autoRefresh: { enabled: GM_getValue('autoRefreshEnabled', false), interval: GM_getValue('autoRefreshInterval', 2), stopKeywords: GM_getValue('autoRefreshStopKeywords', ['不足','不够']) }, fragmentMonitor: { enabled: GM_getValue('fragmentMonitorEnabled', false), checkUrl: 'https://dld.qzapp.z.qq.com/qpet/cgi-bin/phonepk?zapp_uin=&B_UID=0&sid=&channel=0&g_ut=1&cmd=newAct&subtype=154', jumpUrl: 'https://dld.qzapp.z.qq.com/qpet/cgi-bin/phonepk?zapp_uin=&B_UID=0&sid=&channel=0&g_ut=1&cmd=newAct&subtype=155', triggerKeywords: GM_getValue('fragmentTriggerKeywords', ['王重阳', '王处一']), stopKeywords: GM_getValue('fragmentStopKeywords', ['数量:0', '碎片*5']), interval: GM_getValue('fragmentMonitorInterval', 2) }, knightIsland: { enabled: GM_getValue('knightIslandEnabled', true), checkInterval: GM_getValue('knightIslandCheckInterval', 90) }, territoryGrabber: { enabled: GM_getValue('territoryGrabberEnabled', false), targetLevel: GM_getValue('territoryGrabberTargetLevel', 30), retryLimit: GM_getValue('territoryGrabberRetryLimit', 3), baseDelay: GM_getValue('territoryGrabberBaseDelay', 2000), maxRandomDelay: GM_getValue('territoryGrabberMaxRandomDelay', 3000) }, textGame: { enabled: GM_getValue('textGameEnabled', true), highlightKeywords: getHighlightKeywords(), weaponHighlightKeywords: getWeaponHighlightKeywords() }, goodsStock: { enabled: GM_getValue('goodsStockEnabled', true) }, directionKey: { enabled: GM_getValue('directionKeyEnabled', true), scrollAmount: GM_getValue('directionKeyScrollAmount', 200), fastScrollAmount: GM_getValue('directionKeyFastScrollAmount', 300), enableShiftScroll: GM_getValue('directionKeyEnableShiftScroll', true), ignoreInputs: GM_getValue('directionKeyIgnoreInputs', true), smoothScroll: GM_getValue('directionKeySmoothScroll', true) }, scheduledTasks: { enabled: GM_getValue('scheduledTasksEnabled', false), calibrationRefreshMin: GM_getValue('scheduledCalibrationRefreshMin', 30), tasks: GM_getValue('scheduledTasks', [ { name: '定时任务', type: 'daily', action: 'url', target: 'territoryGrabber', date: '', url: ' ', time: '06:00:01', count: 3, interval: 1000, enabled: true } ]) } }; // ========== 命名常量 ========== const KNIGHT_ISLAND_CHECK_INTERVAL = 5 * 60 * 1000; // 侠客岛奖励检查间隔 const SCHEDULED_TASK_STARTUP_DELAY_MS = 3000; // 定时任务启动延迟 // 定时任务(心跳调度):重复方式 const TASK_TYPE_DAILY = 'daily'; // 每日重复 const TASK_TYPE_ONCE = 'once'; // 指定日期,一次性 // 定时任务(心跳调度):执行动作 const TASK_ACTION_URL = 'url'; // 访问链接 const TASK_ACTION_TOGGLE = 'toggle'; // 开启功能开关 const DEFAULT_TOGGLE_TARGET = 'territoryGrabber'; // 「开启开关」的默认目标 const SCHEDULER_TICK_MS = 250; // 调度心跳间隔(按真实时间判定) const SCHEDULE_CATCHUP_WINDOW_MS = 10 * 60 * 1000; // 「指定日期」任务的补跑窗口(过期执行无意义) const CALIBRATION_SAFE_WINDOW_MS = 10 * 60 * 1000; // 临近任务时禁止校准刷新 const SCHEDULE_STATUS_UPDATE_MS = 10 * 1000; // 面板状态刷新间隔 const TASK_CLAIM_TTL_MS = 5 * 60 * 1000; // 跨标签执行权占位有效期 const TASK_RETRY_COOLDOWN_MS = 60 * 1000; // 执行失败后的重试冷却 const TASK_MAX_ATTEMPTS = 5; // 单轮最多尝试次数(含首次) // ========== 功能开关注册表 ========== // 遍历项目现有全部开关;key 必须与 CONFIG 键名一致 // 推导规则:GM 存储键 = key + 'Enabled',面板开关 id = key + 'Toggle' // 后续新增功能:在 CONFIG 加一项 + 在此追加一行即可(noToggle 表示面板暂无对应开关) const FEATURE_SWITCHES = [ { key: 'systemBusy', label: '系统繁忙监控', on: () => startSystemBusyMonitor(), off: () => stopSystemBusyMonitor() }, { key: 'autoRefresh', label: '定时刷新', on: () => startAutoRefresh(), off: () => stopAutoRefresh() }, { key: 'fragmentMonitor', label: '碎片监控', on: () => startFragmentMonitor(), off: () => stopFragmentMonitor() }, { key: 'knightIsland', label: '侠客岛任务', on: () => initKnightIsland(), off: () => deinitKnightIsland() }, { key: 'territoryGrabber', label: '自动抢地盘', on: () => startTerritoryGrabber(), off: () => stopTerritoryGrabber() }, { key: 'textGame', label: '文字游戏', on: () => applyTextGame(), off: () => location.reload() }, { key: 'goodsStock', label: '仓库余量显示', on: () => { if (isViewGoodsPage()) checkAndDisplayGoodsStock(); }, off: () => {}, noToggle: true }, { key: 'directionKey', label: '方向键控制', on: () => initDirectionKeyControl(), off: () => {}, noToggle: true } ]; // ========== 定时任务动作注册表(后续新增动作只需追加一项)========== const TASK_ACTIONS = [ { key: TASK_ACTION_URL, label: '访问链接' }, { key: TASK_ACTION_TOGGLE, label: '开启开关' } ]; // 统一读写功能开关(面板开关与定时任务共用) function setFeatureSwitch(key, enabled) { const sw = FEATURE_SWITCHES.find(s => s.key === key); if (!sw || !CONFIG[sw.key]) { Mylog(`[功能开关] 未找到开关: ${key}`); return false; } CONFIG[sw.key].enabled = enabled; GM_setValue(`${sw.key}Enabled`, enabled); if (!sw.noToggle) { const toggle = document.getElementById(`${sw.key}Toggle`); if (toggle) toggle.checked = enabled; } if (enabled) sw.on(); else sw.off(); Mylog(`[功能开关] ${sw.label} 已${enabled ? '开启' : '关闭'}`); return true; } // 旧数据兼容:v1.10.0 的 territory 类型迁移为「每日 + 开启开关(抢地盘)」 function normalizeTask(task) { const t = Object.assign({}, task); if (t.type === 'territory') { t.type = TASK_TYPE_DAILY; t.action = TASK_ACTION_TOGGLE; t.target = 'territoryGrabber'; } if (t.type !== TASK_TYPE_ONCE) t.type = TASK_TYPE_DAILY; if (t.action !== TASK_ACTION_TOGGLE) t.action = TASK_ACTION_URL; if (!t.target) t.target = DEFAULT_TOGGLE_TARGET; // interval 统一为毫秒整数(旧版本内部本来就是毫秒) const ms = Number(t.interval); t.interval = Number.isFinite(ms) ? Math.max(0, Math.floor(ms)) : 1000; return t; } CONFIG.scheduledTasks.tasks = CONFIG.scheduledTasks.tasks.map(normalizeTask); // 定时器变量 let module2Timer = null; let module3Timer = null; let territoryGrabberRetryCount = 0; let directionKeyLastScrollTime = 0; let taskSaveTimer = null; // 定时任务自动保存计时器(模块级,不污染全局) let textGameStyleInjected = false; // 文字游戏 CSS 是否已注入 let textGameDebounceTimer = null; // 文字游戏防抖计时器 let schedulerTimerId = null; // 定时任务统一心跳 let calibrationTimerId = null; // 计时校准刷新定时器 let lastStatusUpdateAt = 0; // 上次刷新面板状态的时间 /* ========== 文字游戏模块(高亮+替换) ========== */ // 存储佣兵商城条件的检测结果 let mercenaryShopAvailable = false; function checkMercenaryCondition() { const url2 = 'https://dld.qzapp.z.qq.com/qpet/cgi-bin/phonepk?zapp_uin=&B_UID=0&sid=&channel=0&g_ut=1&cmd=mercenarylottery&op=0'; GM_xmlhttpRequest({ method: 'GET', url: url2, onload: function(response) { const html = response.responseText; mercenaryShopAvailable = CONFIG.fragmentMonitor.triggerKeywords.some( keyword => html.includes(keyword)); // 如果文字游戏已开启,重新应用以使"佣兵商城"高亮 if (CONFIG.textGame.enabled) { applyTextGame(); } }, onerror: function(err) { console.warn('检查佣兵商城条件失败:', err); } }); } function saveTextGameSettings() { // 保存高亮关键字 const highlightInput = document.getElementById('highlightKeywords').value; const highlightKeywords = highlightInput.split(/[,,]/) .map(s => s.trim()) .filter(s => s); CONFIG.textGame.highlightKeywords = highlightKeywords; GM_setValue('highlightKeywords', highlightKeywords); // 保存武器高亮关键字 const weaponHighlightInput = document.getElementById('weaponHighlightKeywords').value; const weaponKeywords = weaponHighlightInput.split(/[,,]/) .map(s => s.trim()) .filter(s => s); CONFIG.textGame.weaponHighlightKeywords = weaponKeywords; GM_setValue('weaponHighlightKeywords', weaponKeywords); // 重新应用文字游戏 if (CONFIG.textGame.enabled) { applyTextGame(); } } // HTML 实体转义,防止 XSS function escapeHtml(text) { return String(text) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } // 应用文字游戏(高亮+替换)— 内部实现 function _applyTextGameImpl() { if (!CONFIG.textGame.enabled) return; // CSS 只注入一次,避免重复注入 if (!textGameStyleInjected) { GM_addStyle(` .tm-hp-change { display: inline; white-space: nowrap; } .tm-hp-plus { color: #00aa00; font-weight: bold; } .tm-hp-minus { color: #ff0000; font-weight: bold; } .tm-key-weapon { color: #aa00aa; font-weight: bold; } .tm-keyword-bold { color: #1ba784; font-weight: bold; } `); textGameStyleInjected = true; } // 只取可见渲染文本,排除脚本源码与面板自身,且不触发回流 const bodyText = getVisiblePageText(); const hpRegexChange = /(HP[+-]\d+)/g; const hpRegexRemain = /(HP余\d+)/g; const spiralRegex = /(反弹给对方(\d+)的伤害!)/g; // 动态构建武器正则 const weaponKeywords = CONFIG.textGame.weaponHighlightKeywords || []; const weaponRegex = weaponKeywords.length ? new RegExp(`(${weaponKeywords.map(k => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})`, 'g') : /(?!)/; // 使用用户自定义的关键字 const userKeywords = CONFIG.textGame.highlightKeywords || []; // 动态添加关键字 const keywordSet = new Set(userKeywords); if (bodyText.includes("至尊传功")) { keywordSet.add('经脉'); } if (bodyText.includes("军需处")) { keywordSet.add('五行'); } if (bodyText.includes("达人特惠")) { keywordSet.add('续费达人'); } if (bodyText.includes("藏经阁")) { keywordSet.add('兵法'); } if (mercenaryShopAvailable) { keywordSet.add('佣兵商城'); } const keywordRegex = new RegExp([...keywordSet].map(k => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'), 'g'); const safeReplace = (text) => { // 先转义 HTML 实体,防止 XSS text = escapeHtml(text); // 然后进行高亮处理 if (bodyText.includes("【大乐斗】") || bodyText.includes("Q宠大乐斗")) { text = text.replace(keywordRegex, (keyword) => `${keyword}` ); } text = text.replace(weaponRegex, (weapon) => `${weapon}` ); text = text.replace(hpRegexChange, (change) => `${change}` ); text = text.replace(hpRegexRemain, (remain) => `${remain}` ); text = text.replace(spiralRegex, (fullMatch, fullText, damage) => fullText.replace(damage, `${damage}`) ); return text; }; const processNode = (node) => { // 跳过控制面板及其子元素 if (node.id === 'gameHelperPanel' || node.closest?.('#gameHelperPanel')) { return; } // 跳过所有表单元素及其内部节点 if (node.nodeType === Node.ELEMENT_NODE) { const tagName = node.tagName.toLowerCase(); if (tagName === 'input' || tagName === 'textarea' || tagName === 'select') { return; } } if (node.nodeType === Node.TEXT_NODE && !node.parentNode.classList.contains('tm-hp-processed') && (hpRegexChange.test(node.nodeValue) || hpRegexRemain.test(node.nodeValue) || weaponRegex.test(node.nodeValue) || spiralRegex.test(node.nodeValue) || keywordRegex.test(node.nodeValue))) { const wrapper = document.createElement('span'); wrapper.className = 'tm-hp-processed'; wrapper.innerHTML = safeReplace(node.nodeValue); node.parentNode.replaceChild(wrapper, node); } else if (node.nodeType === Node.ELEMENT_NODE && !node.classList.contains('tm-hp-processed')) { Array.from(node.childNodes).forEach(processNode); } }; processNode(document.body); } // 带防抖的文字游戏应用接口(避免频繁调用导致性能问题) function applyTextGame() { if (!CONFIG.textGame.enabled) return; if (textGameDebounceTimer) { clearTimeout(textGameDebounceTimer); } textGameDebounceTimer = setTimeout(() => { _applyTextGameImpl(); textGameDebounceTimer = null; }, 200); } /* ========== 定时任务模块 ========== */ function sendScheduledRequest(task, index) { return new Promise((resolve) => { GM_xmlhttpRequest({ method: 'GET', url: task.url, headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'Accept': '*/*' }, timeout: 8000, onload: function(response) { Mylog(`[定时任务 ${task.name}] 请求 ${index}/${task.count} - 状态: ${response.status}`); resolve({ success: response.status === 200, status: response.status }); }, onerror: function(error) { Mylog(`[定时任务 ${task.name}] 请求 ${index}/${task.count} 失败: ${error}`); resolve({ success: false, error: error }); }, ontimeout: function() { Mylog(`[定时任务 ${task.name}] 请求 ${index}/${task.count} 超时`); resolve({ success: false, error: 'timeout' }); } }); }); } // 定时任务:开启指定功能开关 function activateFeatureByTask(task) { const sw = FEATURE_SWITCHES.find(s => s.key === task.target); const label = sw ? sw.label : task.target; Mylog(`[定时任务 ${task.name}] 到点,开启开关:${label}`); const ok = setFeatureSwitch(task.target, true); return [{ success: ok, status: 'switch-activated', target: task.target }]; } async function executeScheduledTask(task) { if (!task.enabled) return; // 动作 = 开启开关:目标由任务 target 指定,不局限于某个功能 if ((task.action || TASK_ACTION_URL) === TASK_ACTION_TOGGLE) { return activateFeatureByTask(task); } // 动作 = 访问链接:每日与指定日期走完全相同的请求逻辑 const waitMs = Math.max(0, Number(task.interval) || 0); const startTime = new Date(); Mylog(`[定时任务 ${task.name}] 开始执行 ${task.count} 次请求,间隔 ${waitMs}ms (${startTime.toLocaleString()})`); const results = []; for (let i = 1; i <= task.count; i++) { if (i > 1 && waitMs > 0) { await new Promise(resolve => setTimeout(resolve, waitMs)); } const result = await sendScheduledRequest(task, i); results.push(result); } const successCount = results.filter(r => r.success).length; const endTime = new Date(); const duration = endTime - startTime; task.lastExecution = endTime.toISOString(); GM_setValue(`task_lastExecution_${task.name}`, task.lastExecution); Mylog(`[定时任务 ${task.name}] 执行完成,成功 ${successCount}/${task.count} 次,耗时 ${duration}ms`); return results; } /* ---------- 心跳调度:按真实时间判定,不受长 setTimeout 漂移 / 后台节流影响 ---------- */ function formatDelayTime(ms) { const totalSeconds = Math.max(0, Math.floor(ms / 1000)); const hours = Math.floor(totalSeconds / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); const seconds = totalSeconds % 60; if (hours > 0) return `${hours}小时${minutes}分${seconds}秒`; if (minutes > 0) return `${minutes}分${seconds}秒`; return `${seconds}秒`; } // 计算任务在指定基准日的目标时间戳;「指定日期」类型使用自身日期 function getTaskTargetMs(task, baseMs) { if (!task.time) return null; const [h, m, s = 0] = String(task.time).split(':').map(Number); if ([h, m, s].some(n => Number.isNaN(n))) return null; if ((task.type || TASK_TYPE_DAILY) === TASK_TYPE_ONCE) { const [y, mo, d] = String(task.date || '').split('-').map(Number); if (!y || !mo || !d) return null; return new Date(y, mo - 1, d, h, m, s, 0).getTime(); } const t = new Date(baseMs); t.setHours(h, m, s, 0); return t.getTime(); } // 本轮唯一标识:每天/每次定时只执行一次(GM 持久化,刷新页面不会重复触发) function getTaskRunKey(task, targetMs) { return `${task.type || TASK_TYPE_DAILY}_${targetMs}`; } // 最近一个尚未到来的任务时间(供校准刷新避让) function getNearestUpcomingTaskMs(now) { let nearest = Infinity; CONFIG.scheduledTasks.tasks.forEach(task => { if (!task.enabled || !task.time) return; let target = getTaskTargetMs(task, now); if (target === null) return; if ((task.type || TASK_TYPE_DAILY) !== TASK_TYPE_ONCE && target <= now) { const tomorrow = new Date(now); tomorrow.setDate(tomorrow.getDate() + 1); target = getTaskTargetMs(task, tomorrow.getTime()); } if (target !== null && target > now && target < nearest) nearest = target; }); return nearest; } function getTaskLastSuccess(name) { return GM_getValue(`task_lastSuccess_${name}`, ''); } function updateScheduleStatus() { const statusEl = document.getElementById('taskStatus'); if (!statusEl) return; if (!CONFIG.scheduledTasks.enabled) { statusEl.textContent = '⚠ 调度未启用(请打开本模块开关)'; statusEl.style.color = '#ff9800'; return; } const tasks = CONFIG.scheduledTasks.tasks.filter(t => t.enabled); const today = new Date().toDateString(); const done = tasks.filter(t => { const last = getTaskLastSuccess(t.name); return last && new Date(last).toDateString() === today; }).length; const nearest = getNearestUpcomingTaskMs(Date.now()); const tail = nearest === Infinity ? '无待执行任务' : `下次 ${formatDelayTime(nearest - Date.now())}`; statusEl.textContent = `${tasks.length} 个启用 · 今日成功 ${done}/${tasks.length} · ${tail}`; statusEl.style.color = done === tasks.length ? '#4CAF50' : '#ff9800'; } // 跨标签执行权占位:同一轮只允许一个标签真正执行 function claimTask(task, runKey, now) { const claimKey = `task_claim_${task.name}`; const claim = GM_getValue(claimKey, null); if (claim && claim.runKey === runKey && now - claim.at < TASK_CLAIM_TTL_MS) { return false; } GM_setValue(claimKey, { runKey: runKey, at: now }); return true; } // 执行失败:释放执行权,冷却后重试;达到上限才写标记放弃本轮 function handleTaskFailure(task, runKey, reason) { const attemptKey = `task_attempt_${task.name}`; const prev = GM_getValue(attemptKey, null); const count = (prev && prev.runKey === runKey ? prev.count : 0) + 1; GM_setValue(attemptKey, { runKey: runKey, count: count, at: Date.now(), reason: String(reason) }); GM_setValue(`task_claim_${task.name}`, null); if (count >= TASK_MAX_ATTEMPTS) { GM_setValue(`task_runKey_${task.name}`, runKey); Mylog(`[定时任务 ${task.name}] 连续 ${count} 次未成功,放弃本轮。最后原因: ${reason}`); } else { Mylog(`[定时任务 ${task.name}] 第 ${count}/${TASK_MAX_ATTEMPTS} 次未成功(${reason}),${TASK_RETRY_COOLDOWN_MS / 1000}秒后重试`); } } // 本轮是否允许触发:每日任务当天内任意时刻可补跑,指定日期任务仅 10 分钟窗口 function isTaskDue(targetMs, now, type) { if (now < targetMs) return false; if (type === TASK_TYPE_ONCE) { return now - targetMs <= SCHEDULE_CATCHUP_WINDOW_MS; } return new Date(now).toDateString() === new Date(targetMs).toDateString(); } function schedulerTick() { if (!CONFIG.scheduledTasks.enabled) return; const now = Date.now(); CONFIG.scheduledTasks.tasks.forEach(task => { if (!task.enabled || !task.time) return; const type = task.type || TASK_TYPE_DAILY; const targetMs = getTaskTargetMs(task, now); if (targetMs === null) return; if (!isTaskDue(targetMs, now, type)) return; const runKey = getTaskRunKey(task, targetMs); const storageKey = `task_runKey_${task.name}`; if (GM_getValue(storageKey, '') === runKey) return; // 本轮已完成(成功或已放弃) // 失败重试冷却,避免短时间内反复打请求 const attempt = GM_getValue(`task_attempt_${task.name}`, null); if (attempt && attempt.runKey === runKey && now - attempt.at < TASK_RETRY_COOLDOWN_MS) return; if (!claimTask(task, runKey, now)) return; // 其他标签正在执行 Mylog(`[定时任务 ${task.name}] 到点执行(${type}/${task.action || TASK_ACTION_URL}),目标 ${new Date(targetMs).toLocaleString()}`); Promise.resolve() .then(() => executeScheduledTask(task)) .then(results => { const successCount = Array.isArray(results) ? results.filter(r => r && r.success).length : 0; if (successCount > 0) { // 关键:只有真正成功后才写执行标记 GM_setValue(storageKey, runKey); GM_setValue(`task_lastSuccess_${task.name}`, new Date().toISOString()); GM_setValue(`task_claim_${task.name}`, null); Mylog(`[定时任务 ${task.name}] 本轮成功 ${successCount} 次,已标记完成`); } else { handleTaskFailure(task, runKey, '请求全部失败或未返回结果'); } }) .catch(e => handleTaskFailure(task, runKey, e)); }); if (now - lastStatusUpdateAt >= SCHEDULE_STATUS_UPDATE_MS) { lastStatusUpdateAt = now; updateScheduleStatus(); } } function startCalibrationRefresh() { if (calibrationTimerId) { clearInterval(calibrationTimerId); calibrationTimerId = null; } const minutes = Number(CONFIG.scheduledTasks.calibrationRefreshMin) || 0; if (minutes <= 0) { Mylog('[定时校准] 已关闭'); return; } calibrationTimerId = setInterval(() => { if (!CONFIG.scheduledTasks.enabled) return; const now = Date.now(); const nearest = getNearestUpcomingTaskMs(now); if (nearest - now < CALIBRATION_SAFE_WINDOW_MS) { Mylog('[定时校准] 临近任务执行时间,本次跳过刷新'); return; } // 有到点但尚未成功(或仍在重试)的任务时不刷新,避免打断执行 const hasPendingDueTask = CONFIG.scheduledTasks.tasks.some(task => { if (!task.enabled || !task.time) return false; const type = task.type || TASK_TYPE_DAILY; const targetMs = getTaskTargetMs(task, now); if (targetMs === null || !isTaskDue(targetMs, now, type)) return false; return GM_getValue(`task_runKey_${task.name}`, '') !== getTaskRunKey(task, targetMs); }); if (hasPendingDueTask) { Mylog('[定时校准] 有到点但尚未完成的任务,本次跳过刷新'); return; } Mylog(`[定时校准] 刷新页面以校准计时(间隔 ${minutes} 分钟)`); window.location.reload(); }, minutes * 60 * 1000); Mylog(`[定时校准] 已启用,每 ${minutes} 分钟刷新一次,临近任务自动避让`); } function initScheduledTasks() { stopAllScheduledTasks(); if (!CONFIG.scheduledTasks.enabled) return; Mylog(`[定时任务] 心跳调度启动,共 ${CONFIG.scheduledTasks.tasks.length} 个任务,节拍 ${SCHEDULER_TICK_MS}ms`); schedulerTimerId = setInterval(schedulerTick, SCHEDULER_TICK_MS); schedulerTick(); startCalibrationRefresh(); updateScheduleStatus(); } function stopAllScheduledTasks() { if (schedulerTimerId) { clearInterval(schedulerTimerId); schedulerTimerId = null; } if (calibrationTimerId) { clearInterval(calibrationTimerId); calibrationTimerId = null; } CONFIG.scheduledTasks.tasks.forEach(task => { if (task.timerId) { clearTimeout(task.timerId); task.timerId = null; } }); Mylog('[定时任务] 已停止所有定时任务'); } function saveScheduledTaskSettings() { try { const tasks = []; document.querySelectorAll('.scheduled-task-item').forEach((item, index) => { // 间隔直接以毫秒存储,不再做秒→毫秒换算 const intervalInMs = Math.max(0, Math.floor(Number(item.querySelector('.task-interval').value) || 0)); const type = item.querySelector('.task-type').value; const action = item.querySelector('.task-action').value; const targetEl = item.querySelector('.task-target'); const dateInput = item.querySelector('.task-date'); const task = { name: item.querySelector('.task-name').value.trim() || `任务${index + 1}`, type: type, action: action, target: targetEl ? targetEl.value : DEFAULT_TOGGLE_TARGET, date: dateInput ? dateInput.value.trim() : '', url: item.querySelector('.task-url').value.trim(), time: item.querySelector('.task-time').value, count: parseInt(item.querySelector('.task-count').value) || 1, interval: intervalInMs, enabled: item.querySelector('.task-enabled').checked }; const needUrl = action === TASK_ACTION_URL; const needDate = type === TASK_TYPE_ONCE; if (task.time && (!needUrl || task.url) && (!needDate || task.date)) { tasks.push(task); } }); // 计时校准刷新间隔(0 = 关闭) const calibInput = document.getElementById('calibrationRefreshMin'); if (calibInput) { const minutes = Math.max(0, Number(calibInput.value) || 0); CONFIG.scheduledTasks.calibrationRefreshMin = minutes; GM_setValue('scheduledCalibrationRefreshMin', minutes); } CONFIG.scheduledTasks.tasks = tasks; GM_setValue('scheduledTasks', tasks); updateTaskCount(); const taskStatus = document.getElementById('taskStatus'); if (taskStatus) { taskStatus.textContent = `已保存 ${tasks.length} 个任务`; taskStatus.style.color = "#4CAF50"; } if (CONFIG.scheduledTasks.enabled) { initScheduledTasks(); } Mylog(`[定时任务] 设置已保存,共 ${tasks.length} 个任务`); } catch (error) { console.error("[定时任务] 保存失败:", error); Mylog("[定时任务] 保存失败: " + error.message); const taskStatus = document.getElementById('taskStatus'); if (taskStatus) { taskStatus.textContent = "保存失败"; taskStatus.style.color = "#ff4444"; } } } async function executeTaskNow(taskName) { const task = CONFIG.scheduledTasks.tasks.find(t => t.name === taskName); if (task) { Mylog(`[定时任务] 手动执行: ${taskName}`); return await executeScheduledTask(task); } else { Mylog(`[定时任务] 未找到任务: ${taskName}`); return null; } } function testFirstTask() { if (CONFIG.scheduledTasks.tasks.length > 0) { const firstTask = CONFIG.scheduledTasks.tasks[0]; Mylog(`[定时任务] 测试执行: ${firstTask.name}(测试不写执行标记,不影响今日自动调度)`); Promise.resolve() .then(() => executeScheduledTask(firstTask)) .then(results => { const okCount = Array.isArray(results) ? results.filter(r => r && r.success).length : 0; Mylog(`[定时任务] 测试完成,成功 ${okCount} 次;自动调度异常时可在控制台运行 taskManager.getDiagnostics()`); updateScheduleStatus(); }) .catch(e => Mylog(`[定时任务] 测试出错: ${e}`)); } else { Mylog('[定时任务] 没有可测试的任务'); } } function todayDateString() { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; } function getTaskHint(type, action, target) { const when = type === TASK_TYPE_ONCE ? '指定日期到点' : '每天到点'; if (action === TASK_ACTION_TOGGLE) { const sw = FEATURE_SWITCHES.find(s => s.key === target); return `${when}开启「${sw ? sw.label : target}」开关`; } return `${when}访问链接,间隔可精确到毫秒`; } // 生成任务项 HTML(新增与回显共用) function buildTaskItemHTML(task, index) { const type = task.type || TASK_TYPE_DAILY; const action = task.action || TASK_ACTION_URL; const target = task.target || DEFAULT_TOGGLE_TARGET; const intervalMs = Number.isFinite(Number(task.interval)) ? Math.max(0, Math.floor(Number(task.interval))) : 1000; const date = task.date || todayDateString(); const isOnce = type === TASK_TYPE_ONCE; const isToggle = action === TASK_ACTION_TOGGLE; const typeOptions = [ { value: TASK_TYPE_DAILY, label: '每日' }, { value: TASK_TYPE_ONCE, label: '指定日期' } ].map(o => ``).join(''); const actionOptions = TASK_ACTIONS.map(a => ``).join(''); const targetOptions = FEATURE_SWITCHES.map(s => ``).join(''); return `
${getTaskHint(type, action, target)}
`; } // 按重复方式 / 执行动作显隐字段 function applyTaskTypeVisibility(item) { const type = item.querySelector('.task-type').value; const action = item.querySelector('.task-action').value; const isOnce = type === TASK_TYPE_ONCE; const isToggle = action === TASK_ACTION_TOGGLE; item.querySelector('.task-url-row').style.display = isToggle ? 'none' : 'block'; item.querySelector('.task-date-row').style.display = isOnce ? 'block' : 'none'; item.querySelector('.task-target-row').style.display = isToggle ? 'block' : 'none'; item.querySelector('.task-request-row').style.display = isToggle ? 'none' : 'grid'; item.querySelector('.task-type-hint').textContent = getTaskHint(type, action, item.querySelector('.task-target').value); } function bindTaskItemEvents(item) { item.querySelector('.task-remove').addEventListener('click', function() { removeTaskItem(item); }); item.querySelectorAll('input, select').forEach(el => { el.addEventListener('change', showUnsavedChanges); }); ['.task-type', '.task-action', '.task-target'].forEach(sel => { item.querySelector(sel).addEventListener('change', function() { applyTaskTypeVisibility(item); }); }); } function addNewTask() { const tasksContainer = document.getElementById('scheduledTasksList'); if (!tasksContainer) return; const taskIndex = tasksContainer.children.length + 1; const taskItem = document.createElement('div'); taskItem.className = 'scheduled-task-item'; taskItem.innerHTML = buildTaskItemHTML({ name: `任务${taskIndex}`, type: TASK_TYPE_DAILY, action: TASK_ACTION_URL, target: DEFAULT_TOGGLE_TARGET, date: todayDateString(), url: 'https://dld.qzapp.z.qq.com/qpet/cgi-bin/phonepk?zapp_uin=&sid=&channel=0&g_ut=1&cmd=notice&op=choice&optid=1', time: '00:00:01', count: 3, interval: 1000, enabled: true }, taskIndex - 1); tasksContainer.appendChild(taskItem); bindTaskItemEvents(taskItem); applyTaskTypeVisibility(taskItem); setTimeout(saveScheduledTaskSettings, 100); updateTaskCount(); Mylog("[定时任务] 已添加新任务"); } function removeTaskItem(taskItem) { const tasksContainer = document.getElementById('scheduledTasksList'); if (!tasksContainer) return; if (tasksContainer.children.length > 1) { const taskName = taskItem.querySelector('.task-name').value; taskItem.remove(); Mylog(`[定时任务] 已删除任务: ${taskName}`); updateTaskCount(); setTimeout(saveScheduledTaskSettings, 100); } else { alert('至少需要保留一个任务'); } } function loadScheduledTasksUI() { const tasksList = document.getElementById('scheduledTasksList'); if (!tasksList) return; tasksList.innerHTML = ''; if (CONFIG.scheduledTasks.tasks.length === 0) { CONFIG.scheduledTasks.tasks = [{ name: '凌晨任务', type: TASK_TYPE_DAILY, action: TASK_ACTION_URL, target: DEFAULT_TOGGLE_TARGET, date: '', url: 'https://dld.qzapp.z.qq.com/qpet/cgi-bin/phonepk?zapp_uin=&sid=&channel=0&g_ut=1&cmd=notice&op=choice&optid=1', time: '00:00:01', count: 3, interval: 1000, enabled: true }]; GM_setValue('scheduledTasks', CONFIG.scheduledTasks.tasks); } CONFIG.scheduledTasks.tasks.forEach((task, index) => { const taskItem = document.createElement('div'); taskItem.className = 'scheduled-task-item'; taskItem.innerHTML = buildTaskItemHTML(task, index); tasksList.appendChild(taskItem); bindTaskItemEvents(taskItem); applyTaskTypeVisibility(taskItem); }); const calibInput = document.getElementById('calibrationRefreshMin'); if (calibInput) calibInput.value = CONFIG.scheduledTasks.calibrationRefreshMin; updateTaskCount(); // 面板加载后立刻显示调度状态(调度未启用时 schedulerTick 不会运行,状态栏否则一直停在初始文本) updateScheduleStatus(); } function updateTaskCount() { const taskCountBadge = document.getElementById('taskCountBadge'); const tasksList = document.getElementById('scheduledTasksList'); if (taskCountBadge && tasksList) { const count = tasksList.children.length; taskCountBadge.textContent = `(${count})`; taskCountBadge.style.color = count > 0 ? '#4CAF50' : '#888'; } const taskStatus = document.getElementById('taskStatus'); if (taskStatus) { taskStatus.textContent = `当前有 ${tasksList ? tasksList.children.length : 0} 个任务`; taskStatus.style.color = "#888"; } } function showUnsavedChanges() { const taskStatus = document.getElementById('taskStatus'); if (taskStatus) { taskStatus.textContent = "有未保存的更改"; taskStatus.style.color = "#FFA500"; } // 不再自动保存,避免保存到半成品数据。用户需手动点击"保存"按钮。 } /* ========== 方向键控制功能 ========== */ function initDirectionKeyControl() { if (!CONFIG.directionKey.enabled) return; document.addEventListener('keydown', handleDirectionKeyDown, true); Mylog("[方向键控制] 已启用 - 上下滚动,左右前进后退"); } function isInInputElement(element) { const inputTypes = ['input', 'textarea', 'select']; const contentEditable = element.isContentEditable || element.getAttribute('contenteditable') === 'true'; if (contentEditable) return true; const tagName = element.tagName.toLowerCase(); if (inputTypes.includes(tagName)) { if (tagName === 'input') { const type = element.type.toLowerCase(); const editableTypes = ['text', 'password', 'email', 'search', 'tel', 'url', 'number']; return editableTypes.includes(type); } return true; } return false; } function handleDirectionKeyDown(event) { if (!CONFIG.directionKey.enabled) return; if (CONFIG.directionKey.ignoreInputs && isInInputElement(event.target)) { return; } const { key, shiftKey } = event; if (!['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(key)) { return; } event.preventDefault(); event.stopPropagation(); const now = Date.now(); const scrollDelay = now - directionKeyLastScrollTime; if (scrollDelay < 50) return; directionKeyLastScrollTime = now; let scrollAmount = CONFIG.directionKey.scrollAmount; if (shiftKey && CONFIG.directionKey.enableShiftScroll) { scrollAmount = CONFIG.directionKey.fastScrollAmount; } const scrollOptions = CONFIG.directionKey.smoothScroll ? { behavior: 'smooth' } : {}; switch (key) { case 'ArrowUp': window.scrollBy({ top: -scrollAmount, ...scrollOptions }); break; case 'ArrowDown': window.scrollBy({ top: scrollAmount, ...scrollOptions }); break; case 'ArrowLeft': if (window.history.length > 1) { window.history.back(); } break; case 'ArrowRight': window.history.forward(); break; } } /* ========== 模块1:系统繁忙监控 ========== */ let systemBusyMonitorInterval = null; let lastRefreshTime = 0; function startSystemBusyMonitor() { stopSystemBusyMonitor(); Mylog("[系统繁忙监控] 已启动,正在检测 '" + CONFIG.systemBusy.targetText + "'..."); systemBusyMonitorInterval = setInterval(() => { const now = Date.now(); if (now - lastRefreshTime < CONFIG.systemBusy.refreshCooldown) { return; } // 只检测页面真正渲染出来的文本,排除