// ==UserScript== // @name 宝武学习助手 // @namespace http://tampermonkey.net/ // @version 2.3.68 // @description 全新界面、简单操作:一键自动学完公开课/专区课,自动静音、播放、切下一节,学满时长自动跳下一门;实时显示学习进度与总学时;视频课、音频课都支持;多账号一键切换,登录过期自动补登,断线后接着原来的进度学 // @author jinxhcn // @match *://learn.baowugroup.com/* // @icon https://learn.baowugroup.com/favicon.png // @grant GM_info // @grant GM_openInTab // @grant GM_xmlhttpRequest // @grant GM_getValue // @grant GM_setValue // @grant unsafeWindow // @connect scriptcat.org // @run-at document-idle // @license MIT // ==/UserScript== (function () { 'use strict'; const forceSameWindowNavigation = () => { unsafeWindow.open = function (url) { if (url) { try { location.href = new URL(url, location.href).href; } catch { location.href = url; } } return { closed: true, document: null, focus: () => { }, close: () => { } }; }; document.addEventListener('click', function (e) { const link = e.target.closest('a[target="_blank"]'); if (link) { e.preventDefault(); e.stopPropagation(); const href = link.getAttribute('href'); if (href && !/^javascript:/i.test(href) && href !== '#') { try { location.href = new URL(href, location.href).href; } catch { location.href = href; } } return; } const btn = e.target.closest('button[formtarget="_blank"], input[formtarget="_blank"]'); if (btn) { e.preventDefault(); e.stopPropagation(); btn.removeAttribute('formtarget'); } }, true); document.addEventListener('submit', function (e) { const form = e.target.closest('form'); if (form && form.target === '_blank') { form.target = '_self'; } }, true); const base = document.querySelector('base[target="_blank"]'); if (base) base.target = '_self'; }; const startTaskLoop = (task, runImmediately, intervalMs) => { const execute = async () => { try { await task(); } catch (error) { console.error('startTaskLoop error:', error); } if (intervalMs > 0) { setTimeout(execute, intervalMs); } }; if (runImmediately) { execute(); } else { setTimeout(execute, intervalMs); } }; const createDataStore = (key, defaultData, opts = {}) => { const mirrorKeys = Array.isArray(opts.mirror) ? opts.mirror : []; const mirrorGet = typeof opts.mirrorRead === 'function' ? opts.mirrorRead : null; const mirrorSet = typeof opts.mirrorWrite === 'function' ? opts.mirrorWrite : null; const mirrorKeyOf = (k) => `${key}::${k}`; let mirrorRestored = []; const deepMerge = (target, source) => { const merged = { ...target }; for (const k in source) { if (!Object.prototype.hasOwnProperty.call(source, k)) continue; const srcVal = source[k]; const tgtVal = merged[k]; if ( srcVal !== null && typeof srcVal === 'object' && !Array.isArray(srcVal) && tgtVal !== null && typeof tgtVal === 'object' && !Array.isArray(tgtVal) ) { merged[k] = deepMerge(tgtVal, srcVal); } else { merged[k] = srcVal; } } return merged; }; let data = { ...defaultData }; const store = { init() { let saved = null; try { saved = JSON.parse(localStorage.getItem(key)); } catch { saved = null; } if (saved && typeof saved === 'object') { data = deepMerge(defaultData, saved); } else { data = { ...defaultData }; } mirrorRestored = []; if (mirrorGet) { for (const k of mirrorKeys) { if (saved && Object.prototype.hasOwnProperty.call(saved, k)) continue; const text = mirrorGet(mirrorKeyOf(k)); if (!text) continue; let val = null; try { val = JSON.parse(text); } catch { continue; } if (!val || typeof val !== 'object') continue; data[k] = deepMerge(defaultData[k] || {}, val); mirrorRestored.push(k); } if (mirrorRestored.length) { try { localStorage.setItem(key, JSON.stringify(data)); } catch { } } } if (data.zone) { data.zone.forEach(z => { z.zoneCourses = Array.isArray(z.zoneCourses) ? z.zoneCourses : []; }); } }, save(partial) { for (const k in partial) { const val = partial[k]; if ( val !== null && typeof val === 'object' && !Array.isArray(val) && data[k] !== null && typeof data[k] === 'object' && !Array.isArray(data[k]) ) { Object.assign(data[k], val); } else { data[k] = val; } } localStorage.setItem(key, JSON.stringify(data)); if (mirrorSet) { for (const k of mirrorKeys) { if (!Object.prototype.hasOwnProperty.call(partial, k)) continue; try { mirrorSet(mirrorKeyOf(k), JSON.stringify(data[k])); } catch { } } } }, get(k) { return data[k]; }, mirrorRestored() { return mirrorRestored.slice(); }, mirrorKey(k) { return mirrorKeyOf(k); } }; return store; }; const globalScope = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; globalScope.BWUTL = { fswn: forceSameWindowNavigation, loop: startTaskLoop, createDataStore }; })(); (function () { 'use strict'; const SERVICE = 'https://learn.baowugroup.com/learn-gateway/service'; const BASE_URL = `${SERVICE}/tms/ols`; const API = { publicCourses: `${BASE_URL}/student/queryPageOpenClass`, zoneList: `${BASE_URL}/student/myClassPage`, zoneCourses: `${BASE_URL}/onlineClassCourse/getOnlineClassCourseSortPage`, courseScore: `${BASE_URL}/onlineClassCourse/finishInfo`, getdetailCourse: `${BASE_URL}/onlineClassCourse/detailOnlineClassCourse`, getCourseInfo: `${BASE_URL}/onlineClassCourse/getOnlineClassCourseInfo`, saveCourseDetail: `${BASE_URL}/computeTask/saveComputeTask4StuCourseDetail`, getComputeTask: `${BASE_URL}/computeTask/getComputeTask`, studyHours: `${BASE_URL}/student/queryArchivesStudyDurationStatistics`, outline: `${SERVICE}/tms/rls/courseOutline/queryCourseOutlineContentTreeListSimple`, playProgress: `${BASE_URL}/learnWareProgress/getMaxTimeAndLastTime`, videoCompute: `${BASE_URL}/computeTask/saveComputeTask4AfterVideoPlayed`, propValue: `${SERVICE}/ss/properties/queryPropValue` }; const getToken = () => { try { return JSON.parse(localStorage.getItem('userInfo'))?.accessToken ?? null; } catch { return null; } }; const REQUEST_TIMEOUT_MS = 15000; const post = async (url, data, token = getToken()) => { if (!token) { console.warn('[API] Token 缺失,请求取消'); return { isSuccess: false }; } const controller = typeof AbortController === 'function' ? new AbortController() : null; const timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null; let resp; try { resp = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json;charset=UTF-8', token, }, body: JSON.stringify(data), signal: controller ? controller.signal : undefined, }); } catch (error) { if (error && error.name === 'AbortError') { throw new Error(`请求超时(${REQUEST_TIMEOUT_MS}ms)`); } throw new Error(`请求失败: ${error && error.message ? error.message : error}`); } finally { if (timer) clearTimeout(timer); } if (!resp.ok) { throw new Error(`HTTP ${resp.status}`); } return resp.json(); }; const extractCourseInfo = ({ centerCode, courseGuid, courseName, olClassNo, courseNo }) => ({ centerCode, courseGuid, courseName, olClassNo, courseNo, }); const fetchPublicCourses = async (learnStatus = '1', current = 1, size = 100) => { try { const result = await post(API.publicCourses, { current, size, data: { learnStatus, searchInfo: '', searchType: '1', sortClass: '1', sortType: 'desc', }, }); if (!result.isSuccess) { console.warn('[API] queryPageOpenClass 返回失败'); return null; } const records = result.data?.records || []; return records.map(r => ({ ...extractCourseInfo(r), learnStatus: r.learnStatus, })); } catch (e) { console.warn('[API] queryPageOpenClass 异常:', e && e.message ? e.message : e); return null; } }; const fetchZoneList = async (learnStatus = '1', current = 1, size = 100) => { try { const result = await post(API.zoneList, { current, size, data: { classType: 'ZE0', isLearnNum: '1', keyWord: '', lastLearnTime: '1', learnStatus, sortClass: '1', sortType: 'desc', status: '', }, }); if (!result.isSuccess) { console.warn('[API] myClassPage 返回失败'); return null; } const records = result.data?.records || []; return records.map(r => ({ guid: r.guid, centerCode: r.centerCode, olClassNo: r.olClassNo, olClassType: r.olClassType, olClassName: r.olClassName, })); } catch (e) { console.warn('[API] myClassPage 异常:', e && e.message ? e.message : e); return null; } }; const fetchZoneCoursesDetail = async (centerCode, olClassNo, olClassType) => { const size = 1000; const MAX_PAGE = 50; let all = []; let current = 1; try { while (current <= MAX_PAGE) { const result = await post(API.zoneCourses, { current, size, data: { centerCode, courseName: '', courseTypeCode: '', isMine: '1', isRecursiveCourse: '1', olClassNo, olClassType, }, }); if (!result.isSuccess || !result.data) { if (current === 1) return null; break; } const records = result.data.records || []; all.push(...records.map(c => ({ ...extractCourseInfo({ ...c, courseGuid: c.guid }), learnStatus: c.learnStatus, }))); if (records.length < size) break; current++; } } catch { if (current === 1) return null; } return all; }; const scorePayload = (centerCode, courseNo, olClassNo, tenantCode) => ({ centerCode, courseNo, olClassNo, tenantCode }); const mapScore = (data) => { const detail = data.details?.find((x) => x.attributeCode === 'CE002'); return { passScore: data.passScore ?? null, learnScore: data.learnScore ?? null, requiredDuration: detail ? detail.predValue : null, completedDuration: detail ? detail.finishValue : null, }; }; const readScore = async (payload) => { const result = await post(API.courseScore, payload); return result.isSuccess && result.data ? mapScore(result.data) : null; }; const fetchCourseScore = async (centerCode, courseNo, olClassNo, tenantCode = 'BSTA') => { try { return await readScore(scorePayload(centerCode, courseNo, olClassNo, tenantCode)); } catch { return null; } }; const COMPUTE_POLL_MS = 300; const COMPUTE_MAX_POLLS = 10; const isComputeDone = (task) => !!task && (String(task.calcStatus) === '3' || !!task.calcEndTime); const waitComputeTask = async (guid) => { if (!guid) return null; for (let i = 0; i < COMPUTE_MAX_POLLS; i += 1) { const res = await post(API.getComputeTask, { guid }); const task = res && res.isSuccess ? res.data : null; if (!task) return null; if (isComputeDone(task)) return task; await new Promise((resolve) => setTimeout(resolve, COMPUTE_POLL_MS)); } return null; }; const fetchCourseScoreInVideoPage = async (centerCode, courseNo, olClassNo, tenantCode = 'BSTA') => { try { const payload = scorePayload(centerCode, courseNo, olClassNo, tenantCode); if (!(await readScore(payload))) return null; const saved = await post(API.saveCourseDetail, { classNo: olClassNo, courseNo }); if (!saved.isSuccess || !saved.data) return null; await waitComputeTask(saved.data); return await readScore(payload); } catch { return null; } }; const EMPTY_SCORE = { passScore: null, learnScore: null, requiredDuration: null, completedDuration: null }; const SCORE_CONCURRENCY = 6; let scoreSlotUsed = 0; const scoreSlotWaiters = []; const takeScoreSlot = () => new Promise((resolve) => { if (scoreSlotUsed < SCORE_CONCURRENCY) { scoreSlotUsed += 1; resolve(); return; } scoreSlotWaiters.push(resolve); }); const freeScoreSlot = () => { const next = scoreSlotWaiters.shift(); if (next) next(); else scoreSlotUsed -= 1; }; const withScoreSlot = async (task) => { await takeScoreSlot(); try { return await task(); } finally { freeScoreSlot(); } }; const scoreKeyOf = (course) => `${course.centerCode}|${course.courseNo}|${course.olClassNo}`; const enrichCoursesWithScores = async (courses, options = {}) => { const cached = options.cachedScores && typeof options.cachedScores.get === 'function' ? options.cachedScores : null; const pending = new Map(); const loadScore = (course) => { const key = scoreKeyOf(course); if (!pending.has(key)) { pending.set(key, withScoreSlot(() => fetchCourseScore(course.centerCode, course.courseNo, course.olClassNo))); } return pending.get(key); }; let reused = 0; const result = await Promise.all( courses.map(async (course) => { if (!course.centerCode || !course.courseNo || !course.olClassNo) { return { ...course, score: { ...EMPTY_SCORE } }; } const hit = cached?.get(scoreKeyOf(course)); if (hit) { reused += 1; return { ...course, score: { ...hit } }; } try { const score = await loadScore(course); return { ...course, score: score || { ...EMPTY_SCORE } }; } catch { return { ...course, score: { ...EMPTY_SCORE } }; } }) ); return Object.assign(result, { reusedCount: reused }); }; const fetchCourseInfoByVideoUrl = async (centerCode, guid, stuClient = true) => { try { const detailResult = await post(API.getdetailCourse, { centerCode, guid, stuClient }); if (!detailResult.isSuccess || !detailResult.data) { console.warn('[API] getdetailCourse 失败或无数据'); return null; } const detail = detailResult.data; const { courseNo, olClassNo } = detail; if (!courseNo || !olClassNo) { console.warn('[API] 缺少 courseNo 或 olClassNo'); return null; } let courseName = detail.courseName ?? null; let courseCenterCode = detail.centerCode ?? centerCode; if (!courseName) { const infoResult = await post(API.getCourseInfo, { centerCode, courseNo, olClassNo }); if (!infoResult.isSuccess || !infoResult.data) { console.warn('[API] getCourseInfo 失败或无数据'); return null; } courseName = infoResult.data.courseName ?? null; courseCenterCode = infoResult.data.centerCode ?? courseCenterCode; } return { courseName, centerCode: courseCenterCode, courseGuid: guid, olClassNo, courseNo, learnStatus: detail.learnStatus ?? '1', }; } catch { return null; } }; const getUserId = () => { try { return JSON.parse(localStorage.getItem('userInfo'))?.userId ?? null; } catch { return null; } }; const fetchStudyHours = async () => { const userId = getUserId(); if (!userId) return null; const year = new Date().getFullYear(); const resp = await post(API.studyHours, { beginTimeBegin: `${year}-01-01 00:00:00`, endTimeEnd: `${year}-12-31 23:59:59`, stuCode: String(userId), yearFlag: '2', }); const d = resp && resp.isSuccess ? resp.data : null; if (!d) return null; const num = (v) => Number(v) || 0; return { total: num(d.totalGetHours), public: num(d.publicCourseHours), zone: num(d.studyZoneHours), training: num(d.centralizedTrainingHours), }; }; const hhmmssToSecs = (text) => { const parts = String(text == null ? '' : text).split(':').map(Number); if (parts.length !== 3 || !parts.every((n) => Number.isFinite(n))) return 0; return parts[0] * 3600 + parts[1] * 60 + parts[2]; }; const parseMarks = (text) => String(text == null ? '' : text) .split(',') .map((s) => hhmmssToSecs(s.trim())) .filter((n) => n > 0) .sort((a, b) => a - b); const MEDIA_TYPES = new Set(['1', '2']); const flattenOutline = (chapters, out) => { (chapters || []).forEach((chapter) => { flattenOutline(chapter.children, out); (chapter.content || []).forEach((item) => { if (!MEDIA_TYPES.has(String(item.contentType)) || String(item.status) !== '1') return; out.push({ name: item.newContentName || item.contentName || '', duration: Number(item.duration) || 0, marks: parseMarks(item.markeTimePoint), learned: String(item.learnedStatus) === '1', cataNo: item.cataNo, wareId: item.wareCode, wareType: item.wareType, courseNo: item.courseNo, centerCode: item.centerCode, tenantCode: item.tenantCode, }); }); }); return out; }; const fetchCourseOutline = async (centerCode, courseNo) => { try { const result = await post(API.outline, { centerCode, courseNo, isAppendPre: '1' }); if (!result.isSuccess || !Array.isArray(result.data)) return null; const sections = flattenOutline(result.data, []); return sections.length ? sections : null; } catch { return null; } }; const fetchPlayProgress = async (section, olClassNo) => { if (!section || !olClassNo) return null; try { const result = await post(API.playProgress, { cataNo: section.cataNo, courseNo: section.courseNo, olClassNo, wareId: section.wareId, wareType: section.wareType, }); if (!result.isSuccess || !result.data) return null; return { maxSecs: hhmmssToSecs(result.data.maxPlayTime), lastSecs: hhmmssToSecs(result.data.lastPlayTime), }; } catch { return null; } }; const computeVideoFinish = async (classNo, courseNo) => { if (!classNo || !courseNo) return false; try { const result = await post(API.videoCompute, { classNo, courseNo }); return !!(result && result.isSuccess); } catch { return false; } }; const fetchHeartFrequency = async () => { try { const result = await post(API.propValue, { propertiesKey: 'heartFrequency' }); const secs = Number(result && result.data && result.data.propertiesValue); return secs > 0 ? secs : 0; } catch { return 0; } }; const globalScope = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; globalScope.BWAPI = { getToken, fetchPublicCourses, fetchZoneList, fetchZoneCoursesDetail, fetchCourseScore, fetchCourseScoreInVideoPage, fetchCourseInfoByVideoUrl, fetchStudyHours, enrichCoursesWithScores, hhmmssToSecs, fetchCourseOutline, fetchPlayProgress, computeVideoFinish, fetchHeartFrequency, }; })(); (function () { 'use strict'; const ACCOUNTS_KEY = 'bw_learn_accounts'; const DATA_FIELDS = ['publicCourses', 'zone', 'toLearnList', 'today', 'theme', 'pendingListRefresh']; const SALT = 'bw-learn-tool/accounts/v1'; const xor = (text, key) => { let out = ''; for (let i = 0; i < text.length; i++) { out += String.fromCharCode(text.charCodeAt(i) ^ key.charCodeAt(i % key.length)); } return out; }; const obscure = (plain) => { if (!plain) return ''; try { return btoa(unescape(encodeURIComponent(xor(String(plain), SALT)))); } catch { return ''; } }; const clarify = (masked) => { if (!masked) return ''; try { return xor(decodeURIComponent(escape(atob(String(masked)))), SALT); } catch { return ''; } }; const CAPTURE_KEY = 'bw_learn_login_capture'; const CAPTURE_TTL = 30 * 60 * 1000; const captureBox = () => { try { return typeof localStorage !== 'undefined' ? localStorage : null; } catch { return null; } }; const saveCapture = (capture) => { const box = captureBox(); if (!box || !capture) return false; try { box.setItem(CAPTURE_KEY, JSON.stringify(capture)); return true; } catch { return false; } }; const readCapture = (now = Date.now()) => { const box = captureBox(); if (!box) return null; try { const raw = JSON.parse(box.getItem(CAPTURE_KEY)); if (!raw || typeof raw !== 'object') return null; const at = Number(raw.at) || 0; if (!at || now - at > CAPTURE_TTL) return null; if (!raw.loginId && !raw.phone) return null; return { loginId: String(raw.loginId || ''), password: String(raw.password || ''), phone: String(raw.phone || ''), at }; } catch { return null; } }; const dropCapture = () => { const box = captureBox(); if (!box) return false; try { box.removeItem(CAPTURE_KEY); return true; } catch { return false; } }; const emptyStore = () => ({ current: '', accounts: {}, pendingLogin: 0, skipAutoLogin: 0, smsLogin: 0 }); const ACCOUNTS_BACKUP_KEY = 'bw_learn_accounts_prev'; const gmStore = (() => { try { const getter = typeof GM_getValue === 'function' ? GM_getValue : null; const setter = typeof GM_setValue === 'function' ? GM_setValue : null; return getter && setter ? { get: getter, set: setter } : null; } catch { return null; } })(); const gmRead = (key) => { if (!gmStore) return ''; try { return String(gmStore.get(key, '') || ''); } catch { return ''; } }; const gmWrite = (key, text) => { if (!gmStore) return false; try { gmStore.set(key, text); return true; } catch { return false; } }; const localRead = (key) => { try { return localStorage.getItem(key) || ''; } catch { return ''; } }; const localWrite = (key, text) => { try { localStorage.setItem(key, text); return true; } catch { return false; } }; const writeRaw = (key, text) => gmWrite(key, text) | localWrite(key, text) ? true : false; const rawRead = (key) => gmRead(key) || localRead(key); const parseStore = (text) => { if (!text) return null; let raw = null; try { raw = JSON.parse(text); } catch { return null; } if (!raw || typeof raw !== 'object') return null; const accounts = raw.accounts && typeof raw.accounts === 'object' ? raw.accounts : {}; for (const id of Object.keys(accounts)) { const a = accounts[id]; if (!a || typeof a !== 'object') { delete accounts[id]; continue; } a.id = String(a.id || id); a.name = a.name || ''; a.password = a.password || ''; a.phone = a.phone || ''; a.loginId = a.loginId || ''; a.token = a.token || ''; a.userInfo = a.userInfo && typeof a.userInfo === 'object' ? a.userInfo : null; a.expiresAt = Number(a.expiresAt) || 0; a.usedAt = Number(a.usedAt) || 0; a.data = a.data && typeof a.data === 'object' ? a.data : null; } return { current: raw.current ? String(raw.current) : '', accounts, pendingLogin: Number(raw.pendingLogin) || 0, skipAutoLogin: Number(raw.skipAutoLogin) || 0, smsLogin: Number(raw.smsLogin) || 0, }; }; const healMirror = (store) => { if (!gmStore) return; try { if (localStorage.getItem(ACCOUNTS_KEY)) return; localStorage.setItem(ACCOUNTS_KEY, JSON.stringify(store)); } catch { } }; let recoveredFromBackup = false; let migratedToGm = false; const load = () => { const fromGm = gmStore ? parseStore(gmRead(ACCOUNTS_KEY)) : null; if (fromGm) { healMirror(fromGm); return fromGm; } const fromLocal = parseStore(localRead(ACCOUNTS_KEY)); if (fromLocal) { if (gmWrite(ACCOUNTS_KEY, JSON.stringify(fromLocal))) migratedToGm = true; return fromLocal; } const backup = parseStore(gmRead(ACCOUNTS_BACKUP_KEY)) || parseStore(localRead(ACCOUNTS_BACKUP_KEY)); if (backup) { recoveredFromBackup = true; writeRaw(ACCOUNTS_KEY, JSON.stringify(backup)); return backup; } return emptyStore(); }; const tookBackup = () => recoveredFromBackup; const tookMigration = () => migratedToGm; const accountCount = (store) => (store && store.accounts ? Object.keys(store.accounts).length : 0); const save = (store, opts = {}) => { let text = ''; try { text = JSON.stringify(store); } catch { return false; } const prev = gmRead(ACCOUNTS_KEY) || localRead(ACCOUNTS_KEY); const prevStore = parseStore(prev); if (!opts.allowEmpty && accountCount(store) === 0 && accountCount(prevStore) > 0) return false; if (prev && prev !== text && prevStore) writeRaw(ACCOUNTS_BACKUP_KEY, prev); return writeRaw(ACCOUNTS_KEY, text); }; const storageKind = () => (gmStore ? 'gm' : 'local'); const list = (store = load()) => Object.keys(store.accounts) .map((id) => store.accounts[id]) .sort((a, b) => (b.usedAt || 0) - (a.usedAt || 0)); const get = (id, store = load()) => (id ? store.accounts[String(id)] || null : null); const readUserInfo = () => { try { const raw = JSON.parse(localStorage.getItem('userInfo')); if (!raw || typeof raw !== 'object') return null; const id = raw.loginName || raw.userId; if (!id) return null; return raw; } catch { return null; } }; const tokenExpiry = (userInfo) => { const token = userInfo && userInfo.accessToken; if (!token) return 0; try { const payload = JSON.parse( decodeURIComponent(escape(atob(String(token).split('.')[1].replace(/-/g, '+').replace(/_/g, '/')))) ); return Number(payload && payload.expiresTime) || 0; } catch { return 0; } }; const isAlive = (account, now = Date.now()) => { if (!account) return false; if (!account.token || !account.userInfo) return false; return !account.expiresAt || account.expiresAt > now + 60 * 1000; }; const profileFromUserInfo = (userInfo, prev = null, creds = null) => { const picked = creds && typeof creds === 'object' ? creds : null; const plain = picked && picked.password ? String(picked.password) : ''; return { id: String(userInfo.loginName || userInfo.userId), name: userInfo.userName || userInfo.nick_name || (prev ? prev.name : ''), phone: (picked && picked.phone) || (prev ? prev.phone || '' : ''), password: plain ? obscure(plain) : prev ? prev.password || '' : '', loginId: (picked && picked.loginId) || (prev ? prev.loginId || '' : ''), token: userInfo.accessToken || '', userInfo, expiresAt: tokenExpiry(userInfo), usedAt: Date.now(), data: prev ? prev.data || null : null, }; }; const snapshot = (data) => { const snap = {}; for (const k of DATA_FIELDS) { if (data && data[k] !== undefined) snap[k] = JSON.parse(JSON.stringify(data[k])); } return snap; }; const emptySnapshot = () => ({ publicCourses: [], zone: [], toLearnList: [], today: { date: '', done: 0, minutes: 0 }, theme: 'dark', pendingListRefresh: false, }); const applySnapshot = (snap) => { const out = emptySnapshot(); for (const k of DATA_FIELDS) { if (snap && snap[k] !== undefined) out[k] = snap[k]; } return out; }; const ACCESS_KEY_RE = /prod-core-access$/; const findAccessKey = () => { try { for (let i = 0; i < localStorage.length; i += 1) { const k = localStorage.key(i); if (k && ACCESS_KEY_RE.test(k)) return k; } return ''; } catch { return ''; } }; const readAccessToken = () => { const key = findAccessKey(); if (!key) return ''; try { const raw = JSON.parse(localStorage.getItem(key)); return raw && raw.accessToken ? String(raw.accessToken) : ''; } catch { return ''; } }; const writeAccessToken = (token) => { const key = findAccessKey(); if (!key || !token) return false; try { const raw = JSON.parse(localStorage.getItem(key)) || {}; raw.accessToken = String(token); localStorage.setItem(key, JSON.stringify(raw)); return true; } catch { return false; } }; const clearAccessToken = () => { const key = findAccessKey(); if (!key) return true; try { localStorage.removeItem(key); return true; } catch { return false; } }; const writeUserInfo = (userInfo) => { try { localStorage.setItem('userInfo', JSON.stringify(userInfo)); return true; } catch { return false; } }; const clearUserInfo = () => { let ok = true; try { localStorage.removeItem('userInfo'); } catch { ok = false; } clearAccessToken(); return ok; }; const tokenLoginName = (token) => { if (!token) return ''; try { const payload = JSON.parse( decodeURIComponent(escape(atob(String(token).split('.')[1].replace(/-/g, '+').replace(/_/g, '/')))) ); return String((payload && (payload.loginName || payload.userId)) || ''); } catch { return ''; } }; const globalScope = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; globalScope.BWACC = { ACCOUNTS_KEY, ACCOUNTS_BACKUP_KEY, DATA_FIELDS, CAPTURE_KEY, CAPTURE_TTL, load, save, storageKind, tookBackup, tookMigration, list, get, readUserInfo, tokenExpiry, isAlive, profileFromUserInfo, snapshot, emptySnapshot, applySnapshot, obscure, clarify, writeUserInfo, clearUserInfo, readAccessToken, writeAccessToken, clearAccessToken, tokenLoginName, saveCapture, readCapture, dropCapture, rawRead, rawWrite: writeRaw, }; })(); (function () { 'use strict'; const TEMPLATES = { '0': '07c00ff83ffc3e7c3c3e7c3e7c1f7c1ffc1ffc1ffc1ffc1ff81ff81f7c3e7e3c3e7c3ff81ff007e0', '1': '0fc01fc01fc01bc003c003c003c003c003c003c003c003c003c003c003c003c003c03ffe3ffe3ffc', '2': '0fe03ff87ffe7c7e703f001f001f001f001f003e007e01fc03fc0ff81ff03fc07ffc7ffe7fff7ffe', '3': '1fe03ff81ff8107c003c003c003c003807f807f00ffc07fc003e001e001e001e207e3ffc7ff81fe0', '4': '007000f801f803f807f807780f781e781c783c78387878787ffe7ffe7ffe007c0078007800780070', '5': '3ff87ff87ff87ff87c007c007fa07ff87ffc3ffc00fe003c003c003e003e007e00fc7ff87ff03fc0', '6': '01f807fc1ffc3f083e003c003c003de03ff83ffe7f3e7e1f3c1f3c1f3c1e3e1e3f3e1ffc0ff803f0', '7': '3ffc3ffe3fff1fff007e007e007c00fc00fc01f801f803f003e003e003c007c007c00f800f000e00', '8': '03e00ff80ff81e3c1e3c1e1c1e3c1e3c0ff807f00ff81ffc3e1e3c1e3c1e3c1e3e3c1ffc0ff803f0', '9': '03e00ff83ffc3e3e3c3e7c1e7c1e7c1e3c3f3e7f3fff1fff07df001f001e003e007e1ffc1ff01fc0', '+': '0000000001800180038003800380038003c0fffffffffffe03800380038003800380018000000000', '-': '00000000000000000000000000007ffeffffffffffffffffffffffff000000000000000000000000', '*': '000000000000008001800183f1cf7fff1ff80ff00ff07feef9cf6186018001800180000000000000', '/': '0018003800380038007000f000e000e001e001c003c0038003800700070006000e001e001c001c00', }; const T = 16; const TH = 20; const SIZE = T * TH; const DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; const OPS = ['+', '-', '*', '/']; const POOL_BITS = {}; const hexToBits = (hex) => { const bits = new Array(SIZE); for (let i = 0; i < SIZE; i++) { const nibble = parseInt(hex[Math.floor(i / 4)], 16) || 0; bits[i] = (nibble >> (3 - (i % 4))) & 1; } return bits; }; for (const key of Object.keys(TEMPLATES)) POOL_BITS[key] = hexToBits(TEMPLATES[key]); const MAX_DIST = 78; const makeCanvas = (w, h) => { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; }; const toImage = (source) => { const isImg = source && typeof source === 'object' && String(source.tagName || '').toUpperCase() === 'IMG'; if (isImg && source.naturalWidth > 0) return Promise.resolve(source); return new Promise((resolve, reject) => { const im = isImg ? source : new Image(); const done = () => resolve(im); const fail = () => reject(new Error('验证码图片加载失败')); if (isImg) { im.addEventListener('load', done, { once: true }); im.addEventListener('error', fail, { once: true }); setTimeout(() => (im.naturalWidth > 0 ? resolve(im) : reject(new Error('验证码图片尺寸为空'))), 1500); return; } im.onload = done; im.onerror = fail; im.src = String(source || ''); }); }; const blueMask = (data, w, h) => { const mask = []; const col = new Array(w).fill(0); for (let y = 0; y < h; y++) { const row = new Array(w).fill(0); for (let x = 0; x < w; x++) { const i = (y * w + x) * 4; const r = data[i]; const g = data[i + 1]; const b = data[i + 2]; if (b > 120 && b - r > 50 && b - g > 30) { row[x] = 1; col[x] += 1; } } mask.push(row); } return { mask, col }; }; const splitBlocks = (col, w) => { const blocks = []; let start = -1; for (let x = 0; x < w; x++) { if (col[x] > 0 && start < 0) start = x; else if (col[x] === 0 && start >= 0) { blocks.push([start, x - 1]); start = -1; } } if (start >= 0) blocks.push([start, w - 1]); return blocks; }; const cropBits = (mask, block, h) => { let y0 = h; let y1 = -1; for (let y = 0; y < h; y++) { for (let x = block[0]; x <= block[1]; x++) { if (mask[y][x]) { if (y < y0) y0 = y; if (y > y1) y1 = y; } } } if (y1 < 0) return null; const cw = block[1] - block[0] + 1; const ch = y1 - y0 + 1; const src = makeCanvas(cw, ch); const sx = src.getContext('2d'); const imgData = sx.createImageData(cw, ch); for (let y = 0; y < ch; y++) { for (let x = 0; x < cw; x++) { const v = mask[y0 + y][block[0] + x] ? 0 : 255; const j = (y * cw + x) * 4; imgData.data[j] = v; imgData.data[j + 1] = v; imgData.data[j + 2] = v; imgData.data[j + 3] = 255; } } sx.putImageData(imgData, 0, 0); const dst = makeCanvas(T, TH); const dx = dst.getContext('2d'); dx.fillStyle = '#fff'; dx.fillRect(0, 0, T, TH); const scale = Math.min(TH / ch, T / cw); const dw = Math.max(1, Math.round(cw * scale)); const dh = Math.max(1, Math.round(ch * scale)); dx.drawImage(src, Math.round((T - dw) / 2), Math.round((TH - dh) / 2), dw, dh); const out = dx.getImageData(0, 0, T, TH).data; const bits = new Array(SIZE); for (let i = 0; i < SIZE; i++) bits[i] = out[i * 4] < 128 ? 1 : 0; return bits; }; const distance = (a, b) => { let n = 0; for (let i = 0; i < SIZE; i++) if (a[i] !== b[i]) n += 1; return n; }; const bestMatch = (bits, pool) => { let best = ''; let bestD = Infinity; let secondD = Infinity; for (const key of pool) { const d = distance(bits, POOL_BITS[key]); if (d < bestD) { secondD = bestD; bestD = d; best = key; } else if (d < secondD) { secondD = d; } } return { ch: best, d: bestD, margin: secondD - bestD }; }; const solve = (expr) => { const m = /^(\d)([+\-*/])(\d)$/.exec(String(expr || '')); if (!m) return null; const a = Number(m[1]); const b = Number(m[3]); const op = m[2]; if (op === '+') return a + b; if (op === '-') return a - b >= 0 ? a - b : null; if (op === '*') return a * b; if (op === '/') return b !== 0 && a % b === 0 ? a / b : null; return null; }; const recognize = async (source) => { let im; try { im = await toImage(source); } catch (error) { return { ok: false, reason: 'image', message: error.message }; } const w = im.naturalWidth || im.width; const h = im.naturalHeight || im.height; if (!w || !h) return { ok: false, reason: 'image', message: '图片尺寸为空' }; const base = makeCanvas(w, h); const bx = base.getContext('2d'); bx.drawImage(im, 0, 0); let data; try { data = bx.getImageData(0, 0, w, h).data; } catch { return { ok: false, reason: 'tainted' }; } const { mask, col } = blueMask(data, w, h); const blocks = splitBlocks(col, w); if (blocks.length !== 5) return { ok: false, reason: 'blocks', blocks: blocks.length }; const parts = []; for (let i = 0; i < 3; i++) { const bits = cropBits(mask, blocks[i], h); if (!bits) return { ok: false, reason: 'empty' }; parts.push(bestMatch(bits, i === 1 ? OPS : DIGITS)); } const expr = parts.map((p) => p.ch).join(''); const answer = solve(expr); const maxDist = Math.max(...parts.map((p) => p.d)); const ok = answer !== null && maxDist <= MAX_DIST; return { ok, expr, answer, maxDist, detail: parts.map((p) => `${p.ch}:${p.d}/${p.margin}`).join(' '), reason: ok ? '' : answer === null ? 'solve' : 'distance', }; }; const globalScope = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; globalScope.BWOCR = { recognize, solve, TEMPLATES, MAX_DIST }; })(); (function () { 'use strict'; const FONT_FAMILY = '"Segoe UI","Microsoft YaHei",system-ui,-apple-system,sans-serif'; const MONO_FAMILY = "'Cascadia Code',Consolas,'Courier New',monospace"; const THEMES = { dark: { label: '深色', bg: '#0d1117', shadow: '0 24px 56px rgba(0,0,0,.6), 0 2px 8px rgba(0,0,0,.42)', blur: 'none', vars: { surface: '#161b22', 'surface-hi': '#10151c', track: '#21262d', border: 'rgba(240,246,252,.09)', 'border-strong': 'rgba(240,246,252,.15)', text: '#e6edf3', 'text-rgb': '230,237,243', muted: '#8b949e', 'muted-rgb': '139,148,158', dim: '#6e7681', 'dim-rgb': '110,118,129', accent: '#58a6ff', 'accent-rgb': '88,166,255', ok: '#3fb950', 'ok-rgb': '63,185,80', warn: '#d29922', 'warn-rgb': '210,153,34', danger: '#f85149', 'danger-rgb': '248,81,73', 'danger-solid': '#da3633', 'on-danger': '#ffffff', 'on-danger-rgb': '255,255,255', hover: 'rgba(88,166,255,.09)', head: '#12171f', 'on-accent': '#0d1117', 'on-accent-rgb': '13,17,23' } }, ink: { label: '暖墨', bg: '#1d1b18', shadow: '0 22px 52px rgba(0,0,0,.55), 0 2px 8px rgba(0,0,0,.3)', blur: 'none', vars: { surface: '#26231f', 'surface-hi': '#201e1b', track: '#3b352e', border: 'rgba(255,255,255,.08)', 'border-strong': 'rgba(255,255,255,.13)', text: '#f4efe6', 'text-rgb': '244,239,230', muted: '#a89d8d', 'muted-rgb': '168,157,141', dim: '#746a5d', 'dim-rgb': '116,106,93', accent: '#e0913f', 'accent-rgb': '224,145,63', ok: '#6fbf8b', 'ok-rgb': '111,191,139', warn: '#e5b34a', 'warn-rgb': '229,179,74', danger: '#e2705f', 'danger-rgb': '226,112,95', 'danger-solid': '#b8402c', 'on-danger': '#ffffff', 'on-danger-rgb': '255,255,255', hover: 'rgba(224,145,63,.1)', head: '#221f1c', 'on-accent': '#1d1b18', 'on-accent-rgb': '29,27,24' } }, light: { label: '浅色', bg: '#ffffff', shadow: '0 18px 44px rgba(31,35,40,.16), 0 1px 3px rgba(31,35,40,.08)', blur: 'none', vars: { surface: '#f6f8fa', 'surface-hi': '#eaeef2', track: '#d0d7de', border: 'rgba(31,35,40,.12)', 'border-strong': 'rgba(31,35,40,.18)', text: '#1f2328', 'text-rgb': '31,35,40', muted: '#59636e', 'muted-rgb': '89,99,110', dim: '#6e7781', 'dim-rgb': '110,119,129', accent: '#0969da', 'accent-rgb': '9,105,218', ok: '#1a7f37', 'ok-rgb': '26,127,55', warn: '#9a6700', 'warn-rgb': '154,103,0', danger: '#cf222e', 'danger-rgb': '207,34,46', 'danger-solid': '#cf222e', 'on-danger': '#ffffff', 'on-danger-rgb': '255,255,255', hover: 'rgba(9,105,218,.06)', head: '#f6f8fa', 'on-accent': '#ffffff', 'on-accent-rgb': '255,255,255' } } }; const THEME_ORDER = Object.keys(THEMES); const TONE_KEY = { ok: 'ok', warn: 'warn', accent: 'accent', danger: 'danger', muted: 'muted', dim: 'dim' }; const toneVar = (c) => (TONE_KEY[c] ? `var(--bw-${TONE_KEY[c]})` : (c || 'var(--bw-muted)')); const alpha = (key, a) => `rgba(var(--bw-${key}-rgb),${Math.max(0, Math.min(1, a))})`; const PANEL_WIDTH = 'clamp(480px, 40vw, 620px)'; const FONT_SIZE = 12; const ROW_H = 32; const HEAD_H = 30; const BANNER_H = 32; const SECTION_H = 30; const MAX_ROWS = 9; const PAGE_TALL = () => Math.max(360, Math.min(760, (window.innerHeight || 900) - 80)); const style = (el, s) => Object.assign(el.style, s); const escapeHtml = (str) => String(str ?? '') .replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); let panel, titleBar, titleMark, titleText, accountChip, hoursChip, statusChip, themeBtn, updateBtn, updateDot, logBtn, minBtn, collapseView; let envBtn, envDot; let accountPage, accountPageBody, accountPageTitle, accountBack, accountPageCount; let accountView = { id: '', name: '', list: [], logged: false }; let countdownLeft = 0; let countdownTip = null; let accountForm = null; let accountDeleteAsk = ''; let accountLoginAsk = false; let overview, ovPercent, ovBar, ovBarFill, ovDetail, ovRemain; let tabBar, tabLeft, refreshBtn; let body, tableBox, videoCard, logDrawer, logDrawerBody, footer, footerInfo, mainBtn; let collapsed = false; let interactive = true; let mode = 'browse'; let activeTab = 'public'; let actionVisible = false; let videoVisible = false; let logOpen = false; let doneOpen = false; let themeName = THEME_ORDER[0]; let updateState = { available: false, version: '', checking: false, hidden: false }; let envWarn = { issues: [], at: 0 }; let statusTone = { label: '', tone: 'dim' }; let scriptName = '宝武学习助手'; let scriptVersion = ''; let stats = { total: 0, done: 0, pending: 0 }; let tabCounts = {}; const refreshingTabs = new Set(); let refreshingAll = false; const isRefreshing = (key) => refreshingAll || (key ? refreshingTabs.has(key) : refreshingTabs.size > 0); let lastOpts = null; let sectionInView = false; let lastTableArgs = null; let callbacks = {}; let tabs = [ { key: 'public', label: '公开课' }, { key: 'zone', label: '专区课' } ]; const ring = (size, percent) => { const s = 2.4; const r = (size - s * 2) / 2; const c = 2 * Math.PI * r; const pct = Math.max(0, Math.min(100, Number(percent) || 0)); const off = c * (1 - pct / 100); return ` `; }; const injectStyle = () => { if (document.getElementById('bw-learn-tool-style')) return; const el = document.createElement('style'); el.id = 'bw-learn-tool-style'; el.textContent = `@keyframes bw-pulse{0%,100%{opacity:1}50%{opacity:.25}} #bw-learn-tool-panel{color:var(--bw-text)} #bw-learn-tool-panel .bw-live{animation:bw-pulse 1.7s ease-in-out infinite} #bw-learn-tool-panel .bw-line{transition:background .12s ease} #bw-learn-tool-panel .bw-line:hover{background:var(--bw-hover)} #bw-learn-tool-panel .bw-tab{transition:color .15s ease} #bw-learn-tool-panel .bw-tab:hover{color:var(--bw-text)} #bw-learn-tool-panel .bw-ico{background:none;border:0;padding:0;border-radius:7px;display:flex;align-items:center;justify-content:center; width:24px;height:24px;color:var(--bw-muted);cursor:pointer;flex:none;transition:background .12s ease,color .12s ease;position:relative} #bw-learn-tool-panel .bw-ico:hover{background:var(--bw-hover);color:var(--bw-text)} #bw-learn-tool-panel .bw-main{transition:filter .12s ease,opacity .12s ease} #bw-learn-tool-panel .bw-main:hover{filter:brightness(1.07)} #bw-learn-tool-panel .bw-section:hover{background:var(--bw-hover)} #bw-learn-tool-panel ::-webkit-scrollbar{width:6px;height:6px} #bw-learn-tool-panel ::-webkit-scrollbar-thumb{background:var(--bw-track);border-radius:3px} #bw-learn-tool-panel ::-webkit-scrollbar-thumb:hover{background:var(--bw-dim)} #bw-learn-tool-panel ::-webkit-scrollbar-track{background:transparent}`; document.head.appendChild(el); }; const statusDot = (text, tone) => { const color = toneVar(tone); return ` ${escapeHtml(text)} `; }; const LOG_KEY = 'bw_learn_logs'; const LOG_KEEP_DAYS = 7; const LOG_DAY_MAX = 600; const LOG_DOM_MAX = 300; const LOG_MERGE_MS = 10 * 1000; const LOG_FLUSH_MS = 2000; const logRead = (key) => { try { if (typeof GM_getValue === 'function') return GM_getValue(key, ''); return localStorage.getItem(key) || ''; } catch { return ''; } }; const logWrite = (key, text) => { try { if (typeof GM_setValue === 'function') GM_setValue(key, text); else localStorage.setItem(key, text); return true; } catch { return false; } }; const pad2 = (n) => String(n).padStart(2, '0'); const dayStamp = (offsetDays = 0) => { const d = new Date(Date.now() - offsetDays * 86400000); return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`; }; const clockOf = (t) => { const d = new Date(t); return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`; }; let logDays = null; let logDirty = false; let logFlushTimer = null; let logLast = { x: '', at: 0, n: 0, el: null, head: '' }; const loadLogDays = () => { if (logDays) return logDays; logDays = {}; try { const raw = logRead(LOG_KEY); const obj = raw ? JSON.parse(raw) : null; const days = obj && obj.days ? obj.days : {}; const oldest = dayStamp(LOG_KEEP_DAYS - 1); Object.keys(days).forEach((k) => { if (k < oldest) return; const arr = Array.isArray(days[k]) ? days[k] : []; if (arr.length) logDays[k] = arr.slice(-LOG_DAY_MAX); }); } catch { logDays = {}; } return logDays; }; const flushLogs = () => { if (logFlushTimer) { clearTimeout(logFlushTimer); logFlushTimer = null; } if (!logDirty || !logDays) return; logDirty = false; logWrite(LOG_KEY, JSON.stringify({ v: 1, days: logDays })); }; const scheduleFlush = () => { if (logFlushTimer) return; logFlushTimer = setTimeout(() => { logFlushTimer = null; flushLogs(); }, LOG_FLUSH_MS); }; const appendLog = (plain) => { const days = loadLogDays(); const key = dayStamp(); const arr = days[key] || (days[key] = []); const now = Date.now(); const last = arr[arr.length - 1]; if (last && last.x === plain && now - last.t < LOG_MERGE_MS) { last.n = (last.n || 1) + 1; last.t = now; logDirty = true; scheduleFlush(); return last.n; } arr.push({ t: now, x: plain, n: 1 }); if (arr.length > LOG_DAY_MAX) arr.splice(0, arr.length - LOG_DAY_MAX); logDirty = true; scheduleFlush(); return 1; }; const logLineText = (e) => `[${clockOf(e.t)}] ${e.x}${e.n > 1 ? ` ×${e.n}` : ''}`; const renderLogHistory = () => { if (!logDrawerBody || logDrawerBody.children.length > 0) return; const days = loadLogDays(); const rows = []; Object.keys(days).sort().forEach((k) => (days[k] || []).forEach((e) => rows.push({ ...e, day: k }))); const today = dayStamp(); let shownDay = ''; rows.slice(-LOG_DOM_MAX).forEach((e) => { if (e.day !== shownDay) { shownDay = e.day; const sep = document.createElement('div'); sep.textContent = e.day === today ? '— 今天 —' : `— ${e.day} —`; style(sep, { padding: '6px 0 2px', color: 'var(--bw-dim)', fontSize: '10px' }); logDrawerBody.appendChild(sep); } const line = document.createElement('div'); line.textContent = logLineText(e); style(line, { padding: '1px 0', wordBreak: 'break-word' }); logDrawerBody.appendChild(line); }); const last = rows[rows.length - 1]; if (last) logLast = { x: last.x, at: last.t, n: last.n || 1, el: null, head: '' }; logDrawerBody.scrollTop = logDrawerBody.scrollHeight; }; const addLog = (msg) => { if (!logDrawerBody) return; const raw = String(msg); const stamp = (raw.match(/^\[\d{1,2}:\d{2}:\d{2}\]/) || [''])[0]; const plain = raw.replace(/^\[\d{1,2}:\d{2}:\d{2}\]\s*/, ''); const times = appendLog(plain); if (times > 1 && logLast.el && logLast.x === plain) { logLast.n = times; logLast.el.textContent = `${logLast.head}${plain} ×${times}`; } else { const head = stamp ? `${stamp} ` : `[${clockOf(Date.now())}] `; const line = document.createElement('div'); line.textContent = `${head}${plain}`; style(line, { padding: '1px 0', wordBreak: 'break-word' }); logDrawerBody.appendChild(line); if (logDrawerBody.children.length > LOG_DOM_MAX) logDrawerBody.removeChild(logDrawerBody.children[0]); logLast = { x: plain, at: Date.now(), n: 1, el: line, head }; } logDrawerBody.scrollTop = logDrawerBody.scrollHeight; footerInfo.textContent = plain; footerInfo.title = plain; }; const exportLogs = () => { try { const days = loadLogDays(); const out = []; Object.keys(days).sort().forEach((k) => { out.push(`===== ${k} =====`); (days[k] || []).forEach((e) => out.push(logLineText(e))); out.push(''); }); if (!out.length) return false; const blob = new Blob([out.join('\n')], { type: 'text/plain;charset=utf-8' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = `bw-learn-log-${dayStamp()}.txt`; a.click(); setTimeout(() => { try { URL.revokeObjectURL(a.href); } catch { } }, 3000); return true; } catch { return false; } }; const fmtMinutes = (min) => { const total = Math.max(0, Math.round(Number(min) || 0)); if (total < 60) return `${total} 分钟`; const h = Math.floor(total / 60); const m = total % 60; return m > 0 ? `${h} 小时 ${m} 分` : `${h} 小时`; }; const applyTheme = () => { if (!panel) return; const t = THEMES[themeName] || THEMES.paper; for (const [k, val] of Object.entries(t.vars)) panel.style.setProperty(`--bw-${k}`, val); panel.style.setProperty('--bw-bg', t.bg); panel.style.background = t.bg; panel.style.borderColor = `var(--bw-border-strong)`; panel.style.boxShadow = t.shadow; panel.style.backdropFilter = t.blur; panel.style.webkitBackdropFilter = t.blur; }; const renderOverview = () => { if (!ovPercent) return; const pct = stats.total > 0 ? Math.round((stats.done / stats.total) * 100) : 0; ovPercent.textContent = `${pct}%`; ovPercent.style.color = stats.total > 0 && stats.done === stats.total ? 'var(--bw-ok)' : 'var(--bw-text)'; ovBarFill.style.width = `${pct}%`; ovBarFill.style.background = stats.total > 0 && stats.done === stats.total ? 'var(--bw-ok)' : `linear-gradient(90deg,var(--bw-accent),${alpha('accent', .62)})`; ovDetail.textContent = isRefreshing() ? '正在刷新课程数据…' : stats.total > 0 ? `已完成 ${stats.done} · 待学 ${stats.pending} · 共 ${stats.total} 门` : '暂无数据'; const remain = Number(stats.remainMin) || 0; const remainText = stats.pending > 0 && remain > 0 ? `预计还需 ${fmtMinutes(remain)}` : ''; ovRemain.textContent = remainText; ovRemain.style.display = remainText ? 'inline-block' : 'none'; const hours = Number(stats.hours?.total) || 0; if (hoursChip) { hoursChip.textContent = hours > 0 ? `总学时 ${hours}` : ''; hoursChip.title = hours > 0 ? `账号总学时 ${hours}(公开课 ${Number(stats.hours.public) || 0} · 学习专区 ${Number(stats.hours.zone) || 0})` : ''; hoursChip.style.display = hours > 0 ? 'inline-flex' : 'none'; } }; const setStats = (next) => { stats = { total: 0, done: 0, pending: 0, ...(next || {}) }; renderOverview(); renderCollapseView(); }; const setTabCounts = (map) => { tabCounts = map || {}; renderTabs(); }; const syncLayout = () => { if (!panel) return; const chrome = !collapsed; panel.style.width = collapsed ? 'auto' : PANEL_WIDTH; collapseView.style.display = collapsed ? 'flex' : 'none'; titleBar.style.display = collapsed ? 'none' : 'flex'; overview.style.display = chrome && mode === 'browse' ? 'flex' : 'none'; tabBar.style.display = chrome && mode === 'browse' ? 'flex' : 'none'; body.style.display = chrome ? 'block' : 'none'; footer.style.display = chrome ? 'flex' : 'none'; logDrawer.style.display = chrome && logOpen ? 'block' : 'none'; if (envWrap) envWrap.style.display = chrome && envOpen ? 'flex' : 'none'; if (collapsed) panel.style.height = ''; else if (envOpen) panel.style.height = `${PAGE_TALL()}px`; videoCard.style.display = videoVisible ? 'block' : 'none'; tableBox.style.display = mode === 'study' ? 'none' : 'block'; footerInfo.style.display = mode === 'study' ? 'none' : 'block'; mainBtn.style.flex = mode === 'study' ? '1' : 'none'; mainBtn.style.width = mode === 'study' ? '100%' : 'auto'; mainBtn.style.display = actionVisible ? 'block' : 'none'; }; const renderCollapseView = () => { if (!collapseView) return; const pct = stats.total > 0 ? (stats.done / stats.total) * 100 : 0; const label = isRefreshing() ? '刷新中' : stats.total > 0 ? `${stats.done} / ${stats.total}` : '未加载'; const showStatus = statusTone.label && statusTone.label !== '待学习'; collapseView.innerHTML = `${ring(20, pct)} ${label} ${mode === 'study' ? '自动学习中' : (stats.pending > 0 ? `${stats.pending} 门未完成` : '')} ${showStatus ? statusDot(statusTone.label, statusTone.tone) : ''}`; }; const renderUpdateBtn = () => { if (!updateBtn) return; updateBtn.style.display = updateState.hidden ? 'none' : 'flex'; updateDot.style.display = updateState.available ? 'block' : 'none'; updateBtn.style.color = updateState.available ? 'var(--bw-accent)' : 'var(--bw-muted)'; const base = updateState.checking ? '正在检查更新…' : (updateState.available ? `发现新版本 v${updateState.version},点击升级` : '检查更新'); updateBtn.title = scriptVersion ? `${base}\n当前版本 v${scriptVersion}` : base; }; const renderEnvBtn = () => { if (!envBtn) return; const issues = envWarn.issues || []; envBtn.style.display = 'inline-flex'; if (envDot) envDot.style.display = issues.length ? 'block' : 'none'; envBtn.style.color = issues.length ? 'var(--bw-warn)' : 'var(--bw-muted)'; envBtn.title = issues.length ? `浏览器设置需要调整(${issues.length} 项)\n${issues.map((i) => `· ${i.title}`).join('\n')}\n点击查看怎么改` : '浏览器设置(自动播放 / 不休眠)\n现在没检测到问题,点开可以看两处该怎么设'; }; const setEnvWarn = (issues) => { envWarn = { issues: Array.isArray(issues) ? issues : [], at: Date.now() }; renderEnvBtn(); }; const initials = (id, name) => { const n = String(name || '').trim(); if (n) return /[\u4e00-\u9fa5]/.test(n[0]) ? n[0] : n[0].toUpperCase(); const k = String(id || ''); return k ? k.slice(-2) : '?'; }; const avatarEl = (text, size, active) => { const el = document.createElement('span'); el.textContent = text; style(el, { width: `${size}px`, height: `${size}px`, borderRadius: '50%', flex: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: `${Math.round(size * .38)}px`, fontWeight: '600', lineHeight: '1', boxSizing: 'border-box', background: active ? alpha('accent', .16) : 'var(--bw-surface-hi)', color: active ? 'var(--bw-accent)' : 'var(--bw-muted)', border: `1px solid ${active ? alpha('accent', .45) : 'var(--bw-border)'}` }); return el; }; const iconAction = (svg, title, onClick, tone) => { const b = document.createElement('button'); b.type = 'button'; b.innerHTML = svg; b.title = title; style(b, { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: '26px', height: '26px', padding: '0', flex: 'none', border: '1px solid var(--bw-border)', borderRadius: '7px', background: 'transparent', color: tone || 'var(--bw-muted)', cursor: 'pointer', transition: 'background .12s ease,color .12s ease' }); b.addEventListener('mouseenter', () => { b.style.background = 'var(--bw-hover)'; b.style.color = tone || 'var(--bw-text)'; }); b.addEventListener('mouseleave', () => { b.style.background = 'transparent'; b.style.color = tone || 'var(--bw-muted)'; }); b.addEventListener('mousedown', (e) => e.preventDefault()); b.addEventListener('click', onClick); return b; }; const pageBtn = (text, onClick, opts = {}) => { const b = document.createElement('button'); b.type = 'button'; b.textContent = text; const filled = !!opts.bg; style(b, { flex: opts.flex || 'none', height: opts.small ? '26px' : '32px', padding: opts.small ? '0 9px' : '0 14px', borderRadius: '7px', border: `1px solid ${filled ? 'transparent' : 'var(--bw-border)'}`, background: opts.bg || 'transparent', color: opts.color || (filled ? 'var(--bw-on-accent)' : 'var(--bw-text)'), cursor: 'pointer', fontFamily: FONT_FAMILY, fontSize: opts.small ? '11px' : '12px', whiteSpace: 'nowrap' }); if (!filled) { b.addEventListener('mouseenter', () => { b.style.background = 'var(--bw-hover)'; }); b.addEventListener('mouseleave', () => { b.style.background = 'transparent'; }); } b.addEventListener('mousedown', (e) => e.preventDefault()); if (onClick) b.addEventListener('click', onClick); return b; }; const pageField = (label, value, opts = {}) => { const wrap = document.createElement('label'); style(wrap, { display: 'flex', flexDirection: 'column', gap: '4px', minWidth: '0' }); const lab = document.createElement('span'); lab.textContent = label; style(lab, { fontSize: '10.5px', color: 'var(--bw-muted)' }); const box = document.createElement('div'); style(box, { position: 'relative', display: 'flex' }); const input = document.createElement('input'); input.type = opts.type || 'text'; input.value = value || ''; input.placeholder = opts.placeholder || ''; input.disabled = !!opts.disabled; if (opts.name) input.dataset.field = opts.name; style(input, { width: '100%', height: '30px', boxSizing: 'border-box', padding: opts.toggleable ? '0 40px 0 9px' : '0 9px', borderRadius: '7px', border: '1px solid var(--bw-border)', background: 'var(--bw-surface)', color: 'var(--bw-text)', fontFamily: FONT_FAMILY, fontSize: '12px', outline: 'none', opacity: opts.disabled ? '.62' : '1' }); input.addEventListener('focus', () => { input.style.borderColor = alpha('accent', .6); }); input.addEventListener('blur', () => { input.style.borderColor = 'var(--bw-border)'; }); box.appendChild(input); if (opts.toggleable) { const eye = document.createElement('button'); eye.type = 'button'; eye.textContent = '显示'; style(eye, { position: 'absolute', right: '4px', top: '4px', height: '22px', padding: '0 6px', border: 'none', borderRadius: '5px', background: 'transparent', color: 'var(--bw-muted)', cursor: 'pointer', fontFamily: FONT_FAMILY, fontSize: '10px' }); eye.addEventListener('click', () => { const hidden = input.type === 'password'; input.type = hidden ? 'text' : 'password'; eye.textContent = hidden ? '隐藏' : '显示'; }); box.appendChild(eye); } wrap.appendChild(lab); wrap.appendChild(box); if (opts.title) { wrap.title = opts.title; input.title = opts.title; } return wrap; }; const readField = (row) => row.querySelector('input').value.trim(); const renderAccountChip = () => { if (!accountChip) return; const { id, name, list, logged } = accountView; const showId = !!(logged && id); accountChip.style.display = 'inline-flex'; accountChip.textContent = ''; const av = document.createElement('span'); if (showId) { av.textContent = initials(id, name); } else { av.innerHTML = ` `; } style(av, { width: '17px', height: '17px', borderRadius: '50%', flex: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: '9.5px', fontWeight: '700', lineHeight: '1', background: showId ? alpha('accent', .18) : 'transparent', color: showId ? 'var(--bw-accent)' : 'var(--bw-muted)', border: showId ? '1px solid transparent' : '1px dashed var(--bw-border-strong)' }); const label = document.createElement('span'); label.textContent = showId ? String(id) : '登录'; style(label, { minWidth: '0', overflow: 'hidden', textOverflow: 'ellipsis' }); const care = document.createElement('span'); care.innerHTML = ` `; style(care, { display: 'inline-flex', flex: 'none', color: 'var(--bw-dim)' }); accountChip.appendChild(av); accountChip.appendChild(label); accountChip.appendChild(care); if (showId) { accountChip.title = `当前账号 ${id}${name ? ' · ' + name : ''}(本机共 ${list.length} 个),点开管理`; } else { accountChip.title = list.length ? `未登录(本机记着 ${list.length} 个账号),点开可一键登录,或换个账号登` : '未登录,点开去登录;登录一次就会自动记下账号'; } }; const setAccount = ({ id, name, list, logged } = {}) => { const on = logged == null ? !!id : !!logged; accountView = { id: id || '', name: name || '', list: Array.isArray(list) ? list : [], logged: on, }; renderAccountChip(); if (accountPage && accountPage.style.display !== 'none') renderAccountPage(); }; const setLoginCountdown = (seconds) => { const v = Math.round(Number(seconds) || 0); if (v === countdownLeft) return; countdownLeft = v; if (!countdownTip) return; countdownTip.style.display = v === 0 ? 'none' : 'inline-flex'; countdownTip.textContent = v > 0 ? `${v}s` : '登录中'; }; const fitAccountHeight = () => { if (!panel || !accountPage || collapsed || accountPage.style.display === 'none') return; const apply = () => { if (!panel || collapsed || accountPage.style.display === 'none') return; const headH = (accountPage.firstElementChild || {}).offsetHeight || 0; const bodyH = accountPageBody ? accountPageBody.scrollHeight : 0; if (!headH || !bodyH) return; const chromeH = Math.round(accountPage.getBoundingClientRect().top - panel.getBoundingClientRect().top) || 40; const need = chromeH + headH + bodyH + 6; panel.style.height = `${Math.max(260, Math.min(PAGE_TALL(), need))}px`; }; apply(); if (typeof requestAnimationFrame === 'function') requestAnimationFrame(apply); }; const openAccountPage = () => { if (!accountPage) return; accountForm = null; accountDeleteAsk = ''; accountLoginAsk = false; accountPage.style.display = 'flex'; renderAccountPage(); accountPage.focus(); }; const closeAccountPage = () => { if (!accountPage) return; accountPage.style.display = 'none'; if (panel) panel.style.height = ''; accountForm = null; accountDeleteAsk = ''; accountLoginAsk = false; accountPageBody.textContent = ''; countdownTip = null; }; const renderAccountPage = () => { if (!accountPage || accountPage.style.display === 'none') return; accountPageTitle.textContent = accountForm ? '编辑账号' : (accountView.logged ? '账号' : '登录账号'); accountPageCount.textContent = accountForm ? '' : `${accountView.list.length} 个`; accountBack.style.visibility = accountForm ? 'visible' : 'hidden'; accountPageBody.textContent = ''; accountPageBody.scrollTop = 0; if (accountForm) renderAccountForm(); else renderAccountList(); fitAccountHeight(); }; const renderAccountList = () => { const current = String(accountView.id || ''); countdownTip = null; const cards = document.createElement('div'); style(cards, { display: 'flex', flexDirection: 'column', gap: '8px', flex: 'none' }); if (!accountView.list.length) { const empty = document.createElement('div'); empty.textContent = '还没有记录过账号'; style(empty, { padding: '18px 14px', borderRadius: '10px', border: '1px dashed var(--bw-border-strong)', fontSize: '11px', color: 'var(--bw-dim)', lineHeight: '1.6', textAlign: 'center' }); cards.appendChild(empty); } accountView.list.forEach((acc) => cards.appendChild(accountCard(acc, String(acc.id) === current))); accountPageBody.appendChild(cards); accountPageBody.appendChild(loginNewCard()); }; const accountCard = (acc, isCur) => { const id = String(acc.id); const active = isCur && accountView.logged; const counting = isCur && !accountView.logged && countdownLeft !== 0; const hot = active || counting; const card = document.createElement('div'); style(card, { display: 'flex', alignItems: 'center', gap: '10px', padding: '9px 10px 9px 11px', borderRadius: '10px', border: `1px solid ${hot ? alpha('accent', .42) : 'var(--bw-border)'}`, background: hot ? alpha('accent', .07) : 'var(--bw-surface)' }); card.appendChild(avatarEl(initials(id, acc.name), 34, hot)); const mid = document.createElement('div'); style(mid, { flex: '1 1 auto', minWidth: '0', display: 'flex', flexDirection: 'column', gap: '3px' }); const line1 = document.createElement('div'); style(line1, { display: 'flex', alignItems: 'center', gap: '6px', minWidth: '0' }); const nm = document.createElement('span'); nm.textContent = acc.name || id; style(nm, { fontSize: '12.5px', fontWeight: '600', color: 'var(--bw-text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }); const badge = document.createElement('span'); const alive = !!acc.alive; const okTone = !hot && !isCur && alive; badge.textContent = active ? '当前' : isCur ? '上次使用' : alive ? (accountView.logged ? '可直接切换' : '可直接登录') : '需重新登录'; style(badge, { flex: 'none', fontSize: '9.5px', lineHeight: '15px', height: '15px', padding: '0 6px', borderRadius: '8px', background: hot ? alpha('accent', .18) : okTone ? alpha('ok', .16) : 'var(--bw-surface-hi)', color: hot ? 'var(--bw-accent)' : okTone ? 'var(--bw-ok)' : 'var(--bw-dim)' }); line1.appendChild(nm); line1.appendChild(badge); const meta = document.createElement('div'); const bits = [`工号 ${id}`]; if (acc.phone) bits.push(acc.phone); if (!acc.password) bits.push(acc.phone ? '短信验证码登录' : '未存密码'); meta.textContent = bits.join(' · '); style(meta, { fontSize: '10.5px', color: acc.password || acc.phone ? 'var(--bw-muted)' : 'var(--bw-warn)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', fontVariantNumeric: 'tabular-nums' }); mid.appendChild(line1); mid.appendChild(meta); card.appendChild(mid); const acts = document.createElement('div'); style(acts, { display: 'flex', alignItems: 'center', gap: '4px', flex: 'none' }); if (accountDeleteAsk === id) { const ask = document.createElement('span'); ask.textContent = '删除本机记录?'; style(ask, { fontSize: '10.5px', color: 'var(--bw-danger)' }); acts.appendChild(ask); acts.appendChild(pageBtn('删除', () => { accountDeleteAsk = ''; callbacks.onAccountDelete?.(id); renderAccountPage(); }, { bg: 'var(--bw-danger)', color: '#fff', small: true })); acts.appendChild(pageBtn('取消', () => { accountDeleteAsk = ''; renderAccountPage(); }, { small: true })); } else { if (isCur && !accountView.logged) { countdownTip = document.createElement('span'); countdownTip.textContent = countdownLeft > 0 ? `${countdownLeft}s` : '登录中'; style(countdownTip, { display: countdownLeft === 0 ? 'none' : 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: 'none', minWidth: '27px', height: '16px', padding: '0 5px', borderRadius: '8px', boxSizing: 'border-box', background: alpha('accent', .16), color: 'var(--bw-accent)', fontSize: '10px', fontWeight: '600', lineHeight: '1', fontVariantNumeric: 'tabular-nums' }); countdownTip.title = '倒计时结束会自动登录;期间点别的账号或「登录新账号」可以中断'; acts.appendChild(countdownTip); } if (!active) { const smsOnly = !acc.password; const label = accountView.logged ? (alive ? '切换' : smsOnly ? '手机登录' : '登录切换') : (smsOnly ? (acc.phone ? '手机登录' : '登录') : '一键登录'); const btn = pageBtn(label, () => { closeAccountPage(); callbacks.onAccountSwitch?.(id); }, { bg: 'var(--bw-accent)', small: true }); if (smsOnly) btn.title = '替你把工号和手机号填好并点「获取验证码」,短信验证码要你自己输'; acts.appendChild(btn); } acts.appendChild(iconAction( ``, isCur ? '编辑(密码 / 手机号)' : '编辑', () => { accountDeleteAsk = ''; accountForm = { mode: 'edit', id }; renderAccountPage(); } )); acts.appendChild(iconAction( ``, '删除这个账号的本机记录', () => { accountDeleteAsk = id; renderAccountPage(); }, 'var(--bw-danger)' )); } card.appendChild(acts); return card; }; const loginNewCard = () => { const wrap = document.createElement('div'); style(wrap, { display: 'flex', flexDirection: 'column', gap: '6px', flex: 'none', marginTop: '2px' }); const newBtn = (text, title, onClick) => { const b = document.createElement('button'); b.type = 'button'; b.textContent = text; style(b, { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', width: '100%', height: '34px', flex: 'none', border: '1px dashed var(--bw-border-strong)', borderRadius: '10px', background: 'transparent', color: 'var(--bw-muted)', cursor: 'pointer', fontFamily: FONT_FAMILY, fontSize: '11.5px', transition: 'color .12s ease,border-color .12s ease' }); b.title = title; b.addEventListener('mouseenter', () => { b.style.color = 'var(--bw-accent)'; b.style.borderColor = alpha('accent', .5); }); b.addEventListener('mouseleave', () => { b.style.color = 'var(--bw-muted)'; b.style.borderColor = 'var(--bw-border-strong)'; }); b.addEventListener('click', onClick); return b; }; if (!accountView.logged) { wrap.appendChild(newBtn( '+ 登录新账号', '去登录页用一个新账号登录一次,脚本会自动把工号、密码和姓名记下来', () => { closeAccountPage(); callbacks.onAccountLoginNew?.(); } )); return wrap; } if (accountLoginAsk) { const ask = document.createElement('div'); style(ask, { display: 'flex', alignItems: 'center', gap: '8px', padding: '8px 10px', borderRadius: '10px', border: '1px solid var(--bw-border)', background: 'var(--bw-surface)', flex: 'none' }); const txt = document.createElement('span'); txt.textContent = '会先退出当前账号,再用另一个账号登录'; style(txt, { flex: '1 1 auto', fontSize: '10.5px', color: 'var(--bw-muted)', lineHeight: '1.45' }); ask.appendChild(txt); ask.appendChild(pageBtn('去登录', () => { accountLoginAsk = false; closeAccountPage(); callbacks.onAccountLoginNew?.(); }, { bg: 'var(--bw-accent)', small: true })); ask.appendChild(pageBtn('取消', () => { accountLoginAsk = false; renderAccountPage(); }, { small: true })); wrap.appendChild(ask); return wrap; } wrap.appendChild(newBtn('+ 登录另一个账号', '用另一个账号在登录页登录一次,脚本会自动记录它', () => { accountDeleteAsk = ''; accountLoginAsk = true; renderAccountPage(); })); return wrap; }; const renderAccountForm = () => { const rec = accountView.list.find((a) => String(a.id) === String(accountForm.id)) || {}; const form = document.createElement('div'); style(form, { display: 'flex', flexDirection: 'column', gap: '9px', flex: 'none' }); const grid = document.createElement('div'); style(grid, { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px 10px' }); const idField = pageField('工号', accountForm.id, { disabled: true, name: 'id', title: '账号的唯一标识,由登录信息自动带出,不能改' }); const nameField = pageField('姓名', rec.name || '未获取到', { disabled: true, name: 'name', title: '登录成功后由站点返回,不用也轮不到你填' }); const phoneField = pageField('手机号', rec.phone || '', { placeholder: '选填', name: 'phone', title: '手机号登录时自动记住;没存密码的账号靠它铺场短信登录' }); const pwdField = pageField('密码', rec.password || '', { type: 'password', placeholder: '留空表示不改', name: 'password', toggleable: true, title: '只存在本机(做了简单混淆,不是加密),留空表示不改' }); [idField, nameField, phoneField, pwdField].forEach((f) => grid.appendChild(f)); form.appendChild(grid); const tip = document.createElement('div'); tip.textContent = '密码只保存在本机,不会上传;登录时只填进站点自己的登录框'; tip.title = '密码做了一层简单混淆(不是加密)后存在本机 localStorage,脚本不会把它发到任何别的地方。换电脑或清理浏览器数据后,要重新登录一次。'; style(tip, { fontSize: '10px', color: 'var(--bw-dim)', lineHeight: '1.5', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }); form.appendChild(tip); accountPageBody.appendChild(form); const bar = document.createElement('div'); style(bar, { display: 'flex', gap: '8px', marginTop: '2px', flex: 'none' }); bar.appendChild(pageBtn('保存', () => { callbacks.onAccountSave?.({ id: accountForm.id, password: readField(pwdField), phone: readField(phoneField), }); accountForm = null; renderAccountPage(); }, { bg: 'var(--bw-accent)', flex: '1 1 auto' })); bar.appendChild(pageBtn('取消', () => { accountForm = null; renderAccountPage(); })); accountPageBody.appendChild(bar); setTimeout(() => { const first = accountPageBody.querySelector('input:not([disabled])'); if (first) first.focus(); }, 0); }; const renderTabs = () => { if (!tabLeft) return; tabLeft.innerHTML = ''; tabs.forEach(t => { const active = t.key === activeTab; const btn = document.createElement('button'); btn.className = 'bw-tab'; style(btn, { position: 'relative', display: 'flex', alignItems: 'center', gap: '8px', height: '40px', padding: '0 1px', marginRight: '26px', background: 'none', border: 'none', borderBottom: `2px solid ${active ? 'var(--bw-accent)' : 'transparent'}`, color: active ? 'var(--bw-text)' : 'var(--bw-muted)', fontWeight: active ? '600' : '400', cursor: active ? 'default' : 'pointer', fontSize: '12.5px', fontFamily: 'inherit' }); const label = document.createElement('span'); label.textContent = t.label; btn.appendChild(label); const c = tabCounts[t.key]; if (isRefreshing(t.key)) { const badge = document.createElement('span'); badge.textContent = '刷新中'; badge.title = '正在从平台取这一分类的课程数据'; style(badge, { fontSize: '10.5px', lineHeight: '17px', height: '17px', padding: '0 7px', borderRadius: '9px', background: alpha('accent', .12), color: 'var(--bw-accent)', fontWeight: '400' }); btn.appendChild(badge); } else if (c && c.total) { const pending = Math.max(0, Number(c.pending) || 0); const badge = document.createElement('span'); badge.textContent = `${pending}/${c.total}`; badge.title = pending > 0 ? `${pending} 门未完成,共 ${c.total} 门` : `${c.total} 门全部完成`; style(badge, { fontSize: '10.5px', lineHeight: '17px', height: '17px', padding: '0 7px', borderRadius: '9px', fontVariantNumeric: 'tabular-nums', background: alpha(pending > 0 ? 'warn' : 'ok', .12), color: pending > 0 ? 'var(--bw-warn)' : 'var(--bw-ok)' }); btn.appendChild(badge); } btn.addEventListener('mousedown', (e) => e.preventDefault()); btn.addEventListener('click', () => { if (!interactive || activeTab === t.key) return; activeTab = t.key; doneOpen = false; renderTabs(); callbacks.onTab?.(t.key); }); tabLeft.appendChild(btn); }); }; const toggleLog = (next) => { logOpen = typeof next === 'boolean' ? next : !logOpen; logBtn.style.color = logOpen ? 'var(--bw-accent)' : ''; syncLayout(); if (logOpen) logDrawerBody.scrollTop = logDrawerBody.scrollHeight; }; const buildPanel = (name, cb, version) => { if (document.getElementById('bw-learn-tool-panel')) return; injectStyle(); callbacks = cb || {}; scriptName = name || scriptName; scriptVersion = version || scriptVersion; panel = document.createElement('div'); panel.id = 'bw-learn-tool-panel'; style(panel, { position: 'fixed', bottom: '20px', right: '20px', width: PANEL_WIDTH, maxWidth: 'calc(100vw - 24px)', maxHeight: 'calc(100vh - 40px)', border: '1px solid var(--bw-border-strong)', borderRadius: '14px', zIndex: '9999', fontFamily: FONT_FAMILY, fontSize: `${FONT_SIZE}px`, color: 'var(--bw-text)', display: 'flex', flexDirection: 'column', overflow: 'hidden', boxSizing: 'border-box' }); titleBar = document.createElement('div'); style(titleBar, { display: 'flex', alignItems: 'center', gap: '9px', height: '40px', padding: '0 10px 0 12px', flex: 'none', borderBottom: '1px solid var(--bw-border)', cursor: 'move', userSelect: 'none' }); titleMark = document.createElement('span'); style(titleMark, { width: '3px', height: '14px', borderRadius: '2px', flex: 'none', background: 'linear-gradient(180deg,var(--bw-accent),rgba(var(--bw-accent-rgb),.45))' }); titleBar.appendChild(titleMark); titleText = document.createElement('span'); titleText.textContent = scriptName || '宝武学习助手'; style(titleText, { fontSize: '12.5px', fontWeight: '600', letterSpacing: '.2px', whiteSpace: 'nowrap' }); titleBar.appendChild(titleText); accountChip = document.createElement('button'); accountChip.type = 'button'; accountChip.className = 'bw-chip-btn'; style(accountChip, { display: 'inline-flex', alignItems: 'center', gap: '6px', height: '22px', maxWidth: '132px', minWidth: '0', padding: '0 7px 0 4px', borderRadius: '11px', border: '1px solid var(--bw-border)', background: 'var(--bw-surface)', color: 'var(--bw-text)', cursor: 'pointer', fontFamily: FONT_FAMILY, fontSize: '11px', whiteSpace: 'nowrap', overflow: 'hidden', flex: '0 1 auto', fontVariantNumeric: 'tabular-nums', transition: 'border-color .12s ease,background .12s ease' }); accountChip.addEventListener('mouseenter', () => { accountChip.style.borderColor = alpha('accent', .55); accountChip.style.background = alpha('accent', .08); }); accountChip.addEventListener('mouseleave', () => { accountChip.style.borderColor = 'var(--bw-border)'; accountChip.style.background = 'var(--bw-surface)'; }); accountChip.addEventListener('mousedown', (e) => e.preventDefault()); accountChip.addEventListener('click', (e) => { e.stopPropagation(); if (accountPage && accountPage.style.display !== 'none') closeAccountPage(); else openAccountPage(); }); titleBar.appendChild(accountChip); hoursChip = document.createElement('span'); style(hoursChip, { display: 'none', alignItems: 'center', height: '20px', padding: '0 8px', borderRadius: '10px', background: 'var(--bw-surface)', fontSize: '10.5px', color: 'var(--bw-muted)', whiteSpace: 'nowrap', flex: 'none', fontVariantNumeric: 'tabular-nums' }); titleBar.appendChild(hoursChip); statusChip = document.createElement('span'); style(statusChip, { display: 'inline-flex', alignItems: 'center', gap: '5px', height: '20px', padding: '0 8px', borderRadius: '10px', background: 'transparent', color: 'var(--bw-dim)', fontSize: '11px', maxWidth: '150px', overflow: 'hidden' }); titleBar.appendChild(statusChip); statusTone = { label: '', tone: 'dim' }; const iconBtn = (label, title) => { const b = document.createElement('button'); b.type = 'button'; b.className = 'bw-ico'; b.innerHTML = label; b.title = title || ''; b.addEventListener('mousedown', (e) => e.preventDefault()); return b; }; const iconGroup = document.createElement('div'); style(iconGroup, { display: 'flex', alignItems: 'center', gap: '2px', marginLeft: 'auto', flex: 'none' }); envBtn = iconBtn(` `, '浏览器设置(自动播放 / 不休眠)'); envBtn.style.color = 'var(--bw-muted)'; envDot = document.createElement('span'); style(envDot, { position: 'absolute', top: '3px', right: '3px', width: '6px', height: '6px', borderRadius: '50%', background: 'var(--bw-warn)', display: 'none', boxShadow: '0 0 0 2px var(--bw-bg)' }); envDot.className = 'bw-live'; envBtn.appendChild(envDot); envBtn.addEventListener('click', () => callbacks.onEnvGuide?.()); updateBtn = iconBtn(` `, '检查更新'); updateDot = document.createElement('span'); style(updateDot, { position: 'absolute', top: '3px', right: '3px', width: '6px', height: '6px', borderRadius: '50%', background: 'var(--bw-accent)', display: 'none', boxShadow: '0 0 0 2px var(--bw-bg)' }); updateDot.className = 'bw-live'; updateBtn.appendChild(updateDot); updateBtn.addEventListener('click', () => callbacks.onUpdate?.()); themeBtn = iconBtn(` `, '切换配色'); themeBtn.addEventListener('click', () => { const idx = THEME_ORDER.indexOf(themeName); BWGUI.setTheme(THEME_ORDER[(idx + 1) % THEME_ORDER.length]); }); logBtn = iconBtn(` `, '展开/收起日志'); logBtn.addEventListener('click', () => toggleLog()); minBtn = iconBtn(` `, '折叠'); minBtn.addEventListener('click', () => toggle()); iconGroup.appendChild(envBtn); iconGroup.appendChild(updateBtn); iconGroup.appendChild(themeBtn); iconGroup.appendChild(logBtn); iconGroup.appendChild(minBtn); titleBar.appendChild(iconGroup); panel.appendChild(titleBar); accountPage = document.createElement('div'); accountPage.tabIndex = -1; style(accountPage, { position: 'absolute', left: '0', right: '0', top: '40px', bottom: '0', display: 'none', flexDirection: 'column', background: 'var(--bw-bg)', zIndex: '10001', outline: 'none' }); accountPage.addEventListener('keydown', (e) => { if (e.key !== 'Escape') return; if (accountLoginAsk) { accountLoginAsk = false; renderAccountPage(); } else if (accountForm) { accountForm = null; renderAccountPage(); } else if (accountDeleteAsk) { accountDeleteAsk = ''; renderAccountPage(); } else { closeAccountPage(); } }); const pageHead = document.createElement('div'); style(pageHead, { display: 'flex', alignItems: 'center', gap: '6px', height: '38px', padding: '0 8px', flex: 'none', borderBottom: '1px solid var(--bw-border)', background: 'var(--bw-surface-hi)' }); const headBtn = (svg, title, onClick) => { const b = document.createElement('button'); b.type = 'button'; b.innerHTML = svg; b.title = title; style(b, { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: '24px', height: '24px', padding: '0', flex: 'none', border: 'none', borderRadius: '6px', background: 'transparent', color: 'var(--bw-muted)', cursor: 'pointer', transition: 'background .12s ease,color .12s ease' }); b.addEventListener('mouseenter', () => { b.style.background = 'var(--bw-hover)'; b.style.color = 'var(--bw-text)'; }); b.addEventListener('mouseleave', () => { b.style.background = 'transparent'; b.style.color = 'var(--bw-muted)'; }); b.addEventListener('mousedown', (e) => e.preventDefault()); b.addEventListener('click', onClick); return b; }; accountBack = headBtn( ``, '返回账号列表', () => { accountForm = null; accountDeleteAsk = ''; renderAccountPage(); } ); accountPageTitle = document.createElement('div'); style(accountPageTitle, { fontSize: '12.5px', fontWeight: '600', color: 'var(--bw-text)', whiteSpace: 'nowrap' }); accountPageCount = document.createElement('span'); style(accountPageCount, { fontSize: '10.5px', color: 'var(--bw-dim)', padding: '0 6px', lineHeight: '16px', borderRadius: '8px', background: 'var(--bw-bg)', fontVariantNumeric: 'tabular-nums' }); const pageClose = headBtn( ``, '关闭', closeAccountPage ); style(pageClose, { marginLeft: 'auto' }); pageHead.appendChild(accountBack); pageHead.appendChild(accountPageTitle); pageHead.appendChild(accountPageCount); pageHead.appendChild(pageClose); accountPageBody = document.createElement('div'); style(accountPageBody, { flex: '1 1 auto', minHeight: '0', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '8px', padding: '10px 12px 14px', scrollbarWidth: 'thin' }); accountPage.appendChild(pageHead); accountPage.appendChild(accountPageBody); panel.appendChild(accountPage); collapseView = document.createElement('div'); style(collapseView, { display: 'none', alignItems: 'center', gap: '8px', height: '34px', padding: '0 12px 0 9px', cursor: 'pointer' }); collapseView.addEventListener('click', () => toggle()); panel.appendChild(collapseView); overview = document.createElement('div'); style(overview, { display: 'flex', alignItems: 'center', gap: '14px', padding: '9px 12px 10px', flex: 'none', borderBottom: '1px solid var(--bw-border)' }); const ovLeft = document.createElement('div'); style(ovLeft, { flex: 'none', width: '56px' }); ovPercent = document.createElement('div'); style(ovPercent, { fontSize: '22px', fontWeight: '650', lineHeight: '1.05', letterSpacing: '-.6px', fontVariantNumeric: 'tabular-nums' }); const ovLabel = document.createElement('div'); ovLabel.textContent = '总进度'; style(ovLabel, { fontSize: '10px', color: 'var(--bw-dim)', letterSpacing: '.6px', marginTop: '3px' }); ovLeft.appendChild(ovPercent); ovLeft.appendChild(ovLabel); overview.appendChild(ovLeft); const ovRight = document.createElement('div'); style(ovRight, { flex: '1 1 auto', minWidth: '0' }); ovBar = document.createElement('div'); style(ovBar, { height: '6px', borderRadius: '3px', background: 'var(--bw-track)', overflow: 'hidden' }); ovBarFill = document.createElement('div'); style(ovBarFill, { width: '0%', height: '100%', borderRadius: '3px', transition: 'width .45s cubic-bezier(.22,.8,.3,1), background .3s ease' }); ovBar.appendChild(ovBarFill); const ovMeta = document.createElement('div'); style(ovMeta, { display: 'flex', alignItems: 'center', gap: '10px', marginTop: '7px' }); ovDetail = document.createElement('div'); style(ovDetail, { fontSize: '11px', color: 'var(--bw-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', flex: '1 1 auto', minWidth: '0', fontVariantNumeric: 'tabular-nums' }); ovRemain = document.createElement('div'); style(ovRemain, { fontSize: '10.5px', color: 'var(--bw-dim)', whiteSpace: 'nowrap', flex: 'none', padding: '1px 7px', borderRadius: '8px', background: 'var(--bw-surface)' }); ovMeta.appendChild(ovDetail); ovMeta.appendChild(ovRemain); ovRight.appendChild(ovBar); ovRight.appendChild(ovMeta); overview.appendChild(ovRight); panel.appendChild(overview); tabBar = document.createElement('div'); style(tabBar, { display: 'flex', alignItems: 'stretch', gap: '0', padding: '0 12px', flex: 'none', borderBottom: '1px solid var(--bw-border)', background: 'var(--bw-surface-hi)' }); tabLeft = document.createElement('div'); style(tabLeft, { display: 'flex', alignItems: 'stretch', flex: '1 1 auto', minWidth: '0' }); tabBar.appendChild(tabLeft); refreshBtn = document.createElement('button'); refreshBtn.type = 'button'; refreshBtn.innerHTML = ` 刷新`; style(refreshBtn, { display: 'flex', alignItems: 'center', alignSelf: 'center', background: 'transparent', border: 'none', color: 'var(--bw-muted)', fontSize: '11.5px', fontFamily: 'inherit', cursor: 'pointer', padding: '4px 6px', marginRight: '-6px', borderRadius: '6px', flex: 'none' }); refreshBtn.addEventListener('mousedown', (e) => e.preventDefault()); refreshBtn.addEventListener('click', () => { if (interactive && !refreshBtn.disabled) callbacks.onRefresh?.(activeTab); }); tabBar.appendChild(refreshBtn); panel.appendChild(tabBar); body = document.createElement('div'); style(body, { flex: '1 1 auto', minHeight: '0', display: 'block' }); videoCard = document.createElement('div'); videoCard.id = 'bw-video-card'; style(videoCard, { display: 'none', margin: '12px 12px 4px', background: `radial-gradient(circle at 14% 26%, ${alpha('accent', .12)}, transparent 62%), var(--bw-surface)`, border: `1px solid ${alpha('accent', .2)}`, borderRadius: '12px', padding: '14px 14px 13px' }); body.appendChild(videoCard); tableBox = document.createElement('div'); tableBox.id = 'bw-table-container'; style(tableBox, { overflowX: 'hidden', overflowY: 'auto', scrollbarWidth: 'thin', scrollbarColor: 'var(--bw-track) transparent' }); tableBox.addEventListener('click', (e) => { const cell = e.target.closest('[data-act]'); if (!cell || !interactive) return; const act = cell.dataset.act; if (act === '__done') { doneOpen = !doneOpen; if (lastTableArgs) { const { cols, headers, rows, opts } = lastTableArgs; renderRows(cols, headers, rows, opts, true); } return; } callbacks.onAction?.(act, Number(cell.dataset.idx), tableBox.__ctx); }); body.appendChild(tableBox); panel.appendChild(body); logDrawer = document.createElement('div'); style(logDrawer, { display: 'none', borderTop: '1px solid var(--bw-border)', background: 'var(--bw-surface-hi)', flex: 'none' }); const logHead = document.createElement('div'); style(logHead, { display: 'flex', alignItems: 'center', padding: '7px 12px 3px', fontSize: '11px', color: 'var(--bw-dim)' }); logHead.innerHTML = '运行日志 · 保留 7 天'; const exportLog = document.createElement('span'); exportLog.textContent = '导出'; style(exportLog, { marginLeft: 'auto', cursor: 'pointer', color: 'var(--bw-muted)' }); exportLog.title = '把最近 7 天的日志存成 txt,方便排查问题'; exportLog.addEventListener('click', () => { if (!exportLogs()) exportLog.textContent = '无日志'; }); logHead.appendChild(exportLog); const closeLog = document.createElement('span'); closeLog.textContent = '收起'; style(closeLog, { marginLeft: '10px', cursor: 'pointer', color: 'var(--bw-muted)' }); closeLog.addEventListener('click', () => toggleLog(false)); logHead.appendChild(closeLog); logDrawer.appendChild(logHead); logDrawerBody = document.createElement('div'); style(logDrawerBody, { maxHeight: '132px', overflowY: 'auto', padding: '0 12px 9px', fontFamily: MONO_FAMILY, fontSize: '11px', lineHeight: '1.75', color: 'var(--bw-muted)', scrollbarWidth: 'thin' }); logDrawer.appendChild(logDrawerBody); panel.appendChild(logDrawer); renderLogHistory(); footer = document.createElement('div'); style(footer, { display: 'flex', alignItems: 'center', gap: '10px', padding: '9px 12px', borderTop: '1px solid var(--bw-border)', flex: 'none' }); footerInfo = document.createElement('div'); style(footerInfo, { fontSize: '11px', color: 'var(--bw-dim)', flex: '1 1 auto', minWidth: '0', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', cursor: 'pointer' }); footerInfo.title = '点击展开日志'; footerInfo.addEventListener('click', () => toggleLog()); mainBtn = document.createElement('button'); mainBtn.type = 'button'; mainBtn.id = 'bw-main-btn'; mainBtn.className = 'bw-main'; style(mainBtn, { border: 'none', borderRadius: '8px', padding: '7px 18px', fontWeight: '600', fontSize: '12px', cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap', flex: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: '6px' }); mainBtn.addEventListener('mousedown', (e) => e.preventDefault()); mainBtn.addEventListener('click', () => { if (interactive) callbacks.onMain?.(); }); footer.appendChild(footerInfo); footer.appendChild(mainBtn); panel.appendChild(footer); document.body.appendChild(panel); if (typeof globalScope.addEventListener === 'function') globalScope.addEventListener('pagehide', flushLogs); if (typeof document.addEventListener === 'function') { document.addEventListener('visibilitychange', () => { if (document.hidden) flushLogs(); }); } applyTheme(); let drag = null; titleBar.addEventListener('mousedown', (e) => { if (e.target.closest('button')) return; const rect = panel.getBoundingClientRect(); drag = { x: e.clientX, y: e.clientY, left: rect.left, top: rect.top }; e.preventDefault(); }); document.addEventListener('mousemove', (e) => { if (!drag) return; const left = Math.max(4, Math.min(window.innerWidth - panel.offsetWidth - 4, drag.left + e.clientX - drag.x)); const top = Math.max(4, Math.min(window.innerHeight - panel.offsetHeight - 4, drag.top + e.clientY - drag.y)); style(panel, { left: `${left}px`, top: `${top}px`, right: 'auto', bottom: 'auto' }); }); document.addEventListener('mouseup', () => { drag = null; }); renderTabs(); renderOverview(); renderCollapseView(); renderUpdateBtn(); syncLayout(); }; const toggle = () => { collapsed = !collapsed; if (collapsed && accountPage && accountPage.style.display !== 'none') closeAccountPage(); syncLayout(); }; const applyTableHeight = () => { if (!tableBox) return; const extra = (lastOpts?.banner ? BANNER_H : 0) + (sectionInView ? SECTION_H : 0); const maxH = HEAD_H + ROW_H * MAX_ROWS + extra; tableBox.style.height = 'auto'; tableBox.style.minHeight = '0px'; tableBox.style.maxHeight = `${maxH}px`; }; const headHtml = (cols, headers, top) => `
${headers.map(h => `${escapeHtml(h)}`).join('')}
`; const bannerHtml = (text) => `
← 返回 ${escapeHtml(text)}
`; const sectionHtml = (label, open) => `
${escapeHtml(label)} ${open ? '收起' : '展开'}
`; const cellHtml = (c, ri) => { const cell = typeof c === 'object' && c !== null ? c : { text: c }; const color = cell.color ? toneVar(cell.color) : ''; const act = cell.action ? ` data-act="${cell.action}" data-idx="${ri}"` : ''; const cursor = cell.action ? 'cursor:pointer;' : ''; return `${cell.html ?? escapeHtml(cell.text)}`; }; const rowHtml = (cols, cells, meta, ri) => { const head = `display:grid;grid-template-columns:${cols};gap:10px;align-items:center; height:${ROW_H}px;padding:0 12px;box-sizing:border-box;overflow:hidden;font-size:11.5px;`; const accentBar = meta.current ? `background:${alpha('accent', .07)};border-left:2px solid var(--bw-accent);padding-left:10px;` : `border-left:2px solid transparent;`; const dim = meta.done ? 'opacity:.44;' : ''; const cls = meta.clickable ? 'bw-line bw-click' : 'bw-line'; return `
${(cells || []).map(c => cellHtml(c, ri)).join('')}
`; }; const renderRows = (cols, headers, rows, opts, keepScroll) => { if (!tableBox) return; lastTableArgs = { cols, headers, rows, opts }; lastOpts = opts || {}; tableBox.__ctx = opts?.ctx; const isDone = (r) => !!(r && r.row ? r.row.done : r?.done); const pending = (rows || []).filter(r => !isDone(r)); const done = (rows || []).filter(r => isDone(r)); sectionInView = done.length > 0 && pending.length <= MAX_ROWS; const doneLabel = typeof opts?.doneLabel === 'function' ? opts.doneLabel(done.length) : (opts?.doneLabel || `已完成 ${done.length} 门`); const idxOf = (r, i) => (r?.row && typeof r.row.idx === 'number' ? r.row.idx : i); let html = ''; if (opts?.banner) html += bannerHtml(opts.banner); html += headHtml(cols, headers, opts?.banner ? BANNER_H : 0); pending.forEach((r, i) => { html += rowHtml(cols, r.cells || r, r.row || {}, idxOf(r, i)); }); if (done.length > 0) { html += sectionHtml(doneLabel, doneOpen); if (!doneOpen) { html += `
`; done.forEach((r, i) => { html += rowHtml(cols, r.cells || r, { ...(r.row || {}), done: true }, idxOf(r, pending.length + i)); }); html += '
'; } else { done.forEach((r, i) => { html += rowHtml(cols, r.cells || r, { ...(r.row || {}), done: true }, idxOf(r, pending.length + i)); }); } } const scrollTop = keepScroll ? tableBox.scrollTop : 0; tableBox.innerHTML = html; applyTableHeight(); tableBox.scrollTop = scrollTop; }; const progressCell = (percent, done) => { const pct = Math.max(0, Math.min(100, Math.round(Number(percent) || 0))); const fill = done ? 'var(--bw-ok)' : (pct > 0 ? `linear-gradient(90deg,var(--bw-accent),${alpha('accent', .6)})` : 'transparent'); return { html: ` ${pct}% ` }; }; const showPlaceholder = (text) => { if (!tableBox) return; lastTableArgs = null; tableBox.innerHTML = `
${escapeHtml(text)}
`; }; const courseCells = (r, i) => [ { text: String(i + 1), color: 'dim', align: 'right' }, { text: r.name, strong: !!r.current, title: r.name }, progressCell(r.percent, r.done), { text: r.dur || '-', color: 'muted', title: r.durTitle || r.dur || '' }, { html: statusDot(r.stat, r.statColor || 'muted') } ]; const globalScope = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; const BWGUI = { init({ scriptName: name, tabs: tabDefs, theme, callbacks: cb, version } = {}) { if (Array.isArray(tabDefs) && tabDefs.length) tabs = tabDefs; if (theme && THEMES[theme]) themeName = theme; buildPanel(name || '宝武学习助手', cb, version); return this; }, log: addLog, setAccount, setLoginCountdown, openAccountPage, closeAccountPage, getActiveTab: () => activeTab, setStats, setTabCounts, setTheme(name) { if (!THEMES[name]) return themeName; themeName = name; applyTheme(); if (themeBtn) themeBtn.title = `配色:${THEMES[name].label}(点击切换)`; callbacks.onTheme?.(name); return themeName; }, getTheme: () => themeName, setMode(next) { const target = next === 'study' ? 'study' : 'browse'; if (target === mode) return; mode = target; titleText.textContent = target === 'study' ? '自动学习中' : scriptName; doneOpen = false; applyTableHeight(); renderCollapseView(); syncLayout(); }, setInteractive(on) { interactive = !!on; mainBtn.style.opacity = interactive ? '1' : '0.5'; mainBtn.disabled = !interactive; refreshBtn.disabled = !interactive; refreshBtn.style.opacity = interactive ? '1' : '0.35'; refreshBtn.style.cursor = interactive ? 'pointer' : 'not-allowed'; }, setRefreshing(on, tab) { if (tab) { if (on) refreshingTabs.add(tab); else refreshingTabs.delete(tab); } else { refreshingAll = !!on; refreshingTabs.clear(); } if (refreshBtn) { refreshBtn.disabled = !!on; refreshBtn.style.opacity = on ? '0.35' : '1'; refreshBtn.style.color = on ? 'var(--bw-accent)' : ''; const label = refreshBtn.querySelector('span'); if (label) label.textContent = on ? '刷新中…' : '刷新'; } renderTabs(); renderOverview(); renderCollapseView(); }, setUpdateState(next = {}) { updateState = { ...updateState, ...next }; renderUpdateBtn(); }, setEnvWarn, getEnvWarn: () => envWarn.issues.map((i) => i.key), updateStatus(text, toneOrColor) { if (!statusChip) return; const key = TONE_KEY[toneOrColor] ? toneOrColor : 'muted'; statusTone = { label: text || '', tone: key }; statusChip.style.color = `var(--bw-${key})`; statusChip.style.background = key === 'muted' || key === 'dim' ? 'transparent' : alpha(key, .1); statusChip.innerHTML = ` ${escapeHtml(text || '')}`; statusChip.title = text || ''; renderCollapseView(); }, showPlaceholder, showCourseTable(rows, opts = {}) { if (!rows?.length) { showPlaceholder(opts.empty || '暂无课程数据'); return; } const cols = '28px 1fr 116px 80px 74px'; renderRows(cols, ['#', '课程名称', '学习进度', '时长 / 要求', '状态'], rows.map((r, i) => ({ row: { current: r.current, done: r.done, idx: r.idx ?? i }, cells: courseCells(r, i) })), opts); }, showZoneTable(rows, opts = {}) { if (!rows?.length) { showPlaceholder(opts.empty || '暂无专区数据'); return; } const cols = '28px 1fr 52px 112px 74px'; renderRows(cols, ['#', '专区名称', '课程', '完成度', '状态'], rows.map((r, i) => ({ row: { clickable: true, done: !!r.done, idx: r.idx ?? i }, cells: [ { text: String(i + 1), color: 'dim', align: 'right' }, { text: r.name, action: 'zone', color: 'accent', title: `进入「${r.name}」` }, { text: String(r.count ?? '-'), color: 'muted', align: 'right' }, progressCell(r.percent, r.done), { html: statusDot(r.stat, r.statColor || 'muted') } ] })), { doneLabel: (n) => `已完成 ${n} 个专区`, ...opts, ctx: rows }); }, showQueueTable(rows, opts = {}) { if (!rows?.length) { showPlaceholder(opts.empty || '没有待学课程'); return; } const cols = '28px 1fr 116px 80px 74px'; renderRows(cols, ['#', '待学课程', '学习进度', '时长 / 要求', '状态'], rows.map((r, i) => ({ row: { current: r.current, done: r.done, idx: r.idx ?? i }, cells: courseCells(r, i) })), opts); }, showVideoCard({ title, percent, inner, sub, next, nextDur } = {}) { if (!videoCard) return; const pct = Math.max(0, Math.min(100, Number(percent) || 0)); const pctText = Math.round(pct); const CIRC = 2 * Math.PI * 40; const arc = (CIRC * pct) / 100; const tri = ` `; videoCard.innerHTML = `
${pctText}% ${escapeHtml(inner || '')}
${escapeHtml(title || '')}
${escapeHtml(sub || '')}
${tri} 接下来学 ${escapeHtml(next || '这是最后一门,学完自动结束')} ${nextDur ? `${escapeHtml(nextDur)}` : ''}
`; videoVisible = true; syncLayout(); }, hideVideoCard() { videoVisible = false; syncLayout(); }, setActionBar({ main } = {}) { if (!mainBtn) return; if (!main) { actionVisible = false; syncLayout(); return; } mainBtn.textContent = ''; const tone = main.tone || 'primary'; if (tone === 'danger') { mainBtn.textContent = main.text; style(mainBtn, { background: 'var(--bw-danger-solid)', color: 'var(--bw-on-danger)', border: 'none', borderRadius: '8px', padding: '10px 0', boxShadow: `0 3px 14px ${alpha('danger', .34)}, inset 0 1px 0 rgba(255,255,255,.18)` }); } else if (tone === 'muted') { mainBtn.textContent = main.text; style(mainBtn, { background: 'var(--bw-surface)', color: 'var(--bw-muted)', border: '1px solid var(--bw-border)', borderRadius: '8px', padding: mode === 'study' ? '10px 18px' : '7px 18px', boxShadow: 'none' }); } else { mainBtn.textContent = main.text; style(mainBtn, { background: 'var(--bw-accent)', color: 'var(--bw-on-accent)', border: 'none', borderRadius: '8px', padding: '7px 18px', boxShadow: `0 3px 10px ${alpha('accent', .3)}` }); } mainBtn.disabled = !!main.disabled; mainBtn.style.opacity = main.disabled ? '0.45' : '1'; mainBtn.style.cursor = main.disabled ? 'not-allowed' : 'pointer'; actionVisible = true; syncLayout(); } }; const ENV_GUIDE_SITE = '[*.]learn.baowugroup.com'; let envWrap = null; let envFrame = null; let envOpen = false; const envPageOpen = () => !!(envFrame && envOpen); const closeEnvPage = () => { if (!envWrap) return; envOpen = false; envWrap.style.display = 'none'; if (panel) panel.style.height = ''; }; const esc = (text) => String(text == null ? '' : text) .replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); const envGuideHtml = (issues = []) => { const list = Array.isArray(issues) ? issues : []; const status = list.length ? `
有 ${list.length} 处需要你改一下
` : '
现在没检测到问题
'; return ` 浏览器设置 · 宝武学习助手

