// ==UserScript==
// @name 宝武学习助手
// @namespace http://tampermonkey.net/
// @version 2.4.31
// @description 一键自动学完公开课与专区课:自动静音、播放、切下一节,学满时长自动跳下一门;视频课、音频课都支持;面板实时显示每门课的进度、成绩与总学时,课程列表上直接标出成绩、学习与考试分、学习时长和是否必须考试;多账号一键切换,登录过期自动补登,断线后接着原来的进度学;一轮学完或需要你处理时弹桌面通知;同一账号开多个学习页只让一页真正在跑
// @author jinxhcn
// @match *://learn.baowugroup.com/*
// @icon https://learn.baowugroup.com/favicon.png
// @grant GM_info
// @grant GM_notification
// @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`,
publicCatalog: `${BASE_URL}/onlineClassCourse/pcStuCenterHomeOpenCoursePage`,
zoneList: `${BASE_URL}/student/myClassPage`,
zoneCatalog: `${BASE_URL}/onlineClass/pcStuCenterHomeZonePage`,
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 fetchZoneCatalog = async (centerCode = 'C001') => {
try {
const result = await post(API.zoneCatalog, {
current: 1,
size: 100,
data: { centerCode },
});
if (!result.isSuccess) return null;
return (result.data?.records || [])
.filter((r) => r.olClassName && r.olClassNo)
.map((r) => ({
olClassNo: String(r.olClassNo),
olClassName: String(r.olClassName).trim(),
courseNum: Number(r.courseNum) || 0,
}));
} catch {
return null;
}
};
const fetchPublicCatalog = async (centerCode = 'C001') => {
try {
const result = await post(API.publicCatalog, {
current: 1,
size: 1000,
data: { centerCode, searchInfo: '', sortClass: '1', sortType: 'desc' },
});
if (!result.isSuccess) return null;
return (result.data?.records || [])
.filter((r) => r.courseName && r.courseNo && r.olClassNo)
.map((r) => ({
centerCode: r.centerCode || centerCode,
courseNo: r.courseNo,
olClassNo: r.olClassNo,
courseName: r.courseName,
}));
} catch {
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 = (code) => (data.details || []).find((x) => x.attributeCode === code);
const points = (d) => {
const full = Number(d && d.percentage) || 0;
const pred = Number(d && d.predValue) || 0;
const fin = Number(d && d.finishValue) || 0;
if (!(full > 0)) return { full: 0, got: 0, has: false };
const ratio = pred > 0 ? Math.max(0, Math.min(1, fin / pred)) : 0;
return { full, got: Math.round(full * ratio), has: true };
};
const learn = detail('CE002');
const exam = detail('CE001');
const learnPts = points(learn);
const examPts = points(exam);
return {
totalScore: data.totalScore ?? null,
passScore: data.passScore ?? null,
learnScore: data.learnScore ?? null,
requiredDuration: learn ? learn.predValue : null,
completedDuration: learn ? learn.finishValue : null,
learnFull: learnPts.full,
learnGot: learnPts.got,
examFull: examPts.full,
examGot: examPts.got,
hasExam: examPts.has,
};
};
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,
fetchPublicCatalog,
fetchZoneList,
fetchZoneCatalog,
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 PANEL_EDGE = 20;
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 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 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 = 3;
const LOG_DAY_MAX = 2400;
const LOG_DOM_MAX = 1200;
const LOG_MERGE_MS = 10 * 1000;
const LOG_FLUSH_MS = 5000;
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 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';
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 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: `${PANEL_EDGE}px`, right: `${PANEL_EDGE}px`,
left: 'auto', top: 'auto',
width: PANEL_WIDTH, maxWidth: `calc(100vw - ${PANEL_EDGE * 2}px)`,
maxHeight: `calc(100vh - ${PANEL_EDGE * 2}px)`,
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'
});
buildTitleBar();
buildAccountPage();
buildCollapseView();
buildOverview();
buildTabBar();
buildBody();
buildLogDrawer();
buildFooter();
document.body.appendChild(panel);
bindPanelEvents();
renderTabs();
renderOverview();
renderCollapseView();
renderUpdateBtn();
syncLayout();
};
const toggle = () => {
collapsed = !collapsed;
if (collapsed && accountPage && accountPage.style.display !== 'none') closeAccountPage();
syncLayout();
};
const buildTitleBar = () => {
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: 'default', 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' });
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(updateBtn);
iconGroup.appendChild(themeBtn);
iconGroup.appendChild(logBtn);
iconGroup.appendChild(minBtn);
titleBar.appendChild(iconGroup);
panel.appendChild(titleBar);
};
const buildAccountPage = () => {
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);
};
const buildCollapseView = () => {
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);
};
const buildOverview = () => {
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);
};
const buildTabBar = () => {
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);
};
const buildBody = () => {
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);
};
const buildLogDrawer = () => {
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', gap: '8px',
height: '30px', padding: '0 8px 0 12px', boxSizing: 'border-box',
borderBottom: '1px solid var(--bw-border)',
fontSize: '11px', letterSpacing: '.5px', color: 'var(--bw-dim)', flex: 'none'
});
const logTitle = document.createElement('span');
logTitle.textContent = '日志';
logHead.appendChild(logTitle);
const closeLog = document.createElement('button');
closeLog.type = 'button';
closeLog.title = '收起日志';
closeLog.innerHTML = ``;
style(closeLog, {
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
width: '24px', height: '24px', padding: '0', marginLeft: 'auto', flex: 'none',
border: 'none', borderRadius: '6px', background: 'transparent',
color: 'var(--bw-muted)', cursor: 'pointer', transition: 'background .12s ease,color .12s ease'
});
closeLog.addEventListener('mouseenter', () => { closeLog.style.background = 'var(--bw-hover)'; closeLog.style.color = 'var(--bw-text)'; });
closeLog.addEventListener('mouseleave', () => { closeLog.style.background = 'transparent'; closeLog.style.color = 'var(--bw-muted)'; });
closeLog.addEventListener('mousedown', (e) => e.preventDefault());
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();
};
const buildFooter = () => {
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);
};
const bindPanelEvents = () => {
if (typeof globalScope.addEventListener === 'function') globalScope.addEventListener('pagehide', flushLogs);
if (typeof document.addEventListener === 'function') {
document.addEventListener('visibilitychange', () => { if (document.hidden) flushLogs(); });
}
applyTheme();
};
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();
},
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();
}
};
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 },
autoStudy: { at: 0, guid: '', title: '', tab: '', zone: '' },
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 autoStudyAlive = () => {
const ticket = AppData.get('autoStudy') || {};
return Number(ticket.at || 0) > 0;
};
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 && !autoStudyAlive()) {
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 && !autoStudyAlive() && (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 (!isTabActive()) {
BWGUI.updateStatus('另一页在跑', 'muted');
return;
}
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 (!isTabActive()) {
BWGUI.setActionBar({ main: { text: '在本页接管', tone: 'muted' } });
return;
}
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, isTabActive(),
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 () => {
tabLockTakeover();
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 } });
clearAutoStudy();
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}`);
markAutoStudy(first, { tab, zone: scopeName || '' });
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 } });
clearAutoStudy();
lastTableSignature = '';
lastUiSignature = '';
markListRefresh();
log('⏸️ 已停止自动学习,返回个人中心');
logTodaySummary();
location.assign('https://learn.baowugroup.com/#/userCenter');
};
const REBUILD_MAX = 2;
let rebuildTries = 0;
let lastRebuildAt = 0;
let rebuilding = false;
const maybeRebuildQueue = (state) => {
const plan = AppData.get('autoStudy') || {};
if (!plan.at || !plan.tab || rebuilding) return false;
if (Date.now() - Number(plan.at) > AUTO_STUDY_TTL) return false;
if (!state.isLogin || isLoginPage() || isStudyView(state)) return false;
if (!liveLogin().id) return false;
if ((AppData.get('toLearnList') || []).length) return false;
if (rebuildTries >= REBUILD_MAX) return false;
if (Date.now() - lastRebuildAt < 20000) return false;
const tab = plan.tab === 'zone' ? 'zone' : 'public';
const zoneName = String(plan.zone || '');
rebuildTries += 1;
lastRebuildAt = Date.now();
rebuilding = true;
(async () => {
try {
if (!hasData(tab)) {
log(`↩️ 待学列表已丢失,正在按上次的${TAB_NAME[tab]}重新加载…`);
if (!(await loadCourses(tab))) return;
}
let scope = null;
if (tab === 'zone' && zoneName) {
const zones = AppData.get('zone') || [];
const hit = zones.findIndex(z => String(z.olClassName || '') === zoneName);
if (hit >= 0) scope = hit;
}
const queue = buildQueue(tab, scope);
if (!queue.length) {
log(`🎉 已按上次的${TAB_NAME[tab]}重新检查,没有待学课程`);
clearAutoStudy();
return;
}
const first = queue.find(c => String(c.courseGuid) === String(plan.guid)) || queue[0];
if (!first.centerCode || !first.courseGuid) {
log('⚠️ 重建待学列表时发现课程信息不完整,已暂停(请点击右上角刷新)');
return;
}
AppData.save({ toLearnList: queue, state: { isAutoLearning: true } });
zoneView = scope;
markAutoStudy(first, { tab, zone: scope == null ? '' : zoneName });
log(`↩️ 待学列表已丢失,按上次的${TAB_NAME[tab]}${scope == null ? '' : `「${zoneName}」`}重建 ${queue.length} 门,继续学习:${first.courseName}`);
location.assign(`https://learn.baowugroup.com/#/courseStudy?centerCode=${first.centerCode}&guid=${first.courseGuid}`);
} finally {
rebuilding = false;
}
})();
return true;
};
const handleMainAction = async () => {
if (!isTabActive()) {
tabLockTakeover();
lastTableSignature = '';
lastUiSignature = '';
syncUi(AppData.get('state'));
return;
}
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 CARD_RULES = [
{ item: '.list-item', img: '.list-img', title: '.list-title' },
{ item: '.study-card', img: '.card-img-wrap', title: '.card-title' },
{ item: '.content-item', img: '.content-img', title: '.content-name' },
{ item: '.public-course-main', img: '.main-img', title: '.main-title .text-auto-nowrap' },
{ item: '.side-card', img: '.side-img', title: '.side-title .text-auto-nowrap' }
];
const BADGE_SCAN_MS = 2500;
const CATALOG_TTL = 10 * 60 * 1000;
const SCORE_TTL = 10 * 60 * 1000;
const FETCH_MAX = 4;
const idByName = new Map();
const scoreByName = new Map();
const zoneCatalog = new Map();
const fetching = new Set();
let catalogAt = 0;
let catalogLoading = false;
let zoneCatalogAt = 0;
let zoneCatalogLoading = false;
let zoneCoursesAt = 0;
let zoneCoursesLoading = false;
let zoneCoursesGuid = '';
let inflight = 0;
const nameOf = (v) => String(v || '').trim();
const courseIndex = () => {
const map = new Map();
const put = (c) => {
const name = nameOf(c && c.courseName);
if (!name || map.has(name)) return;
map.set(name, c);
if (c.courseNo && c.olClassNo) idByName.set(name, c);
};
(AppData.get('publicCourses') || []).forEach(put);
(AppData.get('zone') || []).forEach((z) => (z.zoneCourses || []).forEach(put));
return map;
};
const fmtMin = (v) => String(Math.round(Number(v) || 0));
const fmtDur = (v) => {
const m = Math.round(Number(v) || 0);
if (m <= 0) return '0 分';
if (m < 60) return `${m} 分`;
const h = Math.floor(m / 60);
const r = m % 60;
return r ? `${h} 小时 ${r} 分` : `${h} 小时`;
};
const scoreDone = (score) => {
if (!score) return false;
const done = Number(score.learnScore) || 0;
const pass = Number(score.passScore) || 0;
const used = Number(score.completedDuration) || 0;
const need = Number(score.requiredDuration) || 0;
return (pass > 0 && done >= pass) || (need > 0 && used >= need);
};
const badgeOf = (course, scoreOverride) => {
const score = scoreOverride || (course && course.score);
if (!score) return null;
const done = Number(score.learnScore) || 0;
const pass = Number(score.passScore) || 0;
const used = Number(score.completedDuration) || 0;
const need = Number(score.requiredDuration) || 0;
const learnFull = Number(score.learnFull) || 0;
const examFull = Number(score.examFull) || 0;
const finished = scoreDone(score);
const started = used > 0 || done > 0 || Number(course && course.learnStatus) === 1;
const state = finished ? '已完成' : started ? '进行中' : '未学习';
const tone = finished ? 'ok' : started ? 'run' : 'idle';
const examTag = pass > 0 && learnFull > 0
? (examFull > 0 ? (learnFull >= pass ? 'none' : 'must') : 'absent')
: '';
const split = learnFull > 0 || examFull > 0;
const line1 = `成绩 ${fmtMin(done)} / 及格 ${fmtMin(pass)}`;
const line2 = split
? `学习 ${fmtMin(score.learnGot)}/${fmtMin(learnFull)} · 考试 ${examFull > 0 ? `${fmtMin(score.examGot)}/${fmtMin(examFull)}` : '无'}`
: `已学 ${fmtMin(used)}/${fmtMin(need)} 分钟`;
const line3 = need > 0 ? `时长:${fmtDur(used)} / ${fmtDur(need)}` : '';
return {
tone, state, line1, line2, line3, examTag,
title: `${state} · ${line1} · ${line2}${line3 ? ` · ${line3}` : ''}`
};
};
const badgeIdle = () => ({ tone: 'idle', state: '未学习', line1: '成绩 — / 及格 —', line2: '正在读取…', line3: '', examTag: '', title: '这门课还没有学习记录' });
const zoneIndex = () => {
const map = new Map();
(AppData.get('zone') || []).forEach((z) => {
const name = nameOf(z.olClassName);
const list = (z.zoneCourses || []).filter((c) => c && c.courseName);
if (!name || !list.length || map.has(name)) return;
let needMin = 0;
let usedMin = 0;
list.forEach((c) => {
needMin += Number(c.score && c.score.requiredDuration) || 0;
usedMin += Number(c.score && c.score.completedDuration) || 0;
});
map.set(name, {
total: list.length,
done: list.filter((c) => scoreDone(c.score)).length,
needMin,
usedMin
});
});
return map;
};
const badgeOfZone = (zone) => {
const total = Number(zone.total) || 0;
const done = Number(zone.done) || 0;
if (!total) return null;
const tone = done >= total ? 'ok' : done > 0 ? 'run' : 'idle';
return {
tone,
state: done >= total ? '已完成' : done > 0 ? '进行中' : '未学习',
line1: `${done} / ${total} 门`,
line2: done >= total ? '该专区已学完' : `还剩 ${total - done} 门`,
line3: Math.round(Number(zone.needMin) || 0) > 0
? `时长:${fmtDur(zone.usedMin)} / ${fmtDur(zone.needMin)}`
: '',
examTag: '',
title: `该专区已完成 ${done} / ${total} 门`
};
};
const TONE_BAR = {
ok: '#34d399',
run: '#fbbf24',
idle: '#60a5fa'
};
const BADGE_BG = 'rgba(9,14,26,.84)';
const BADGE_FG = '#f8fafc';
const BADGE_DIM = 'rgba(248,250,252,.8)';
const BADGE_FAINT = 'rgba(248,250,252,.58)';
const EXAM_TAGS = {
absent: { text: '无考试', solid: false },
none: { text: '无需考试', solid: false },
must: { text: '必须考试', solid: true }
};
const BADGE_STYLE = {
position: 'absolute', top: '7px', left: '7px', zIndex: '5',
display: 'flex', alignItems: 'stretch', gap: '8px',
padding: '7px 9px', borderRadius: '6px',
background: BADGE_BG, color: BADGE_FG,
backdropFilter: 'blur(6px)', webkitBackdropFilter: 'blur(6px)',
boxShadow: '0 2px 10px rgba(3,8,18,.28)',
border: 'none', textShadow: 'none',
pointerEvents: 'none', userSelect: 'none', whiteSpace: 'nowrap',
fontVariantNumeric: 'tabular-nums'
};
const paintBadge = (item, info, rule) => {
const box = item.querySelector(rule.img);
if (!box) return false;
const host = box.tagName === 'IMG' ? (box.parentElement || box) : box;
const sig = `${info.tone}|${info.state}|${info.line1}|${info.line2}|${info.line3 || ''}|${info.examTag || ''}`;
let el = host.querySelector('.bw-course-badge');
if (el && el.dataset.sig === sig) return true;
if (!el) {
const cs = getComputedStyle(host);
if (cs.position === 'static') host.style.position = 'relative';
el = document.createElement('div');
el.className = 'bw-course-badge';
host.appendChild(el);
}
const bar = TONE_BAR[info.tone] || TONE_BAR.idle;
const tight = (host.getBoundingClientRect().width || 0) < 240;
const s1 = tight ? 11.5 : 13;
const s2 = tight ? 10 : 11.5;
Object.assign(el.style, BADGE_STYLE, {
padding: tight ? '5px 8px' : '7px 9px',
gap: tight ? '6px' : '8px'
});
el.title = info.title;
const tag = EXAM_TAGS[info.examTag];
const tagHtml = tag
? (tag.solid
? `${tag.text}`
: `${tag.text}`)
: '';
el.innerHTML = ``
+ ``
+ `${info.state}`
+ `${info.line1}`
+ `${tagHtml}${info.line2}`
+ (info.line3
? `${info.line3}`
: '')
+ ``;
el.dataset.sig = sig;
return true;
};
const pageCenterCode = () => {
try {
const p = parseHashParams(location.hash);
return p.centerCode || 'C001';
} catch { return 'C001'; }
};
const ensureCatalog = () => {
if (catalogLoading || Date.now() - catalogAt < CATALOG_TTL) return;
catalogLoading = true;
Promise.resolve()
.then(() => BWAPI.fetchPublicCatalog(pageCenterCode()))
.then((list) => {
if (!list) return;
list.forEach((c) => {
const name = nameOf(c.courseName);
if (name && !idByName.has(name)) idByName.set(name, c);
});
catalogAt = Date.now();
})
.catch(() => { })
.then(() => { catalogLoading = false; });
};
const ensureZoneCatalog = () => {
if (zoneCatalogLoading || Date.now() - zoneCatalogAt < CATALOG_TTL) return;
zoneCatalogLoading = true;
Promise.resolve()
.then(() => BWAPI.fetchZoneCatalog(pageCenterCode()))
.then((list) => {
if (!list) return;
list.forEach((z) => {
const name = nameOf(z.olClassName);
if (name && !zoneCatalog.has(name)) zoneCatalog.set(name, z);
});
zoneCatalogAt = Date.now();
})
.catch(() => { })
.then(() => { zoneCatalogLoading = false; });
};
const ensureZoneCourses = () => {
const guid = pageZoneGuid();
if (!guid) return;
if (zoneCoursesLoading || (guid === zoneCoursesGuid && Date.now() - zoneCoursesAt < CATALOG_TTL)) return;
zoneCoursesLoading = true;
Promise.resolve()
.then(() => BWAPI.fetchZoneCoursesDetail(pageCenterCode(), guid, 'ZE0'))
.then((list) => {
if (!list || !list.length) return;
zoneCoursesGuid = guid;
zoneCoursesAt = Date.now();
list.forEach((c) => {
const name = nameOf(c.courseName);
if (name && !idByName.has(name) && c.courseNo && c.olClassNo) idByName.set(name, c);
});
})
.catch(() => { })
.then(() => { zoneCoursesLoading = false; });
};
const pageZoneGuid = () => {
try { return String(parseHashParams(location.hash).guid || ''); } catch { return ''; }
};
const queueScore = (name) => {
const id = idByName.get(name);
if (!id || fetching.has(name) || inflight >= FETCH_MAX) return;
const hit = scoreByName.get(name);
if (hit && Date.now() - hit.at < SCORE_TTL) return;
fetching.add(name);
inflight += 1;
Promise.resolve()
.then(() => BWAPI.fetchCourseScore(id.centerCode, id.courseNo, id.olClassNo))
.then((score) => { if (score) scoreByName.set(name, { score, at: Date.now() }); })
.catch(() => { })
.then(() => { fetching.delete(name); inflight -= 1; });
};
const cachedScore = (name) => {
const hit = scoreByName.get(name);
return hit && Date.now() - hit.at < SCORE_TTL ? hit.score : null;
};
const refreshCourseBadges = () => {
const index = courseIndex();
const zones = zoneIndex();
if (!index.size && !zones.size) return 0;
let painted = 0;
let unknown = 0;
CARD_RULES.forEach((rule) => {
document.querySelectorAll(rule.item).forEach((item) => {
const titleEl = item.querySelector(rule.title);
if (!titleEl) return;
const name = nameOf(titleEl.textContent);
if (!name) return;
if (index.has(name)) {
const course = index.get(name);
const score = course.score || cachedScore(name);
if (score) {
if (paintBadge(item, badgeOf(course, score), rule)) painted += 1;
} else {
if (paintBadge(item, badgeIdle(), rule)) painted += 1;
queueScore(name);
}
return;
}
if (zones.has(name)) {
const info = badgeOfZone(zones.get(name));
if (info && paintBadge(item, info, rule)) painted += 1;
return;
}
if (zoneCatalog.has(name)) {
const z = zoneCatalog.get(name);
const info = badgeOfZone({ done: 0, total: z.courseNum });
if (info && paintBadge(item, info, rule)) painted += 1;
return;
}
const score = cachedScore(name);
if (score) {
if (paintBadge(item, badgeOf(null, score), rule)) painted += 1;
return;
}
unknown += 1;
queueScore(name);
});
});
if (unknown) {
ensureCatalog();
ensureZoneCourses();
ensureZoneCatalog();
}
return painted;
};
const initCourseBadge = () => {
let timer = 0;
const later = () => {
if (timer) return;
timer = setTimeout(() => { timer = 0; refreshCourseBadges(); }, 600);
};
if (typeof MutationObserver === 'function' && document.body) {
try {
new MutationObserver(later).observe(document.body, { childList: true, subtree: true });
} catch (e) { }
}
BWUTL.loop(() => refreshCourseBadges(), false, BADGE_SCAN_MS);
};
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();
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_REMIND = 60 * 60 * 1000;
const playStall = { guid: '', since: 0, saidAt: 0 };
const resetPlayStall = () => {
playStall.guid = '';
playStall.since = 0;
playStall.saidAt = 0;
btnClickMiss.count = 0;
};
const trackPlayStall = () => {
const guid = String(getCurrentCourseGuid() || '');
if (playStall.guid !== guid) {
playStall.guid = guid;
playStall.since = Date.now();
playStall.saidAt = 0;
return;
}
if (!playStall.since) playStall.since = Date.now();
if (Date.now() - playStall.since < PLAY_STALL_LIMIT) return;
const first = !playStall.saidAt;
if (!first && Date.now() - playStall.saidAt < PLAY_STALL_REMIND) return;
playStall.saidAt = Date.now();
const list = AppData.get('toLearnList') || [];
const cur = list.find(c => String(c.courseGuid) === guid);
const name = cur ? cur.courseName : '当前课程';
if (!first) {
log(`⏳ 《${name}》仍未开始播放,继续等待(不跳过该课程)`);
return;
}
log(`⏳ 《${name}》已连续 5 分钟未开始播放,继续等待、不跳过该课程。可手动点击播放按钮,或在 edge://settings/content/mediaAutoplay 将自动播放设为「允许」`);
};
const noMedia = { guid: '', since: 0, saidAt: 0 };
const trackNoMedia = () => {
const guid = String(getCurrentCourseGuid() || '');
if (noMedia.guid !== guid) {
noMedia.guid = guid;
noMedia.since = Date.now();
noMedia.saidAt = 0;
return;
}
if (!noMedia.since) noMedia.since = Date.now();
if (Date.now() - noMedia.since < PLAY_STALL_LIMIT) return;
const first = !noMedia.saidAt;
if (!first && Date.now() - noMedia.saidAt < PLAY_STALL_REMIND) return;
noMedia.saidAt = Date.now();
const list = AppData.get('toLearnList') || [];
const cur = list.find(c => String(c.courseGuid) === guid);
const name = cur ? cur.courseName : '当前课程';
if (!first) {
log(`⏳ 《${name}》播放器仍未出现,继续等待(不跳过该课程)`);
return;
}
log(`⏳ 《${name}》播放器一直未出现(页面可能未加载完成),继续等待、不跳过该课程。可刷新页面重试`);
};
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 {
tabLockBeat();
const active = isTabActive();
if (active) watchAccountChange();
refreshAccountUi();
if (active) maybeArmResume(BWACC.load());
syncLoginPageUi();
if (active) {
maybeFillSmsLogin();
maybeSubmitSmsCode();
tryAutoLogin();
}
let media = getMediaElement();
const state = active
? updateAppDataState(media)
: {
...AppData.get('state'),
isVideoPage: !!media,
isVideoMuted: media ? !!media.muted : false,
isVideoPlaying: media ? !media.paused : false
};
updateLearningStatusDisplay(state);
syncUi(state);
if (!active) {
renderTable();
updateVideoCard(state);
return;
}
applyResumeSeek(media);
trackResumePoint(state, media);
applyServerSeek(media).catch(() => { });
if (maybeResumeLearning(state)) return;
if (maybeResumeStudyQueue(state)) return;
if (maybeRebuildQueue(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 && document.querySelector('#xg-video, #previewFrame')) trackNoMedia();
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('⚠️ 播放未能自动开始(可能被浏览器拦截),继续等待、不跳过该课程');
}
trackPlayStall();
} else if (media && !media.paused && playStall.guid) {
resetPlayStall();
}
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 completionHandled = { guid: '', at: 0 };
const isDuplicateCompletion = (guid) => {
const key = String(guid || '');
if (!key) return false;
if (completionHandled.guid === key && Date.now() - completionHandled.at < 60000) return true;
completionHandled.guid = key;
completionHandled.at = Date.now();
return false;
};
const handleCourseCompletion = (completedCourse, toLearnList, isAutoLearning) => {
if (isDuplicateCompletion(completedCourse.courseGuid)) return;
const courseType = completedCourse.courseType || '单课程';
patchCourseScore(completedCourse.courseGuid, completedCourse.score);
bumpToday(completedCourse.score?.requiredDuration);
const queueRun = isAutoLearning || autoStudyAlive();
if (!queueRun) {
log('🏁 单课程学习完成,返回个人中心');
notify('这门课学完了', `《${completedCourse.courseName}》已学完,进度和成绩已经记到平台上`, `done:${completedCourse.courseGuid}`);
clearAutoStudy();
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}`);
markAutoStudy(next);
location.assign(`https://learn.baowugroup.com/#/courseStudy?centerCode=${next.centerCode}&guid=${next.courseGuid}`);
} else if (autoStudyAlive() && courseType === '单课程') {
log('⚠️ 待学列表中未找到本轮其他课程,可能是网站刷新时清除;返回列表页重新构建');
logTodaySummary();
markListRefresh();
location.assign('https://learn.baowugroup.com/#/userCenter');
} else {
log('🎉 所有课程学习完成,返回个人中心');
clearAutoStudy();
logTodaySummary();
notifyAllDone('这一轮已经全部学完,面板停在个人中心,可以回来看一眼成绩了');
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 && !autoStudyAlive()) {
log('⏸️ 已停止自动重播,请手动检查该课程(可能是考试未通过)');
notifyNeedHand(`《${skipped.courseName}》自动重播 ${MAX_REPLAY} 次仍未通过,请手动检查(可能是考试没过)`);
clearAutoStudy();
return;
}
if (remaining.length > 0) {
const next = remaining[0];
log(`➡️ 跳过该课程,继续学习:${next.courseName}`);
markAutoStudy(next);
location.assign(`https://learn.baowugroup.com/#/courseStudy?centerCode=${next.centerCode}&guid=${next.courseGuid}`);
} else {
log('🎉 待学课程已全部处理,返回个人中心');
clearAutoStudy();
logTodaySummary();
notifyAllDone('待学队列已经跑完(学完 + 跳过),回来看看有没有需要重学的');
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 = 3 * 60 * 1000;
let lastScoreLogAt = 0;
const SCORE_FORCE_INTERVAL = 60 * 1000;
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_FORCE_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 });
if (Date.now() - lastScoreLogAt >= SCORE_LOG_INTERVAL) 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(`⚠️ 成绩获取失败:${readableError(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;
const prev = outlines.get(key);
outlines.set(key, { at: Date.now(), sections });
const done = sections.filter((s) => s.learned).length;
const prevDone = prev ? prev.sections.filter((s) => s.learned).length : -1;
if (prevDone !== done) 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 AUTO_STUDY_TTL = 24 * 60 * 60 * 1000;
const AUTO_STUDY_RETRY = 3;
let autoStudyJumps = 0;
let lastAutoJumpAt = 0;
const emptyAutoStudy = () => ({ at: 0, guid: '', title: '', tab: '', zone: '' });
const clearAutoStudy = () => AppData.save({ autoStudy: emptyAutoStudy() });
const markAutoStudy = (course, intent) => {
if (!course || !course.courseGuid) return clearAutoStudy();
const old = AppData.get('autoStudy') || {};
const tab = (intent && intent.tab) || old.tab || '';
const zone = intent && 'zone' in intent ? String(intent.zone || '') : String(old.zone || '');
AppData.save({
autoStudy: { at: Date.now(), guid: String(course.courseGuid), title: course.courseName || '', tab, zone }
});
};
const maybeResumeStudyQueue = (state) => {
const plan = AppData.get('autoStudy') || {};
if (!plan.at) return false;
if (Date.now() - Number(plan.at) > AUTO_STUDY_TTL) {
clearAutoStudy();
return false;
}
if (!state.isLogin || isLoginPage() || isStudyView(state)) return false;
if (!liveLogin().id) return false;
const pending = (AppData.get('toLearnList') || []).filter((c) => !isCourseFinished(c.score));
if (!pending.length) {
if (!plan.tab) clearAutoStudy();
return false;
}
const next = pending.find((c) => String(c.courseGuid) === String(plan.guid)) || pending[0];
if (!next.centerCode || !next.courseGuid) {
log('⚠️ 待学课程信息不完整,已停止自动学习(请点击右上角刷新后重新开始)');
clearAutoStudy();
return false;
}
if (Date.now() - lastAutoJumpAt < 15000) return false;
if (autoStudyJumps >= AUTO_STUDY_RETRY) {
log('⚠️ 课程页多次打开失败,已停止自动学习;再次点击「开始学习」即可重新开始');
clearAutoStudy();
return false;
}
autoStudyJumps += 1;
lastAutoJumpAt = Date.now();
log(`↩️ 页面已重新加载,继续学习:${next.courseName}`);
AppData.save({
state: { isAutoLearning: true },
autoStudy: {
at: Date.now(), guid: String(next.courseGuid), title: next.courseName || '',
tab: plan.tab || '', zone: plan.zone || ''
}
});
location.assign(`https://learn.baowugroup.com/#/courseStudy?centerCode=${next.centerCode}&guid=${next.courseGuid}`);
return true;
};
const NOTIFY_SAME_GAP = 10 * 60 * 1000;
const NOTIFY_ANY_GAP = 30 * 1000;
const NOTIFY_URL = 'https://learn.baowugroup.com/#/userCenter';
const NOTIFY_ICON = 'https://learn.baowugroup.com/favicon.png';
const notifyGate = { key: '', at: 0, anyAt: 0 };
const notifySupported = () => typeof GM_notification === 'function';
const resetNotifyGate = () => {
notifyGate.key = '';
notifyGate.at = 0;
notifyGate.anyAt = 0;
};
const notifyNow = (title, text, opts = {}) => {
if (!notifySupported()) return false;
try {
const ret = GM_notification({
title: `宝武学习助手 · ${title}`,
text: String(text || ''),
image: NOTIFY_ICON,
tag: opts.tag || 'bw-learn',
url: opts.url || NOTIFY_URL
});
log(`🔔 桌面通知:${title}`);
if (ret && typeof ret.then === 'function') {
ret.then((ok) => {
if (ok === false) log('⚠️ 系统未显示通知:请检查 Windows「通知」设置中 Microsoft Edge 是否已关闭(或专注助手是否在静音)');
}).catch((error) => {
log(`⚠️ 桌面通知发送失败:${readableError(error)}`);
});
}
return true;
} catch (error) {
log(`⚠️ 桌面通知发送失败:${readableError(error)}`);
return false;
}
};
const notify = (title, text, key) => {
const now = Date.now();
const k = String(key || title || '');
if (notifyGate.key === k && now - notifyGate.at < NOTIFY_SAME_GAP) return false;
if (now - notifyGate.anyAt < NOTIFY_ANY_GAP) return false;
notifyGate.key = k;
notifyGate.at = now;
notifyGate.anyAt = now;
return notifyNow(title, text, { tag: k });
};
const notifyAllDone = (text) => notify('课程全部学完', text, 'alldone');
const notifyNeedHand = (text) => notify('需要你处理一下', text, 'hand');
const TAB_LOCK_KEY = 'bw_learn_tab_lock';
const TAB_LOCK_BEAT = 5 * 1000;
const TAB_LOCK_TTL = 30 * 1000;
const tabLock = { id: '', own: true, beatAt: 0, peer: '' };
const tabLockRead = () => {
try {
const raw = localStorage.getItem(TAB_LOCK_KEY);
if (!raw) return null;
const got = JSON.parse(raw);
return got && got.id ? got : null;
} catch { return null; }
};
const tabLockFresh = (got) => !!got && Date.now() - Number(got.at || 0) < TAB_LOCK_TTL;
const tabLockWrite = () => {
try {
localStorage.setItem(TAB_LOCK_KEY, JSON.stringify({ id: tabLock.id, at: Date.now() }));
return true;
} catch { return false; }
};
const tabLockClear = () => {
try {
const got = tabLockRead();
if (got && got.id === tabLock.id) localStorage.removeItem(TAB_LOCK_KEY);
} catch { }
};
const isTabActive = () => tabLock.own;
const tabLockPeer = () => tabLock.peer;
const tabLockClaim = (why) => {
tabLock.own = true;
tabLock.peer = '';
tabLock.beatAt = Date.now();
if (!tabLockWrite()) return false;
if (why) log(why);
return true;
};
const tabLockInit = () => {
tabLock.id = `t${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
const got = tabLockRead();
if (tabLockFresh(got) && String(got.id) !== tabLock.id) {
tabLock.own = false;
tabLock.peer = String(got.id);
log('👀 其他标签页正在运行学习任务,本页仅显示、不执行:点击底部「在本页接管」可切换过来');
} else {
tabLockClaim('');
}
if (typeof window.addEventListener !== 'function') return;
window.addEventListener('storage', (e) => {
if (e.key !== TAB_LOCK_KEY) return;
const now = tabLockRead();
if (tabLockFresh(now) && String(now.id) !== tabLock.id) {
if (tabLock.own) log('👀 其他标签页已接管学习任务,本页转为仅显示');
tabLock.own = false;
tabLock.peer = String(now.id);
return;
}
if (!tabLock.own) tabLockClaim('🙋 原来那个标签页已经不在了,本页接着跑');
});
window.addEventListener('pagehide', tabLockRelease);
};
const tabLockBeat = () => {
if (!tabLock.id) return;
const now = Date.now();
if (now - tabLock.beatAt < TAB_LOCK_BEAT) return;
tabLock.beatAt = now;
const got = tabLockRead();
const mine = !got || String(got.id) === tabLock.id;
if (tabLock.own) {
if (!mine && tabLockFresh(got)) {
tabLock.own = false;
tabLock.peer = String(got.id);
log('👀 本页挂起期间其他标签页已接管学习任务,本页恢复为仅显示');
return;
}
tabLockWrite();
return;
}
if (!mine && tabLockFresh(got)) return;
tabLockClaim('🙋 原来那个标签页已经不在了,本页接着跑');
};
const tabLockTakeover = () => {
if (tabLock.own) return true;
return tabLockClaim('🙋 已在本页接管学习,原来那个标签页会自己变成只读');
};
const tabLockRelease = () => {
if (!tabLock.own) return;
tabLock.own = false;
tabLockClear();
};
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();
clearAutoStudy();
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();
clearAutoStudy();
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();
clearAutoStudy();
}
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();
clearAutoStudy();
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();
clearAutoStudy();
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();
clearAutoStudy();
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) {
const why = {
image: '图片未获取', tainted: '图片无法读取', blocks: '字符不完整',
empty: '未识别到内容', solve: '算式计算失败', distance: '置信度不足'
}[result.reason] || '置信度不足';
log(`🤖 验证码识别失败(${why}),更换验证码后重试`);
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,
onTheme: handleThemeChange,
onAccountSwitch: switchAccount,
onAccountSave: saveAccountProfile,
onAccountDelete: deleteAccount,
onAccountLoginNew: loginAnotherAccount
}
});
installLoginCapture();
refreshAccountUi();
initCourseBadge();
tabLockInit();
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();
}
})();