把单文件脚本拆成 src/ 下 13 个 ES 模块,用 esbuild 打回同名 .user.js, 产物文件名不变,dev/ 热加载链路无需改动。 - build.mjs:esbuild 打包(--watch / --minify),版本号只从 package.json 读取,同时替换 meta.js 的 @version 与 config.js 的 VERSION - 统一版本号来源,消除 package.json / meta.js / config.js 三处手写 - 补回 'use strict'(esbuild IIFE 默认不带,属真实行为回归) - 清理重复实现:pauseAllMedia、listData、shortQuery、drain、clearPending、 cbAuto 模块级引用、共用 cssText - 去掉搬代码时残留的 IIFE 缩进、死字段、二次兜底默认值、过期注释 - README / dev/README 同步构建流程与目录结构 行为无变化,仅 src/config.js 的 CFG 改成构建期注入版本号。
615 lines
21 KiB
JavaScript
615 lines
21 KiB
JavaScript
// ======== 列表页 ========
|
||
import { SHORT_CATALOG_TTL, SS_SHORT_CATALOG, TAG } from './config.js';
|
||
import { R, S, state, save, resetCourseRuntime } from './state.js';
|
||
import { norm, textOf, truncate } from './utils.js';
|
||
import { clickNode } from './player.js';
|
||
import { setStatus, updatePanel } from './panel.js';
|
||
import { failCurrent, stopBatch } from './complete.js';
|
||
|
||
export function scanCards() {
|
||
return [...document.querySelectorAll('li.kng-list-new__item')].map((li, i) => {
|
||
const titleEl = li.querySelector('.yxtf-tooltip');
|
||
const tags = [...li.querySelectorAll('.kng-list-new__tag')].map(textOf);
|
||
const status = tags.find((t) => /已学完|学习中|未开始|未学习|已完成/.test(t)) ||
|
||
tags.find((t) => t !== '课程') || '';
|
||
return {
|
||
li: li,
|
||
i: i,
|
||
title: norm(titleEl ? titleEl.innerText : ''),
|
||
status: status,
|
||
tags: tags,
|
||
};
|
||
});
|
||
}
|
||
|
||
export function currentPage() {
|
||
const el = document.querySelector('.yxtf-pager .number.active');
|
||
if (!el) return null;
|
||
const n = Number(textOf(el));
|
||
return Number.isFinite(n) ? n : null;
|
||
}
|
||
|
||
export function maxPageNumber() {
|
||
const nums = [...document.querySelectorAll('.yxtf-pager .number')]
|
||
.map((e) => Number(textOf(e)))
|
||
.filter((n) => Number.isFinite(n) && n > 0);
|
||
return nums.length ? Math.max.apply(null, nums) : null;
|
||
}
|
||
|
||
export function cardsSignature(cards) {
|
||
cards = cards || scanCards();
|
||
if (!cards.length) return '';
|
||
return cards.length + '|' + cards[0].title + '|' + cards[cards.length - 1].title;
|
||
}
|
||
|
||
export function jumpToPage(target) {
|
||
if (!target) return false;
|
||
if (Date.now() - R.lastPageJumpAt < 3000) return false;
|
||
R.lastPageJumpAt = Date.now();
|
||
R.pageChangeAt = Date.now();
|
||
R.pageChangeSig = cardsSignature();
|
||
|
||
const input = document.querySelector(
|
||
'.yxtf-pagination__editor input, .yxtf-pagination input[type="number"]'
|
||
);
|
||
if (input) {
|
||
try {
|
||
const setter = Object.getOwnPropertyDescriptor(
|
||
window.HTMLInputElement.prototype, 'value'
|
||
).set;
|
||
setter.call(input, String(target));
|
||
} catch (e) {
|
||
input.value = String(target);
|
||
}
|
||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||
input.dispatchEvent(new Event('change', { bubbles: true }));
|
||
input.dispatchEvent(new KeyboardEvent('keydown', {
|
||
key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true,
|
||
}));
|
||
console.log(TAG, '跳转到第', target, '页');
|
||
return true;
|
||
}
|
||
|
||
const btn = [...document.querySelectorAll('.yxtf-pager .number')]
|
||
.find((e) => Number(textOf(e)) === target);
|
||
if (btn) {
|
||
btn.click();
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
export function nextPage() {
|
||
if (Date.now() - R.lastPageJumpAt < 3000) return;
|
||
R.lastPageJumpAt = Date.now();
|
||
R.pageChangeAt = Date.now();
|
||
R.pageChangeSig = cardsSignature();
|
||
const btn = document.querySelector('.yxtf-pagination .btn-next');
|
||
if (btn && !btn.disabled) {
|
||
btn.click();
|
||
console.log(TAG, '翻到下一页');
|
||
}
|
||
}
|
||
|
||
// ======== 短课程优先(时长正序) ========
|
||
// 列表卡片本身不显示时长,但列表组件(ul.kng-list-new.__vue__)的 kngListData
|
||
// 里每门课都带 studyHours(秒)。当前页可据此按时长排序;要进一步跨页优先,
|
||
// 再用同一套列表接口一次性读取全部课程,按 studyHours 正序排队。
|
||
// 接口失败时逐级降级:跨页队列 → 当前页时长排序 → 原列表顺序,绝不卡住批量任务。
|
||
|
||
export function formatDuration(seconds) {
|
||
const n = Number(seconds);
|
||
if (!Number.isFinite(n) || n <= 0) return '时长未知';
|
||
const minutes = Math.max(1, Math.round(n / 60));
|
||
if (minutes < 60) return minutes + ' 分钟';
|
||
const h = Math.floor(minutes / 60);
|
||
const m = minutes % 60;
|
||
return h + ' 小时' + (m ? ' ' + m + ' 分钟' : '');
|
||
}
|
||
|
||
function listData(vm) {
|
||
return (vm && vm.kngListData) || [];
|
||
}
|
||
|
||
// 列表页组件:优先取直接挂载 kngListData 的父组件
|
||
export function listVm() {
|
||
const ul = document.querySelector('ul.kng-list-new');
|
||
let vm = ul && ul.__vue__;
|
||
while (vm && !Array.isArray(vm.kngListData)) vm = vm.$parent;
|
||
return vm && Array.isArray(vm.kngListData) ? vm : null;
|
||
}
|
||
|
||
// 列表接口的分页/排序参数:缓存 key 与实际请求共用同一份默认值,避免两处飘移
|
||
function shortQuery(vm) {
|
||
return {
|
||
pageSize: Number(vm && vm.pageSize) || 16,
|
||
orderBy: (vm && vm.sortColumn) || 'createTime',
|
||
orderType: (vm && vm.sortType) || 'desc',
|
||
};
|
||
}
|
||
|
||
export function shortCatalogKey(vm) {
|
||
const q = shortQuery(vm);
|
||
const key = {
|
||
collegeId: (vm && vm.collegeId) || '',
|
||
catalogId: (vm && vm.currentCatalogId) || '',
|
||
title: (vm && vm.searchKey) || '',
|
||
type: vm && vm.kngType != null ? vm.kngType : '',
|
||
allTag: vm && vm.tagIds && vm.tagIds.length ? 0 : 1,
|
||
tagIds: (vm && vm.tagIds) || [],
|
||
orderBy: q.orderBy,
|
||
orderType: q.orderType,
|
||
pageSize: q.pageSize,
|
||
};
|
||
return JSON.stringify(key);
|
||
}
|
||
|
||
export function readShortCatalog(key) {
|
||
try {
|
||
const raw = sessionStorage.getItem(SS_SHORT_CATALOG);
|
||
if (!raw) return null;
|
||
const obj = JSON.parse(raw);
|
||
if (!obj || obj.key !== key || !Array.isArray(obj.items)) return null;
|
||
if (Date.now() - (obj.at || 0) > SHORT_CATALOG_TTL) return null;
|
||
return obj;
|
||
} catch (e) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
export function writeShortCatalog(cat) {
|
||
if (!cat) return;
|
||
try {
|
||
sessionStorage.setItem(SS_SHORT_CATALOG, JSON.stringify(cat));
|
||
} catch (e) { /* 容量不足时只保留内存队列 */ }
|
||
}
|
||
|
||
export function shortApiBase() {
|
||
try {
|
||
const hit = performance.getEntriesByType('resource')
|
||
.map(function (e) { return e.name; })
|
||
.find(function (u) { return /\/kng\/knowledge\/pagelist/.test(u); });
|
||
if (hit) return new URL(hit).origin + '/kng/knowledge/pagelist';
|
||
} catch (e) { /* 用默认域名 */ }
|
||
return 'https://api-phx-tc.yunxuetang.cn/kng/knowledge/pagelist';
|
||
}
|
||
|
||
export function shortCatalogRequest(vm) {
|
||
const orgId = (vm && vm.collegeId) || localStorage.getItem('orgId') || '';
|
||
const token = localStorage.getItem('token') || '';
|
||
if (!token) throw new Error('未找到登录 token,可能尚未登录或登录已过期');
|
||
|
||
const body = JSON.stringify({
|
||
collegeId: orgId,
|
||
catalogId: (vm && vm.currentCatalogId) || '',
|
||
title: (vm && vm.searchKey) || '',
|
||
type: vm && vm.kngType != null ? vm.kngType : '',
|
||
allTag: vm && vm.tagIds && vm.tagIds.length ? 0 : 1,
|
||
tagIds: (vm && vm.tagIds) || [],
|
||
});
|
||
const headers = {
|
||
'content-type': 'application/json;charset=UTF-8',
|
||
accept: 'application/json, text/plain, */*',
|
||
token: token,
|
||
'yxt-orgdomain': location.hostname,
|
||
source: '501',
|
||
};
|
||
return { body: body, headers: headers };
|
||
}
|
||
|
||
// 一次性读取列表接口(limit=6000 可覆盖当前 5000+ 门课程的站点),
|
||
// 只保留「未学完」的课程,并映射到它所在的页码。
|
||
async function fetchShortCatalog(vm) {
|
||
const key = shortCatalogKey(vm);
|
||
const q = shortQuery(vm);
|
||
const req = shortCatalogRequest(vm);
|
||
const api = shortApiBase();
|
||
const datas = [];
|
||
let offset = 0;
|
||
let total = Infinity;
|
||
let requests = 0;
|
||
|
||
while (offset < total && requests < 20) {
|
||
const limit = Number.isFinite(total) ? Math.min(6000, total - offset) : 6000;
|
||
if (limit <= 0) break;
|
||
const url = api + '?limit=' + limit + '&offset=' + offset +
|
||
'&orderType=' + encodeURIComponent(q.orderType) +
|
||
'&orderBy=' + encodeURIComponent(q.orderBy);
|
||
const res = await fetch(url, { method: 'POST', headers: req.headers, body: req.body });
|
||
if (!res.ok) throw new Error('列表接口 HTTP ' + res.status);
|
||
const json = await res.json();
|
||
const list = json && json.datas;
|
||
if (!Array.isArray(list)) throw new Error('列表接口返回格式异常');
|
||
if (!list.length) break;
|
||
datas.push.apply(datas, list);
|
||
total = Number(json.paging && json.paging.count);
|
||
if (!Number.isFinite(total)) total = datas.length;
|
||
offset += list.length;
|
||
requests++;
|
||
}
|
||
|
||
const items = [];
|
||
datas.forEach(function (item, index) {
|
||
if (!item || !item.title) return;
|
||
if (Number(item.status) === 2 || item.studyComplete === 1 || item.studyComplete === true) return;
|
||
const seconds = Number(item.studyHours);
|
||
items.push({
|
||
id: item.id ? String(item.id) : '',
|
||
title: norm(item.title),
|
||
duration: Number.isFinite(seconds) && seconds > 0 ? seconds : 0,
|
||
status: item.status,
|
||
page: Math.floor(index / q.pageSize) + 1,
|
||
});
|
||
});
|
||
// 时长未知的排最后;相同时按原来的列表顺序(页码)
|
||
items.sort(function (a, b) {
|
||
const da = a.duration > 0 ? a.duration : Number.MAX_SAFE_INTEGER;
|
||
const db = b.duration > 0 ? b.duration : Number.MAX_SAFE_INTEGER;
|
||
return da === db ? a.page - b.page : da - db;
|
||
});
|
||
|
||
return { key: key, at: Date.now(), pageSize: q.pageSize, total: datas.length, items: items };
|
||
}
|
||
|
||
// 返回 'off' | 'loading' | 'ready' | 'failed'
|
||
export function ensureShortCatalog() {
|
||
if (!state.preferShort) return 'off';
|
||
|
||
const vm = listVm();
|
||
if (!vm) {
|
||
if (!R.shortNoVmSince) R.shortNoVmSince = Date.now();
|
||
if (Date.now() - R.shortNoVmSince > 5000) {
|
||
R.shortCatalogFailedAt = Date.now();
|
||
if (Date.now() - (R.shortWarnedAt || 0) > 10000) {
|
||
R.shortWarnedAt = Date.now();
|
||
console.warn(TAG, '未找到课程列表组件,退回当前页时长排序');
|
||
setStatus('未读取到课程列表数据,先按当前页时长排序');
|
||
}
|
||
return 'failed';
|
||
}
|
||
return 'loading';
|
||
}
|
||
R.shortNoVmSince = 0;
|
||
|
||
const key = shortCatalogKey(vm);
|
||
if (R.shortCatalog && R.shortCatalog.key === key &&
|
||
Date.now() - (R.shortCatalog.at || 0) < SHORT_CATALOG_TTL) {
|
||
return 'ready';
|
||
}
|
||
|
||
if (R.shortCatalogLoading) {
|
||
if (Date.now() - R.shortFetchStartedAt > 20000) {
|
||
R.shortCatalogLoading = false;
|
||
R.shortCatalogFailedAt = Date.now();
|
||
return 'failed';
|
||
}
|
||
return 'loading';
|
||
}
|
||
if (R.shortCatalogFailedAt && Date.now() - R.shortCatalogFailedAt < 30000) return 'failed';
|
||
|
||
const cached = readShortCatalog(key);
|
||
if (cached) {
|
||
R.shortCatalog = cached;
|
||
return 'ready';
|
||
}
|
||
|
||
R.shortCatalogLoading = true;
|
||
R.shortFetchStartedAt = Date.now();
|
||
setStatus('正在读取课程时长,优先安排短课程…');
|
||
fetchShortCatalog(vm).then(function (cat) {
|
||
R.shortCatalogLoading = false;
|
||
if (!state.preferShort) return;
|
||
R.shortCatalogFailedAt = 0;
|
||
R.shortCatalog = cat;
|
||
writeShortCatalog(cat);
|
||
const shortest = cat.items[0];
|
||
console.log(TAG, '短课程队列已就绪:待学', cat.items.length, '门;最短',
|
||
shortest ? formatDuration(shortest.duration) : '无');
|
||
setStatus(shortest
|
||
? '优先短课程:共 ' + cat.items.length + ' 门待学,最短 ' + formatDuration(shortest.duration)
|
||
: '时长队列为空,按当前页继续');
|
||
updatePanel();
|
||
}).catch(function (e) {
|
||
R.shortCatalogLoading = false;
|
||
R.shortCatalogFailedAt = Date.now();
|
||
if (!state.preferShort) return;
|
||
console.warn(TAG, '读取课程时长失败,退回当前页时长排序:',
|
||
e && e.message ? e.message : e);
|
||
setStatus('未能读取全部课程时长,先按当前页时长排序');
|
||
updatePanel();
|
||
});
|
||
return 'loading';
|
||
}
|
||
|
||
export function shortFallback(reason) {
|
||
R.shortCatalog = null;
|
||
R.shortCatalogFailedAt = Date.now();
|
||
try { sessionStorage.removeItem(SS_SHORT_CATALOG); } catch (e) { /* ignore */ }
|
||
if (Date.now() - (R.shortWarnedAt || 0) > 10000) {
|
||
R.shortWarnedAt = Date.now();
|
||
console.warn(TAG, '短课程优先暂不可用,退回当前页时长排序:', reason);
|
||
setStatus('短课程优先暂不可用,先按当前页时长排序');
|
||
}
|
||
}
|
||
|
||
export function pendingShortItems() {
|
||
const cat = R.shortCatalog;
|
||
if (!cat) return [];
|
||
return cat.items.filter(function (item) {
|
||
if (!item || !item.title) return false;
|
||
if (S.done[item.title] || S.failed[item.title]) return false;
|
||
return true;
|
||
});
|
||
}
|
||
|
||
// 列表卡片 -> 课程 id。卡片的打开逻辑按 id 跳转,而播放页 URL 带 kngId:
|
||
// 有了 id 就能在标题还没刷新时准确判断「进的是不是队列里的这门课」,
|
||
// 不再因为页面标题短暂是 loading/在线课堂 就误判并退回列表。
|
||
export function courseIdOfCard(card) {
|
||
if (!card) return '';
|
||
const vm = listVm();
|
||
const data = listData(vm);
|
||
const byIndex = data[card.i];
|
||
const t = norm(card.title);
|
||
if (byIndex && String(byIndex.id || '') && norm(byIndex.title) === t) {
|
||
return String(byIndex.id);
|
||
}
|
||
const hit = data.find(function (x) { return x && norm(x.title) === t; });
|
||
return hit && hit.id ? String(hit.id) : '';
|
||
}
|
||
|
||
export function durationOfCard(card, vm) {
|
||
if (!card) return 0;
|
||
const data = listData(vm);
|
||
const hit = data.find(function (item) { return norm(item.title) === card.title; });
|
||
const n = hit ? Number(hit.studyHours) : 0;
|
||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||
}
|
||
|
||
// 优先用课程 id 匹配卡片,避免同名课程(平台上确实有)点错;
|
||
// id 不可用时再退回标题匹配。
|
||
export function cardForShortItem(cards, item) {
|
||
if (!item) return null;
|
||
if (item.id) {
|
||
const vm = listVm();
|
||
const data = listData(vm);
|
||
const index = data.findIndex(function (x) { return x && String(x.id) === item.id; });
|
||
if (index >= 0 && cards[index] && cards[index].title === item.title) return cards[index];
|
||
}
|
||
return cards.find(function (c) { return c.title === item.title; }) || null;
|
||
}
|
||
|
||
export function sortCardsByDuration(cards, vm) {
|
||
vm = vm || listVm();
|
||
return cards.slice().sort(function (a, b) {
|
||
const da = durationOfCard(a, vm) || Number.MAX_SAFE_INTEGER;
|
||
const db = durationOfCard(b, vm) || Number.MAX_SAFE_INTEGER;
|
||
return da - db;
|
||
});
|
||
}
|
||
|
||
export function forgetShortCourse(title) {
|
||
const t = norm(title);
|
||
if (!t || !R.shortCatalog || !Array.isArray(R.shortCatalog.items)) return;
|
||
const before = R.shortCatalog.items.length;
|
||
R.shortCatalog.items = R.shortCatalog.items.filter(function (item) { return item.title !== t; });
|
||
if (R.shortCatalog.items.length !== before) writeShortCatalog(R.shortCatalog);
|
||
}
|
||
|
||
// 返回 { card } 表示本 tick 可以进入该课程;{ wait: true } 表示正在加载/翻页。
|
||
export function chooseShortCourse(cards, pending) {
|
||
if (!state.preferShort) return null;
|
||
const status = ensureShortCatalog();
|
||
|
||
if (status === 'loading') return { wait: true };
|
||
|
||
if (status === 'ready') {
|
||
const items = pendingShortItems();
|
||
if (items.length) {
|
||
const target = items[0];
|
||
const page = currentPage() || S.listPage || 1;
|
||
if (target.page && target.page !== page) {
|
||
if (Date.now() - R.shortJumpAt < 6000) return { wait: true };
|
||
R.shortJumpAt = Date.now();
|
||
if (jumpToPage(target.page)) {
|
||
S.listPage = target.page;
|
||
save();
|
||
setStatus('优先短课程:转到第 ' + target.page + ' 页(' +
|
||
formatDuration(target.duration) + ')');
|
||
return { wait: true };
|
||
}
|
||
if (Date.now() - R.lastPageJumpAt < 3500) return { wait: true };
|
||
shortFallback('无法跳转到第 ' + target.page + ' 页');
|
||
} else {
|
||
const card = cardForShortItem(cards, target);
|
||
if (card) {
|
||
if (card.status === '已学完' || S.done[card.title] || S.failed[card.title]) {
|
||
// 缓存与实际状态不一致:剔除这一门,下一 tick 继续挑下一门
|
||
forgetShortCourse(card.title);
|
||
return { wait: true };
|
||
}
|
||
card.duration = target.duration;
|
||
R.shortJumpAt = 0;
|
||
return { card: card };
|
||
}
|
||
// 刚翻到目标页时卡片可能还没渲染完
|
||
if (Date.now() - R.shortJumpAt < 8000) return { wait: true };
|
||
shortFallback('目标课程不在第 ' + target.page + ' 页');
|
||
}
|
||
}
|
||
}
|
||
|
||
// 兜底:当前页未学完课程按时长正序
|
||
if (pending && pending.length) {
|
||
const vm = listVm();
|
||
const sorted = sortCardsByDuration(pending, vm);
|
||
if (sorted.length) {
|
||
sorted[0].duration = durationOfCard(sorted[0], vm);
|
||
return { card: sorted[0] };
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
export function listTick() {
|
||
const cards = scanCards();
|
||
if (!cards.length) return; // 列表还没渲染
|
||
|
||
// 等待翻页后的新卡片,避免用旧卡片做判断
|
||
if (R.pageChangeSig) {
|
||
if (cardsSignature(cards) === R.pageChangeSig &&
|
||
Date.now() - R.pageChangeAt < 10000) {
|
||
return;
|
||
}
|
||
R.pageChangeSig = '';
|
||
}
|
||
if (R.pageChangeAt && Date.now() - R.pageChangeAt < 1500) return;
|
||
|
||
if (S.listUrl !== location.href) {
|
||
S.listUrl = location.href;
|
||
save();
|
||
}
|
||
|
||
const page = currentPage();
|
||
|
||
// 回到列表后,恢复到课程所在的页码
|
||
if (S.returning) {
|
||
if (page != null && S.listPage && page !== S.listPage) {
|
||
R.restoreAttempts++;
|
||
if (R.restoreAttempts > 12) {
|
||
console.warn(TAG, '页码恢复失败,改用当前页继续');
|
||
S.listPage = page || 1;
|
||
S.returning = false;
|
||
save();
|
||
} else if (S.listPage > page) {
|
||
// 短课程优先会直接跳到很靠后的页(例如第 307 页),
|
||
// 不能一页一页 nextPage,否则要翻几百次;优先用页码输入框直跳。
|
||
if (jumpToPage(S.listPage)) return;
|
||
nextPage();
|
||
return;
|
||
} else {
|
||
jumpToPage(S.listPage);
|
||
return;
|
||
}
|
||
} else {
|
||
S.returning = false;
|
||
R.restoreAttempts = 0;
|
||
save();
|
||
setStatus('回到列表第 ' + (page || 1) + ' 页,继续…');
|
||
}
|
||
}
|
||
|
||
// 记录当前页
|
||
if (!S.returning && page != null && page !== S.listPage) {
|
||
S.listPage = page;
|
||
save();
|
||
}
|
||
|
||
// 已在进入课程的过程中:等路由跳转
|
||
if (S.current && S.phase === 'entering') {
|
||
const waited = Date.now() - (S.current.startedAt || 0);
|
||
if (waited > 15000) {
|
||
failCurrent('未能进入课程页面');
|
||
return;
|
||
}
|
||
// 列表卡片点击偶尔会落在脚本/路由就绪之前(页面毫无反应)。还停在列表时
|
||
// 最多补点两次,而不是直接把这门课记成失败跳过。
|
||
if (waited > 4000 && R.entryRetries < 2 &&
|
||
Date.now() - R.lastCardClickAt > 4000) {
|
||
const card = cards.find(function (c) { return c.title === S.current.title; });
|
||
if (card) {
|
||
R.entryRetries++;
|
||
R.lastCardClickAt = Date.now();
|
||
console.log(TAG, '进入课程超时,重试点击卡片(第', R.entryRetries, '次)');
|
||
setStatus('重新进入课程:' + truncate(S.current.title, 22));
|
||
try { clickNode(card.li); } catch (e) { /* ignore */ }
|
||
}
|
||
}
|
||
return;
|
||
}
|
||
|
||
// 从课程页意外回到列表:判断当前课程是已完成还是中断
|
||
if (S.current && S.phase === 'learning') {
|
||
if (!R.listWithCurrentSince) R.listWithCurrentSince = Date.now();
|
||
if (Date.now() - R.listWithCurrentSince < 5000) return;
|
||
|
||
const card = cards.find(function (c) { return c.title === S.current.title; });
|
||
if (card && /已学完|已完成|已学习/.test(card.status)) {
|
||
S.done[S.current.title] = Date.now();
|
||
forgetShortCourse(S.current.title);
|
||
S.completedThisRun = (S.completedThisRun || 0) + 1;
|
||
}
|
||
S.current = null;
|
||
S.phase = 'idle';
|
||
S.returning = false;
|
||
R.listWithCurrentSince = 0;
|
||
save();
|
||
setStatus('已重置中断的课程状态,继续…');
|
||
}
|
||
|
||
if (S.current) return; // 其他异常情况,等路由
|
||
|
||
const pending = cards.filter((c) => {
|
||
if (!c.title) return false;
|
||
if (/已学完|已完成|已学习/.test(c.status)) return false;
|
||
if (S.done[c.title]) return false;
|
||
if (S.failed[c.title]) return false;
|
||
return true;
|
||
});
|
||
|
||
// 优先短课程:先读时长队列,跨页挑总时长最短的未学完课程;
|
||
// 接口不可用时 chooseShortCourse 会退回当前页时长排序或原列表顺序。
|
||
if (state.preferShort) {
|
||
const choice = chooseShortCourse(cards, pending);
|
||
if (choice && choice.wait) return;
|
||
if (choice && choice.card) {
|
||
if (Date.now() - R.lastCardClickAt < 5000) return;
|
||
startCourse(choice.card);
|
||
return;
|
||
}
|
||
}
|
||
|
||
if (pending.length) {
|
||
if (Date.now() - R.lastCardClickAt < 5000) return;
|
||
startCourse(pending[0]);
|
||
return;
|
||
}
|
||
|
||
const max = maxPageNumber();
|
||
if (page != null && max && page < max) {
|
||
nextPage();
|
||
return;
|
||
}
|
||
|
||
stopBatch('所有页面的未学完课程都已处理完毕');
|
||
}
|
||
|
||
export function startCourse(card) {
|
||
const page = currentPage() || S.listPage || 1;
|
||
S.current = {
|
||
title: card.title,
|
||
id: courseIdOfCard(card),
|
||
status: card.status,
|
||
startedAt: Date.now(),
|
||
page: page,
|
||
duration: card.duration || 0,
|
||
};
|
||
S.listPage = page;
|
||
S.phase = 'entering';
|
||
S.returning = false;
|
||
R.lastCardClickAt = Date.now();
|
||
R.shortJumpAt = 0;
|
||
resetCourseRuntime();
|
||
save();
|
||
const durationText = card.duration ? '(' + formatDuration(card.duration) + ')' : '';
|
||
setStatus('进入课程' + durationText + ':' + truncate(card.title, 28));
|
||
console.log(TAG, '进入课程', card.title, '状态', card.status,
|
||
card.duration ? '时长 ' + formatDuration(card.duration) : '');
|
||
try {
|
||
card.li.click();
|
||
} catch (e) {
|
||
console.error(TAG, e);
|
||
failCurrent('课程卡片点击失败');
|
||
}
|
||
}
|