// ==UserScript== // @name 宝武学习助手 // @namespace http://tampermonkey.net/ // @version 2.2.57 // @description 1.自动获取公开课/专区课列表与成绩;2.多课程自动学习,自动静音、播放、下一节、跳下一门;3.实时显示学习进度与总学时;4.学完自动更新课程状态 // @author jinxhcn // @match *://learn.baowugroup.com/* // @icon https://learn.baowugroup.com/favicon.png // @require https://scriptcat.org/lib/7205/1.1.6/bw_learn_tool_api_lib.js?sha384-5KJB0ReHQHLJBGHqODyZkiI3elje4NoKgUIZrHdpGS1X4aKF67IXwe3TGQbzpRXy // @require https://scriptcat.org/lib/7206/1.2.16/bw_learn_tool_gui_lib.js?sha384-tiYs0iZAVhREHoZBFqcjM29v/FI+J0/uEjBqTlY8TIrhM3G2Ve+r5fczst1nwfOv // @require https://scriptcat.org/lib/7207/1.1.1/bw_learn_tool_utl_lib.js?sha384-qRmvECTY4fyJutJBvzZU7Gjm49cRp5wwFU1dFG0dBNCjFQ2xL+tPE0Vpe9B1gWuh // @grant GM_info // @grant GM_xmlhttpRequest // @grant unsafeWindow // @connect scriptcat.org // @connect 127.0.0.1 // @run-at document-idle // @license MIT // ==/UserScript== (function () { 'use strict'; const BWAPI = unsafeWindow.BWAPI; const BWGUI = unsafeWindow.BWGUI; const BWUTL = unsafeWindow.BWUTL; const log = (msg) => BWGUI.log(`[${new Date().toLocaleTimeString()}] ${msg}`); const DEFAULT_DATA = { url: { currentUrl: '', previousUrl: '' }, token: '', state: { isLogin: false, isAutoLearning: false, learningType: null, isVideoPage: false, isVideoMuted: false, isVideoPlaying: false }, publicCourses: [], zone: [], toLearnList: [], pendingListRefresh: false, theme: 'dark' }; const AppData = BWUTL.createDataStore('bw_learn_app_data', DEFAULT_DATA); 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 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 ? { previousUrl: oldUrl, currentUrl: newUrl } : null; }; const getTokenChange = (oldToken) => { const token = BWAPI.getToken(); return token !== oldToken ? token : null; }; const getVideoElement = () => document.querySelector('#xg-video video'); const isCourseRoute = () => location.href.includes('courseStudy?'); const isStudyView = (state) => state.isVideoPage || isCourseRoute(); const getStateChanges = (oldState, video) => { const changes = {}; const isLogin = !location.href.includes('auth/login'); if (oldState.isLogin !== isLogin) { changes.isLogin = isLogin; log(`🔐 登录状态:${isLogin ? '已登录' : '未登录'}`); } const isVideoPage = !!video; const isVideoMuted = video?.muted ?? false; const isVideoPlaying = video ? !video.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 && 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 = (video) => { 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, video); 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 () => { try { const allCourses = await BWAPI.fetchPublicCourses(''); if (!allCourses) { log('❌ 公开课没加载出来:没收到数据(网络超时,或登录已失效),请点右上角刷新重试'); return false; } AppData.save({ publicCourses: await BWAPI.enrichCoursesWithScores(allCourses) }); return true; } catch (error) { log(`❌ 公开课没加载出来:${readableError(error)}`); return false; } }; const getZoneCoursesList = async () => { 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()); 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); }) .then(enriched => { zone.zoneCourses = enriched; }) .catch(err => { log(`⚠️ 专区「${zone.olClassName || zone.olClassNo}」的课程没加载出来:${readableError(err)}`); zone.zoneCourses = []; }) ) ); AppData.save({ zone: uniqueZones }); 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 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 = (video, guid) => { if (!video || String(guid) !== localWatch.guid) return; const t = Number(video.currentTime); if (!Number.isFinite(t)) return; if (localWatch.lastT != null && !video.paused) { const delta = t - localWatch.lastT; if (delta > 0 && delta <= 5) localWatch.seconds += delta; } localWatch.lastT = t; }; const localWatchedComp = (video, guid, serverComp) => { if (!video || String(guid) !== localWatch.guid) { localWatch.guid = String(guid); localWatch.seconds = 0; localWatch.baseline = serverComp; localWatch.lastT = video ? Number(video.currentTime) : null; return serverComp; } sampleLocalWatch(video, 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 video = getVideoElement(); const vDur = Number(video?.duration) || 0; const vPos = Number(video?.currentTime) || 0; const localComp = req > 0 ? localWatchedComp(video, 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 videoPct = vDur > 1 ? (vPos / vDur) * 100 : null; const percent = reached ? 100 : (videoPct != null ? Math.min(99, videoPct) : 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 || ''}`; if (signature === lastVideoSignature) return; lastVideoSignature = signature; const remainText = reached ? '已学够时长,正在确认成绩' : (comp - serverComp >= 0.5 && comp >= req - 0.05) ? '本集已播完,正在等系统记录' : (remain >= 1 ? `剩余约 ${fmtInt(remain)} 分钟` : '剩余不到 1 分钟'); BWGUI.showVideoCard({ title: course.courseName, percent, inner: `${Math.floor(comp)}/${fmtInt(req)} 分`, sub: `第 ${index + 1} / ${queue.length} 门 · ${remainText}`, 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); lastTableSignature = ''; renderTable({ force: true }); syncUi(AppData.get('state')); let ok = false; try { ok = tab === 'public' ? await getPublicCoursesList() : await getZoneCoursesList(); } catch (error) { log(`❌ ${TAB_NAME[tab]}加载出错:${readableError(error)}`); ok = false; } finally { loading[tab] = false; BWGUI.setRefreshing(false); lastTableSignature = ''; renderTable({ force: true }); syncUi(AppData.get('state')); } 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); }; 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 video = getVideoElement(); if (video && !video.paused) video.pause(); AppData.save({ state: { isAutoLearning: false } }); lastTableSignature = ''; lastUiSignature = ''; markListRefresh(); log('⏸️ 已停止自动学习,返回个人中心'); 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 playCurrentVideo = (video) => { if (!video || video.ended || !video.paused) return false; 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 (el?.offsetParent) { el.click(); log(`▶️ 点击${name}`); return true; } } video.play().catch(() => { }); log('▶️ 自动点击播放'); return 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 cleanupVideoOverlays = () => { document.querySelector('.xgplayer-start')?.classList.add('hide'); const overlay = document.querySelector('.video-overlay'); if (overlay) overlay.style.display = 'none'; }; 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 { let video = getVideoElement(); const state = updateAppDataState(video); updateLearningStatusDisplay(state); syncUi(state); maybeAutoLoad(state); maybeRefreshAfterLearning(state); renderTable(); updateVideoCard(state); if (state.isVideoPage) { ensureCurrentCourseInfo(); dismissTrainingPopup(); if (video && !video.isConnected) video = getVideoElement(); if (video && !state.isVideoMuted) { video.muted = true; log('🔇 视频已静音'); } if (video && !state.isVideoPlaying) { playCurrentVideo(video); } if (tryClickNextChapter()) return; if (video && !video.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); 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('🎉 所有课程学习完成,返回个人中心'); 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('🎉 待学课程已全部处理,返回个人中心'); 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 (!state.isVideoPage) 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 IS_BETA = /-beta$/.test(GM_info.script.version); const RELEASE_META_URL = 'https://scriptcat.org/api/v2/scripts/6740'; const RELEASE_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 BETA_URL = 'http://127.0.0.1:18081/bw_learn_tool.beta.user.js'; const CHECK_URL = IS_BETA ? BETA_URL : RELEASE_META_URL; const INSTALL_URL = IS_BETA ? BETA_URL : RELEASE_INSTALL_URL; const UPDATE_CHECK_INTERVAL = IS_BETA ? 10 * 60 * 1000 : 6 * 60 * 60 * 1000; const VER_RE = /^\s*\/\/\s*@version\s+(.+?)\s*$/m; 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 VER_RE.exec(text)?.[1] || 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 handleThemeChange = (name) => { AppData.save({ theme: name }); }; const bootstrap = () => { AppData.init(); BWUTL.fswn(); BWGUI.init({ scriptName: GM_info.script.name, tabs: TABS, theme: AppData.get('theme') || 'dark', callbacks: { onTab: handleTabChange, onRefresh: handleRefresh, onMain: handleMainAction, onAction: handleTableAction, onUpdate: doUpgrade, onTheme: handleThemeChange } }); 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); log(`🚀 ${GM_info.script.name} v${GM_info.script.version} 启动成功`); setTimeout(() => checkUpdate(true), 3000); BWUTL.loop(() => checkUpdate(true), false, UPDATE_CHECK_INTERVAL); if (IS_BETA) console.log(BWAPI.version, BWGUI.version, BWUTL.version); }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', bootstrap); } else { bootstrap(); } })();