dsh-ustc-campus 0.2.15 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +74 -72
- package/dist/client.js +5946 -1061
- package/package.json +63 -60
- package/src/account-data.mjs +194 -0
- package/src/bb-actions.mjs +3 -1
- package/src/bb.mjs +15 -9
- package/src/campus-transit.mjs +58 -52
- package/src/client.mjs +74 -633
- package/src/concurrency.mjs +13 -0
- package/src/custom-feeds.mjs +3 -0
- package/src/exams.mjs +21 -7
- package/src/feed.mjs +10 -72
- package/src/grades.mjs +30 -16
- package/src/host.mjs +39 -172
- package/src/library-spaces.mjs +39 -35
- package/src/material.mjs +2268 -65
- package/src/mcp-host.mjs +18 -23
- package/src/mcp.mjs +4 -4
- package/src/recommender.mjs +64 -24
- package/src/school.mjs +218 -154
- package/src/snapshot-cache.mjs +98 -0
- package/src/state.mjs +57 -15
- package/src/youth-actions.mjs +52 -58
- package/src/youth.mjs +55 -26
package/package.json
CHANGED
|
@@ -1,60 +1,63 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "dsh-ustc-campus",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
"
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
"
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
"
|
|
15
|
-
|
|
16
|
-
"
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
"
|
|
21
|
-
"./
|
|
22
|
-
"./
|
|
23
|
-
"./
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
"
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
"
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
"
|
|
39
|
-
|
|
40
|
-
"@deepseek-ai/dsh-client-ui-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
"
|
|
48
|
-
"
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
"
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
"
|
|
55
|
-
"
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
"
|
|
59
|
-
}
|
|
60
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "dsh-ustc-campus",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"license": "AGPL-3.0-only",
|
|
5
|
+
"description": "非官方科大校园工作台:在 DeepSeek Harness 中查询课表、作业、二课、图书馆与校园班车",
|
|
6
|
+
"homepage": "https://github.com/TwinJades/dsh-ustc-campus#readme",
|
|
7
|
+
"bugs": {
|
|
8
|
+
"url": "https://github.com/TwinJades/dsh-ustc-campus/issues"
|
|
9
|
+
},
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/TwinJades/dsh-ustc-campus.git"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=22.13.0",
|
|
17
|
+
"dsh": ">=0.2.2-rc.2 <0.3.0"
|
|
18
|
+
},
|
|
19
|
+
"exports": {
|
|
20
|
+
".": "./src/host.mjs",
|
|
21
|
+
"./tools": "./src/tools.mjs",
|
|
22
|
+
"./mcp-host": "./src/mcp-host.mjs",
|
|
23
|
+
"./client": "./dist/client.js",
|
|
24
|
+
"./package.json": "./package.json"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"cordis.patch.yml",
|
|
28
|
+
"src/*.mjs",
|
|
29
|
+
"dist/client.js",
|
|
30
|
+
"demo/demo.ics",
|
|
31
|
+
"third_party/"
|
|
32
|
+
],
|
|
33
|
+
"dsh": {
|
|
34
|
+
"bundle": {
|
|
35
|
+
"patch": "./cordis.patch.yml"
|
|
36
|
+
},
|
|
37
|
+
"client": {
|
|
38
|
+
"platform": "web",
|
|
39
|
+
"inject": [
|
|
40
|
+
"@deepseek-ai/dsh-client-ui-layout",
|
|
41
|
+
"@deepseek-ai/dsh-client-ui-sidebar",
|
|
42
|
+
"@deepseek-ai/dsh-client-ui-tool"
|
|
43
|
+
]
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
"scripts": {
|
|
47
|
+
"build": "node scripts/build.mjs",
|
|
48
|
+
"prepare": "npm run build",
|
|
49
|
+
"prepublishOnly": "npm run build",
|
|
50
|
+
"test:campus": "node --test test/*.test.mjs",
|
|
51
|
+
"smoke:upstreams": "node scripts/upstreams.mjs"
|
|
52
|
+
},
|
|
53
|
+
"dependencies": {
|
|
54
|
+
"@modelcontextprotocol/sdk": "1.32.2",
|
|
55
|
+
"cheerio": "1.1.2",
|
|
56
|
+
"ical.js": "2.2.1",
|
|
57
|
+
"playwright-core": "1.65.1",
|
|
58
|
+
"zod": "4.6.7"
|
|
59
|
+
},
|
|
60
|
+
"devDependencies": {
|
|
61
|
+
"esbuild": "0.25.12"
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { createSnapshotCache } from './snapshot-cache.mjs';
|
|
3
|
+
import { localTime, YOUTH_SERVICE } from './youth.mjs';
|
|
4
|
+
|
|
5
|
+
const HOUR = 60 * 60_000;
|
|
6
|
+
const RECOVERY_RETRY_MS = 60_000;
|
|
7
|
+
const AGES = { timetable: 6 * HOUR, exams: 2 * HOUR, enrolled: HOUR / 2 };
|
|
8
|
+
const AGENDA_KEYS = Object.keys(AGES);
|
|
9
|
+
const EMPTY = { state: 'not_connected', complete: false, entries: [] };
|
|
10
|
+
const NO_FEED = { extraItems: [], extraSources: [] };
|
|
11
|
+
const usable = result => result?.state === 'ok' || result?.state === 'empty';
|
|
12
|
+
const usableEnrollment = (value, previous) => usable(value) && (value.complete || !previous?.complete);
|
|
13
|
+
const TRANSIENT_STATES = new Set(['pending', 'not_connected', 'expired', 'signed_out']);
|
|
14
|
+
const shouldBackoff = value => !TRANSIENT_STATES.has(value?.state);
|
|
15
|
+
const inRange = (entry, from, through) => entry.date >= from && entry.date <= through;
|
|
16
|
+
|
|
17
|
+
function toFeed(act) {
|
|
18
|
+
const start = localTime(act.holdStart);
|
|
19
|
+
const end = localTime(act.holdEnd);
|
|
20
|
+
const clock = (value, stamp) => stamp ? value.trim().slice(11, 16) : null;
|
|
21
|
+
const startClock = clock(act.holdStart, start);
|
|
22
|
+
const endClock = clock(act.holdEnd, end);
|
|
23
|
+
return {
|
|
24
|
+
id: `youth-enrolling:${act.id}`, youthItemId: act.id, source: 'youth-enrolling',
|
|
25
|
+
category: 'activity', intent: 'activity', requiresRegistration: true,
|
|
26
|
+
title: act.title, url: YOUTH_SERVICE, date: start?.date ?? null,
|
|
27
|
+
time: startClock && endClock ? `${startClock}-${endClock}` : startClock,
|
|
28
|
+
location: act.location, start: start?.epoch ?? null, end: end?.epoch ?? null,
|
|
29
|
+
secondClassroom: true, organizer: act.organizer, enrollmentRatio: act.enrollmentRatio,
|
|
30
|
+
remainingSlots: act.remainingSlots, hours: act.hours, registered: act.registered
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function createAccountData({ dir, school, youth, createExams, now = Date.now }) {
|
|
35
|
+
const cache = createSnapshotCache(join(dir, 'school-cache.json'), { now });
|
|
36
|
+
if (!school.ownsCachedData()) cache.clear();
|
|
37
|
+
const exams = createExams(cache);
|
|
38
|
+
let epoch = 0;
|
|
39
|
+
let closed = false;
|
|
40
|
+
let restoring;
|
|
41
|
+
let recoveryFailedAt = -Infinity;
|
|
42
|
+
let titledSnapshot;
|
|
43
|
+
let titles = [];
|
|
44
|
+
let lastSchoolState = school.status().state;
|
|
45
|
+
|
|
46
|
+
function timetable(force) {
|
|
47
|
+
return cache.refresh('timetable', school.semesterAgenda, {
|
|
48
|
+
maxAge: AGES.timetable, force, accept: usable, backoff: shouldBackoff
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const refreshExams = force => exams.snapshot({ force }).catch(error => ({ ...EMPTY,
|
|
53
|
+
state: ['not_connected', 'authentication_required'].includes(error?.code) ? 'not_connected' : 'unavailable' }));
|
|
54
|
+
const refreshYouth = force => cache.refresh('enrolled', () => youth.read(), {
|
|
55
|
+
maxAge: AGES.enrolled, force, accept: value => usableEnrollment(value, cache.get('enrolled')?.value), backoff: shouldBackoff
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
function restoreSession() {
|
|
59
|
+
if (restoring) return restoring;
|
|
60
|
+
const owner = epoch;
|
|
61
|
+
// A timetable promise can settle before sign-in does. Check the live
|
|
62
|
+
// session independently and leave the timetable timestamp alone.
|
|
63
|
+
const task = Promise.resolve().then(async () => {
|
|
64
|
+
if (owner !== epoch || closed) return false;
|
|
65
|
+
const status = school.status().state;
|
|
66
|
+
if (status !== 'connected' && status !== 'pending') await school.summary();
|
|
67
|
+
return school.status().state === 'connected';
|
|
68
|
+
}).catch(() => false).then(connected => {
|
|
69
|
+
if (owner !== epoch || closed) return false;
|
|
70
|
+
recoveryFailedAt = connected ? -Infinity : now();
|
|
71
|
+
return connected;
|
|
72
|
+
}).finally(() => { if (restoring === task) restoring = undefined; });
|
|
73
|
+
restoring = task;
|
|
74
|
+
return task;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function refreshDue() {
|
|
78
|
+
if (cache.due('timetable', AGES.timetable)) timetable(false).catch(() => {});
|
|
79
|
+
if (cache.due('exams', AGES.exams)) void refreshExams(false);
|
|
80
|
+
if (cache.due('enrolled', AGES.enrolled)) refreshYouth(false).catch(() => {});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function revalidate(status) {
|
|
84
|
+
if (status === 'connected') {
|
|
85
|
+
refreshDue();
|
|
86
|
+
} else if (!restoring && now() - recoveryFailedAt >= RECOVERY_RETRY_MS
|
|
87
|
+
&& AGENDA_KEYS.some(key => cache.due(key, AGES[key]))) {
|
|
88
|
+
const owner = epoch;
|
|
89
|
+
void restoreSession().then(connected => {
|
|
90
|
+
if (connected && owner === epoch && !closed && school.status().state === 'connected') refreshDue();
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function timetableFor(data) {
|
|
96
|
+
const owner = epoch;
|
|
97
|
+
const cached = school.ownsCachedData() && cache.get('timetable')?.value;
|
|
98
|
+
if (cached && school.status().state === 'connected' && cache.due('timetable', AGES.timetable)) timetable(false).catch(() => {});
|
|
99
|
+
const snapshot = cached || await timetable(false);
|
|
100
|
+
return school.sliceAgenda(owner === epoch && snapshot ? snapshot : EMPTY, data);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function agenda(data) {
|
|
104
|
+
const from = data.from, through = data.through;
|
|
105
|
+
const owner = epoch;
|
|
106
|
+
const owned = school.ownsCachedData();
|
|
107
|
+
let rows = AGENDA_KEYS.map(key => owned ? cache.get(key)?.value : undefined);
|
|
108
|
+
const hit = rows.some(Boolean);
|
|
109
|
+
const status = school.status().state;
|
|
110
|
+
if (status === 'connected' && lastSchoolState !== 'connected') cache.clearFailures();
|
|
111
|
+
lastSchoolState = status;
|
|
112
|
+
const force = data.refresh === true;
|
|
113
|
+
let syncing = false;
|
|
114
|
+
if (!closed && status !== 'pending' && (force || !hit)) {
|
|
115
|
+
if (status === 'connected' || (force && owned) || (await school.credentialStatus()).enabled) {
|
|
116
|
+
if (owner === epoch) {
|
|
117
|
+
const liveReady = typeof school.isLive === 'function' ? school.isLive() : status === 'connected';
|
|
118
|
+
if (status !== 'connected' || (!hit && !liveReady)) {
|
|
119
|
+
const schoolData = await timetable(force);
|
|
120
|
+
rows = [schoolData, ...(owner === epoch && schoolData?.state === 'ok' ? await Promise.all([refreshExams(force), refreshYouth(force)]) : [])];
|
|
121
|
+
} else {
|
|
122
|
+
rows = await Promise.all([timetable(force), refreshExams(force), refreshYouth(force)]);
|
|
123
|
+
}
|
|
124
|
+
if (owner === epoch && owned) rows = AGENDA_KEYS.map((key, i) => {
|
|
125
|
+
const previous = cache.get(key)?.value;
|
|
126
|
+
const accept = key === 'enrolled' ? usableEnrollment(rows[i], previous) : usable(rows[i]);
|
|
127
|
+
return accept ? rows[i] : previous ?? rows[i];
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
} else if (!closed && hit) {
|
|
132
|
+
if (status !== 'pending') revalidate(status);
|
|
133
|
+
syncing = Boolean(restoring) || AGENDA_KEYS.some(key => cache.syncing(key));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (owner !== epoch || closed) rows = [];
|
|
137
|
+
const [schoolData, exam = EMPTY, enrolled = EMPTY] = rows;
|
|
138
|
+
const course = schoolData && school.sliceAgenda(schoolData, { from, through });
|
|
139
|
+
const examRows = exam.entries.filter(entry => inRange(entry, from, through));
|
|
140
|
+
const youthRows = enrolled.entries.filter(entry => inRange(entry, from, through));
|
|
141
|
+
return {
|
|
142
|
+
school: { state: course?.state ?? school.status().state, complete: course?.complete ?? false },
|
|
143
|
+
exams: { state: usable(exam) ? examRows.length ? 'ok' : 'empty' : exam.state, complete: exam.complete },
|
|
144
|
+
youth: { state: enrolled.state, complete: enrolled.complete, verifiedCount: youthRows.length },
|
|
145
|
+
schoolEntries: [...(course?.entries ?? []), ...examRows, ...youthRows],
|
|
146
|
+
stale: owner === epoch && hit && !force,
|
|
147
|
+
syncing: owner === epoch && syncing,
|
|
148
|
+
cachedAt: school.ownsCachedData() ? cache.get('timetable')?.at ?? null : null
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function courseTitles() {
|
|
153
|
+
const snapshot = school.ownsCachedData() ? cache.get('timetable')?.value : undefined;
|
|
154
|
+
if (snapshot !== titledSnapshot) {
|
|
155
|
+
titledSnapshot = snapshot;
|
|
156
|
+
titles = snapshot ? [...new Set(snapshot.entries.map(row => row.title).filter(Boolean))].slice(0, 40) : [];
|
|
157
|
+
}
|
|
158
|
+
return titles;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function feed() {
|
|
162
|
+
return (school.ownsCachedData() && cache.get('enrolling')?.value) || NO_FEED;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function refreshFeed(force) {
|
|
166
|
+
if (closed || school.status().state !== 'connected') return;
|
|
167
|
+
return cache.refresh('enrolling', async () => {
|
|
168
|
+
const res = await youth.enrollingFeed();
|
|
169
|
+
if (!usable(res)) return undefined;
|
|
170
|
+
const items = new Map();
|
|
171
|
+
for (const act of res.items) items.set(act.id, toFeed(act));
|
|
172
|
+
return { extraItems: [...items.values()], extraSources: [{
|
|
173
|
+
id: 'youth-enrolling', label: '青春科大 · 报名中二课', category: 'activity', fetchedAt: now(), error: null
|
|
174
|
+
}] };
|
|
175
|
+
}, { maxAge: 5 * 60_000, force, accept: Boolean });
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return { cache, exams, agenda, timetableFor, courseTitles, feed, refreshFeed,
|
|
179
|
+
invalidate() {
|
|
180
|
+
epoch++;
|
|
181
|
+
restoring = undefined;
|
|
182
|
+
recoveryFailedAt = -Infinity;
|
|
183
|
+
lastSchoolState = 'signed_out';
|
|
184
|
+
titledSnapshot = undefined;
|
|
185
|
+
titles = [];
|
|
186
|
+
cache.clear();
|
|
187
|
+
},
|
|
188
|
+
close() {
|
|
189
|
+
closed = true;
|
|
190
|
+
epoch++;
|
|
191
|
+
cache.cancelPending();
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
}
|
package/src/bb-actions.mjs
CHANGED
|
@@ -147,7 +147,9 @@ export function createBbActions({bb}) {
|
|
|
147
147
|
}
|
|
148
148
|
}
|
|
149
149
|
async function status(id) {
|
|
150
|
-
|
|
150
|
+
prune();
|
|
151
|
+
const row = drafts.get(id);
|
|
152
|
+
if (!row) return { state: 'not_found', id, message: '找不到此 BB 请求,或请求已过期' };
|
|
151
153
|
if(row.preparation?.state==='uncertain' && !row.busy) {
|
|
152
154
|
row.busy=true;
|
|
153
155
|
try { row.preparation=await bb.submissionStatus({preparationId:row.preparation.preparationId,verify:true}); }
|
package/src/bb.mjs
CHANGED
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
import { join } from 'node:path';
|
|
25
25
|
import { DatabaseSync } from 'node:sqlite';
|
|
26
26
|
import { load } from 'cheerio';
|
|
27
|
+
import { mapLimited } from './concurrency.mjs';
|
|
27
28
|
|
|
28
29
|
export const BB_ORIGIN = 'https://www.bb.ustc.edu.cn';
|
|
29
30
|
export const BB_PORTAL_PATH = '/webapps/portal/execute/tabs/tabAction?tab_tab_group_id=_1_1';
|
|
@@ -61,8 +62,9 @@ const MAX_DESCRIPTION_CHARS = 3_000;
|
|
|
61
62
|
const MAX_TITLE_CHARS = 300;
|
|
62
63
|
const MAX_PREPARATION_MS = 24 * 60 * 60 * 1000;
|
|
63
64
|
const APPROVAL_LEASE_MS = 120_000; // Longer than the conversation approval timeout.
|
|
64
|
-
const REQUEST_TIMEOUT_MS =
|
|
65
|
-
const
|
|
65
|
+
const REQUEST_TIMEOUT_MS = 12_000;
|
|
66
|
+
const REVIEW_TIMEOUT_MS = 8_000;
|
|
67
|
+
const HISTORY_TIMEOUT_MS = 30_000;
|
|
66
68
|
const MAX_REDIRECTS = 5;
|
|
67
69
|
const SENSITIVE_QUERY = ['nonce', 'csrf', 'session', 'password', 'ticket', 'token'];
|
|
68
70
|
const PHASE_RANK = new Map(BB_PHASES.map((phase, index) => [phase, index]));
|
|
@@ -403,18 +405,17 @@ async function listAssignmentsInternal(context, courseId, maxPages, limit, check
|
|
|
403
405
|
if (!visited.has(candidate) && !queue.includes(candidate)) queue.push(candidate);
|
|
404
406
|
});
|
|
405
407
|
}
|
|
406
|
-
const listed = assignments
|
|
408
|
+
const listed = assignments;
|
|
407
409
|
if (checkStatus) {
|
|
408
|
-
|
|
409
|
-
const item = listed[i];
|
|
410
|
+
const checked = await mapLimited(listed, 4, async item => {
|
|
410
411
|
try {
|
|
411
412
|
const target = reviewUrl(item, courseId, item.contentId);
|
|
412
|
-
const page = await fetchPage(context, target, { timeout:
|
|
413
|
+
const page = await fetchPage(context, target, { timeout: REVIEW_TIMEOUT_MS });
|
|
413
414
|
const review = parseReview(page.text, { includeAttachmentNames: false, assignment: item });
|
|
414
415
|
const mergedDueText = [...(review.dueText ?? []), ...item.dueText]
|
|
415
416
|
.filter((line, idx, arr) => line && arr.indexOf(line) === idx)
|
|
416
417
|
.slice(0, 4);
|
|
417
|
-
|
|
418
|
+
return {
|
|
418
419
|
...item,
|
|
419
420
|
pageKind: review.pageKind,
|
|
420
421
|
submissionState: review.submissionState,
|
|
@@ -428,13 +429,18 @@ async function listAssignmentsInternal(context, courseId, maxPages, limit, check
|
|
|
428
429
|
};
|
|
429
430
|
} catch (error) {
|
|
430
431
|
if (error instanceof BbError && error.code === 'authentication_required') throw error;
|
|
431
|
-
|
|
432
|
+
return {
|
|
432
433
|
...item,
|
|
433
434
|
submissionState: 'unknown',
|
|
434
435
|
attemptOpened: false,
|
|
435
436
|
statusNote: error instanceof BbError ? error.message : '无法读取该作业的提交状态。'
|
|
436
437
|
};
|
|
437
438
|
}
|
|
439
|
+
});
|
|
440
|
+
for (let i = 0; i < checked.length; i++) {
|
|
441
|
+
const result = checked[i];
|
|
442
|
+
if (result.status === 'rejected') throw result.reason;
|
|
443
|
+
listed[i] = result.value;
|
|
438
444
|
}
|
|
439
445
|
}
|
|
440
446
|
return {
|
|
@@ -1273,7 +1279,7 @@ export function createBb({ withSchoolContext, dataDir, connectReadSession } = {}
|
|
|
1273
1279
|
return run(async (context) => {
|
|
1274
1280
|
const assignment = await locate(context, courseId, contentId);
|
|
1275
1281
|
const target = reviewUrl(assignment, courseId, contentId);
|
|
1276
|
-
const page = await fetchPage(context, target, { timeout:
|
|
1282
|
+
const page = await fetchPage(context, target, { timeout: REVIEW_TIMEOUT_MS });
|
|
1277
1283
|
return {
|
|
1278
1284
|
courseId,
|
|
1279
1285
|
contentId,
|
package/src/campus-transit.mjs
CHANGED
|
@@ -18,13 +18,13 @@
|
|
|
18
18
|
* - 中区 (中校区) has no standalone stop; queries map to nearest 东区/西区 hub stops with explicit guidance.
|
|
19
19
|
* - 国金院 is not available on the mobile timetable selector.
|
|
20
20
|
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
* (day type, origin), which is what makes offline reads honest: the result
|
|
24
|
-
* says that it is cached and when it was fetched.
|
|
21
|
+
* Only fixed official URLs are read. The last good timetable for each
|
|
22
|
+
* (day type, origin) persists locally when the Host supplies a data directory.
|
|
25
23
|
*/
|
|
26
24
|
|
|
27
25
|
import { load } from 'cheerio';
|
|
26
|
+
import { join } from 'node:path';
|
|
27
|
+
import { createSnapshotCache } from './snapshot-cache.mjs';
|
|
28
28
|
|
|
29
29
|
import { errorText, fetchText, sanitizeText } from './public-fetch.mjs';
|
|
30
30
|
|
|
@@ -48,7 +48,7 @@ export const TRANSIT_SOURCE = Object.freeze({
|
|
|
48
48
|
});
|
|
49
49
|
|
|
50
50
|
const SOURCE_HOSTS = [TRANSIT_SOURCE.host];
|
|
51
|
-
const FRESH_MS =
|
|
51
|
+
const FRESH_MS = 24 * 60 * 60 * 1000;
|
|
52
52
|
const FETCH_TIMEOUT_MS = 15_000;
|
|
53
53
|
const MAX_BYTES = 512 * 1024;
|
|
54
54
|
const MAX_CACHE_ENTRIES = 16;
|
|
@@ -63,6 +63,27 @@ const SCHEDULE_DATE_PATTERN =
|
|
|
63
63
|
/(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日\s*运行/;
|
|
64
64
|
const TIME_PATTERN = /^(\d{1,2}):(\d{2})(?:\s*(#))?$/;
|
|
65
65
|
|
|
66
|
+
// 国办发明电〔2025〕7号、〔2026〕10号;日期用通知正文,不推算农历。
|
|
67
|
+
const HOLIDAYS = {
|
|
68
|
+
'2026': [['01-01', '01-03', '元旦'], ['02-15', '02-23', '春节'], ['04-04', '04-06', '清明节'],
|
|
69
|
+
['05-01', '05-05', '劳动节'], ['06-19', '06-21', '端午节'], ['09-25', '09-27', '中秋节'], ['10-01', '10-07', '国庆节']],
|
|
70
|
+
'2027': [['01-01', '01-03', '元旦'], ['02-05', '02-13', '春节'], ['04-03', '04-05', '清明节'],
|
|
71
|
+
['05-01', '05-05', '劳动节'], ['06-09', '06-09', '端午节'], ['09-15', '09-15', '中秋节'], ['10-01', '10-07', '国庆节']]
|
|
72
|
+
};
|
|
73
|
+
const MAKEUP_WORKDAYS = new Set([
|
|
74
|
+
'2026-01-04', '2026-02-14', '2026-02-28', '2026-05-09', '2026-09-20', '2026-10-10',
|
|
75
|
+
'2027-01-31', '2027-02-14', '2027-05-08', '2027-09-26', '2027-10-09'
|
|
76
|
+
]);
|
|
77
|
+
|
|
78
|
+
function calendarDayType({ date, weekdayRuleDayType }) {
|
|
79
|
+
const monthDay = date.slice(5);
|
|
80
|
+
const holiday = HOLIDAYS[date.slice(0, 4)]?.find(([from, through]) => monthDay >= from && monthDay <= through);
|
|
81
|
+
const isVacationMonth = ['01', '02', '07', '08'].includes(date.slice(5, 7));
|
|
82
|
+
if (holiday) return { autoScheduleType: 'holiday', dayBadge: holiday[2], dayBasis: 'holiday_calendar', isVacationMonth };
|
|
83
|
+
if (MAKEUP_WORKDAYS.has(date)) return { autoScheduleType: 'workday', dayBadge: '调休班', dayBasis: 'makeup_workday', isVacationMonth };
|
|
84
|
+
return { autoScheduleType: weekdayRuleDayType, dayBadge: weekdayRuleDayType === 'holiday' ? '节假日' : '工作日',
|
|
85
|
+
dayBasis: 'weekend_rule', isVacationMonth };
|
|
86
|
+
}
|
|
66
87
|
const WEEKDAY_LABELS = Object.freeze([
|
|
67
88
|
'星期日',
|
|
68
89
|
'星期一',
|
|
@@ -691,16 +712,10 @@ export function createCampusTransit(options = {}) {
|
|
|
691
712
|
const opts = options && typeof options === 'object' ? options : {};
|
|
692
713
|
const fetchImpl = typeof opts.fetch === 'function' ? opts.fetch : globalThis.fetch;
|
|
693
714
|
const now = typeof opts.now === 'function' ? opts.now : Date.now;
|
|
694
|
-
const cache =
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
if (cache.size >= MAX_CACHE_ENTRIES && !cache.has(key)) {
|
|
699
|
-
const oldest = cache.keys().next().value;
|
|
700
|
-
if (oldest !== undefined) cache.delete(oldest);
|
|
701
|
-
}
|
|
702
|
-
cache.set(key, entry);
|
|
703
|
-
}
|
|
715
|
+
const cache = createSnapshotCache(opts.dir && join(opts.dir, 'transit-cache.json'), {
|
|
716
|
+
now: () => nowValue(now), limit: MAX_CACHE_ENTRIES, retryMs: FRESH_MS
|
|
717
|
+
});
|
|
718
|
+
const failures = new Map();
|
|
704
719
|
|
|
705
720
|
async function fetchSchedule(url, dayType, parser = 'campus') {
|
|
706
721
|
const html = await fetchText(url, {
|
|
@@ -749,29 +764,16 @@ export function createCampusTransit(options = {}) {
|
|
|
749
764
|
}
|
|
750
765
|
|
|
751
766
|
async function load(url, dayType, key, parser = 'campus') {
|
|
752
|
-
const cached = cache.get(key);
|
|
753
|
-
if (cached
|
|
754
|
-
|
|
767
|
+
const cached = cache.get(key)?.value;
|
|
768
|
+
if (cached) {
|
|
769
|
+
if (cache.due(key, FRESH_MS)) {
|
|
770
|
+
cache.refresh(key, () => fetchSchedule(url, dayType, parser)).then(() => failures.delete(key), error => failures.set(key, error));
|
|
771
|
+
}
|
|
772
|
+
return { entry: cached, cached: true, stale: nowValue(now) - cached.fetchedAt >= FRESH_MS, error: failures.get(key) ?? null };
|
|
755
773
|
}
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
const request = fetchSchedule(url, dayType, parser)
|
|
760
|
-
.then((entry) => {
|
|
761
|
-
remember(key, entry);
|
|
762
|
-
return { entry, cached: false, stale: false, error: null };
|
|
763
|
-
})
|
|
764
|
-
.catch((error) => {
|
|
765
|
-
if (cached) {
|
|
766
|
-
return { entry: cached, cached: true, stale: true, error };
|
|
767
|
-
}
|
|
768
|
-
throw error;
|
|
769
|
-
})
|
|
770
|
-
.finally(() => {
|
|
771
|
-
inflight.delete(key);
|
|
772
|
-
});
|
|
773
|
-
inflight.set(key, request);
|
|
774
|
-
return request;
|
|
774
|
+
// With no usable snapshot, report the actual upstream error to this caller.
|
|
775
|
+
const entry = await cache.refresh(key, () => fetchSchedule(url, dayType, parser), { force: true });
|
|
776
|
+
return { entry, cached: false, stale: false, error: null };
|
|
775
777
|
}
|
|
776
778
|
|
|
777
779
|
function dedupeGaoxinRoutes(routes) {
|
|
@@ -819,13 +821,9 @@ export function createCampusTransit(options = {}) {
|
|
|
819
821
|
if (stale) {
|
|
820
822
|
warnings.push({
|
|
821
823
|
code: 'stale_cache',
|
|
822
|
-
message:
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
if (explicit && entry.dayType !== weekdayRuleDayType) {
|
|
826
|
-
warnings.push({
|
|
827
|
-
code: 'explicit_overrides_weekday',
|
|
828
|
-
message: `指定 ${entry.dayType} 与按星期给出的 ${weekdayRuleDayType} 提示不同,已按指定类型返回`
|
|
824
|
+
message: error
|
|
825
|
+
? `无法刷新官方时刻表,显示 ${isoFromEpoch(entry.fetchedAt)} 读取的缓存:${errorText(error)}`
|
|
826
|
+
: '正在后台校对官方时刻表,暂显示上次成功缓存'
|
|
829
827
|
});
|
|
830
828
|
}
|
|
831
829
|
|
|
@@ -846,8 +844,8 @@ export function createCampusTransit(options = {}) {
|
|
|
846
844
|
source: sourceFromEntry(entry, basis),
|
|
847
845
|
cached,
|
|
848
846
|
stale,
|
|
849
|
-
errorCode:
|
|
850
|
-
error:
|
|
847
|
+
errorCode: error?.code ?? null,
|
|
848
|
+
error: error ? errorText(error) : null,
|
|
851
849
|
warnings,
|
|
852
850
|
...(transferNotice ? { transferNotice } : {})
|
|
853
851
|
};
|
|
@@ -1131,6 +1129,14 @@ export function createCampusTransit(options = {}) {
|
|
|
1131
1129
|
if (!parsedDate) {
|
|
1132
1130
|
return invalid('invalid_date', '日期必须是有效的 YYYY-MM-DD 公历日期');
|
|
1133
1131
|
}
|
|
1132
|
+
const day = calendarDayType(parsedDate);
|
|
1133
|
+
const requested = scheduleTypeFrom(query?.scheduleType ?? query?.dayType);
|
|
1134
|
+
const manual = requested != null && requested !== day.autoScheduleType;
|
|
1135
|
+
const out = await readDate(query, parsedDate, requested, day.autoScheduleType);
|
|
1136
|
+
return { ...out, ...day, ...(manual ? { dayBasis: 'manual_override', dayBadge: requested === 'holiday' ? '节假日' : '工作日' } : {}) };
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
async function readDate(query, parsedDate, requested, autoScheduleType) {
|
|
1134
1140
|
const { date, weekday, weekdayLabel, weekdayRuleDayType } = parsedDate;
|
|
1135
1141
|
const weekdayHint = {
|
|
1136
1142
|
dayType: weekdayRuleDayType,
|
|
@@ -1165,7 +1171,7 @@ export function createCampusTransit(options = {}) {
|
|
|
1165
1171
|
toCampus
|
|
1166
1172
|
});
|
|
1167
1173
|
}
|
|
1168
|
-
const
|
|
1174
|
+
const selected = requested ?? (query.autoResolve === true ? autoScheduleType : null);
|
|
1169
1175
|
if (requested === undefined) {
|
|
1170
1176
|
return invalid(
|
|
1171
1177
|
'invalid_schedule_type',
|
|
@@ -1189,21 +1195,21 @@ export function createCampusTransit(options = {}) {
|
|
|
1189
1195
|
date,
|
|
1190
1196
|
weekday,
|
|
1191
1197
|
weekdayLabel,
|
|
1192
|
-
dayType:
|
|
1198
|
+
dayType: selected,
|
|
1193
1199
|
weekdayRuleDayType,
|
|
1194
1200
|
weekdayHint,
|
|
1195
|
-
scheduleTypeBasis: requested ? 'explicit' : 'unspecified',
|
|
1201
|
+
scheduleTypeBasis: requested ? 'explicit' : selected ? 'class' : 'unspecified',
|
|
1196
1202
|
fromCampus,
|
|
1197
1203
|
toCampus,
|
|
1198
|
-
source: emptySource(TRANSIT_SOURCE.baseUrl,
|
|
1204
|
+
source: emptySource(TRANSIT_SOURCE.baseUrl, selected, requested ? 'explicit' : selected ? 'class' : 'unspecified'),
|
|
1199
1205
|
reason: 'adjacent_campus_walk',
|
|
1200
1206
|
transferNotice: strategy.transferNotice,
|
|
1201
1207
|
message: '中校区与东区/西区/北区相邻,可步行经通道直达,无需校车。'
|
|
1202
1208
|
});
|
|
1203
1209
|
}
|
|
1204
1210
|
|
|
1205
|
-
if (
|
|
1206
|
-
return evaluateStrategy(strategy,
|
|
1211
|
+
if (selected) {
|
|
1212
|
+
return evaluateStrategy(strategy, selected, parsedDate, fromCampus, toCampus, Boolean(requested));
|
|
1207
1213
|
}
|
|
1208
1214
|
|
|
1209
1215
|
const dayTypes = ['workday', 'holiday'];
|