feat: 每日积分模式与 Bark 完成提醒

- 按课时类型计分:文档 1 / 视频 3 / 音频 2 / 微课 2,每次 3 分,单日封顶 24 分;满额换类,无内容即停
- 积分计数落 localStorage,跨刷新/重启保留、跨天清零;面板与无头 TUI 都显示今日积分
- 运行器自己收尾时通过 Bark 推送今日积分、完成门数、用时和结束原因;手动停止与 --check 不推送
- 新增 --points-mode / --bark-* 参数及对应 YUN_XUE_TANG_* 环境变量
- 补充 points / notify 离线回归测试与 OpenSpec 配置

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
voidandClaude Sonnet 4.6 committed 2026-11-01 22:19:52 +08:00
1 parent 17217dbeb1
commit 0eb4c40629
31 files changed
+2954 -21

No files matched your search

+2
View File
@@ -29,7 +29,9 @@ export const LS_PENDING = 'yun-xue-tang-auto-start-after-login';
// ---- sessionStorage:本次进度 + 本次运行状态(换标签页/重启即作废) ----
export const SS_RUN_STATE = 'yun-xue-tang-run-state-v3';
export const SS_SHORT_CATALOG = 'yun-xue-tang-short-catalog-v1';
export const SS_POINTS_INVENTORY = 'yun-xue-tang-points-inventory-v1';
export const SHORT_CATALOG_TTL = 5 * 60 * 1000;
export const POINTS_INVENTORY_TTL = 5 * 60 * 1000;
// 旧版本把「进度 + 运行意图」整块塞进 localStorage,只用于一次性迁移(迁移后即删除)
export const LEGACY_LS_BATCH = 'yun-xue-tang-batch-v2';
+51 -2
View File
@@ -1,6 +1,8 @@
// ======== 课程页 ========
import { CFG, TAG } from './config.js';
import { R, S, saveRunState, PHASE_LEARNING } from './state.js';
import { R, S, state, points, saveRunState, PHASE_LEARNING } from './state.js';
import { detectLessonType, pointLabel } from './points.js';
import { pointsAfterLesson } from './list.js';
import { goToList, mediaPage } from './route.js';
import { courseIdFromUrl, norm, textOf, truncate, findVisibleClickable } from './utils.js';
import { later } from './lifecycle.js';
@@ -15,6 +17,40 @@ import {
import { examTick, examPhase } from './exam.js';
import { completeCurrent, failCurrent } from './complete.js';
// ---- 每日积分:把「课时完成」折算成一次任务 ----
// 类型在播放期间就按 lessonId 缓存下来:平台记账或自动切节后页面可能已经
// 跳到下一节,事后再读目录就不知道刚完成的是哪一类了。
function pointLessonId(key) {
const courseId = (S.activeCourse && S.activeCourse.id) || courseIdFromUrl() || '';
return courseId + '|' + (key || 'media');
}
function rememberLessonType(key) {
if (!state.pointsEnabled) return;
const li = lessonActiveLi();
const tagEl = li ? li.querySelector('.tag-type') : null;
const type = detectLessonType({
tag: tagEl ? textOf(tagEl) : '',
hash: location.hash,
});
if (!type) return;
R.lessonType = type;
R.lessonTypes[pointLessonId(key)] = type;
}
// 记一次课时完成;返回计入的类型(没计入/识别不出来返回 '')
function recordLessonPoint(key) {
if (!state.pointsEnabled) return '';
const id = pointLessonId(key);
const type = R.lessonTypes[id] || R.lessonType || detectLessonType({ hash: location.hash });
if (!type) return '';
if (!points.record(type, id)) return '';
const text = points.snapshot().text;
console.log(TAG, '积分 +3:' + pointLabel(type) + '(' + text + ')');
setStatus('积分 +3:' + pointLabel(type) + '(' + text + ')');
return type;
}
export function courseTick() {
R.listWithCurrentSince = 0;
if (!S.activeCourse) {
@@ -86,6 +122,8 @@ export function courseTick() {
if (!examPhase() && !isSummaryComplete() && enterPendingExamLesson()) return;
// 6) 整门课程是否已完成 / 平台是否刚记录了一节
// 先把当前课时的类型记下来,后面平台记账/课程完成时才知道该给哪一类计分。
rememberLessonType(readActiveLessonKey());
const summary = readSummary();
const prevSummaryX = R.lastSummary ? R.lastSummary.x : -1;
if (summary) {
@@ -95,6 +133,7 @@ export function courseTick() {
const confirmed = !!(R.lastSummary && R.lastSummary.complete);
R.lastSummary = summary;
if (confirmed) {
recordLessonPoint(R.waitLessonKey || R.lastLessonKey);
completeCurrent();
return;
}
@@ -108,6 +147,11 @@ export function courseTick() {
const curKey = readActiveLessonKey();
R.lastSummary = summary;
// 平台刚记录了一节 → 按这一节的类型计一次积分
const pointType = (!isMedia && summary.kind !== 'percent')
? recordLessonPoint(prevKey) : '';
if (pointType && pointsAfterLesson(pointType)) return;
// 单视频/音频页的百分比是播放进度,不是「一节学完」,不能据此切节
if (!isMedia && summary.kind !== 'percent' && (!prevKey || curKey === prevKey)) {
// 平台已记账但没有自动切节 → 脚本主动切下一节
@@ -209,6 +253,7 @@ export function courseTick() {
}
R.waitStart = 0;
R.lastProgressAt = Date.now();
recordLessonPoint(R.waitLessonKey || R.lastLessonKey);
completeCurrent();
return;
}
@@ -219,6 +264,8 @@ export function courseTick() {
R.lastLessonKey = newKey;
R.doneLatchKey = '';
R.lastProgressAt = Date.now();
const pointType = recordLessonPoint(R.waitLessonKey);
if (pointType && pointsAfterLesson(pointType)) return;
setStatus('已自动进入下一节');
return;
}
@@ -227,9 +274,10 @@ export function courseTick() {
if (!isMedia && s2 && s2.x > R.waitSummaryX) {
R.waitStart = 0;
R.lastProgressAt = Date.now();
const pointType = recordLessonPoint(R.waitLessonKey || R.lastLessonKey);
if (s2.complete) {
completeCurrent();
} else {
} else if (!pointType || !pointsAfterLesson(pointType)) {
advanceLesson();
}
return;
@@ -304,6 +352,7 @@ export function advanceLesson() {
const s = readSummary();
if (s && s.complete) {
recordLessonPoint(R.waitLessonKey || R.lastLessonKey);
completeCurrent();
} else {
setStatus('没有找到下一节,等待课程完成…');
+5 -2
View File
@@ -1,7 +1,7 @@
// ======== 主循环 ========
'use strict';
import { CFG, VERSION, TAG } from './config.js';
import { R, S, state, saveRunState, flushRunState, invalidateShortCatalog } from './state.js';
import { R, S, state, points, saveRunState, flushRunState, invalidateShortCatalog } from './state.js';
import { every, later, onWindow } from './lifecycle.js';
import { courseIdFromUrl } from './utils.js';
import { route, mediaPage } from './route.js';
@@ -12,6 +12,7 @@ import {
chooseShortCourse, sortCardsByDuration, formatDuration,
pendingShortItems, scanCards, currentPage, maxPageNumber,
startCourse, jumpToPage, nextPage,
ensurePointsInventory, pointsAvailability, pointsDone, pointsTarget, pointsAfterLesson, startStandalone,
} from './list.js';
import { courseTick, manualCourseTick } from './course.js';
import {
@@ -76,7 +77,7 @@ if (window.top !== window.self) {
try {
Object.defineProperty(window, '__yunXueTangAuto', {
value: {
S, R, state, tick, save: saveRunState, flush: flushRunState, route,
S, R, state, points, tick, save: saveRunState, flush: flushRunState, route,
// CFG 暴露给无头运行器:可用 --max / YUN_XUE_TANG_MAX_COURSES 覆盖本次运行的门数上限
CFG,
mediaPage, courseIdFromUrl,
@@ -98,6 +99,8 @@ try {
completeCurrent, failCurrent, skipCurrent, courseSkipped,
// 以下供开发/真机测试驱动内部路径使用:
scanCards, currentPage, maxPageNumber, startCourse, jumpToPage, nextPage,
ensurePointsInventory, pointsAvailability, pointsDone, pointsTarget,
pointsAfterLesson, startStandalone,
listTick, courseTick, manualCourseTick,
loginFields, findLoginVm, checkLoginAgreement, setNativeValue,
saveCreds, loadCreds, clearSavedCreds,
+275 -3
View File
@@ -1,9 +1,13 @@
// ======== 列表页 ========
import { SHORT_CATALOG_TTL, SS_SHORT_CATALOG, TAG } from './config.js';
import {
R, S, state, saveRunState, setTargetCatalogUrl, resetCourseRuntime, invalidateShortCatalog,
PHASE_ENTERING, PHASE_LEARNING, PHASE_IDLE,
SHORT_CATALOG_TTL, SS_SHORT_CATALOG, SS_POINTS_INVENTORY, POINTS_INVENTORY_TTL, TAG,
} from './config.js';
import {
R, S, state, points, saveRunState, setTargetCatalogUrl, resetCourseRuntime,
invalidateShortCatalog, PHASE_ENTERING, PHASE_LEARNING, PHASE_IDLE,
} from './state.js';
import { apiTypeKey, detectLessonType, nextTarget, pointLabel, POINT_RULES } from './points.js';
import { goToList } from './route.js';
import { norm, textOf, truncate } from './utils.js';
import { clickNode } from './player.js';
import { setStatus, updatePanel } from './panel.js';
@@ -352,6 +356,247 @@ export function shortFallback(reason) {
}
}
// ======== 每日积分:文档/音频/微课库存 ========
// 列表默认只显示课程容器(fileType=course),文档/音频/微课是单条知识,
// 要用列表接口的 type 过滤(1=文档 2=视频 3=音频,更高编号留给微课)单独找。
// 只读未学完的条目;视频额度不靠这里(靠课程里的视频课时)。
function emptyPointsInventory() {
return { at: Date.now(), doc: [], audio: [], micro: [] };
}
function pointsInventoryCacheKey(vm) {
return String((vm && vm.collegeId) || localStorage.getItem('orgId') || '');
}
function readPointsInventory(key) {
try {
const raw = sessionStorage.getItem(SS_POINTS_INVENTORY);
if (!raw) return null;
const obj = JSON.parse(raw);
if (!obj || obj.key !== key || !obj.doc || !obj.audio || !obj.micro) return null;
if (Date.now() - (obj.at || 0) > POINTS_INVENTORY_TTL) return null;
return obj;
} catch (e) {
return null;
}
}
function writePointsInventory(inv, key) {
if (!inv) return;
try {
sessionStorage.setItem(SS_POINTS_INVENTORY, JSON.stringify({
key: key, at: inv.at, doc: inv.doc, audio: inv.audio, micro: inv.micro,
}));
} catch (e) { /* 容量不足时只用内存库存 */ }
}
function routeForFileType(fileType) {
const s = String(fileType || '').toLowerCase();
if (s === 'audio') return 'audio/play';
if (s === 'video') return 'video/play';
if (s === 'document' || s === 'doc') return 'document/play';
if (s === 'article') return 'article/play';
if (/micro/.test(s)) return 'micro/play';
return 'ppt/play';
}
// 一次读齐文档/音频/微课库存。单类失败不影响其它类;全失败才算读取失败。
async function fetchPointsInventory(vm) {
const req = shortCatalogRequest(vm);
const baseBody = JSON.parse(req.body);
const api = shortApiBase();
const inv = emptyPointsInventory();
const seen = new Set();
const types = [1, 3, 4, 5, 6, 7, 8];
let failed = 0;
for (const type of types) {
let list = null;
try {
const body = JSON.stringify(Object.assign({}, baseBody, { type: String(type) }));
const res = await fetch(api + '?limit=50&offset=0&orderType=desc&orderBy=createTime', {
method: 'POST', headers: req.headers, body: body,
});
if (!res.ok) throw new Error('HTTP ' + res.status);
const json = await res.json();
list = Array.isArray(json && json.datas) ? json.datas : [];
} catch (e) {
failed++;
continue;
}
for (const item of list) {
if (!item || !item.title) continue;
if (Number(item.status) === 2 || item.studyComplete === 1 || item.studyComplete === true) continue;
const key = apiTypeKey(item.type) || detectLessonType({ fileType: item.fileType });
if (!key || key === 'video') continue; // 视频靠课程里的课时
const id = item.id ? String(item.id) : '';
if (!id || seen.has(id)) continue;
seen.add(id);
inv[key].push({
id: id,
title: norm(item.title),
fileType: item.fileType || '',
route: routeForFileType(item.fileType),
hours: Number(item.studyHours) || 0,
});
}
}
if (failed >= types.length) throw new Error('积分库存接口全部失败');
return inv;
}
// 返回 'off' | 'loading' | 'ready' | 'failed'
export function ensurePointsInventory() {
if (!state.pointsEnabled) return 'off';
if (R.pointsInventory) return 'ready';
const vm = listVm();
if (!vm) {
if (!R.pointsNoVmSince) R.pointsNoVmSince = Date.now();
if (Date.now() - R.pointsNoVmSince > 5000) {
R.pointsInventory = emptyPointsInventory();
R.pointsInventoryFailedAt = Date.now();
if (Date.now() - (R.pointsWarnedAt || 0) > 10000) {
R.pointsWarnedAt = Date.now();
console.warn(TAG, '未找到课程列表组件,积分库存按「只有视频课时」处理');
}
return 'failed';
}
return 'loading';
}
R.pointsNoVmSince = 0;
if (R.pointsInventoryLoading) {
if (Date.now() - R.pointsFetchStartedAt > 20000) {
R.pointsInventoryLoading = false;
R.pointsInventory = emptyPointsInventory();
R.pointsInventoryFailedAt = Date.now();
return 'failed';
}
return 'loading';
}
if (R.pointsInventoryFailedAt && Date.now() - R.pointsInventoryFailedAt < 30000) return 'failed';
const key = pointsInventoryCacheKey(vm);
const cached = readPointsInventory(key);
if (cached) {
R.pointsInventory = cached;
return 'ready';
}
R.pointsInventoryLoading = true;
R.pointsFetchStartedAt = Date.now();
setStatus('正在读取文档/音频/微课库存…');
fetchPointsInventory(vm).then(function (inv) {
R.pointsInventoryLoading = false;
R.pointsInventory = inv;
writePointsInventory(inv, key);
const parts = POINT_RULES
.filter(function (r) { return r.key !== 'video'; })
.map(function (r) { return r.label + ' ' + ((inv[r.key] && inv[r.key].length) || 0) + ' 条'; });
console.log(TAG, '积分库存已就绪:' + parts.join(','));
updatePanel();
}).catch(function (e) {
R.pointsInventoryLoading = false;
R.pointsInventory = emptyPointsInventory();
R.pointsInventoryFailedAt = Date.now();
if (Date.now() - (R.pointsWarnedAt || 0) > 10000) {
R.pointsWarnedAt = Date.now();
console.warn(TAG, '读取积分库存失败,按「只有视频课时」处理:', e && e.message ? e.message : e);
}
});
return 'loading';
}
// 某类还有没有可学的单条内容(排除本轮已完成 / 已跳过)
function nextPointsItem(type) {
const inv = R.pointsInventory;
const arr = (inv && inv[type]) || [];
return arr.find(function (item) {
if (!item || !item.title) return false;
if (S.completedTitles[item.title] || courseSkipped(item.title)) return false;
return true;
}) || null;
}
export function pointsAvailability(videoAvailable) {
return {
doc: !!nextPointsItem('doc'),
video: videoAvailable !== false,
audio: !!nextPointsItem('audio'),
micro: !!nextPointsItem('micro'),
};
}
export function pointsDone() {
if (!state.pointsEnabled) return false;
return points.done(pointsAvailability());
}
export function pointsTarget() {
return nextTarget({
isFull: function (key) { return points.isFull(key); },
available: pointsAvailability(),
});
}
// 从当前课程页回列表,交给 listTick 停止或换下一类。
function leaveForPoints(reason) {
if (S.activeCourse) {
S.activeCourse = null;
S.coursePhase = PHASE_IDLE;
}
S.awaitingListReturn = true;
saveRunState();
setStatus(reason);
console.log(TAG, reason);
goToList(true);
}
// 本类刚满额 / 今日任务已无内容时离开课程页。
// 返回 true = 已经发起跳转,调用方不要再切下一节。
export function pointsAfterLesson(type) {
if (!state.pointsEnabled) return false;
if (!R.pointsInventory) { ensurePointsInventory(); return false; }
if (pointsDone()) {
leaveForPoints('今日积分:可用内容已学完(' + points.summary() + ')');
return true;
}
if (type && points.isFull(type)) {
const target = pointsTarget();
if (target && target.type !== type) {
leaveForPoints('“' + pointLabel(type) + '”已满额,切换学习“' + pointLabel(target.type) + '”');
return true;
}
}
return false;
}
// 进入单条文档/音频/微课:直接按 kngId 打开对应播放页
export function startStandalone(item, type) {
if (!item) return false;
R.lastCardClickAt = Date.now();
R.shortJumpAt = 0;
S.activeCourse = {
title: item.title,
id: item.id,
startedAt: Date.now(),
standalone: true,
pointType: type,
};
S.coursePhase = PHASE_ENTERING;
S.awaitingListReturn = false;
resetCourseRuntime();
saveRunState();
const label = pointLabel(type);
setStatus('进入' + label + ':' + truncate(item.title, 26));
console.log(TAG, '进入' + label, item.title, '(积分模式)');
location.href = location.origin + '/kng/#/' + item.route + '?kngId=' + encodeURIComponent(item.id);
return true;
}
export function pendingShortItems() {
const cat = R.shortCatalog;
if (!cat) return [];
@@ -605,6 +850,33 @@ export function listTick() {
}
R.retryStatusSec = -1;
// 每日积分模式:先补文档/音频/微课的单条内容;视频额度靠课程里的视频课时。
// 四类都满额(或剩余类型确认没内容)就收尾,不再无意义地刷课。
if (state.pointsEnabled) {
const invStatus = ensurePointsInventory();
if (invStatus === 'loading') return;
if (pointsDone()) {
const text = points.summary();
console.log(TAG, '今日积分:可用内容已学完', text);
stopBatch('今日积分:可用内容已学完(' + text + ')');
return;
}
const target = pointsTarget();
if (!target) {
stopBatch('今日积分任务:剩余类型都没有可学内容');
return;
}
if (target.kind === 'item') {
const item = nextPointsItem(target.type);
if (item) {
if (Date.now() - R.lastCardClickAt < 3000) return;
startStandalone(item, target.type);
return;
}
}
// target.kind === 'course':继续走下面的短课程 / 原顺序选课
}
const pending = cards.filter((c) => {
if (!c.title) return false;
if (/已学完|已完成|已学习/.test(c.status)) return false;
+39 -1
View File
@@ -1,6 +1,7 @@
// ======== 面板 ========
import { CFG, VERSION, LS_ENABLED, LS_PREFER_SHORT, SS_SHORT_CATALOG, PANEL_ID, TAG } from './config.js';
import { R, S, state, saveRunState } from './state.js';
import { R, S, state, points, saveRunState } from './state.js';
import { LS_POINTS_MODE } from './points.js';
import { route } from './route.js';
import { isLoginPage, startBatch, doLoginAndStart, clearSavedCreds } from './login.js';
@@ -14,6 +15,9 @@ let labelAuto = null;
let labelBatch = null;
let labelShort = null;
let cbPreferShort = null;
let labelPoints = null;
let cbPoints = null;
let pointsEl = null;
let cbAuto = null;
let loginBox = null;
export let loginUserEl = null;
@@ -58,13 +62,20 @@ export function updatePanel() {
}
if (cbAuto) cbAuto.checked = state.autoPlayEnabled;
if (cbPreferShort) cbPreferShort.checked = state.preferShortCourses;
if (cbPoints) cbPoints.checked = state.pointsEnabled;
if (pointsEl) {
pointsEl.style.display = state.pointsEnabled ? 'block' : 'none';
pointsEl.textContent = state.pointsEnabled ? points.summary() : '';
}
const onLogin = isLoginPage();
if (loginBox) loginBox.style.display = onLogin ? 'block' : 'none';
if (labelAuto) labelAuto.style.display = onLogin ? 'none' : 'flex';
if (labelBatch) labelBatch.style.display = onLogin ? 'none' : 'flex';
if (labelShort) labelShort.style.display = onLogin ? 'none' : 'flex';
if (labelPoints) labelPoints.style.display = onLogin ? 'none' : 'flex';
if (statsEl) statsEl.style.display = onLogin ? 'none' : 'block';
if (pointsEl) pointsEl.style.display = onLogin ? 'none' : (state.pointsEnabled ? 'block' : 'none');
if (btnOne) {
// 「停止刷课」只在播放页出现;列表页等位置始终显示「一键刷课」
const onCourse = route() === 'course' && !!S.activeCourse;
@@ -255,6 +266,27 @@ export function buildPanel() {
labelShort.appendChild(cbPreferShort);
labelShort.appendChild(document.createTextNode('优先短课程(时长正序)'));
labelPoints = document.createElement('label');
labelPoints.style.cssText = LABEL_CSS;
cbPoints = document.createElement('input');
cbPoints.type = 'checkbox';
cbPoints.id = 'yun-xue-tang-points-enabled';
cbPoints.checked = state.pointsEnabled;
cbPoints.title = '按课时类型计分:文档1 / 视频3 / 音频2 / 微课2,每天最多 24 分';
cbPoints.addEventListener('change', function () {
state.pointsEnabled = cbPoints.checked;
points.setEnabled(state.pointsEnabled);
try { localStorage.setItem(LS_POINTS_MODE, state.pointsEnabled ? '1' : '0'); } catch (e) {}
R.pointsInventory = null;
R.pointsInventoryFailedAt = 0;
setStatus(state.pointsEnabled
? '已开启每日积分模式:' + points.summary()
: '已关闭每日积分模式,恢复普通刷课');
updatePanel();
});
labelPoints.appendChild(cbPoints);
labelPoints.appendChild(document.createTextNode('每日积分模式(凑满 24 分就停)'));
statusEl = document.createElement('div');
statusEl.id = 'yun-xue-tang-status';
statusEl.textContent = '待机';
@@ -264,6 +296,10 @@ export function buildPanel() {
statsEl.id = 'yun-xue-tang-stats';
statsEl.style.cssText = 'margin-top:2px;color:#aaa;';
pointsEl = document.createElement('div');
pointsEl.id = 'yun-xue-tang-points';
pointsEl.style.cssText = 'margin-top:2px;color:#8ee6c0;';
const hint = document.createElement('div');
hint.textContent = '真实播放计时 · 保持窗口可见';
hint.style.cssText = 'margin-top:6px;color:#777;font-size:11px;';
@@ -280,8 +316,10 @@ export function buildPanel() {
box.appendChild(labelAuto);
box.appendChild(labelBatch);
box.appendChild(labelShort);
box.appendChild(labelPoints);
box.appendChild(statusEl);
box.appendChild(statsEl);
box.appendChild(pointsEl);
box.appendChild(hint);
box.appendChild(footer);
document.documentElement.appendChild(box);
+267
View File
@@ -0,0 +1,267 @@
// ======== 每日积分模式 ========
// 平台按「学习完成」发积分,四类任务各有每日上限:
// 文档 1 次 + 视频 3 次 + 音频 2 次 + 微课 2 次,每次 3 分,单日最多 24 分。
//
// 这里的口径是「完成一个课时算一次」,不是「完成一整门课」:
// · 多课时课程里每学完一节视频/文档/音频/微课,各计一次;
// · 单视频/音频/课件播放页学完即计一次;
// · 类型识别不出来的课时不猜、不计分;
// · 同一天同一课时重复上报(刷新、重进、平台重发)只计一次。
//
// 计数落 localStorage 并带日期,跨刷新/运行器重启不丢,跨天自动清零。
// 纯数据逻辑,不碰 DOM,方便脱离浏览器直接测。
export const POINT_RULES = [
{ key: 'doc', label: '文档', cap: 1 },
{ key: 'video', label: '视频', cap: 3 },
{ key: 'audio', label: '音频', cap: 2 },
{ key: 'micro', label: '微课', cap: 2 },
];
export const POINTS_PER_TASK = 3;
export const MAX_DAILY_POINTS = POINT_RULES.reduce((n, r) => n + r.cap, 0) * POINTS_PER_TASK;
export const LS_POINTS_MODE = 'yun-xue-tang-daily-points-mode';
export const LS_POINTS_STATE = 'yun-xue-tang-daily-points-v1';
// 顺序有讲究:微课/文档/音频在前,视频最后。某一类同时命中多个关键词时,
// 按更具体的类型算(例如「微课视频」按微课,而不是按视频)。
const TYPE_MATCHERS = [
['micro', /微课|micro/i],
['doc', /文档|课件|ppt|document|article/i],
['audio', /音频|audio/i],
['video', /视频|video/i],
];
/**
* 识别一个课时的积分类型。
* 优先级:播放页路由 > 接口 fileType > 目录里的 tag-type 文本。
* 多课时课程的路由(#/course/play)不带类型,会落到 tag-type 上。
* 识别不出来返回 '',调用方不应计分。
*/
export function detectLessonType(input) {
input = input || {};
const sources = [input.hash, input.fileType, input.tag];
for (const src of sources) {
if (!src) continue;
const s = String(src);
for (const pair of TYPE_MATCHERS) {
if (pair[1].test(s)) return pair[0];
}
}
return '';
}
/** 列表接口的 type 字段:1=文档/课件 2=视频 3=音频;0 是课程容器,不计。 */
export function apiTypeKey(type) {
const n = Number(type);
if (n === 1) return 'doc';
if (n === 2) return 'video';
if (n === 3) return 'audio';
return '';
}
/** 类型的中文名(日志/面板用);未知类型原样返回 */
export function pointLabel(key) {
const rule = POINT_RULES.find((r) => r.key === key);
return rule ? rule.label : (key || '未知');
}
/**
* 选择本轮该补哪一类:按 文档 → 视频 → 音频 → 微课 的顺序,
* 跳过已满额和确认没有内容的类型。
*
* @param {object} opts
* @param {Function} opts.isFull (key) => boolean
* @param {object} [opts.available] { doc, video, audio, micro };false = 没内容。
* video 的可用性由调用方根据「还有没有可学的课程」判断。
* @returns {{type:string, kind:'item'|'course'}|null} null = 今日任务已无可做项
*/
export function nextTarget(opts) {
opts = opts || {};
const isFull = typeof opts.isFull === 'function' ? opts.isFull : () => false;
const available = opts.available || {};
for (const rule of POINT_RULES) {
if (isFull(rule.key)) continue;
if (rule.key === 'video') {
// 视频额度靠课程里的视频课时完成,不依赖单条库存
if (available.video !== false) return { type: 'video', kind: 'course' };
continue;
}
if (available[rule.key]) return { type: rule.key, kind: 'item' };
}
return null;
}
function pad2(n) {
return n < 10 ? '0' + n : '' + n;
}
function dayKey(ms) {
const d = new Date(ms);
return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate());
}
function blankState(date) {
const counts = {};
for (const rule of POINT_RULES) counts[rule.key] = 0;
return { date: date, counts: counts, seen: {} };
}
function normalizeState(obj) {
const state = blankState(obj && obj.date ? String(obj.date) : '');
for (const rule of POINT_RULES) {
const n = Number(obj && obj.counts && obj.counts[rule.key]);
state.counts[rule.key] = Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
}
if (obj && obj.seen && typeof obj.seen === 'object') state.seen = obj.seen;
return state;
}
/**
* @param {object} [opts]
* @param {Function} [opts.now] 取当前时间(毫秒),测试用假时钟
* @param {object} [opts.storage] getItem/setItem,默认 localStorage
* @param {boolean} [opts.enabled] 是否启用积分模式,默认 true
* @param {string} [opts.storageKey]
*/
export function createPointsTracker(opts = {}) {
const now = opts.now || (() => Date.now());
const storage = opts.storage !== undefined
? opts.storage
: (typeof localStorage !== 'undefined' ? localStorage : null);
const storageKey = opts.storageKey || LS_POINTS_STATE;
let enabled = opts.enabled !== undefined ? !!opts.enabled : true;
let state = load();
rollover(); // 打开页面时如果已经跨天,先清零再用
function load() {
try {
const raw = storage && storage.getItem(storageKey);
if (!raw) return blankState(dayKey(now()));
return normalizeState(JSON.parse(raw));
} catch (e) {
return blankState(dayKey(now()));
}
}
function save() {
try {
if (storage) storage.setItem(storageKey, JSON.stringify(state));
} catch (e) { /* 容量不足 / 隐私模式:内存里照常计数 */ }
}
/** 跨天自动清零;返回是否发生了重置 */
function rollover() {
const today = dayKey(now());
if (state.date === today) return false;
state = blankState(today);
save();
return true;
}
function ruleOf(key) {
return POINT_RULES.find((r) => r.key === key) || null;
}
function count(key) {
return state.counts[key] || 0;
}
function cap(key) {
const rule = ruleOf(key);
return rule ? rule.cap : 0;
}
function isFull(key) {
return count(key) >= cap(key);
}
function remaining(key) {
return Math.max(0, cap(key) - count(key));
}
/**
* 记一次课时完成。
* @param {string} key detectLessonType 的返回值
* @param {string} [lessonId] 当天去重键(建议 courseId|lessonKey);空串表示不去重
* @returns {boolean} 是否真的计入了
*/
function record(key, lessonId) {
rollover();
if (!enabled) return false;
if (!ruleOf(key) || isFull(key)) return false;
if (lessonId) {
if (state.seen[lessonId]) return false;
state.seen[lessonId] = 1;
}
state.counts[key] = count(key) + 1;
save();
return true;
}
function totalPoints() {
let total = 0;
for (const rule of POINT_RULES) {
total += Math.min(count(rule.key), rule.cap) * POINTS_PER_TASK;
}
return total;
}
function maxPoints() {
return MAX_DAILY_POINTS;
}
function allFull() {
return POINT_RULES.every((rule) => isFull(rule.key));
}
/**
* 今日任务是否已完成:四类都满额,或剩余额度的类型都确认没有内容。
* available 缺省时不把「没内容」当成完成依据(避免误停)。
*/
function done(available) {
return POINT_RULES.every((rule) =>
isFull(rule.key) || (!!available && available[rule.key] === false));
}
function progress() {
return POINT_RULES.map((rule) => ({
key: rule.key,
label: rule.label,
count: Math.min(count(rule.key), rule.cap),
cap: rule.cap,
}));
}
function summary() {
const parts = progress().map((p) => p.label + p.count + '/' + p.cap);
return '今日积分 ' + totalPoints() + '/' + maxPoints() + ' · ' + parts.join(' ');
}
function snapshot() {
return {
enabled: enabled,
date: state.date,
total: totalPoints(),
max: maxPoints(),
progress: progress(),
text: summary(),
};
}
function setEnabled(on) {
enabled = !!on;
if (enabled) rollover();
}
function isEnabled() {
return enabled;
}
return {
record, count, cap, isFull, remaining, totalPoints, maxPoints,
allFull, done, progress, summary, snapshot, setEnabled, isEnabled, rollover,
};
}
+1 -1
View File
@@ -17,7 +17,7 @@ export function route() {
// 单媒体播放页(没有多课时目录):完成判定看进度百分比/「已完成学习」,
// 不需要找下一节。
export function mediaPage() {
return /^#\/(?:video|audio|ppt|document|article)\/play(?:[?/]|$)/i.test(location.hash || '');
return /^#\/(?:video|audio|ppt|document|article|micro|microcourse)\/play(?:[?/]|$)/i.test(location.hash || '');
}
// 回列表页。
+18
View File
@@ -13,11 +13,13 @@ import {
CFG, LS_ENABLED, LS_PREFER_SHORT, LS_TARGET_CATALOG_URL,
SS_RUN_STATE, SS_SHORT_CATALOG, LEGACY_LS_BATCH,
} from './config.js';
import { createPointsTracker, LS_POINTS_MODE } from './points.js';
// ======== 用户偏好(localStorage) ========
export const state = {
autoPlayEnabled: true, // 当前课程自动连播(自己点开的课)
preferShortCourses: CFG.preferShortCourses, // 列表刷课时优先后时长更短的课程(正序)
pointsEnabled: true, // 每日积分模式:按课时类型计分并封顶
};
try {
state.autoPlayEnabled = localStorage.getItem(LS_ENABLED) !== '0';
@@ -26,6 +28,12 @@ try {
const v = localStorage.getItem(LS_PREFER_SHORT);
if (v === '0' || v === '1') state.preferShortCourses = v === '1';
} catch (e) { /* ignore */ }
try {
state.pointsEnabled = localStorage.getItem(LS_POINTS_MODE) !== '0';
} catch (e) { /* ignore */ }
// 每日积分计数落 localStorage(带日期,跨刷新/重启不丢,跨天自动清零)
export const points = createPointsTracker({ enabled: state.pointsEnabled });
// ======== 本次运行状态(sessionStorage) ========
export const PHASE_ENTERING = 'entering';
@@ -248,6 +256,15 @@ export const R = {
shortNoVmSince: 0,
shortWarnedAt: 0,
retryStatusSec: -1, // 「等待重试」提示上次写出的剩余秒数(只在变化时刷状态)
// 每日积分模式:当前课时的类型缓存(课时 id → doc/video/audio/micro),
// 以及文档/音频/微课的单条库存(视频靠课程里的课时,不单独存)
lessonTypes: {},
pointsInventory: null,
pointsInventoryLoading: false,
pointsInventoryFailedAt: 0,
pointsFetchStartedAt: 0,
pointsNoVmSince: 0,
pointsWarnedAt: 0,
};
// 丢掉时长队列缓存:下一次选课会重新调列表接口,拿平台实时的
@@ -264,6 +281,7 @@ export function invalidateShortCatalog() {
export function resetCourseRuntime() {
R.lastLessonKey = '';
R.doneLatchKey = '';
R.lessonTypes = {};
R.lastSummary = null;
R.lastCountdown = null;
R.lastProgressAt = Date.now();