浏览器设置

这两处设置都在浏览器里,插件没有权限替你改,只能把「点哪里、填什么」写清楚。改一次就好,以后不用再动:第一处让课程自己开始播,第二处让学习页不被浏览器停掉。

${status}

① 允许视频自动播放

这一项管的是「网页能不能自己开始播放」,视频课、音频课都算。

不打开它,课程打开后会停在 0:00 等你点播放。人不在电脑前,它就一直停在那儿。

浏览器页面上写的字是「控制是否自动播放网站上的音频及视频」,说的是同一件事。

edge://settings/content/mediaAutoplay
  1. 复制上面的地址,粘到浏览器最上面的地址栏,按回车。(网页里的链接点不进设置页,只能粘地址)
  2. 找到「控制是否自动播放网站上的音频及视频」,把右边的选项改成「允许」。
  3. 只想给学习网站放行:同一页再往下找「允许」列表,点「添加」,把 ${ENV_GUIDE_SITE} 填进去,保存。
  4. 回到学习页,点一下播放按钮试试。

② 别让浏览器把学习页停掉

浏览器为了省内存,会把长时间没动静的页面「冻」起来。看着页面还在,其实里面全停了,学习进度一点都不动。

这一项插件查不出来(浏览器不告诉网页自己是怎么设置的),所以平时不会主动提醒你;要挂机过夜,先花一分钟做一遍。

