mirror of
https://github.com/jackwener/OpenCLI.git
synced 2026-09-14 18:25:42 +08:00
4fe9a73ebc
* refactor: migrate adapter imports to package exports Replace all relative imports (../../src/registry.js, ../../browser/cdp.js, etc.) with package exports (@jackwener/opencli/registry, @jackwener/opencli/errors, etc.) across all 484 adapter files. This decouples adapter import resolution from directory structure: - User CLIs in ~/.opencli/clis/ resolve via node_modules symlink - Internal adapters resolve via Node.js self-referencing - No more shim files needed for import resolution Changes: - package.json: add sub-path exports for all public modules - clis/**: replace relative imports with @jackwener/opencli/... - discovery.ts: simplify ensureUserCliCompatShims to symlink-only - registry-api.ts: export CommandArgs type - Remove root-level shim directories (browser/, download/, pipeline/) - Remove shim entries from tsconfig.json include and package.json files * test: add regression tests for package exports Prevents regressions like #788/#791 by: 1. Scanning all adapter files for forbidden relative imports (../../src/, ../../browser/, etc.) — fails if any remain 2. Verifying every package.json export maps to an existing source file 18 new test cases. * fix: use junction on Windows + broaden test patterns - discovery.ts: use 'junction' symlink type on Windows (no admin required) - package-exports.test.ts: generalize forbidden patterns to catch any depth of ../ traversal (not just ../../ and ../../../) * fix: update stale vi.mock/importActual paths in adapter tests Test files still used old relative paths for vi.mock() and vi.importActual() calls. Updated 5 test files to use package exports. Also broadened regression test patterns to catch mock/importActual paths. * fix: use rm instead of unlink for symlink cleanup, add warn on failure Addresses review feedback from Astro-Han: - rm() handles both symlinks and stale directories (unlink fails on dirs) - Log a warning when symlink creation fails instead of silent catch * docs: update import examples to use package exports Update all documentation, contributing guides, and skills to use @jackwener/opencli/registry instead of ../../src/registry.js. Without this, users following the docs would write adapters with broken imports since the old shim files are no longer created.
267 lines
9.7 KiB
TypeScript
267 lines
9.7 KiB
TypeScript
/**
|
|
* Chaoxing (学习通) shared helpers.
|
|
*
|
|
* Flow: initSession → getCourses → enterCourse → getTabIframeUrl → navigate → parse DOM
|
|
* Chaoxing has no flat "list all assignments" API; data is behind session-gated
|
|
* course pages loaded as iframes.
|
|
*/
|
|
|
|
import type { IPage } from '@jackwener/opencli/types';
|
|
|
|
// ── Utilities ────────────────────────────────────────────────────────
|
|
|
|
/** Sleep for given milliseconds (anti-scraping delay). */
|
|
export function sleep(ms: number): Promise<void> {
|
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
}
|
|
|
|
/** Execute a credentialed fetch in the browser context, returning JSON or text. */
|
|
export async function fetchChaoxing(page: IPage, url: string): Promise<any> {
|
|
const urlJs = JSON.stringify(url);
|
|
return page.evaluate(`
|
|
async () => {
|
|
const res = await fetch(${urlJs}, { credentials: "include" });
|
|
const text = await res.text();
|
|
try { return JSON.parse(text); } catch {}
|
|
return text;
|
|
}
|
|
`);
|
|
}
|
|
|
|
/** Format a timestamp (seconds or milliseconds or date string) to YYYY-MM-DD HH:mm. */
|
|
export function formatTimestamp(ts: unknown): string {
|
|
if (ts == null || ts === '' || ts === 0) return '';
|
|
if (typeof ts === 'string' && !/^\d+$/.test(ts.trim())) return ts.trim();
|
|
const num = Number(ts);
|
|
if (Number.isNaN(num) || num <= 0) return String(ts);
|
|
const millis = num > 1e12 ? num : num * 1000;
|
|
const d = new Date(millis);
|
|
if (Number.isNaN(d.getTime())) return String(ts);
|
|
const yyyy = d.getFullYear();
|
|
const mm = String(d.getMonth() + 1).padStart(2, '0');
|
|
const dd = String(d.getDate()).padStart(2, '0');
|
|
const hh = String(d.getHours()).padStart(2, '0');
|
|
const mi = String(d.getMinutes()).padStart(2, '0');
|
|
return `${yyyy}-${mm}-${dd} ${hh}:${mi}`;
|
|
}
|
|
|
|
/** Map numeric work status to Chinese label. */
|
|
export function workStatusLabel(status: unknown): string {
|
|
if (status == null || status === '') return '未知';
|
|
const s = Number(status);
|
|
if (s === 0) return '未交';
|
|
if (s === 1) return '已交';
|
|
if (s === 2) return '已批阅';
|
|
const str = String(status).trim();
|
|
return str || '未知';
|
|
}
|
|
|
|
// ── Course list ──────────────────────────────────────────────────────
|
|
|
|
export interface ChaoxingCourse {
|
|
courseId: string;
|
|
classId: string;
|
|
cpi: string;
|
|
title: string;
|
|
}
|
|
|
|
/** Fetch enrolled course list via backclazzdata JSON API. */
|
|
export async function getCourses(page: IPage): Promise<ChaoxingCourse[]> {
|
|
const resp = await fetchChaoxing(
|
|
page,
|
|
'https://mooc1-api.chaoxing.com/mycourse/backclazzdata?view=json&rss=1',
|
|
);
|
|
if (!resp || typeof resp !== 'object') return [];
|
|
const channelList: any[] = resp.channelList ?? [];
|
|
const courses: ChaoxingCourse[] = [];
|
|
for (const channel of channelList) {
|
|
const content = channel?.content;
|
|
if (!content) continue;
|
|
const courseData = content.course?.data;
|
|
if (!Array.isArray(courseData)) continue;
|
|
for (const c of courseData) {
|
|
courses.push({
|
|
courseId: String(c.id ?? ''),
|
|
classId: String(content.id ?? ''),
|
|
cpi: String(channel.cpi ?? ''),
|
|
title: String(c.name ?? ''),
|
|
});
|
|
}
|
|
}
|
|
return courses;
|
|
}
|
|
|
|
// ── Session & course entry ───────────────────────────────────────────
|
|
|
|
/** Navigate to the interaction page to establish a Chaoxing session. */
|
|
export async function initSession(page: IPage): Promise<void> {
|
|
await page.goto('https://mooc2-ans.chaoxing.com/mooc2-ans/visit/interaction');
|
|
}
|
|
|
|
/**
|
|
* Enter a course via stucoursemiddle redirect (establishes course session + enc).
|
|
* After this call the browser is on the course page.
|
|
*/
|
|
export async function enterCourse(page: IPage, course: ChaoxingCourse): Promise<void> {
|
|
const url =
|
|
`https://mooc1.chaoxing.com/visit/stucoursemiddle` +
|
|
`?courseid=${course.courseId}&clazzid=${course.classId}&cpi=${course.cpi}&ismooc2=1&v=2`;
|
|
await page.goto(url);
|
|
}
|
|
|
|
/**
|
|
* On the course page, click a tab (作业 / 考试) and return the iframe src
|
|
* that gets loaded. Returns empty string if the tab is not found.
|
|
*/
|
|
export async function getTabIframeUrl(page: IPage, tabName: string): Promise<string> {
|
|
const nameJs = JSON.stringify(tabName);
|
|
const result: any = await page.evaluate(`
|
|
async () => {
|
|
const tabs = document.querySelectorAll('a[data-url]');
|
|
let target = null;
|
|
for (const tab of tabs) {
|
|
if ((tab.innerText || '').trim() === ${nameJs}) { target = tab; break; }
|
|
}
|
|
if (!target) return '';
|
|
target.click();
|
|
await new Promise(r => setTimeout(r, 2000));
|
|
const iframe = document.getElementById('frame_content-hd') || document.querySelector('iframe');
|
|
return iframe?.src || '';
|
|
}
|
|
`);
|
|
return typeof result === 'string' ? result : '';
|
|
}
|
|
|
|
// ── Assignment parsing ───────────────────────────────────────────────
|
|
|
|
export interface AssignmentRow {
|
|
course: string;
|
|
title: string;
|
|
deadline: string;
|
|
status: string;
|
|
score: string;
|
|
}
|
|
|
|
/**
|
|
* Parse assignments from the current page DOM (the 作业列表 page).
|
|
* The page uses `.ulDiv li` items with status/deadline/score info.
|
|
*/
|
|
export async function parseAssignmentsFromDom(page: IPage, courseName: string): Promise<AssignmentRow[]> {
|
|
const raw: any[] = await page.evaluate(`
|
|
(() => {
|
|
const items = [];
|
|
// Each assignment is a li or div block; try multiple selectors
|
|
const blocks = document.querySelectorAll('.ulDiv li, .work-list-item, .listContent > div, ul > li');
|
|
for (const block of blocks) {
|
|
const text = (block.innerText || '').trim();
|
|
if (!text || text.length < 3) continue;
|
|
// Skip filter buttons and headers
|
|
if (/^(全部|已完成|未完成|筛选)$/.test(text)) continue;
|
|
items.push(text);
|
|
}
|
|
// Fallback: split body text by common patterns
|
|
if (items.length === 0) {
|
|
const body = (document.body?.innerText || '').trim();
|
|
return [body];
|
|
}
|
|
return items;
|
|
})()
|
|
`) ?? [];
|
|
|
|
const rows: AssignmentRow[] = [];
|
|
for (const text of raw) {
|
|
if (typeof text !== 'string' || text.length < 3) continue;
|
|
// Skip noise
|
|
if (/^(全部|已完成|未完成|筛选|暂无|提交的作业将经过)/.test(text)) continue;
|
|
|
|
const lines = text.split('\n').map((l: string) => l.trim()).filter(Boolean);
|
|
if (!lines.length) continue;
|
|
|
|
// First meaningful line is the title
|
|
const title = lines[0].replace(/\s+/g, ' ').trim();
|
|
if (!title || /^(全部|已完成|未完成|筛选)$/.test(title)) continue;
|
|
|
|
// Extract status: 未交 / 待批阅 / 已完成 / 已批阅
|
|
const statusMatch = text.match(/(未交|待批阅|已完成|已批阅)/);
|
|
const status = statusMatch?.[1] ?? '';
|
|
|
|
// Extract deadline: "剩余XXX" or date pattern
|
|
const remainMatch = text.match(/(剩余[\d天小时分钟秒]+)/);
|
|
const dateMatch = text.match(/(\d{4}[-/.]\d{1,2}[-/.]\d{1,2}(?:\s+\d{1,2}:\d{2})?)/);
|
|
const deadline = remainMatch?.[1] ?? dateMatch?.[1] ?? '';
|
|
|
|
// Extract score (exclude "分钟")
|
|
const scoreMatch = text.match(/(\d+(?:\.\d+)?)\s*分(?!钟)/);
|
|
const score = scoreMatch?.[1] ?? '';
|
|
|
|
rows.push({ course: courseName, title, deadline, status, score });
|
|
}
|
|
return rows;
|
|
}
|
|
|
|
// ── Exam parsing ─────────────────────────────────────────────────────
|
|
|
|
export interface ExamRow {
|
|
course: string;
|
|
title: string;
|
|
start: string;
|
|
end: string;
|
|
status: string;
|
|
score: string;
|
|
}
|
|
|
|
/** Parse exams from the current page DOM (the 考试列表 page). */
|
|
export async function parseExamsFromDom(page: IPage, courseName: string): Promise<ExamRow[]> {
|
|
const raw: any[] = await page.evaluate(`
|
|
(() => {
|
|
const items = [];
|
|
const blocks = document.querySelectorAll('.ulDiv li, .exam-list-item, .listContent > div, ul > li');
|
|
for (const block of blocks) {
|
|
const text = (block.innerText || '').trim();
|
|
if (!text || text.length < 3) continue;
|
|
if (/^(全部|已完成|未完成|筛选|暂无)$/.test(text)) continue;
|
|
items.push(text);
|
|
}
|
|
if (items.length === 0) {
|
|
const body = (document.body?.innerText || '').trim();
|
|
return [body];
|
|
}
|
|
return items;
|
|
})()
|
|
`) ?? [];
|
|
|
|
// Check for "暂无考试"
|
|
if (raw.length === 1 && typeof raw[0] === 'string' && raw[0].includes('暂无考试')) {
|
|
return [];
|
|
}
|
|
|
|
const rows: ExamRow[] = [];
|
|
for (const text of raw) {
|
|
if (typeof text !== 'string' || text.length < 3) continue;
|
|
if (/^(全部|已完成|未完成|筛选|暂无)/.test(text)) continue;
|
|
|
|
const lines = text.split('\n').map((l: string) => l.trim()).filter(Boolean);
|
|
if (!lines.length) continue;
|
|
|
|
const title = lines[0].replace(/\s+/g, ' ').trim();
|
|
if (!title || /^(全部|已完成|未完成|筛选)$/.test(title)) continue;
|
|
|
|
// Extract dates
|
|
const dates = text.match(/\d{4}[-/.]\d{1,2}[-/.]\d{1,2}\s+\d{1,2}:\d{2}/g) ?? [];
|
|
const start = dates[0] ?? '';
|
|
const end = dates[1] ?? '';
|
|
|
|
// Status
|
|
const statusMatch = text.match(/(未开始|进行中|已结束|已完成|未交|待批阅)/);
|
|
let status = statusMatch?.[1] ?? '';
|
|
if (!status && text.includes('剩余')) status = '进行中';
|
|
|
|
// Score (exclude "分钟")
|
|
const scoreMatch = text.match(/(\d+(?:\.\d+)?)\s*分(?!钟)/);
|
|
const score = scoreMatch?.[1] ?? '';
|
|
|
|
rows.push({ course: courseName, title, start, end, status, score });
|
|
}
|
|
return rows;
|
|
}
|