edge://settings/system/managePerformance
  1. 复制地址,粘到地址栏,按回车。
  2. 找到「保持这些网站处于活动状态」(有的版本叫「永不休眠」),点「添加」。
  3. 把 ${ENV_GUIDE_SITE} 填进去,保存。
  4. 回到学习页,按一下 F5 刷新。

测法是把这个窗口切到后台 10 秒再切回来,看这页还在不在动。后台一秒才动一次是正常的(浏览器都这么省电,跟上面设没设好无关),真被停掉是一次都不动。不过结果只代表「现在」——想确认设置有没有生效,最实在的是让课播着、人走开 10 分钟,回来看进度涨没涨。

改完回学习页,右上角那颗按钮会从琥珀色变回灰色;还是琥珀色,说明某一项没生效,照上面再做一遍。这颗按钮一直都在,随时可以回来翻这份说明。

`; }; const openEnvPage = (html) => { if (!panel) return false; if (!envWrap) { envWrap = document.createElement('div'); style(envWrap, { position: 'absolute', left: '0', right: '0', top: '40px', bottom: '0', display: 'none', flexDirection: 'column', background: 'var(--bw-bg)', zIndex: '10001' }); const head = document.createElement('div'); style(head, { display: 'flex', alignItems: 'center', gap: '6px', height: '34px', padding: '0 8px', flex: 'none', borderBottom: '1px solid var(--bw-border)', background: 'var(--bw-surface-hi)' }); head.appendChild(pageBtn('返回', () => closeEnvPage(), { small: true })); const title = document.createElement('div'); title.textContent = '浏览器设置'; style(title, { fontSize: '12px', fontWeight: '600', flex: '1 1 auto', paddingLeft: '2px' }); head.appendChild(title); envFrame = document.createElement('iframe'); envFrame.title = '浏览器设置'; style(envFrame, { flex: '1 1 auto', width: '100%', border: '0', background: 'transparent' }); envWrap.appendChild(head); envWrap.appendChild(envFrame); panel.appendChild(envWrap); } envFrame.srcdoc = html; envWrap.style.display = 'flex'; envOpen = true; const tall = PAGE_TALL(); if (tall > (panel.getBoundingClientRect().height || 0)) panel.style.height = `${tall}px`; return true; }; BWGUI.envGuideHtml = envGuideHtml; BWGUI.openEnvPage = openEnvPage; BWGUI.closeEnvPage = closeEnvPage; BWGUI.isEnvPageOpen = envPageOpen; globalScope.BWGUI = BWGUI; })(); (function () { 'use strict'; if (window.top !== window.self) return; const BWAPI = unsafeWindow.BWAPI; const BWGUI = unsafeWindow.BWGUI; const BWUTL = unsafeWindow.BWUTL; const BWACC = unsafeWindow.BWACC; const BWOCR = unsafeWindow.BWOCR; const log = (msg) => BWGUI.log(`[${new Date().toLocaleTimeString()}] ${msg}`); const DEFAULT_DATA = { url: { currentUrl: '' }, token: '', state: { isLogin: false, isAutoLearning: false, learningType: null, isVideoPage: false, isVideoMuted: false, isVideoPlaying: false }, publicCourses: [], zone: [], toLearnList: [], pendingListRefresh: false, resume: { url: '', pos: 0, title: '', at: 0, armed: false, armedAt: 0, seekAt: 0, settleAt: 0 }, today: { date: '', done: 0, minutes: 0 }, theme: 'dark' }; const RESUME_MIRROR = (() => { let lastText = ''; let lastAt = 0; return { read: (k) => BWACC.rawRead(k), write: (k, text) => { const now = Date.now(); let onlyPos = false; if (lastText) { try { const a = JSON.parse(lastText); const b = JSON.parse(text); onlyPos = a.url === b.url && a.title === b.title && a.armed === b.armed && a.seekAt === b.seekAt && a.settleAt === b.settleAt; } catch { onlyPos = false; } } if (onlyPos && now - lastAt < 15000) return; lastText = text; lastAt = now; BWACC.rawWrite(k, text); } }; })(); const AppData = BWUTL.createDataStore('bw_learn_app_data', DEFAULT_DATA, { mirror: ['resume'], mirrorRead: RESUME_MIRROR.read, mirrorWrite: RESUME_MIRROR.write }); const TABS = [ { key: 'public', label: '公开课' }, { key: 'zone', label: '专区课' } ]; const TAB_NAME = { public: '公开课', zone: '专区课' }; const loading = { public: false, zone: false }; let zoneView = null; let autoLoadStarted = false; const fmtInt = (v) => (v === undefined || v === null || v === '' ? '-' : Math.round(parseFloat(v))); const readableError = (error) => { const raw = String(error?.message || error || '').trim(); if (/failed to fetch|networkerror|load failed|network request failed/i.test(raw)) return '网络连接失败'; if (/timeout|timed out|aborted/i.test(raw)) return '网络超时'; if (/\bHTTP (401|403)\b/i.test(raw)) return '登录已失效,请重新登录'; if (/\bHTTP 5\d\d\b/i.test(raw)) return '平台服务器暂时不可用'; if (/\bHTTP 4\d\d\b/i.test(raw)) return '请求被平台拒绝'; return raw ? `未知问题(${raw})` : '未知问题'; }; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const decodeParamPart = (raw) => { try { const norm = String(raw).replace(/-/g, '+').replace(/_/g, '/'); const bin = atob(norm + '==='.slice((norm.length + 3) % 4)); return new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0))); } catch { return String(raw); } }; const parseHashParams = (hash) => { const out = {}; const q = String(hash || '').indexOf('?'); if (q === -1) return out; String(hash).substring(q + 1).split('&').forEach((pair) => { const eq = pair.indexOf('='); if (eq === -1) return; const keyMatch = /^~q\d+\.(.+)$/.exec(pair.slice(0, eq)); if (!keyMatch) { try { out[decodeURIComponent(pair.slice(0, eq))] = decodeURIComponent(pair.slice(eq + 1)); } catch { out[pair.slice(0, eq)] = pair.slice(eq + 1); } return; } const valueMatch = /^~q\d+\.(.*)$/.exec(pair.slice(eq + 1)); out[decodeParamPart(keyMatch[1])] = valueMatch ? decodeParamPart(valueMatch[1]) : pair.slice(eq + 1); }); return out; }; const getCurrentCourseGuid = () => parseHashParams(window.location.hash).guid || null; const isCourseFinished = (score) => { if (!score) return false; const req = Number(score.requiredDuration); const comp = Number(score.completedDuration); if (!(req > 0 && comp > req)) return false; const passScore = Number(score.passScore); if (!(passScore > 0)) return true; const learnScore = Number(score.learnScore); return Number.isFinite(learnScore) && learnScore >= passScore; }; const getUrlChange = (oldUrl) => { const newUrl = location.href; return newUrl !== oldUrl ? { currentUrl: newUrl } : null; }; const getTokenChange = (oldToken) => { const token = BWAPI.getToken(); return token !== oldToken ? token : null; }; const getFrameDocument = () => { try { return document.querySelector('#previewFrame')?.contentDocument || null; } catch { return null; } }; const getMediaElement = () => { const local = document.querySelector('#xg-video video'); if (local) return local; const doc = getFrameDocument(); return doc ? (doc.querySelector('video') || doc.querySelector('audio')) : null; }; const isCourseRoute = () => location.href.includes('courseStudy?'); const isStudyView = (state) => state.isVideoPage || isCourseRoute(); const getStateChanges = (oldState, media) => { const changes = {}; const isLogin = !location.href.includes('auth/login'); if (oldState.isLogin !== isLogin) { changes.isLogin = isLogin; log(`🔐 登录状态:${isLogin ? '已登录' : '未登录'}`); } const isVideoPage = !!media; const isVideoMuted = media?.muted ?? false; const isVideoPlaying = media ? !media.paused : false; if (oldState.isVideoPage !== isVideoPage || oldState.isVideoMuted !== isVideoMuted || oldState.isVideoPlaying !== isVideoPlaying) { Object.assign(changes, { isVideoPage, isVideoMuted, isVideoPlaying }); } if (!isCourseRoute() && !isVideoPage && oldState.isAutoLearning) { changes.isAutoLearning = false; log('⏹️ 自动学习已停止'); } if ((isVideoPage || isCourseRoute()) && oldState.isAutoLearning) { const courseGuid = getCurrentCourseGuid(); const toLearnList = AppData.get('toLearnList') || []; const matched = toLearnList.find(item => String(item.courseGuid) === String(courseGuid)); const newType = matched ? (matched.courseType === '公开课' ? 'public' : matched.courseType === '专区课' ? 'zone' : null) : null; if (oldState.learningType !== newType) { changes.learningType = newType; log(`📚 当前学习:${newType ? TAB_NAME[newType] : '未识别'} ${matched ? `· ${matched.courseName}` : ''}`.trim()); } } else if (oldState.learningType !== null) { changes.learningType = null; } return Object.keys(changes).length > 0 ? changes : null; }; const updateAppDataState = (media) => { const oldUrl = AppData.get('url').currentUrl; const oldToken = AppData.get('token'); const oldState = AppData.get('state'); const updates = {}; const urlChange = getUrlChange(oldUrl); if (urlChange) updates.url = urlChange; const token = getTokenChange(oldToken); if (token !== null) updates.token = token; const stateChanges = getStateChanges(oldState, media); if (stateChanges) { if (stateChanges.isAutoLearning === false) updates.toLearnList = []; updates.state = stateChanges; } const currentIsVideoPage = stateChanges?.isVideoPage ?? oldState.isVideoPage; if (!isCourseRoute() && !currentIsVideoPage && (AppData.get('toLearnList') || []).length > 0) { updates.toLearnList = []; } if (Object.keys(updates).length > 0) AppData.save(updates); return { ...oldState, ...(stateChanges || {}) }; }; const updateLearningStatusDisplay = (state) => { let text = '待学习'; let tone = 'muted'; if (!state.isLogin) { text = '未登录'; tone = 'warn'; } else if (state.isAutoLearning) { text = state.learningType === 'zone' ? '学习中·专区课' : state.learningType === 'public' ? '学习中·公开课' : '学习中'; tone = state.isVideoPage && state.isVideoPlaying ? 'accent' : 'warn'; } else if (state.isVideoPage && state.isVideoPlaying) { text = '学习中·单门课'; tone = 'accent'; } BWGUI.updateStatus(text, tone); }; const getPublicCoursesList = async (full = false) => { try { const allCourses = await BWAPI.fetchPublicCourses(''); if (!allCourses) { log('❌ 公开课没加载出来:没收到数据(网络超时,或登录已失效),请点右上角刷新重试'); return false; } const cachedScores = full ? null : finishedScoreCache(); const enriched = await BWAPI.enrichCoursesWithScores(allCourses, { cachedScores }); auditScoreShape(enriched); AppData.save({ publicCourses: enriched }); return true; } catch (error) { log(`❌ 公开课没加载出来:${readableError(error)}`); return false; } }; const getZoneCoursesList = async (full = false) => { try { const zoneList = await BWAPI.fetchZoneList(''); if (!zoneList) { log('❌ 专区课没加载出来:没收到数据(网络超时,或登录已失效),请点右上角刷新重试'); return false; } const zoneMap = new Map(); zoneList.forEach(zone => { if (!zoneMap.has(zone.olClassNo)) { zoneMap.set(zone.olClassNo, { ...zone, zoneCourses: [] }); } }); const uniqueZones = Array.from(zoneMap.values()); const cachedScores = full ? null : finishedScoreCache(); let reusedTotal = 0; const loaded = []; await Promise.allSettled( uniqueZones.map(zone => BWAPI.fetchZoneCoursesDetail(zone.centerCode, zone.olClassNo, zone.olClassType) .then(courses => { if (!courses) throw new Error('没有收到数据'); return BWAPI.enrichCoursesWithScores(courses, { cachedScores }); }) .then(enriched => { zone.zoneCourses = enriched; reusedTotal += Number(enriched.reusedCount) || 0; loaded.push(...enriched); }) .catch(err => { log(`⚠️ 专区「${zone.olClassName || zone.olClassNo}」的课程没加载出来:${readableError(err)}`); zone.zoneCourses = []; }) ) ); AppData.save({ zone: uniqueZones }); auditScoreShape(loaded); if (reusedTotal > 0) log(`📦 沿用本地记录 ${reusedTotal} 门已完成的课,少查 ${reusedTotal} 次`); return true; } catch (error) { log(`❌ 专区课没加载出来:${readableError(error)}`); return false; } }; const percentOf = (score) => { const req = Number(score?.requiredDuration); const comp = Number(score?.completedDuration); if (!(req > 0)) return 0; return Math.max(0, Math.min(100, (comp / req) * 100)); }; const buildQueue = (tab, zoneIndex = null) => { const queue = []; if (tab === 'public') { (AppData.get('publicCourses') || []).forEach(c => { if (!isCourseFinished(c.score)) queue.push({ ...c, courseType: '公开课' }); }); return queue; } const zones = AppData.get('zone') || []; const targets = zoneIndex != null && zones[zoneIndex] ? [zones[zoneIndex]] : zones; targets.forEach(zone => { (zone.zoneCourses || []).forEach(c => { if (!isCourseFinished(c.score)) queue.push({ ...c, courseType: '专区课' }); }); }); return queue; }; const activeScope = () => (BWGUI.getActiveTab() === 'zone' ? zoneView : null); const scopeCourses = (tab) => { if (tab === 'public') return AppData.get('publicCourses') || []; const zones = AppData.get('zone') || []; const targets = tab === 'zone' && zoneView != null && zones[zoneView] ? [zones[zoneView]] : zones; return targets.reduce((acc, z) => acc.concat(z.zoneCourses || []), []); }; let studyHours = null; const tabStats = (tab) => { const list = scopeCourses(tab); let done = 0; let remainMin = 0; list.forEach(c => { if (isCourseFinished(c.score)) { done += 1; return; } const req = Number(c.score?.requiredDuration) || 0; const comp = Number(c.score?.completedDuration) || 0; remainMin += Math.max(0, req - comp); }); return { total: list.length, done, pending: list.length - done, remainMin, hours: studyHours }; }; const STUDY_HOURS_INTERVAL = 5 * 60 * 1000; let refreshingHours = false; const refreshStudyHours = async () => { if (refreshingHours) return; refreshingHours = true; try { const next = await BWAPI.fetchStudyHours(); if (!next) return; const keys = ['total', 'public', 'zone', 'training']; const changed = !studyHours || keys.some((k) => Number(studyHours[k]) !== Number(next[k])); studyHours = next; if (changed) BWGUI.setStats(tabStats(BWGUI.getActiveTab())); } catch (error) { log(`⚠️ 总学时没取到:${readableError(error)}`); } finally { refreshingHours = false; } }; const hasData = (tab) => ((tab === 'public' ? AppData.get('publicCourses') : AppData.get('zone')) || []).length > 0; const finishedScoreCache = () => { const cache = new Map(); const put = (c) => { if (!c?.centerCode || !c?.courseNo || !c?.olClassNo) return; if (!isCourseFinished(c.score)) return; cache.set(`${c.centerCode}|${c.courseNo}|${c.olClassNo}`, c.score); }; (AppData.get('publicCourses') || []).forEach(put); (AppData.get('zone') || []).forEach(z => (z.zoneCourses || []).forEach(put)); return cache; }; let scoreShapeWarned = false; const auditScoreShape = (courses) => { const list = Array.isArray(courses) ? courses : []; const usable = list.filter(c => c && c.centerCode && c.courseNo && c.olClassNo); if (usable.length < 5 || scoreShapeWarned) return; const empty = usable.filter(c => !(Number(c.score?.requiredDuration) > 0)).length; if (empty / usable.length < 0.5) return; scoreShapeWarned = true; log(`⚠️ 有 ${empty}/${usable.length} 门课读不到学习进度,可能是平台改版了。如果一直这样,请到脚本页反馈`); }; const todayKey = () => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; }; const readToday = () => { const t = AppData.get('today') || {}; if (t.date !== todayKey()) return { date: todayKey(), done: 0, minutes: 0 }; return { date: t.date, done: Number(t.done) || 0, minutes: Number(t.minutes) || 0 }; }; const bumpToday = (minutes) => { const t = readToday(); const add = Math.max(0, Number(minutes) || 0); AppData.save({ today: { date: t.date, done: t.done + 1, minutes: t.minutes + add } }); }; const logTodaySummary = () => { const t = readToday(); if (t.done <= 0) return; log(`📅 今天已学完 ${t.done} 门,累计 ${Math.round(t.minutes)} 分钟`); }; const patchCourseScore = (courseGuid, score) => { if (!score || !courseGuid) return; const isMatch = (c) => String(c.courseGuid) === String(courseGuid); const pub = AppData.get('publicCourses') || []; if (pub.some(isMatch)) { AppData.save({ publicCourses: pub.map((c) => (isMatch(c) ? { ...c, score } : c)) }); } const zones = AppData.get('zone') || []; if (zones.some((z) => (z.zoneCourses || []).some(isMatch))) { AppData.save({ zone: zones.map((z) => { const courses = z.zoneCourses || []; if (!courses.some(isMatch)) return z; return { ...z, zoneCourses: courses.map((c) => (isMatch(c) ? { ...c, score } : c)) }; }) }); } }; const markListRefresh = () => AppData.save({ pendingListRefresh: true }); const statOf = (course, currentGuid) => { if (isCourseFinished(course.score)) return { text: '已完成', color: 'ok' }; if (currentGuid && String(course.courseGuid) === String(currentGuid)) return { text: '学习中', color: 'accent' }; return percentOf(course.score) > 0 ? { text: '未完成', color: 'warn' } : { text: '待学', color: 'muted' }; }; const sortDoneLast = (rows) => rows.filter(r => !r.done).concat(rows.filter(r => r.done)); const courseRows = (courses, currentGuid) => sortDoneLast((courses || []).map(c => { const stat = statOf(c, currentGuid); const req = Number(c.score?.requiredDuration); const comp = Number(c.score?.completedDuration); return { name: c.courseName, percent: percentOf(c.score), dur: `${fmtInt(comp)} / ${fmtInt(req)}`, durTitle: `已学 ${fmtInt(comp)} 分钟 / 要求 ${fmtInt(req)} 分钟`, stat: stat.text, statColor: stat.color, done: isCourseFinished(c.score), current: !!currentGuid && String(c.courseGuid) === String(currentGuid) }; })); const zoneRows = (zones) => sortDoneLast((zones || []).map((zone, idx) => { const courses = zone.zoneCourses || []; const pending = courses.filter(c => !isCourseFinished(c.score)).length; return { idx, name: zone.olClassName || zone.olClassNo, count: courses.length, pending, percent: courses.length > 0 ? ((courses.length - pending) / courses.length) * 100 : 0, done: courses.length > 0 && pending === 0, stat: courses.length === 0 ? '无课程' : (pending === 0 ? '已完成' : (pending < courses.length ? '未完成' : '未开始')), statColor: courses.length === 0 ? 'muted' : (pending === 0 ? 'ok' : (pending < courses.length ? 'warn' : 'accent')) }; })); let lastTableSignature = ''; const updateTabCounts = () => { const brief = (list) => (list.length === 0 ? null : { pending: list.filter(c => !isCourseFinished(c.score)).length, total: list.length }); const zones = AppData.get('zone') || []; const allZone = zones.reduce((acc, z) => acc.concat(z.zoneCourses || []), []); BWGUI.setTabCounts({ public: brief(AppData.get('publicCourses') || []), zone: brief(allZone) }); }; const renderTable = (opts = {}) => { const state = AppData.get('state'); BWGUI.setStats(tabStats(BWGUI.getActiveTab())); updateTabCounts(); if (!state.isLogin) { if (lastTableSignature === 'guest' && !opts.force) return; lastTableSignature = 'guest'; BWGUI.showPlaceholder('请先登录宝武学习平台'); return; } const currentGuid = getCurrentCourseGuid(); let signature, draw; if (isStudyView(state)) { const queue = AppData.get('toLearnList') || []; signature = `queue|${currentGuid}|${queue.map(c => `${c.courseGuid}:${c.score?.completedDuration}:${isCourseFinished(c.score)}`).join(',')}`; const rows = sortDoneLast(queue.map(c => { const stat = statOf(c, currentGuid); const req = Number(c.score?.requiredDuration); const comp = Number(c.score?.completedDuration); return { name: c.courseName, percent: percentOf(c.score), dur: `${fmtInt(comp)} / ${fmtInt(req)}`, durTitle: `已学 ${fmtInt(comp)} 分钟 / 要求 ${fmtInt(req)} 分钟`, stat: stat.text, statColor: stat.color, done: isCourseFinished(c.score), current: !!currentGuid && String(c.courseGuid) === String(currentGuid) }; })); draw = () => BWGUI.showQueueTable(rows, { empty: '正在读取课程信息…' }); } else if (BWGUI.getActiveTab() === 'zone') { const zones = AppData.get('zone') || []; const zone = zoneView != null ? zones[zoneView] : null; if (zone) { const courses = zone.zoneCourses || []; signature = `zoneCourse|${zoneView}|${currentGuid}|${courses.map(c => `${c.courseGuid}:${c.score?.completedDuration}:${isCourseFinished(c.score)}`).join(',')}`; const rows = courseRows(courses, currentGuid); draw = () => BWGUI.showCourseTable(rows, { banner: `当前专区:${zone.olClassName || zone.olClassNo} · ${courses.length} 门`, empty: '该专区暂无课程' }); } else { signature = `zone|${loading.zone}|${zones.map(z => `${z.olClassNo}:${(z.zoneCourses || []).length}`).join(',')}`; draw = () => BWGUI.showZoneTable(zoneRows(zones), { empty: loading.zone ? '正在加载专区课程…' : '还没有专区数据,点右上角「刷新」' }); } } else { const courses = AppData.get('publicCourses') || []; signature = `public|${loading.public}|${currentGuid}|${courses.map(c => `${c.courseGuid}:${c.score?.completedDuration}:${isCourseFinished(c.score)}`).join(',')}`; const rows = courseRows(courses, currentGuid); draw = () => BWGUI.showCourseTable(rows, { empty: loading.public ? '正在加载公开课…' : '还没有数据,点右上角「刷新」' }); } if (signature === lastTableSignature && !opts.force) return; lastTableSignature = signature; draw(); }; const localWatch = { guid: '', seconds: 0, baseline: 0, lastT: null }; const sampleLocalWatch = (media, guid) => { if (!media || String(guid) !== localWatch.guid) return; const t = Number(media.currentTime); if (!Number.isFinite(t)) return; if (localWatch.lastT != null && !media.paused) { const delta = t - localWatch.lastT; if (delta > 0 && delta <= 5) localWatch.seconds += delta; } localWatch.lastT = t; }; const localWatchedComp = (media, guid, serverComp) => { if (!media || String(guid) !== localWatch.guid) { localWatch.guid = String(guid); localWatch.seconds = 0; localWatch.baseline = serverComp; localWatch.lastT = media ? Number(media.currentTime) : null; return serverComp; } sampleLocalWatch(media, guid); return localWatch.baseline + localWatch.seconds / 60; }; let lastVideoSignature = ''; const updateVideoCard = (state) => { if (!isStudyView(state)) { if (lastVideoSignature !== '') { lastVideoSignature = ''; BWGUI.hideVideoCard(); } return; } const queue = AppData.get('toLearnList') || []; const guid = getCurrentCourseGuid(); const index = queue.findIndex(c => String(c.courseGuid) === String(guid)); const course = index >= 0 ? queue[index] : null; if (!course) { if (lastVideoSignature !== 'pending') { lastVideoSignature = 'pending'; BWGUI.showVideoCard({ title: '正在读取课程信息…', percent: 0, inner: '—', sub: '请稍候' }); } return; } const req = Number(course.score?.requiredDuration); const serverComp = Number(course.score?.completedDuration) || 0; const reached = req > 0 && serverComp >= req; const media = getMediaElement(); const vDur = Number(media?.duration) || 0; const vPos = Number(media?.currentTime) || 0; const localComp = req > 0 ? localWatchedComp(media, course.courseGuid, serverComp) : serverComp; const comp = req > 0 ? Math.max(serverComp, Math.min(localComp, req)) : serverComp; const reqPercent = req > 0 ? (comp / req) * 100 : 0; const mediaPct = vDur > 1 ? (vPos / vDur) * 100 : null; const percent = reached ? 100 : Math.min(99, Math.max(mediaPct || 0, reqPercent)); const remain = Math.max(0, req - comp); const nextCourse = queue[index + 1]; const nextReq = Number(nextCourse?.score?.requiredDuration) || 0; const signature = `${course.courseGuid}|${queue.length}|${index}|${Math.round(percent)}|${Math.round(serverComp * 10)}|${nextCourse?.courseGuid || ''}|${outlineBrief(course)}|${heartHint()}`; if (signature === lastVideoSignature) return; lastVideoSignature = signature; const remainText = reached ? '已学够时长,正在确认成绩' : (comp - serverComp >= 0.5 && comp >= req - 0.05) ? `本集已播完,正在等系统记录${heartHint()}` : (remain >= 1 ? `剩余约 ${fmtInt(remain)} 分钟` : '剩余不到 1 分钟'); const brief = outlineBrief(course); const subParts = [`第 ${index + 1} / ${queue.length} 门`]; if (brief) subParts.push(brief); subParts.push(remainText); BWGUI.showVideoCard({ title: course.courseName, percent, inner: `${Math.floor(comp)}/${fmtInt(req)} 分`, sub: subParts.join(' · '), next: nextCourse ? nextCourse.courseName : '', nextDur: nextReq > 0 ? `${fmtInt(nextReq)} 分钟` : '' }); }; const updateActionBar = (state, stats) => { if (isStudyView(state)) { if (state.isAutoLearning) { BWGUI.setActionBar({ main: { text: '停止并返回个人中心', tone: 'danger' } }); } else { BWGUI.setActionBar({ main: { text: '返回个人中心', tone: 'muted' } }); } return; } if (!state.isLogin) { BWGUI.setActionBar({ main: { text: '请先登录', tone: 'muted', disabled: true } }); return; } if (loading.public || loading.zone) { BWGUI.setActionBar({ main: { text: '加载中…', tone: 'muted', disabled: true } }); return; } if (stats.total === 0) { BWGUI.setActionBar({ main: { text: '重新加载', tone: 'primary' } }); return; } if (stats.pending === 0) { BWGUI.setActionBar({ main: { text: '已全部完成', tone: 'muted', disabled: true } }); return; } const scoped = BWGUI.getActiveTab() === 'zone' && zoneView != null; BWGUI.setActionBar({ main: { text: `${scoped ? '学习本专区' : '学习'} ${stats.pending} 门`, tone: 'primary' } }); }; let lastUiSignature = ''; const syncUi = (state) => { const tab = BWGUI.getActiveTab(); const study = isStudyView(state); const stats = study ? { total: 0, done: 0, pending: 0 } : tabStats(tab); const signature = [ state.isLogin, study, state.isAutoLearning, tab, zoneView, loading.public, loading.zone, stats.total, stats.pending ].join('|'); if (signature === lastUiSignature) return; lastUiSignature = signature; BWGUI.setMode(study ? 'study' : 'browse'); BWGUI.setInteractive(state.isLogin); updateActionBar(state, stats); }; const loadCourses = async (tab, opts = {}) => { if (loading[tab]) return false; loading[tab] = true; BWGUI.setRefreshing(true, tab); lastTableSignature = ''; renderTable({ force: true }); syncUi(AppData.get('state')); let ok = false; try { ok = tab === 'public' ? await getPublicCoursesList(!!opts.full) : await getZoneCoursesList(!!opts.full); } catch (error) { log(`❌ ${TAB_NAME[tab]}加载出错:${readableError(error)}`); ok = false; } finally { loading[tab] = false; lastTableSignature = ''; renderTable({ force: true }); syncUi(AppData.get('state')); BWGUI.setRefreshing(false, tab); } if (ok) { const s = tabStats(tab); log(`✅ ${TAB_NAME[tab]}已加载 ${s.total} 门,未完成 ${s.pending} 门`); if (!opts.silentHours) refreshStudyHours(); } return ok; }; const COURSE_REFRESH_INTERVAL = 30 * 60 * 1000; let refreshingLists = false; const refreshAllCourseLists = async (reason) => { if (refreshingLists) return; const state = AppData.get('state'); if (!state.isLogin || isStudyView(state)) return; refreshingLists = true; try { let loaded = 0; for (const tab of TABS.map((t) => t.key)) { if (await loadCourses(tab, { silentHours: true })) loaded += 1; } await refreshStudyHours(); if (loaded > 0) log(`🔄 课程信息已更新(${reason})`); } finally { refreshingLists = false; } }; const maybeRefreshAfterLearning = (state) => { if (!AppData.get('pendingListRefresh')) return; if (!state.isLogin || isStudyView(state)) return; AppData.save({ pendingListRefresh: false }); log('🔄 回到课程列表,正在更新课程信息…'); refreshAllCourseLists('刚结束学习'); }; const handleTabChange = async (key) => { zoneView = null; lastTableSignature = ''; renderTable({ force: true }); syncUi(AppData.get('state')); if (!hasData(key) && !loading[key]) await loadCourses(key); }; const handleRefresh = async (tab) => { log(`⏳ 正在刷新${TAB_NAME[tab]}(重新查询全部成绩)…`); await loadCourses(tab, { full: true }); }; const startLearning = async () => { const tab = BWGUI.getActiveTab(); const state = AppData.get('state'); if (!state.isLogin) { log('❌ 未登录,无法开始学习'); return; } if (!hasData(tab)) { log(`⏳ 还没有${TAB_NAME[tab]}数据,正在加载…`); if (!(await loadCourses(tab))) { log('❌ 课程数据没取到,暂不开始学习(请检查网络,或重新登录后再试)'); return; } } const scope = activeScope(); const queue = buildQueue(tab, scope); const scopeName = scope != null ? (AppData.get('zone') || [])[scope]?.olClassName : null; if (queue.length === 0) { AppData.save({ state: { isAutoLearning: false } }); log(`🎉 ${scopeName ? `「${scopeName}」` : `所有${TAB_NAME[tab]}`}已完成,无需学习`); return; } AppData.save({ toLearnList: queue }); log(`📋 待学习${scopeName ? `「${scopeName}」` : TAB_NAME[tab]}共 ${queue.length} 门`); const first = queue[0]; if (!first.centerCode || !first.courseGuid) { log('⚠️ 这门课的信息不完整,无法打开学习页(请点右上角刷新重试)'); return; } log(`🚀 学习课程: ${first.courseName}`); AppData.save({ state: { isAutoLearning: true } }); location.assign(`https://learn.baowugroup.com/#/courseStudy?centerCode=${first.centerCode}&guid=${first.courseGuid}`); }; const stopLearning = () => { const media = getMediaElement(); if (media && !media.paused) media.pause(); AppData.save({ state: { isAutoLearning: false } }); lastTableSignature = ''; lastUiSignature = ''; markListRefresh(); log('⏸️ 已停止自动学习,返回个人中心'); logTodaySummary(); location.assign('https://learn.baowugroup.com/#/userCenter'); }; const handleMainAction = async () => { const state = AppData.get('state'); if (isStudyView(state)) { if (state.isAutoLearning) { stopLearning(); return; } log('↩️ 返回个人中心'); location.assign('https://learn.baowugroup.com/#/userCenter'); return; } const tab = BWGUI.getActiveTab(); if (!hasData(tab)) { await loadCourses(tab); return; } await startLearning(); }; const handleTableAction = (action, index) => { if (action === 'zone') { zoneView = index; lastTableSignature = ''; renderTable({ force: true }); syncUi(AppData.get('state')); return; } if (action === 'back') { zoneView = null; lastTableSignature = ''; renderTable({ force: true }); syncUi(AppData.get('state')); } }; const maybeAutoLoad = (state) => { if (autoLoadStarted || !state.isLogin || isStudyView(state)) return; autoLoadStarted = true; const tab = BWGUI.getActiveTab(); if (hasData(tab)) { log(`✅ 已登录,上次的${TAB_NAME[tab]}信息还在,可以直接开始学习`); return; } log(`⏳ 已登录,自动加载${TAB_NAME[tab]}数据…`); loadCourses(tab); }; const autoplayMiss = { guid: '', count: 0, loggedAt: 0 }; const isShown = (el) => { if (!el || el.disabled) return false; try { return el.offsetParent !== null; } catch { return false; } }; const logGate = new Map(); const logThrottled = (key, msg, ms = 60000) => { const now = Date.now(); if (now - (logGate.get(key) || 0) < ms) return; logGate.set(key, now); log(msg); }; const playBlocked = { guid: '', at: 0 }; const notePlayBlocked = (err) => { if (!err || err.name !== 'NotAllowedError') return; const guid = String(getCurrentCourseGuid() || ''); if (playBlocked.guid === guid) return; playBlocked.guid = guid; playBlocked.at = Date.now(); noteAutoplayBlocked(); log('⛔ 浏览器拦了自动播放(网页要先有人点一下才肯出声)。到 edge://settings/content/mediaAutoplay 把「控制是否自动播放网站上的音频及视频」改成「允许」,课程才能自己开始'); }; const startMedia = (media) => { let p = null; try { p = media.play(); } catch (e) { notePlayBlocked(e); return false; } if (p && typeof p.catch === 'function') p.catch((e) => notePlayBlocked(e)); return true; }; const btnClickMiss = { key: '', count: 0 }; const playCurrentMedia = (media) => { if (!media) return false; if (media.ended) { try { media.currentTime = 0; if (media.readyState === 0) media.load(); } catch { } } if (!media.paused) return false; const key = String(getCurrentCourseGuid() || ''); if (btnClickMiss.key !== key) { btnClickMiss.key = key; btnClickMiss.count = 0; } const doc = media.ownerDocument || document; if (doc !== document) { const btn = [...doc.querySelectorAll('#playOverlay .play-btn, .play-overlay .play-btn, .play-button')] .find((el) => isShown(el)); if (btn && btnClickMiss.count < 3) { btnClickMiss.count += 1; btn.click(); logThrottled('play-btn', '▶️ 点击课件内播放按钮'); return true; } logThrottled('play-audio', '▶️ 自动播放课件音频', 5 * 60 * 1000); startMedia(media); return true; } const strategies = [ { sel: '.xgplayer-start', name: '中央播放按钮' }, { sel: '.xgplayer-play .xgplayer-icon', name: '控制栏播放图标' }, { sel: '#xg-video, .xgplayer', name: '视频画面区域' }, ]; for (const { sel, name } of strategies) { const el = document.querySelector(sel); if (isShown(el)) { el.click(); logThrottled(`play-${name}`, `▶️ 点击${name}`); return true; } } logThrottled('play-auto', '▶️ 自动点击播放'); startMedia(media); return true; }; const PLAY_STALL_LIMIT = 5 * 60 * 1000; const PLAY_STALL_MAX_SKIP = 3; const playStall = { guid: '', since: 0, skips: 0 }; const resetPlayStall = (clearSkips) => { playStall.guid = ''; playStall.since = 0; btnClickMiss.count = 0; if (clearSkips) playStall.skips = 0; }; const trackPlayStall = (state) => { const guid = String(getCurrentCourseGuid() || ''); if (playStall.guid !== guid) { playStall.guid = guid; playStall.since = Date.now(); return; } if (!playStall.since) playStall.since = Date.now(); if (Date.now() - playStall.since < PLAY_STALL_LIMIT) return; playStall.since = Date.now(); const list = AppData.get('toLearnList') || []; const cur = list.find(c => String(c.courseGuid) === guid); const name = cur ? cur.courseName : '当前课程'; log(`⛔ 《${name}》5 分钟没能开始播放,不再干等(自动播放被拦:到 edge://settings/content/mediaAutoplay 把自动播放改成「允许」)`); playStall.skips += 1; if (!state.isAutoLearning || !cur) { replayState.stopped = true; log('⏸️ 需要你手动点一下播放按钮;点开之后脚本会自动接管(静音、续播、跳下一门)'); return; } if (playStall.skips > PLAY_STALL_MAX_SKIP) { AppData.save({ state: { isAutoLearning: false } }); log('⏸️ 连续几门课都播不起来,已停止自动学习。先把自动播放放开(见上一条日志)再点「开始学习」'); return; } handleCourseSkipped(cur, list, true); }; const tryClickNextChapter = () => { const btn = document.querySelector('.play-chapter button.el-button--primary'); if (btn?.offsetParent && !btn.disabled && btn.textContent.includes('播放下一节')) { log('⏭️ 自动点击 "播放下一节"'); btn.click(); return true; } return false; }; const cleanupOverlaysIn = (doc) => { if (!doc) return; doc.querySelector('.xgplayer-start')?.classList.add('hide'); const overlay = doc.querySelector('.video-overlay'); if (overlay) overlay.style.display = 'none'; }; const cleanupVideoOverlays = () => { cleanupOverlaysIn(document); cleanupOverlaysIn(getFrameDocument()); }; const POPUP_TEXT = /休息|专注学习|专注模式|挂机|长时间未操作|还在学习/; const POPUP_BUTTON = /继续|知道了|确定|好的|关闭/; const isElementVisible = (el) => { const rect = el.getBoundingClientRect(); return rect.width > 0 && rect.height > 0; }; let popupLoggedAt = 0; const dismissTrainingPopup = () => { for (const box of document.querySelectorAll('.el-message-box, .el-dialog, .el-message')) { if (!isElementVisible(box) || !POPUP_TEXT.test(box.textContent || '')) continue; const btn = [...box.querySelectorAll('button')].find(b => isElementVisible(b) && POPUP_BUTTON.test(b.textContent || '')); if (!btn) continue; btn.click(); if (Date.now() - popupLoggedAt > 5000) { popupLoggedAt = Date.now(); log(`💤 检测到「${(btn.textContent || '').trim()}」弹窗,已自动关闭`); } return true; } return false; }; const MAX_REPLAY = 3; const replayState = { guid: null, count: 0, stopped: false }; const skippedCourses = new Set(); const replayKey = (guid) => String(guid ?? 'unknown'); const bumpReplayCount = (guid) => { const key = replayKey(guid); if (replayState.guid !== key) { replayState.guid = key; replayState.count = 0; replayState.stopped = false; } replayState.count += 1; return replayState.count; }; const isReplayStopped = (guid) => replayState.stopped && replayState.guid === replayKey(guid); let fetchingCourseInfo = false; const ensureCurrentCourseInfo = async () => { if (fetchingCourseInfo) return; const params = parseHashParams(window.location.hash); const centerCode = params.centerCode; const courseGuid = params.guid; if (!centerCode || !courseGuid) return; const list = AppData.get('toLearnList') || []; if (list.some(c => String(c.courseGuid) === String(courseGuid))) return; fetchingCourseInfo = true; try { const info = await BWAPI.fetchCourseInfoByVideoUrl(centerCode, courseGuid); if (info) { let score = null; try { score = await BWAPI.fetchCourseScore(info.centerCode, info.courseNo, info.olClassNo); } catch { } const courseType = '单课程'; const enriched = { ...info, courseType, score: score || { passScore: null, learnScore: null, requiredDuration: null, completedDuration: null } }; const currentList = AppData.get('toLearnList') || []; const filtered = currentList.filter(c => String(c.courseGuid) !== String(courseGuid)); filtered.push(enriched); AppData.save({ toLearnList: filtered }); log(`📋 课程信息已读取:${enriched.courseName}`); renderTable({ force: true }); } } catch (error) { log(`⚠️ 课程信息没取到:${readableError(error)}`); } finally { fetchingCourseInfo = false; } }; const loop_2s = async () => { try { checkEnvHeartbeat(); watchAccountChange(); refreshAccountUi(); maybeArmResume(BWACC.load()); syncLoginPageUi(); maybeFillSmsLogin(); maybeSubmitSmsCode(); tryAutoLogin(); let media = getMediaElement(); const state = updateAppDataState(media); updateLearningStatusDisplay(state); syncUi(state); applyResumeSeek(media); trackResumePoint(state, media); applyServerSeek(media).catch(() => { }); if (maybeResumeLearning(state)) return; maybeAutoLoad(state); maybeRefreshAfterLearning(state); renderTable(); updateVideoCard(state); if (isStudyView(state)) { ensureCurrentCourseInfo(); ensureOutline(state); noteVideoEnded(media); dismissTrainingPopup(); if (media && !media.isConnected) media = getMediaElement(); if (media && !state.isVideoMuted) { media.muted = true; log('🔇 已自动静音'); } if (media && !state.isVideoPlaying) { playCurrentMedia(media); const key = String(getCurrentCourseGuid() || ''); if (autoplayMiss.guid !== key) { autoplayMiss.guid = key; autoplayMiss.count = 0; } autoplayMiss.count += 1; if (autoplayMiss.count === 4 && Date.now() - autoplayMiss.loggedAt > 60000) { autoplayMiss.loggedAt = Date.now(); log('⚠️ 播放没能自动开始(可能是浏览器拦了自动播放),再试 5 分钟还不行就跳过这门'); } trackPlayStall(state); } else if (media && !media.paused && playStall.guid) { resetPlayStall(true); } if (tryClickNextChapter()) return; if (media && !media.paused) { cleanupVideoOverlays(); } const allButtons = document.querySelectorAll('button.el-button'); const replayBtn = [...allButtons].find(btn => btn.textContent.includes('重新播放') && btn.offsetParent); if (replayBtn) { const currentGuid = getCurrentCourseGuid(); if (isReplayStopped(currentGuid)) return; if (currentGuid && skippedCourses.has(String(currentGuid))) return; const toLearnList = AppData.get('toLearnList') || []; const currentCourse = toLearnList.find(c => String(c.courseGuid) === String(currentGuid)); if (currentCourse) { let latestScore = null; try { latestScore = await BWAPI.fetchCourseScoreInVideoPage( currentCourse.centerCode, currentCourse.courseNo, currentCourse.olClassNo ); } catch { } const updatedScore = latestScore || currentCourse.score; if (isCourseFinished(updatedScore)) { log('✅ 课程已完成,自动跳转下一节'); const updatedCourse = { ...currentCourse, score: updatedScore }; handleCourseCompletion(updatedCourse, toLearnList, state.isAutoLearning); return; } const times = bumpReplayCount(currentGuid); if (times > MAX_REPLAY) { log(`⚠️ 重播 ${MAX_REPLAY} 次还是没学完(已学 ${fmtInt(updatedScore?.completedDuration)}/${fmtInt(updatedScore?.requiredDuration)} 分钟,得分 ${fmtInt(updatedScore?.learnScore)}/${fmtInt(updatedScore?.passScore)}),先跳过:${currentCourse.courseName}`); skippedCourses.add(String(currentGuid)); replayState.stopped = true; handleCourseSkipped(currentCourse, toLearnList, state.isAutoLearning); return; } log(`🔄 课程未完成,自动重播(第 ${times}/${MAX_REPLAY} 次)`); replayBtn.click(); return; } const times = bumpReplayCount(currentGuid); if (times > MAX_REPLAY) { log(`⚠️ 连续重播 ${MAX_REPLAY} 次都没读到课程信息,已停止自动重播`); replayState.stopped = true; if (currentGuid) skippedCourses.add(String(currentGuid)); return; } log(`🔄 检测到“重新播放”按钮,尝试自动重播(第 ${times}/${MAX_REPLAY} 次)`); replayBtn.click(); return; } } } catch (err) { log(`运行出错:${readableError(err)}`); } }; const handleCourseCompletion = (completedCourse, toLearnList, isAutoLearning) => { const courseType = completedCourse.courseType || '单课程'; patchCourseScore(completedCourse.courseGuid, completedCourse.score); bumpToday(completedCourse.score?.requiredDuration); if (!isAutoLearning || courseType === '单课程') { log('🏁 单课程学习完成,返回个人中心'); markListRefresh(); location.assign('https://learn.baowugroup.com/#/userCenter'); return; } const remaining = toLearnList.filter(c => { if (String(c.courseGuid) === String(completedCourse.courseGuid)) return false; return !isCourseFinished(c.score); }); log(`📊 还剩 ${remaining.length} 门没学(共 ${toLearnList.length} 门)`); AppData.save({ toLearnList: remaining }); renderTable({ force: true }); if (remaining.length > 0) { const next = remaining[0]; log(`➡️ 继续学习下一课程: ${next.courseName}`); location.assign(`https://learn.baowugroup.com/#/courseStudy?centerCode=${next.centerCode}&guid=${next.courseGuid}`); } else { log('🎉 所有课程学习完成,返回个人中心'); logTodaySummary(); AppData.save({ state: { isAutoLearning: false }, toLearnList: [] }); markListRefresh(); location.assign('https://learn.baowugroup.com/#/userCenter'); } }; const handleCourseSkipped = (skipped, toLearnList, isAutoLearning) => { const remaining = toLearnList.filter(c => String(c.courseGuid) !== String(skipped.courseGuid) && !isCourseFinished(c.score) ); log(`📊 跳过这门后还剩 ${remaining.length} 门(共 ${toLearnList.length} 门)`); AppData.save({ toLearnList: remaining }); renderTable({ force: true }); if (!isAutoLearning || skipped.courseType === '单课程') { log('⏸️ 已停止自动重播,请手动检查该课程(可能是考试还没通过)'); return; } if (remaining.length > 0) { const next = remaining[0]; log(`➡️ 已跳过,改学下一课程: ${next.courseName}`); location.assign(`https://learn.baowugroup.com/#/courseStudy?centerCode=${next.centerCode}&guid=${next.courseGuid}`); } else { log('🎉 待学课程已全部处理,返回个人中心'); logTodaySummary(); AppData.save({ state: { isAutoLearning: false }, toLearnList: [] }); markListRefresh(); location.assign('https://learn.baowugroup.com/#/userCenter'); } }; let scoreUpdateLock = false; const SCORE_POLL_INTERVAL = 20 * 1000; const SCORE_LOG_INTERVAL = 60 * 1000; let lastScoreLogAt = 0; let lastForceRefreshAt = 0; const logScore = (score, prefix) => { lastScoreLogAt = Date.now(); log(`${prefix} 已学 ${fmtInt(score.completedDuration)}/${fmtInt(score.requiredDuration)} 分钟,得分 ${fmtInt(score.learnScore)}/${fmtInt(score.passScore)}`); }; const loop_20s = async () => { if (scoreUpdateLock) return; const state = AppData.get('state'); if (!isStudyView(state)) return; const params = parseHashParams(window.location.hash); const centerCode = params.centerCode; const courseGuid = params.guid; if (!centerCode || !courseGuid) return; scoreUpdateLock = true; try { let toLearnList = AppData.get('toLearnList') || []; let target = toLearnList.find(c => String(c.courseGuid) === String(courseGuid)); if (!target) return; const oldScore = target.score || {}; const readScore = () => BWAPI.fetchCourseScore(target.centerCode, target.courseNo, target.olClassNo); const dueRefresh = Date.now() - lastForceRefreshAt >= SCORE_LOG_INTERVAL; if (dueRefresh) lastForceRefreshAt = Date.now(); let newScore = dueRefresh ? await BWAPI.fetchCourseScoreInVideoPage(target.centerCode, target.courseNo, target.olClassNo) : await readScore(); if (!newScore) newScore = await readScore(); const reached = !!newScore && Number(newScore.requiredDuration) > 0 && Number(newScore.completedDuration) > Number(newScore.requiredDuration); if (reached) { newScore = (await BWAPI.fetchCourseScoreInVideoPage(target.centerCode, target.courseNo, target.olClassNo)) || newScore; } if (newScore) { const isSame = newScore.completedDuration === oldScore.completedDuration && newScore.learnScore === oldScore.learnScore && newScore.passScore === oldScore.passScore && newScore.requiredDuration === oldScore.requiredDuration; if (isSame) { if (Date.now() - lastScoreLogAt >= SCORE_LOG_INTERVAL) logScore(newScore, '⏱️ 进度检查:'); } else { const updatedList = toLearnList.map(c => (c.courseGuid === courseGuid ? { ...c, score: newScore } : c)); AppData.save({ toLearnList: updatedList }); logScore(newScore, '🔄 学习进度:'); const req = Number(newScore.requiredDuration); const oldDone = Number(oldScore.requiredDuration) > 0 && Number(oldScore.completedDuration) > Number(oldScore.requiredDuration); const newDone = req > 0 && Number(newScore.completedDuration) > req; if (newDone && !oldDone) { const finalList = updatedList.map(c => c.courseGuid === courseGuid ? { ...c, learnStatus: '2', score: newScore } : c); AppData.save({ toLearnList: finalList }); log('✅ 当前课程学习完成'); handleCourseCompletion(target, finalList, state.isAutoLearning); return; } renderTable({ force: true }); } } } catch (e) { log('获取成绩失败: ' + e); } finally { scoreUpdateLock = false; } }; const OUTLINE_TTL = 10 * 60 * 1000; const outlines = new Map(); const outlineLoading = new Map(); const seekTried = new Set(); const computedVideos = new Set(); let heartSecs = 0; const currentCourse = () => { const guid = getCurrentCourseGuid(); if (!guid) return null; return (AppData.get('toLearnList') || []).find((c) => String(c.courseGuid) === String(guid)) || null; }; const outlineOf = (course) => (course ? outlines.get(String(course.courseGuid)) : null); const fmtPlayAt = (secs) => { const s = Math.max(0, Math.round(Number(secs) || 0)); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; }; const ensureOutline = (state) => { if (!isStudyView(state)) return; const course = currentCourse(); if (!course || !course.courseNo) return; const key = String(course.courseGuid); const hit = outlines.get(key); if (hit && Date.now() - hit.at < OUTLINE_TTL) return; if (outlineLoading.has(key)) return; const task = BWAPI.fetchCourseOutline(course.centerCode, course.courseNo) .then((sections) => { outlineLoading.delete(key); if (!sections) return; outlines.set(key, { at: Date.now(), sections }); const done = sections.filter((s) => s.learned).length; log(`🗂️ 《${course.courseName}》共 ${sections.length} 节,已完成 ${done} 节`); }) .catch(() => { outlineLoading.delete(key); }); outlineLoading.set(key, task); }; const outlineBrief = (course) => { const hit = outlineOf(course); if (!hit) return ''; const total = hit.sections.length; const done = hit.sections.filter((s) => s.learned).length; return `${total} 节 · 已完成 ${done} 节`; }; const pickSection = (sections, duration) => (sections || []).find( (s) => !s.learned && s.duration > 0 && Math.abs(s.duration - duration) <= 5 ); const applyServerSeek = async (media) => { if (!media || !(Number(media.duration) > 60)) return false; if (Number(media.currentTime) > 3) return false; const course = currentCourse(); if (!course) return false; const key = `${course.courseGuid}|${Math.round(Number(media.duration))}`; if (seekTried.has(key)) return false; seekTried.add(key); const resume = AppData.get('resume') || {}; if (resume.seekAt && Date.now() - resume.seekAt < 10 * 60 * 1000) return false; let hit = outlineOf(course); if (!hit) { const sections = await BWAPI.fetchCourseOutline(course.centerCode, course.courseNo); if (!sections) return false; hit = { at: Date.now(), sections }; outlines.set(String(course.courseGuid), hit); } const section = pickSection(hit.sections, Number(media.duration)); if (!section) return false; const progress = await BWAPI.fetchPlayProgress(section, course.olClassNo); if (!progress || progress.maxSecs < 30) return false; if (progress.maxSecs > section.duration - 10) return false; if (Number(media.currentTime) > 3) return false; try { media.currentTime = progress.maxSecs - 2; } catch { return false; } log(`⏩ 按服务端记录续播《${section.name}》:从 ${fmtPlayAt(progress.maxSecs)} 接着播`); return true; }; const noteVideoEnded = (media) => { if (!media || !media.ended) return; const course = currentCourse(); if (!course) return; const src = String(media.currentSrc || media.src || ''); const key = `${course.courseGuid}|${src}`; if (computedVideos.has(key)) return; computedVideos.add(key); BWAPI.computeVideoFinish(course.olClassNo, course.courseNo).then((ok) => { if (ok) log('🧮 本节已播完,已让站点重算这门课的成绩'); }); }; const loadHeartInterval = () => { BWAPI.fetchHeartFrequency().then((secs) => { if (secs > 0) heartSecs = secs; }); }; const heartHint = () => (heartSecs > 0 ? `(站点每 ${heartSecs} 秒记一次)` : ''); const CHECK_URL = 'https://scriptcat.org/api/v2/scripts/6740'; const INSTALL_URL = 'https://scriptcat.org/scripts/code/6740/%E5%AE%9D%E6%AD%A6%E5%AD%A6%E4%B9%A0%E5%8A%A9%E6%89%8B.user.js'; const UPDATE_CHECK_INTERVAL = 15 * 60 * 1000; const HTTP_TIMEOUT = 20000; const httpGetText = (url) => new Promise((resolve, reject) => { if (typeof GM_xmlhttpRequest === 'function') { GM_xmlhttpRequest({ method: 'GET', url: `${url}${url.includes('?') ? '&' : '?'}t=${Date.now()}`, timeout: HTTP_TIMEOUT, onload: (res) => { if (res.status >= 200 && res.status < 300) resolve(res.responseText); else reject(new Error(`HTTP ${res.status}`)); }, onerror: () => reject(new Error('Failed to fetch')), ontimeout: () => reject(new Error('timeout')) }); return; } const controller = typeof AbortController === 'function' ? new AbortController() : null; const timer = controller ? setTimeout(() => controller.abort(), HTTP_TIMEOUT) : null; fetch(`${url}${url.includes('?') ? '&' : '?'}t=${Date.now()}`, { cache: 'no-store', signal: controller ? controller.signal : undefined }) .then((resp) => (resp.ok ? resp.text() : Promise.reject(new Error(`HTTP ${resp.status}`)))) .then((text) => { if (timer) clearTimeout(timer); resolve(text); }) .catch((error) => { if (timer) clearTimeout(timer); reject(error); }); }); const pickVersion = (text) => { try { const json = JSON.parse(text); const script = json?.data?.script; const v = script?.version || script?.meta_json?.version?.[0]; if (v) return String(v); } catch { } return null; }; const updateState = { checking: false, available: false, version: '', checked: false }; const parseVersion = (v) => String(v || '').trim().replace(/^v/i, '').split(/[.+-]/).filter(Boolean); const isNewerVersion = (remote, local) => { const a = parseVersion(remote); const b = parseVersion(local); if (!a.length) return false; for (let i = 0; i < Math.max(a.length, b.length); i += 1) { const x = Number(a[i]); const y = Number(b[i]); const nx = Number.isFinite(x) ? x : 0; const ny = Number.isFinite(y) ? y : 0; if (nx !== ny) return nx > ny; } return false; }; const applyUpdateState = () => { BWGUI.setUpdateState({ available: updateState.available, version: updateState.version, checking: updateState.checking, hidden: false }); }; const checkUpdate = async (silent = true) => { if (updateState.checking) return updateState; updateState.checking = true; applyUpdateState(); try { const remoteVersion = pickVersion(await httpGetText(CHECK_URL)); if (!remoteVersion) throw new Error('没读到最新版本号'); const current = GM_info.script.version; updateState.version = remoteVersion; updateState.available = isNewerVersion(remoteVersion, current); updateState.checked = true; if (updateState.available) { log(`⬆️ 发现新版本 v${remoteVersion}(当前 v${current}),点右上角 ↑ 升级`); } else if (!silent) { log(`✅ 已是最新版本 v${current}`); } } catch (error) { updateState.checked = true; if (!silent) log(`⚠️ 检查更新失败,稍后会自动再试(${readableError(error)})`); } finally { updateState.checking = false; applyUpdateState(); } return updateState; }; const doUpgrade = async () => { if (!updateState.available) { await checkUpdate(false); if (!updateState.available) return; } log(`⬆️ 正在升级到 v${updateState.version},请在跳出的安装页点「安装」`); location.assign(INSTALL_URL); }; const RESUME_TTL = 24 * 60 * 60 * 1000; const RESUME_SEEK_WINDOW = 10 * 60 * 1000; const fmtClock = (sec) => { const s = Math.max(0, Math.round(Number(sec) || 0)); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; }; const emptyResume = () => ({ url: '', pos: 0, title: '', at: 0, armed: false, armedAt: 0, seekAt: 0, settleAt: 0 }); const courseLabel = (title) => { const t = String(title || '').trim(); if (!t) return '学习页'; return /《/.test(t) ? t : `《${t}》`; }; const resumeUsable = (resume, now = Date.now(), ttl = RESUME_TTL) => { if (!resume || !resume.url) return false; if (!/courseStudy/.test(String(resume.url))) return false; const at = Number(resume.at || 0); return !!at && now - at <= ttl; }; const resumeUrl = (url) => { try { const u = new URL(String(url)); u.searchParams.set('_', String(Date.now())); return u.toString(); } catch { return String(url); } }; const clearResume = () => AppData.save({ resume: emptyResume() }); const sameResumeCourse = (url, guid) => { const cur = String(guid || ''); if (!cur) return true; try { const want = String(parseHashParams(new URL(String(url)).hash).guid || ''); return !want || want === cur; } catch { return true; } }; const armResumeAfterExpire = (source) => { const resume = AppData.get('resume') || {}; if (!resumeUsable(resume)) return false; if (resume.armed) return true; AppData.save({ resume: { ...resume, armed: true, armedAt: Date.now(), seekAt: 0, settleAt: 0 } }); const at = Number(resume.pos || 0) > 5 ? `(${fmtClock(resume.pos)})` : ''; log(`💾 ${source},已记住退出前的${courseLabel(resume.title)}${at},登录后自动回去`); return true; }; const trackResumePoint = (state, media) => { if (!state.isLogin || isLoginPage()) return; const url = location.href; if (!/courseStudy/.test(url)) return; const pos = media && Number.isFinite(media.currentTime) ? Math.floor(media.currentTime) : 0; const old = AppData.get('resume') || {}; if (Number(old.seekAt || 0)) return; const samePage = old.url === url; const prev = Number(old.pos || 0); if (samePage && pos < prev - 5) { if (Date.now() - Number(old.at || 0) >= 5000) { AppData.save({ resume: { ...old, at: Date.now() } }); } return; } if (samePage && Math.abs(prev - pos) < 5) return; const guid = getCurrentCourseGuid(); const course = (AppData.get('toLearnList') || []).find((c) => String(c.courseGuid) === String(guid)); AppData.save({ resume: { ...old, url, pos, title: (course && course.courseName) || (samePage ? old.title || '' : ''), at: Date.now(), } }); }; const applyResumeSeek = (media) => { const resume = AppData.get('resume') || {}; const seekAt = Number(resume.seekAt || 0); if (!seekAt) return; if (Date.now() - seekAt > RESUME_SEEK_WINDOW) { AppData.save({ resume: { ...resume, seekAt: 0 } }); return; } if (!sameResumeCourse(resume.url, getCurrentCourseGuid())) { AppData.save({ resume: { ...resume, seekAt: 0 } }); log(`↩️ 已经换到别的课,${courseLabel(resume.title)}的进度不再定位`); return; } if (!media || !(media.readyState >= 1)) return; const pos = Number(resume.pos || 0); const cur = Number(media.currentTime || 0); if (pos > 5 && cur < pos - 10) { const target = Math.max(0, pos - 2); media.currentTime = target; log(`↩️ 已回到退出前的进度 ${fmtClock(target)},继续学习`); } AppData.save({ resume: { ...resume, seekAt: 0 } }); }; const maybeResumeLearning = (state) => { const resume = AppData.get('resume') || {}; if (!resume.armed || !resumeUsable(resume)) return false; if (!state.isLogin || isLoginPage()) return false; if (!liveLogin().id) return false; if (isStudyView(state)) { const same = sameResumeCourse(resume.url, getCurrentCourseGuid()); AppData.save({ resume: { ...resume, armed: false, seekAt: same ? Date.now() : 0 } }); log(same ? `↩️ 已回到退出前的${courseLabel(resume.title)}` : `↩️ 已经换到别的课,不再回到${courseLabel(resume.title)}`); return false; } const settleAt = Number(resume.settleAt || 0); if (settleAt && Date.now() - settleAt < 2000) return false; AppData.save({ resume: { ...resume, armed: false, seekAt: Date.now() } }); log(`↩️ 正在回到退出前的${courseLabel(resume.title)}`); location.assign(resumeUrl(resume.url)); return true; }; const ENV_BEAT_GAP = 90 * 1000; const envState = { autoplayAt: 0, frozenMs: 0, frozenAt: 0, discarded: false, warned: '' }; let envBeat = 0; const autoplayPolicy = () => { try { const fn = navigator.getAutoplayPolicy; if (typeof fn === 'function') return String(fn.call(navigator, 'mediaelement') || ''); } catch (e) { } return ''; }; const fmtSpan = (ms) => { const min = Math.round(ms / 60000); if (min < 60) return `${min} 分钟`; const h = Math.floor(min / 60); return min % 60 > 0 ? `${h} 小时 ${min % 60} 分` : `${h} 小时`; }; const envIssues = () => { const issues = []; const policy = autoplayPolicy(); if (envState.autoplayAt || policy === 'disallowed') { issues.push({ key: 'autoplay', title: '自动播放被拦住', detail: envState.autoplayAt ? '音频课会一直停在开头,等你点一下播放' : '浏览器现在不许网页自己出声,音频课不会自己开始' }); } if (envState.frozenMs >= ENV_BEAT_GAP) { issues.push({ key: 'sleep', title: '学习页被浏览器停过', detail: `停了 ${fmtSpan(envState.frozenMs)},这段时间进度一点都不动` }); } else if (envState.discarded) { issues.push({ key: 'sleep', title: '学习页被浏览器清出过内存', detail: '页面被重新加载了一次,那段时间进度不动' }); } return issues; }; const noteAutoplayBlocked = () => { envState.autoplayAt = envState.autoplayAt || Date.now(); refreshEnvWarn(); }; const checkEnvHeartbeat = () => { const now = Date.now(); const prev = envBeat; envBeat = now; if (!prev) return false; const gap = now - prev; if (gap < ENV_BEAT_GAP) return false; envState.frozenMs += gap; envState.frozenAt = now; log(`🧊 页面被冻结了约 ${fmtSpan(gap)}:这段时间 2 秒循环一次都没跑,课程进度不会动`); refreshEnvWarn(); return true; }; const refreshEnvWarn = () => { const issues = envIssues(); try { BWGUI.setEnvWarn(issues); } catch (e) { } const key = issues.map((i) => i.key).sort().join(','); if (key === envState.warned) return issues; const had = envState.warned; envState.warned = key; if (!key) { if (had) log('✅ 浏览器两处设置都正常了,⚠ 已经收起来'); return issues; } log(`🛠️ 检测到 ${issues.length} 项浏览器设置需要调整(${issues.map((i) => i.title).join('、')}),点标题栏右上的 ⚠ 看怎么改`); return issues; }; const silentWavUrl = () => { const rate = 8000; const n = 800; const buf = new Uint8Array(44 + n); const view = new DataView(buf.buffer); const put = (off, str) => { for (let i = 0; i < str.length; i++) buf[off + i] = str.charCodeAt(i); }; put(0, 'RIFF'); view.setUint32(4, 36 + n, true); put(8, 'WAVE'); put(12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true); view.setUint32(24, rate, true); view.setUint32(28, rate, true); view.setUint16(32, 1, true); view.setUint16(34, 8, true); put(36, 'data'); view.setUint32(40, n, true); buf.fill(128, 44); return URL.createObjectURL(new Blob([buf], { type: 'audio/wav' })); }; const tryPlaySilent = (muted) => new Promise((resolve) => { let url = ''; try { url = silentWavUrl(); const audio = new Audio(); audio.src = url; audio.muted = muted; const p = audio.play(); Promise.resolve(p).then(() => { try { audio.pause(); } catch (e) { } try { URL.revokeObjectURL(url); } catch (e) { } resolve(true); }, () => { try { URL.revokeObjectURL(url); } catch (e) { } resolve(false); }); } catch (e) { try { if (url) URL.revokeObjectURL(url); } catch (err) { } resolve(false); } }); const probeAutoplay = async () => { if (await tryPlaySilent(false)) return 'sound'; if (await tryPlaySilent(true)) return 'muted'; return 'none'; }; const openInTab = (url) => { try { if (typeof GM_openInTab !== 'function') return false; GM_openInTab(url, { active: true, insert: true, setParent: true }); return true; } catch (e) { return false; } }; const openEnvGuide = () => { let html = ''; try { html = BWGUI.envGuideHtml(envIssues()); } catch (e) { log('⚠️ 说明页生成失败:' + readableError(e)); return; } let url = ''; try { url = URL.createObjectURL(new Blob([html], { type: 'text/html;charset=utf-8' })); } catch (e) { } if (url && openInTab(url)) { log('📖 已在新标签页打开「浏览器设置」说明页'); return; } if (BWGUI.openEnvPage(html)) { log('📖 已打开「浏览器设置」说明页'); return; } log('⚠️ 说明页打不开:面板还没建好'); }; const watchEnvReturn = () => { document.addEventListener('visibilitychange', () => { if (document.visibilityState !== 'visible') return; if (!envState.autoplayAt || Date.now() - envState.autoplayAt < 15 * 1000) return; Promise.resolve(probeAutoplay()).then((verdict) => { if (verdict === 'none') return; envState.autoplayAt = 0; refreshEnvWarn(); log('✅ 自动播放已经放开,这项不用再管了'); }); }); }; const initEnvWatch = () => { envBeat = Date.now(); if (document.wasDiscarded) envState.discarded = true; watchEnvReturn(); refreshEnvWarn(); }; const appSnapshot = () => { const out = {}; for (const key of BWACC.DATA_FIELDS) out[key] = AppData.get(key); return out; }; const resetRuntimeState = () => { AppData.save({ state: { ...DEFAULT_DATA.state } }); }; const liveLogin = () => { if (isLoginPage()) return { live: null, id: '' }; const live = BWACC.readUserInfo(); if (live) return { live, id: String(live.loginName || live.userId || '') }; const token = BWACC.readAccessToken(); if (!token) return { live: null, id: '' }; const id = BWACC.tokenLoginName(token); const saved = id ? BWACC.get(id, BWACC.load()) : null; if (!saved) return { live: null, id: '' }; const base = saved.userInfo || {}; const restored = { ...base, loginName: base.loginName || id, userId: base.userId || id, accessToken: token, }; BWACC.writeUserInfo(restored); return { live: restored, id }; }; let lastAccountSig = ''; const refreshAccountUi = (force = false) => { const store = BWACC.load(); const { live, id: liveId } = liveLogin(); const current = liveId ? BWACC.get(liveId, store) : null; const name = (current && current.name) || (live && (live.userName || live.nick_name)) || ''; const list = BWACC.list(store).map((a) => ({ id: a.id, name: a.name, alive: BWACC.isAlive(a), password: BWACC.clarify(a.password), phone: a.phone })); const sig = [ liveId, name, list.map((a) => `${a.id}:${a.alive ? 1 : 0}:${a.name || ''}:${a.password ? 1 : 0}`).join(','), ].join('|'); if (!force && sig === lastAccountSig) return; lastAccountSig = sig; BWGUI.setAccount({ logged: !!liveId, id: liveId || String(store.current || ''), name, list }); }; const takeCapture = (liveId) => { const cap = BWACC.readCapture(); if (!cap) return null; if (!cap.loginId && !cap.phone) return null; const sameId = cap.loginId === liveId || cap.phone === liveId; const fresh = Date.now() - cap.at < 5 * 60 * 1000; return sameId || fresh ? cap : null; }; const adoptLiveAccount = (live, store) => { const liveId = String(live.loginName || live.userId || ''); if (!liveId) return ''; const prevId = String(store.current || ''); const existed = store.accounts[liveId]; const cap = takeCapture(liveId); if (prevId && prevId !== liveId && store.accounts[prevId]) { store.accounts[prevId].data = BWACC.snapshot(appSnapshot()); } let recorded = false; if (existed) { existed.token = live.accessToken || existed.token; existed.userInfo = live; existed.expiresAt = BWACC.tokenExpiry(live); existed.usedAt = Date.now(); existed.name = live.userName || live.nick_name || existed.name || ''; const livePhone = live.mobile || live.phone || live.telephone || ''; if (livePhone) existed.phone = String(livePhone); if (cap) { if (cap.phone) existed.phone = cap.phone; if (cap.password) existed.password = BWACC.obscure(cap.password); if (cap.loginId) existed.loginId = cap.loginId; recorded = true; if (cap.password) log(`🔐 已把这次登录填的密码存进账号 ${liveId},下次不用再输`); } } else { store.accounts[liveId] = BWACC.profileFromUserInfo(live, null, cap); recorded = true; log(`👤 已自动记录账号 ${liveId}${live.userName ? ' · ' + live.userName : ''}${cap && cap.password ? ',密码已保存' : ''}`); } if (cap) BWACC.dropCapture(); delete store.skipAutoLogin; delete store.smsLogin; autoLogin.stopped = false; autoLogin.submit = 0; autoLogin.rounds = 0; autoLogin.lastCode = ''; const switched = !!(prevId && prevId !== liveId); if (switched) { const snap = existed && existed.data ? BWACC.applySnapshot(existed.data) : BWACC.emptySnapshot(); AppData.save(snap); resetRuntimeState(); autoLoadStarted = false; lastTableSignature = ''; lastUiSignature = ''; clearResume(); log(`👤 账号已切换为 ${liveId}${live.userName ? ' · ' + live.userName : ''},课程数据已换成该账号的`); } store.current = liveId; BWACC.save(store); return switched ? 'switched' : recorded ? 'recorded' : ''; }; const maybeArmResume = (store) => { if (liveLogin().id) return; if (skipAutoLoginSet(store)) return; const acc = store.current ? BWACC.get(store.current, store) : null; if (!acc) return; const resume = AppData.get('resume') || {}; if (resume.armed) return; if (!resumeUsable(resume)) return; armResumeAfterExpire(isLoginPage() ? '登录态已失效,站点退回了登录页' : '登录态已失效,站点已退出登录'); }; const syncAccountOnBoot = () => { const store = BWACC.load(); const restored = BWACC.tookBackup(); const { live } = liveLogin(); if (live) { adoptLiveAccount(live, store); const resume = AppData.get('resume') || {}; if (resume.armed && resumeUsable(resume)) { AppData.save({ resume: { ...resume, settleAt: Date.now() } }); } } return restored; }; let seenLoginId = ''; let lastUserClickAt = 0; const watchAccountChange = () => { const { live, id: liveId } = liveLogin(); if (!liveId) { if (seenLoginId) { const store = BWACC.load(); const acc = store.current ? BWACC.get(store.current, store) : null; const expiresAt = acc && acc.expiresAt ? Number(acc.expiresAt) : 0; const expired = !expiresAt || expiresAt < Date.now(); const armed = Number(store.pendingLogin || 0); const wanted = armed > 0 && Date.now() - armed < 10 * 60 * 1000; const clicked = lastUserClickAt > 0 && Date.now() - lastUserClickAt < 8000; if (!expired && !wanted && clicked && !skipAutoLoginSet(store)) { store.skipAutoLogin = Date.now(); delete store.pendingLogin; BWACC.save(store); clearResume(); log('👋 已退出登录,之后不再自动登录;你自己登录成功后自动记录会恢复'); } else if (!wanted && !skipAutoLoginSet(store)) { armResumeAfterExpire(expired ? '登录态已过期' : '登录态被站点清掉了'); } seenLoginId = ''; refreshAccountUi(); } return; } if (liveId === seenLoginId) return; seenLoginId = liveId; const store = BWACC.load(); const result = adoptLiveAccount(live, store); const arrived = AppData.get('resume') || {}; if (arrived.armed && resumeUsable(arrived)) { AppData.save({ resume: { ...arrived, settleAt: Date.now() } }); } if (loginListShown) { loginListShown = false; loginCountdownSent = true; stopLoginCountdown(); BWGUI.closeAccountPage(); } BWGUI.setTheme(AppData.get('theme') || 'dark'); refreshAccountUi(true); if (result === 'switched') refreshAllCourseLists('切换账号'); }; const saveAccountProfile = ({ id, password, phone }) => { const store = BWACC.load(); const exist = store.accounts[id]; if (!exist) { log(`⚠️ 没有找到账号 ${id},账号是用它登录一次后自动记录的`); return; } exist.phone = phone || ''; if (password) exist.password = BWACC.obscure(password); BWACC.save(store); refreshAccountUi(); log(`👤 已更新账号 ${id}${exist.name ? ' · ' + exist.name : ''}${password ? '(密码已保存)' : ''}`); }; const deleteAccount = (id) => { const store = BWACC.load(); if (!store.accounts[id]) return; delete store.accounts[id]; if (store.current === id) { const rest = Object.keys(store.accounts); store.current = rest.length ? rest[0] : ''; } BWACC.save(store, { allowEmpty: true }); refreshAccountUi(); log(`🗑️ 已删除账号 ${id}`); }; const switchAccount = (targetId) => { const store = BWACC.load(); const target = BWACC.get(targetId, store); if (!target) return; stopLoginCountdown(target.password ? -1 : 0); loginCountdownSent = true; loginListShown = true; if (store.current === targetId && liveLogin().id) return; const playing = getMediaElement(); if (playing && !playing.paused) playing.pause(); if (store.current && store.accounts[store.current]) { store.accounts[store.current].data = BWACC.snapshot(appSnapshot()); } store.current = targetId; target.usedAt = Date.now(); const snap = target.data ? BWACC.applySnapshot(target.data) : BWACC.emptySnapshot(); BWACC.save(store); AppData.save(snap); resetRuntimeState(); const keptResume = AppData.get('resume') || {}; if (!keptResume.armed) clearResume(); if (!isLoginPage() && BWACC.isAlive(target) && target.userInfo) { delete store.skipAutoLogin; store.pendingLogin = Date.now(); BWACC.save(store); BWACC.writeUserInfo(target.userInfo); BWACC.writeAccessToken(target.userInfo.accessToken); log(`👤 切换到 ${targetId}${target.name ? ' · ' + target.name : ''}(登录态还在,免登录)`); location.reload(); return; } if (!target.password) { if (!target.phone) { log(`👤 ${targetId} 没有保存密码和手机号,只能自己手动登录一次`); return; } clearResume(); store.smsLogin = Date.now(); delete store.pendingLogin; delete store.skipAutoLogin; BWACC.clearUserInfo(); BWACC.save(store); autoLogin.stopped = true; log(`👤 正在用 ${targetId}${target.name ? ' · ' + target.name : ''} 的手机号登录,短信验证码需要你自己填`); if (!isLoginPage()) goLoginPage(); return; } BWACC.clearUserInfo(); store.pendingLogin = Date.now(); delete store.skipAutoLogin; BWACC.save(store); log(`👤 正在用 ${targetId}${target.name ? ' · ' + target.name : ''} 登录`); if (isLoginPage()) { autoLogin.stopped = false; autoLogin.submit = 0; autoLogin.rounds = 0; autoLogin.lastCode = ''; return; } goLoginPage(); }; const loginAnotherAccount = () => { const store = BWACC.load(); stopLoginCountdown(); loginCountdownSent = true; loginListShown = true; BWGUI.closeAccountPage(); clearResume(); if (!liveLogin().id) { delete store.pendingLogin; delete store.smsLogin; store.skipAutoLogin = Date.now(); BWACC.save(store); if (isLoginPage()) { log('👤 已停用自动登录,请用新账号登录一次(登录成功后会自动记录)'); return; } goLoginPage(); return; } if (store.current && store.accounts[store.current]) { store.accounts[store.current].data = BWACC.snapshot(appSnapshot()); } delete store.pendingLogin; delete store.smsLogin; store.skipAutoLogin = Date.now(); BWACC.save(store); BWACC.clearUserInfo(); log('👤 已退出当前账号,请用另一个账号登录,登录成功后会自动记录'); goLoginPage(); }; const goLoginPage = () => location.replace(`https://learn.baowugroup.com/?_=${Date.now()}#/auth/login`); const AUTO_SUBMIT_LIMIT = 2; const AUTO_ROUND_LIMIT = 8; const autoLogin = { running: false, submit: 0, rounds: 0, stopped: false, notice: false, lastCode: '' }; const isLoginPage = () => location.href.includes('auth/login'); const fillInput = (input, value) => { const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set; setter.call(input, value); input.dispatchEvent(new Event('input', { bubbles: true })); input.dispatchEvent(new Event('change', { bubbles: true })); }; const loginFields = () => { const visible = [...document.querySelectorAll('input')].filter((e) => e.offsetParent !== null); const tab = (text) => [...document.querySelectorAll('div,span,li')].find( (e) => e.offsetParent !== null && (e.innerText || '').trim() === text ); return { idBox: visible.find((e) => /工号|通行证/.test(e.placeholder || '')), pwdBox: visible.find((e) => e.type === 'password'), codeBox: visible.find((e) => e.type !== 'password' && /验证码/.test(e.placeholder || '') && !/短信/.test(e.placeholder || '')), phoneBox: visible.find((e) => /手机号码|手机号(?!码)/.test(e.placeholder || '')), smsCodeBox: visible.find((e) => /短信验证码/.test(e.placeholder || '')), loginBtn: [...document.querySelectorAll('button')].find( (b) => b.offsetParent !== null && !b.disabled && (b.innerText || '').trim() === '登录' ), captcha: document.querySelector('img.captcha-image'), pwdTab: tab('账号登录'), smsTab: tab('手机号登录'), }; }; const sendCodeBtn = () => { const hit = [...document.querySelectorAll('button,span,a')].find((e) => { if (e.offsetParent === null || e.disabled) return false; const text = (e.innerText || '').replace(/\s/g, ''); return /^(获取验证码|发送验证码|获取短信验证码|发送短信验证码)$/.test(text); }); return hit || null; }; const readLoginInputs = () => { const visible = [...document.querySelectorAll('input')].filter((e) => e.offsetParent !== null); const byPlaceholder = (re) => visible.find((e) => re.test(e.placeholder || '')); const idBox = byPlaceholder(/工号|通行证/); const pwdBox = visible.find((e) => e.type === 'password'); const phoneBox = byPlaceholder(/手机号码|手机号(?!码)/); const loginId = idBox ? String(idBox.value || '').trim() : ''; if (!loginId) return null; const password = pwdBox ? String(pwdBox.value || '') : ''; const phone = phoneBox ? String(phoneBox.value || '').trim() : ''; if (!password && !phone) return null; return { loginId, password, phone: /^1\d{10}$/.test(loginId) ? loginId : phone, at: Date.now(), }; }; const captureLoginForm = () => { const creds = readLoginInputs(); if (creds) BWACC.saveCapture(creds); }; const installLoginCapture = () => { document.addEventListener('click', () => { lastUserClickAt = Date.now(); }, true); document.addEventListener('click', (event) => { if (!isLoginPage()) return; const target = event.target; const btn = target && target.closest ? target.closest('button,[role="button"]') : null; if (!btn || (btn.innerText || '').replace(/\s/g, '') !== '登录') return; captureLoginForm(); }, true); document.addEventListener('keydown', (event) => { if (event.key !== 'Enter' || !isLoginPage()) return; const box = readLoginInputs(); if (box) BWACC.saveCapture(box); }, true); document.addEventListener('input', (event) => { const el = event.target; if (!el || !/短信验证码/.test(el.placeholder || '')) return; maybeSubmitSmsCode(); }, true); document.addEventListener('click', (event) => { const target = event.target; const hit = target && target.closest ? target.closest('button,[role="button"],a,span,div') : null; if (!hit) return; const text = (hit.innerText || '').replace(/\s/g, ''); if (!/^(退出登录|退出系统|注销|登出|退出)$/.test(text)) return; const store = BWACC.load(); store.skipAutoLogin = Date.now(); delete store.pendingLogin; BWACC.save(store); clearResume(); log('👋 已记下你要自己登录,这次不自动填表'); }, true); }; const refreshCaptcha = () => { const img = document.querySelector('img.captcha-image'); if (img) img.click(); }; const LOGIN_COUNTDOWN = 10; const loginCountdown = { id: '', left: 0, timer: null }; let loginListShown = false; let loginCountdownSent = false; const stopLoginCountdown = (mark = 0) => { if (loginCountdown.timer) { clearInterval(loginCountdown.timer); loginCountdown.timer = null; } loginCountdown.left = 0; loginCountdown.id = ''; BWGUI.setLoginCountdown(mark); }; const loginFormTouched = (expectId) => { const fields = loginFields(); if (!fields.idBox) return false; if (fields.codeBox && String(fields.codeBox.value || '').trim()) return true; const typed = String(fields.idBox.value || '').trim(); return !!(typed && expectId && typed !== expectId); }; const startLoginCountdown = (acc) => { const id = String(acc.id); loginCountdown.id = id; loginCountdown.left = LOGIN_COUNTDOWN; BWGUI.setLoginCountdown(loginCountdown.left); log(`⏳ ${id}${acc.name ? ' · ' + acc.name : ''} 将在 ${LOGIN_COUNTDOWN} 秒后自动登录,点别的账号或「登录新账号」可取消`); loginCountdown.timer = setInterval(() => { if (!isLoginPage() || liveLogin().id) { stopLoginCountdown(); return; } if (loginFormTouched(String(acc.loginId || id))) { stopLoginCountdown(); const store = BWACC.load(); store.skipAutoLogin = Date.now(); delete store.pendingLogin; BWACC.save(store); autoLogin.stopped = true; log('👀 检测到你在手动登录,倒计时已取消'); return; } loginCountdown.left -= 1; if (loginCountdown.left > 0) { BWGUI.setLoginCountdown(loginCountdown.left); return; } stopLoginCountdown(-1); log('🤖 倒计时结束,开始自动登录'); switchAccount(id); tryAutoLogin(); }, 1000); }; const syncLoginPageUi = () => { if (!isLoginPage()) { if (loginCountdown.timer) stopLoginCountdown(); return; } const store = BWACC.load(); const logged = !!liveLogin().id; const acc = store.current ? BWACC.get(store.current, store) : null; if (!logged && !loginListShown && acc) { loginListShown = true; refreshAccountUi(true); BWGUI.openAccountPage(); } if (logged || skipAutoLoginSet(store)) { if (loginCountdown.timer) stopLoginCountdown(); return; } if (!loginCountdown.timer && !autoLogin.running) BWGUI.setLoginCountdown(0); if (!acc || !acc.password) return; if (loginCountdownSent || loginCountdown.left !== 0 || loginCountdown.timer) return; loginCountdownSent = true; startLoginCountdown(acc); }; const SMS_LOGIN_TTL = 10 * 60 * 1000; const smsFill = { sentAt: 0, lastLogAt: 0 }; const prepareSmsLogin = (acc) => { const f = loginFields(); if (!f.phoneBox && f.smsTab) { f.smsTab.click(); return 'wait'; } if (!f.phoneBox) return 'wait'; if (f.smsCodeBox && String(f.smsCodeBox.value || '').trim()) return 'skip'; const loginId = String(acc.loginId || acc.id || ''); const phone = String(acc.phone || ''); if (f.idBox && f.idBox.value.trim() && f.idBox.value.trim() !== loginId) return 'skip'; let filled = false; if (f.idBox && f.idBox.value.trim() !== loginId) { fillInput(f.idBox, loginId); filled = true; } if (phone && f.phoneBox.value.trim() !== phone) { fillInput(f.phoneBox, phone); filled = true; } if (filled) return 'wait'; if (!f.phoneBox.value.trim()) return 'wait'; const btn = sendCodeBtn(); if (!btn) return 'wait'; if (Date.now() - smsFill.sentAt < 60 * 1000) return 'done'; smsFill.sentAt = Date.now(); btn.click(); log(`📱 已填好工号 ${loginId} 和手机号 ${phone},并点了「获取验证码」;收到短信后自己把验证码填上就能登录`); return 'done'; }; const SMS_SUBMIT_DELAY = 700; const smsSubmit = { code: '', at: 0, timer: null }; const smsSubmitBtn = (codeBox) => { let root = codeBox; for (let i = 0; i < 10 && root && root !== document.body; i += 1) { root = root.parentElement; if (!root) break; const btn = [...root.querySelectorAll('button')].find( (b) => b.offsetParent !== null && !b.disabled && (b.innerText || '').trim() === '登录' ); if (btn) return btn; } return null; }; const submitSmsCode = () => { if (!isLoginPage()) return false; const box = loginFields().smsCodeBox; if (!box) return false; const code = String(box.value || '').trim(); if (!/^\d{6}$/.test(code)) return false; if (smsSubmit.code === code) return false; const btn = smsSubmitBtn(box); if (!btn) return false; smsSubmit.code = code; smsSubmit.at = Date.now(); log('📨 短信验证码已填满 6 位,自动点「登录」'); btn.click(); return true; }; const clearSmsSubmit = () => { if (smsSubmit.timer) { clearTimeout(smsSubmit.timer); smsSubmit.timer = null; } }; const maybeSubmitSmsCode = () => { if (!isLoginPage()) return false; const box = loginFields().smsCodeBox; if (!box) return false; const code = String(box.value || '').trim(); if (!/^\d{6}$/.test(code) || smsSubmit.code === code) { clearSmsSubmit(); return false; } clearSmsSubmit(); smsSubmit.timer = setTimeout(() => { smsSubmit.timer = null; submitSmsCode(); }, SMS_SUBMIT_DELAY); return true; }; const maybeFillSmsLogin = () => { if (!isLoginPage()) return false; const store = BWACC.load(); const at = Number(store.smsLogin || 0); if (!at) return false; const drop = () => { delete store.smsLogin; BWACC.save(store); }; if (Date.now() - at > SMS_LOGIN_TTL) { drop(); return false; } if (liveLogin().id) { drop(); return false; } const acc = store.current ? BWACC.get(store.current, store) : null; if (!acc || acc.password || !acc.phone) { drop(); return false; } const result = prepareSmsLogin(acc); if (result === 'wait') { if (Date.now() - at > 30 * 1000 && Date.now() - smsFill.lastLogAt > 5000) { smsFill.lastLogAt = Date.now(); log('📱 没找到「手机号登录」页签或「获取验证码」按钮,请自己点一下页签、填好手机号再获取验证码'); } return true; } drop(); if (result === 'skip') log('👀 检测到你在自己填短信登录,脚本不再动输入框'); return true; }; const skipAutoLoginSet = (store) => Number(store.skipAutoLogin || 0) > 0; const shouldAutoLogin = () => { if (!isLoginPage() || autoLogin.stopped) return false; if (autoLogin.running || autoLogin.submit >= AUTO_SUBMIT_LIMIT || autoLogin.rounds >= AUTO_ROUND_LIMIT) return false; if (loginCountdown.left > 0) return false; const store = BWACC.load(); if (skipAutoLoginSet(store)) return false; const acc = store.current ? BWACC.get(store.current, store) : null; if (!acc) return false; if (!acc.password) { if (!autoLogin.notice && !Number(store.smsLogin || 0)) { autoLogin.notice = true; log(`👤 账号 ${acc.id} 是手机号登录的,没有保存密码,请在账号页点「手机登录」`); } return false; } const armed = Number(store.pendingLogin || 0); if (armed > 0 && Date.now() - armed < 10 * 60 * 1000) return true; if (!liveLogin().id) return true; const expired = acc.expiresAt ? acc.expiresAt < Date.now() : !acc.token; return !!expired; }; const waitLogin = async (timeout) => { const started = Date.now(); while (Date.now() - started < timeout) { if (!isLoginPage() || BWACC.readUserInfo()) return true; await sleep(300); } return false; }; const tryAutoLogin = async () => { if (!shouldAutoLogin()) return; const store = BWACC.load(); const acc = BWACC.get(store.current, store); const password = BWACC.clarify(acc.password); if (!password) return; const fields = loginFields(); if (!fields.pwdBox && fields.pwdTab) { fields.pwdTab.click(); await sleep(400); return; } if (!fields.idBox || !fields.pwdBox || !fields.codeBox || !fields.loginBtn || !fields.captcha) return; if (autoLogin.lastCode && fields.codeBox.value === autoLogin.lastCode) { fillInput(fields.codeBox, ''); autoLogin.lastCode = ''; } const idVal = fields.idBox.value.trim(); const loginId = String(acc.loginId || acc.id); if ((idVal && idVal !== loginId) || fields.codeBox.value) { autoLogin.stopped = true; log('👀 检测到你在手动登录,自动填表已让位'); return; } autoLogin.running = true; autoLogin.rounds += 1; try { fillInput(fields.idBox, loginId); fillInput(fields.pwdBox, password); const result = await BWOCR.recognize(fields.captcha); if (!result.ok) { log(`🤖 验证码没认准(${result.reason || '未知'}),换一张重试`); refreshCaptcha(); await sleep(1000); return; } fillInput(fields.codeBox, String(result.answer)); autoLogin.lastCode = String(result.answer); captureLoginForm(); autoLogin.submit += 1; log(`🤖 自动登录 ${acc.id}:${result.expr}=${result.answer},正在提交…`); fields.loginBtn.click(); if (await waitLogin(8000)) { autoLogin.stopped = true; loginCountdownSent = true; delete store.pendingLogin; delete store.skipAutoLogin; BWACC.save(store); const fresh = BWACC.readUserInfo(); if (fresh) adoptLiveAccount(fresh, BWACC.load()); const resume = AppData.get('resume') || {}; if (resume.armed) AppData.save({ resume: { ...resume, settleAt: Date.now() } }); log('✅ 自动登录成功'); } else { log(`⚠️ 第 ${autoLogin.submit} 次自动登录没成功,换一张验证码重试`); refreshCaptcha(); await sleep(1200); } } catch (error) { log(`⚠️ 自动登录出错:${readableError(error)}`); } finally { autoLogin.running = false; } }; const handleThemeChange = (name) => { AppData.save({ theme: name }); }; const dropLegacyData = () => { const url = AppData.get('url'); if (!url || !('previousUrl' in url)) return; delete url.previousUrl; AppData.save({ url }); }; const bootstrap = () => { AppData.init(); const resumeKey = AppData.mirrorKey('resume'); if (resumeUsable(AppData.get('resume')) && !BWACC.rawRead(resumeKey)) { AppData.save({ resume: { ...(AppData.get('resume') || {}) } }); } dropLegacyData(); const restoredResume = AppData.mirrorRestored().includes('resume') && resumeUsable(AppData.get('resume')); const restoredAccountBackup = syncAccountOnBoot(); BWUTL.fswn(); BWGUI.init({ scriptName: GM_info.script.name, version: GM_info.script.version, tabs: TABS, theme: AppData.get('theme') || 'dark', callbacks: { onTab: handleTabChange, onRefresh: handleRefresh, onMain: handleMainAction, onAction: handleTableAction, onUpdate: doUpgrade, onEnvGuide: openEnvGuide, onTheme: handleThemeChange, onAccountSwitch: switchAccount, onAccountSave: saveAccountProfile, onAccountDelete: deleteAccount, onAccountLoginNew: loginAnotherAccount } }); installLoginCapture(); refreshAccountUi(); initEnvWatch(); if (restoredAccountBackup) log('⚠️ 账号库上次没读出来,已用备份恢复;记录都在,建议重新登录确认一次'); else if (BWACC.tookMigration()) log('📦 账号库已搬到脚本管理器的存储里,站点清理页面数据不会再丢'); else if (BWACC.storageKind() !== 'gm') log('⚠️ 没拿到脚本管理器的存储权限,账号库只能存在页面里,站点清理数据时可能丢'); if (restoredResume) { const kept = AppData.get('resume') || {}; log(`💾 页面数据被站点清过,已从脚本管理器找回上次学到的位置:${courseLabel(kept.title)} ${fmtClock(kept.pos)}`); } applyUpdateState(); setTimeout(() => refreshStudyHours(), 1200); BWUTL.loop(refreshStudyHours, false, STUDY_HOURS_INTERVAL); BWUTL.loop(() => refreshAllCourseLists('定时检查'), false, COURSE_REFRESH_INTERVAL); BWUTL.loop(loop_2s, true, 2000); BWUTL.loop(loop_20s, true, SCORE_POLL_INTERVAL); loadHeartInterval(); log(`🚀 ${GM_info.script.name} v${GM_info.script.version} 启动成功`); setTimeout(() => checkUpdate(true), 3000); BWUTL.loop(() => checkUpdate(true), false, UPDATE_CHECK_INTERVAL); }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', bootstrap); } else { bootstrap(); } })();