dsh-ustc-campus 0.2.15 → 0.3.3

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/package.json CHANGED
@@ -1,60 +1,63 @@
1
- {
2
- "name": "dsh-ustc-campus",
3
- "version": "0.2.15",
4
- "description": "非官方科大校园工作台:在 DeepSeek Harness 中查询课表、作业、二课、图书馆与校园班车",
5
- "homepage": "https://github.com/TwinJades/dsh-ustc-campus#readme",
6
- "bugs": {
7
- "url": "https://github.com/TwinJades/dsh-ustc-campus/issues"
8
- },
9
- "repository": {
10
- "type": "git",
11
- "url": "git+https://github.com/TwinJades/dsh-ustc-campus.git"
12
- },
13
- "type": "module",
14
- "engines": {
15
- "node": ">=22.13.0",
16
- "dsh": ">=0.2.2-rc.2 <0.3.0"
17
- },
18
- "exports": {
19
- ".": "./src/host.mjs",
20
- "./tools": "./src/tools.mjs",
21
- "./mcp-host": "./src/mcp-host.mjs",
22
- "./client": "./dist/client.js",
23
- "./package.json": "./package.json"
24
- },
25
- "files": [
26
- "cordis.patch.yml",
27
- "src/*.mjs",
28
- "dist/client.js",
29
- "demo/demo.ics",
30
- "third_party/"
31
- ],
32
- "dsh": {
33
- "bundle": {
34
- "patch": "./cordis.patch.yml"
35
- },
36
- "client": {
37
- "platform": "web",
38
- "inject": [
39
- "@deepseek-ai/dsh-client-ui-layout",
40
- "@deepseek-ai/dsh-client-ui-sidebar"
41
- ]
42
- }
43
- },
44
- "scripts": {
45
- "build": "node scripts/build.mjs",
46
- "prepublishOnly": "npm run build",
47
- "test:campus": "node --test test/*.test.mjs",
48
- "smoke:upstreams": "node scripts/upstreams.mjs"
49
- },
50
- "dependencies": {
51
- "@modelcontextprotocol/sdk": "1.32.2",
52
- "cheerio": "1.1.2",
53
- "ical.js": "2.2.1",
54
- "playwright-core": "1.65.1",
55
- "zod": "4.6.7"
56
- },
57
- "devDependencies": {
58
- "esbuild": "0.25.12"
59
- }
60
- }
1
+ {
2
+ "name": "dsh-ustc-campus",
3
+ "version": "0.3.3",
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,279 @@
1
+ import { join } from 'node:path';
2
+ import { createSnapshotCache } from './snapshot-cache.mjs';
3
+ import { localTime, YOUTH_SERVICE } from './youth.mjs';
4
+ import { DAY } from './calendar.mjs';
5
+
6
+ const HOUR = 60 * 60_000;
7
+ const RECOVERY_RETRY_MS = 60_000;
8
+ const AGES = { timetable: 6 * HOUR, exams: 2 * HOUR, enrolled: HOUR / 2 };
9
+ const AGENDA_KEYS = Object.keys(AGES);
10
+ const ASSIGNMENT_AGE = HOUR / 2;
11
+ const RESERVATION_AGE = 5 * 60_000;
12
+ const EMPTY = { state: 'not_connected', complete: false, entries: [] };
13
+ const NO_FEED = { extraItems: [], extraSources: [] };
14
+ const usable = result => result?.state === 'ok' || result?.state === 'empty';
15
+ const usableEnrollment = (value, previous) => usable(value) && (value.complete || !previous?.complete);
16
+ const TRANSIENT_STATES = new Set(['pending', 'not_connected', 'expired', 'signed_out']);
17
+ const shouldBackoff = value => !TRANSIENT_STATES.has(value?.state);
18
+ const inRange = (entry, from, through) => entry.date >= from && entry.date <= through;
19
+
20
+ function* westWeeks(from, through) {
21
+ const day = Date.parse(`${from}T00:00:00Z`);
22
+ const first = day - ((new Date(day).getUTCDay() + 6) % 7) * DAY;
23
+ const last = Date.parse(`${through}T00:00:00Z`);
24
+ for (let week = first; week <= last; week += 7 * DAY) {
25
+ const monday = new Date(week).toISOString().slice(0, 10);
26
+ yield { key: `library-west:${monday}`, from: monday, through: new Date(week + 6 * DAY).toISOString().slice(0, 10) };
27
+ }
28
+ }
29
+
30
+ function toFeed(act) {
31
+ const start = localTime(act.holdStart);
32
+ const end = localTime(act.holdEnd);
33
+ const clock = (value, stamp) => stamp ? value.trim().slice(11, 16) : null;
34
+ const startClock = clock(act.holdStart, start);
35
+ const endClock = clock(act.holdEnd, end);
36
+ return {
37
+ id: `youth-enrolling:${act.id}`, youthItemId: act.id, source: 'youth-enrolling',
38
+ category: 'activity', intent: 'activity', requiresRegistration: true,
39
+ title: act.title, url: YOUTH_SERVICE, date: start?.date ?? null,
40
+ time: startClock && endClock ? `${startClock}-${endClock}` : startClock,
41
+ location: act.location, start: start?.epoch ?? null, end: end?.epoch ?? null,
42
+ secondClassroom: true, organizer: act.organizer, enrollmentRatio: act.enrollmentRatio,
43
+ remainingSlots: act.remainingSlots, hours: act.hours, registered: act.registered
44
+ };
45
+ }
46
+
47
+ export function createAccountData({ dir, school, youth, bb, libraryBooking, hsLibrary, createExams, now = Date.now }) {
48
+ const cache = createSnapshotCache(join(dir, 'school-cache.json'), { now });
49
+ if (!school.ownsCachedData()) cache.clear();
50
+ const exams = createExams(cache);
51
+ let epoch = 0;
52
+ let closed = false;
53
+ let restoring;
54
+ let recoveryFailedAt = -Infinity;
55
+ let titledSnapshot;
56
+ let titles = [];
57
+ const supplementStatus = new Map();
58
+ let lastSchoolState = school.status().state;
59
+
60
+ function timetable(force) {
61
+ return cache.refresh('timetable', school.semesterAgenda, {
62
+ maxAge: AGES.timetable, force, accept: usable, backoff: shouldBackoff
63
+ });
64
+ }
65
+
66
+ const refreshExams = force => exams.snapshot({ force }).catch(error => ({ ...EMPTY,
67
+ state: ['not_connected', 'authentication_required'].includes(error?.code) ? 'not_connected' : 'unavailable' }));
68
+ const refreshYouth = force => cache.refresh('enrolled', () => youth.read(), {
69
+ maxAge: AGES.enrolled, force, accept: value => usableEnrollment(value, cache.get('enrolled')?.value), backoff: shouldBackoff
70
+ });
71
+ function refreshSupplement(source, force) {
72
+ const { key, load, maxAge } = source;
73
+ return cache.refresh(key, async () => {
74
+ const owner = epoch;
75
+ let snapshot;
76
+ try { snapshot = await load(); }
77
+ catch (error) {
78
+ const disconnected = ['SCHOOL_NOT_CONNECTED', 'authentication_required'].includes(error?.code);
79
+ snapshot = { ...EMPTY, state: disconnected ? 'not_connected' : 'unavailable' };
80
+ }
81
+ if (owner === epoch) {
82
+ supplementStatus.delete(key);
83
+ if (supplementStatus.size >= 64) supplementStatus.delete(supplementStatus.keys().next().value);
84
+ supplementStatus.set(key, { state: snapshot.state, complete: snapshot.complete });
85
+ }
86
+ return snapshot;
87
+ }, { maxAge, force, accept: value => value?.complete || ((usable(value) || value?.state === 'partial')
88
+ && (key !== 'assignments' || !cache.get(key)?.value.complete)) });
89
+ }
90
+
91
+ const assignmentsSource = bb && { key: 'assignments', load: bb.agenda, maxAge: ASSIGNMENT_AGE };
92
+ const hsSource = hsLibrary && { key: 'library-hs', load: () => hsLibrary.agenda({}), maxAge: RESERVATION_AGE };
93
+ const westSource = window => ({ key: window.key, load: () => libraryBooking.agenda(window), maxAge: RESERVATION_AGE });
94
+
95
+ function refreshAfterWrite(key, load) {
96
+ const owner = epoch;
97
+ const pending = cache.syncing(key) && load(false);
98
+ const refresh = () => owner === epoch && !closed && load(true);
99
+ void (pending ? pending.then(refresh, refresh) : refresh()).catch(() => {});
100
+ }
101
+
102
+ function refreshReservations(campus, date) {
103
+ const source = campus === 'hs' ? hsSource : westSource(westWeeks(date, date).next().value);
104
+ refreshAfterWrite(source.key, force => refreshSupplement(source, force));
105
+ }
106
+
107
+ function restoreSession() {
108
+ if (restoring) return restoring;
109
+ const owner = epoch;
110
+ // A timetable promise can settle before sign-in does. Check the live
111
+ // session independently and leave the timetable timestamp alone.
112
+ const task = Promise.resolve().then(async () => {
113
+ if (owner !== epoch || closed) return false;
114
+ const status = school.status().state;
115
+ if (status !== 'connected' && status !== 'pending') await school.summary();
116
+ return school.status().state === 'connected';
117
+ }).catch(() => false).then(connected => {
118
+ if (owner !== epoch || closed) return false;
119
+ recoveryFailedAt = connected ? -Infinity : now();
120
+ return connected;
121
+ }).finally(() => { if (restoring === task) restoring = undefined; });
122
+ restoring = task;
123
+ return task;
124
+ }
125
+
126
+ function refreshDue() {
127
+ if (cache.due('timetable', AGES.timetable)) timetable(false).catch(() => {});
128
+ if (cache.due('exams', AGES.exams)) void refreshExams(false);
129
+ if (cache.due('enrolled', AGES.enrolled)) refreshYouth(false).catch(() => {});
130
+ }
131
+
132
+ async function timetableFor(data) {
133
+ const owner = epoch;
134
+ const cached = school.ownsCachedData() && cache.get('timetable')?.value;
135
+ if (cached && school.status().state === 'connected' && cache.due('timetable', AGES.timetable)) timetable(false).catch(() => {});
136
+ const snapshot = cached || await timetable(false);
137
+ return school.sliceAgenda(owner === epoch && snapshot ? snapshot : EMPTY, data);
138
+ }
139
+
140
+ async function agenda(data) {
141
+ const from = data.from, through = data.through;
142
+ const owner = epoch;
143
+ const owned = school.ownsCachedData();
144
+ let rows = AGENDA_KEYS.map(key => owned ? cache.get(key)?.value : undefined);
145
+ const hit = rows.some(Boolean);
146
+ const status = school.status().state;
147
+ if (status === 'connected' && lastSchoolState !== 'connected') cache.clearFailures();
148
+ lastSchoolState = status;
149
+ const force = data.refresh === true;
150
+ let syncing = false;
151
+ const reservationSources = [...(hsSource ? [hsSource] : []),
152
+ ...(libraryBooking ? Array.from(westWeeks(from, through), westSource) : [])];
153
+ const supplements = assignmentsSource ? [assignmentsSource, ...reservationSources] : reservationSources;
154
+ const reads = [];
155
+ function syncSupplements() {
156
+ for (const source of supplements) {
157
+ if (force) reads.push(refreshSupplement(source, true));
158
+ else if (cache.due(source.key, source.maxAge)) void refreshSupplement(source, false);
159
+ }
160
+ }
161
+ if (!closed && status !== 'pending' && (force || !hit)) {
162
+ if (status === 'connected' || (force && owned) || (await school.credentialStatus()).enabled) {
163
+ if (owner === epoch) {
164
+ const liveReady = typeof school.isLive === 'function' ? school.isLive() : status === 'connected';
165
+ if (status !== 'connected' || (!hit && !liveReady)) {
166
+ const schoolData = await timetable(force);
167
+ if (owner === epoch && (schoolData?.state === 'ok' || school.status().state === 'connected')) {
168
+ syncSupplements();
169
+ rows = [schoolData, ...await Promise.all([refreshExams(force), refreshYouth(force)])];
170
+ } else rows = [schoolData];
171
+ } else {
172
+ syncSupplements();
173
+ rows = await Promise.all([timetable(force), refreshExams(force), refreshYouth(force)]);
174
+ }
175
+ if (owner === epoch && owned) rows = AGENDA_KEYS.map((key, i) => {
176
+ const previous = cache.get(key)?.value;
177
+ const accept = key === 'enrolled' ? usableEnrollment(rows[i], previous) : usable(rows[i]);
178
+ return accept ? rows[i] : previous ?? rows[i];
179
+ });
180
+ }
181
+ }
182
+ } else if (!closed && hit) {
183
+ const refreshAll = () => {
184
+ refreshDue();
185
+ syncSupplements();
186
+ };
187
+ if (status === 'connected') refreshAll();
188
+ else if (status !== 'pending' && (restoring || (now() - recoveryFailedAt >= RECOVERY_RETRY_MS
189
+ && (AGENDA_KEYS.some(key => cache.due(key, AGES[key]))
190
+ || supplements.some(({ key, maxAge }) => cache.due(key, maxAge)))))) {
191
+ void restoreSession().then(connected => {
192
+ if (connected && owner === epoch && !closed && school.status().state === 'connected') {
193
+ if (lastSchoolState !== 'connected') cache.clearFailures();
194
+ lastSchoolState = 'connected';
195
+ refreshAll();
196
+ }
197
+ });
198
+ }
199
+ syncing = Boolean(restoring) || AGENDA_KEYS.some(key => cache.syncing(key));
200
+ }
201
+
202
+ if (force) await Promise.all(reads);
203
+ const current = owner === epoch && !closed;
204
+ if (!current) rows = [];
205
+ syncing ||= current && (Boolean(restoring) || supplements.some(source => cache.syncing(source.key)));
206
+ const visible = current && school.ownsCachedData();
207
+ function supplemental(source) {
208
+ if (!visible || !source) return EMPTY;
209
+ const cached = cache.get(source.key)?.value ?? EMPTY;
210
+ const last = supplementStatus.get(source.key);
211
+ return last ? { ...last, entries: cached.entries } : cached;
212
+ }
213
+ const [schoolData, exam = EMPTY, enrolled = EMPTY] = rows;
214
+ const course = schoolData && school.sliceAgenda(schoolData, { from, through });
215
+ const examRows = exam.entries.filter(entry => inRange(entry, from, through));
216
+ const youthRows = enrolled.entries.filter(entry => inRange(entry, from, through));
217
+ const assignments = supplemental(assignmentsSource);
218
+ const deadlines = assignments.entries.filter(entry => inRange(entry, from, through));
219
+ const bookings = reservationSources.map(supplemental);
220
+ const reservationRows = bookings.flatMap(snapshot => snapshot.entries.filter(entry => inRange(entry, from, through)));
221
+ return {
222
+ school: { state: course?.state ?? school.status().state, complete: course?.complete ?? false },
223
+ exams: { state: usable(exam) ? examRows.length ? 'ok' : 'empty' : exam.state, complete: exam.complete },
224
+ youth: { state: enrolled.state, complete: enrolled.complete, verifiedCount: youthRows.length },
225
+ assignments: { state: deadlines.length ? 'ok' : usable(assignments) ? assignments.complete ? 'empty' : 'partial' : assignments.state,
226
+ complete: assignments.complete },
227
+ reservations: { count: reservationRows.length, complete: bookings.every(snapshot => snapshot.complete) },
228
+ schoolEntries: [...(course?.entries ?? []), ...examRows, ...youthRows, ...deadlines, ...reservationRows],
229
+ stale: current && !force && (hit || syncing),
230
+ syncing: current && syncing,
231
+ cachedAt: school.ownsCachedData() ? cache.get('timetable')?.at ?? null : null
232
+ };
233
+ }
234
+
235
+ function courseTitles() {
236
+ const snapshot = school.ownsCachedData() ? cache.get('timetable')?.value : undefined;
237
+ if (snapshot !== titledSnapshot) {
238
+ titledSnapshot = snapshot;
239
+ titles = snapshot ? [...new Set(snapshot.entries.map(row => row.title).filter(Boolean))].slice(0, 40) : [];
240
+ }
241
+ return titles;
242
+ }
243
+
244
+ function feed() {
245
+ return (school.ownsCachedData() && cache.get('enrolling')?.value) || NO_FEED;
246
+ }
247
+
248
+ function refreshFeed(force) {
249
+ if (closed || school.status().state !== 'connected') return;
250
+ return cache.refresh('enrolling', async () => {
251
+ const res = await youth.enrollingFeed();
252
+ if (!usable(res)) return undefined;
253
+ const items = new Map();
254
+ for (const act of res.items) items.set(act.id, toFeed(act));
255
+ return { extraItems: [...items.values()], extraSources: [{
256
+ id: 'youth-enrolling', label: '青春科大 · 报名中二课', category: 'activity', fetchedAt: now(), error: null
257
+ }] };
258
+ }, { maxAge: 5 * 60_000, force, accept: Boolean });
259
+ }
260
+
261
+ return { cache, exams, agenda, timetableFor, courseTitles, feed, refreshFeed, refreshReservations,
262
+ refreshEnrollment: () => refreshAfterWrite('enrolled', refreshYouth),
263
+ invalidate() {
264
+ epoch++;
265
+ restoring = undefined;
266
+ recoveryFailedAt = -Infinity;
267
+ lastSchoolState = 'signed_out';
268
+ titledSnapshot = undefined;
269
+ supplementStatus.clear();
270
+ titles = [];
271
+ cache.clear();
272
+ },
273
+ close() {
274
+ closed = true;
275
+ epoch++;
276
+ cache.cancelPending();
277
+ }
278
+ };
279
+ }
@@ -147,7 +147,9 @@ export function createBbActions({bb}) {
147
147
  }
148
148
  }
149
149
  async function status(id) {
150
- const row=item(id);
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,8 @@ 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';
28
+ import { shanghaiEpoch } from './public-fetch.mjs';
27
29
 
28
30
  export const BB_ORIGIN = 'https://www.bb.ustc.edu.cn';
29
31
  export const BB_PORTAL_PATH = '/webapps/portal/execute/tabs/tabAction?tab_tab_group_id=_1_1';
@@ -61,8 +63,10 @@ const MAX_DESCRIPTION_CHARS = 3_000;
61
63
  const MAX_TITLE_CHARS = 300;
62
64
  const MAX_PREPARATION_MS = 24 * 60 * 60 * 1000;
63
65
  const APPROVAL_LEASE_MS = 120_000; // Longer than the conversation approval timeout.
64
- const REQUEST_TIMEOUT_MS = 30_000;
65
- const HISTORY_TIMEOUT_MS = 180_000;
66
+ const REQUEST_TIMEOUT_MS = 12_000;
67
+ const REVIEW_TIMEOUT_MS = 8_000;
68
+ const HISTORY_TIMEOUT_MS = 30_000;
69
+ const AGENDA_SCAN_MS = 18_000;
66
70
  const MAX_REDIRECTS = 5;
67
71
  const SENSITIVE_QUERY = ['nonce', 'csrf', 'session', 'password', 'ticket', 'token'];
68
72
  const PHASE_RANK = new Map(BB_PHASES.map((phase, index) => [phase, index]));
@@ -198,17 +202,19 @@ function requestContext(context) {
198
202
  }
199
203
 
200
204
 
201
- async function fetchPage(context, rawUrl, { timeout = REQUEST_TIMEOUT_MS } = {}) {
205
+ async function fetchPage(context, rawUrl, { timeout = REQUEST_TIMEOUT_MS, stopAt = Infinity } = {}) {
202
206
  const request = requestContext(context);
203
207
  let url = safeUrl(rawUrl);
204
208
  for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects += 1) {
209
+ const remaining = Math.ceil(stopAt - performance.now());
210
+ requireValue(remaining > 0, 'BB 读取超时,请稍后重试。', 'upstream_error');
205
211
  assertReadablePath(url);
206
212
  let response;
207
213
  try {
208
214
  response = await request.get(url.href, {
209
215
  maxRedirects: 0,
210
216
  failOnStatusCode: false,
211
- timeout
217
+ timeout: Math.min(timeout, remaining)
212
218
  });
213
219
  } catch (error) {
214
220
  const message = error && /timeout/i.test(String(error.message))
@@ -358,7 +364,7 @@ function parseAssignments(html, courseId) {
358
364
  return assignments;
359
365
  }
360
366
 
361
- async function listAssignmentsInternal(context, courseId, maxPages, limit, checkStatus = false) {
367
+ async function listAssignmentsInternal(context, courseId, maxPages, limit, checkStatus = false, stopAt = Infinity) {
362
368
  requireValue(typeof courseId === 'string' && ID.test(courseId), '请使用有效的 BB 课程 ID。');
363
369
  requireValue(Number.isSafeInteger(maxPages) && maxPages >= 1 && maxPages <= 15,
364
370
  'maxPages 必须为 1–15 的整数。');
@@ -366,7 +372,7 @@ async function listAssignmentsInternal(context, courseId, maxPages, limit, check
366
372
  'limit 必须为 1–50 的整数。');
367
373
  requireValue(typeof checkStatus === 'boolean', 'checkStatus 必须为布尔值。');
368
374
  const launcher = `/webapps/blackboard/execute/launcher?type=Course&id=${encodeURIComponent(courseId)}`;
369
- const entry = await fetchPage(context, launcher);
375
+ const entry = await fetchPage(context, launcher, { stopAt });
370
376
  const queue = [];
371
377
  for (const path of parseMenuLinks(entry.text, courseId)) {
372
378
  const url = safeUrl(path);
@@ -383,7 +389,7 @@ async function listAssignmentsInternal(context, courseId, maxPages, limit, check
383
389
  const path = queue.shift();
384
390
  if (visited.has(path)) continue;
385
391
  visited.add(path);
386
- const page = await fetchPage(context, path);
392
+ const page = await fetchPage(context, path, { stopAt });
387
393
  for (const item of parseAssignments(page.text, courseId)) {
388
394
  if (identifiers.has(item.contentId)) continue;
389
395
  identifiers.add(item.contentId);
@@ -403,18 +409,17 @@ async function listAssignmentsInternal(context, courseId, maxPages, limit, check
403
409
  if (!visited.has(candidate) && !queue.includes(candidate)) queue.push(candidate);
404
410
  });
405
411
  }
406
- const listed = assignments.slice(0, limit);
412
+ const listed = assignments;
407
413
  if (checkStatus) {
408
- for (let i = 0; i < listed.length; i += 1) {
409
- const item = listed[i];
414
+ const checked = await mapLimited(listed, 4, async item => {
410
415
  try {
411
416
  const target = reviewUrl(item, courseId, item.contentId);
412
- const page = await fetchPage(context, target, { timeout: HISTORY_TIMEOUT_MS });
417
+ const page = await fetchPage(context, target, { timeout: REVIEW_TIMEOUT_MS });
413
418
  const review = parseReview(page.text, { includeAttachmentNames: false, assignment: item });
414
419
  const mergedDueText = [...(review.dueText ?? []), ...item.dueText]
415
420
  .filter((line, idx, arr) => line && arr.indexOf(line) === idx)
416
421
  .slice(0, 4);
417
- listed[i] = {
422
+ return {
418
423
  ...item,
419
424
  pageKind: review.pageKind,
420
425
  submissionState: review.submissionState,
@@ -428,20 +433,25 @@ async function listAssignmentsInternal(context, courseId, maxPages, limit, check
428
433
  };
429
434
  } catch (error) {
430
435
  if (error instanceof BbError && error.code === 'authentication_required') throw error;
431
- listed[i] = {
436
+ return {
432
437
  ...item,
433
438
  submissionState: 'unknown',
434
439
  attemptOpened: false,
435
440
  statusNote: error instanceof BbError ? error.message : '无法读取该作业的提交状态。'
436
441
  };
437
442
  }
443
+ });
444
+ for (let i = 0; i < checked.length; i++) {
445
+ const result = checked[i];
446
+ if (result.status === 'rejected') throw result.reason;
447
+ listed[i] = result.value;
438
448
  }
439
449
  }
440
450
  return {
441
451
  courseId,
442
452
  assignments: listed,
443
453
  pagesChecked: visited.size,
444
- truncated: queue.length > 0 || assignments.length > limit,
454
+ truncated: queue.some(path => !visited.has(path)) || assignments.length === limit,
445
455
  statusChecked: checkStatus,
446
456
  attemptsOpened: false,
447
457
  scope: 'reachable_course_content_pages',
@@ -467,8 +477,10 @@ function reviewUrl(entry, courseId, contentId) {
467
477
  return url.href;
468
478
  }
469
479
 
480
+ const DEADLINE_PATTERN = /\b(20\d{2})(?:年\s*|[-/.])(\d{1,2})(?:月\s*|[-/.])(\d{1,2})日?(?:\s*(?:星期[一二三四五六日天]|[((](?:星期|周)?[一二三四五六日天][))]))?\s*(?:T\s*)?(上午|下午)?\s*(\d{1,2})[::](\d{2})(?!\d)(?!\s*(?::\d{2}\s*)?(?:Z\b|[+-]\d{2}:?\d{2}))/;
481
+
470
482
  function deadline(text) {
471
- const match = /(20\d{2})年\s*(\d{1,2})月\s*(\d{1,2})日(?:\s*星期\S)?\s*(上午|下午)?\s*(\d{1,2})[::](\d{2})/.exec(String(text ?? ''));
483
+ const match = DEADLINE_PATTERN.exec(String(text ?? ''));
472
484
  if (!match) return null;
473
485
  const year = Number(match[1]);
474
486
  const month = Number(match[2]);
@@ -479,11 +491,7 @@ function deadline(text) {
479
491
  if (hour < 1 || hour > 12) return null;
480
492
  hour = (hour % 12) + (match[4] === '下午' ? 12 : 0);
481
493
  }
482
- if (hour > 23 || minute > 59) return null;
483
- const check = new Date(Date.UTC(year, month - 1, day, hour, minute));
484
- if (check.getUTCFullYear() !== year || check.getUTCMonth() !== month - 1
485
- || check.getUTCDate() !== day || check.getUTCHours() !== hour
486
- || check.getUTCMinutes() !== minute) return null;
494
+ if (shanghaiEpoch(year, month, day, hour, minute) === null) return null;
487
495
  const pad = (value) => String(value).padStart(2, '0');
488
496
  return `${year}-${pad(month)}-${pad(day)}T${pad(hour)}:${pad(minute)}:00+08:00`;
489
497
  }
@@ -597,6 +605,67 @@ function parseReview(html, { includeAttachmentNames = false, assignment = null }
597
605
  return next;
598
606
  }
599
607
 
608
+ async function readAssignmentAgenda(context) {
609
+ const stopAt = performance.now() + AGENDA_SCAN_MS;
610
+ const portal = await fetchPage(context, BB_PORTAL_PATH, { stopAt });
611
+ const courses = parseCourses(portal.text);
612
+ if (!courses.length) return { state: 'unavailable', complete: false, entries: [] };
613
+
614
+ const listings = await mapLimited(courses, 4, course =>
615
+ listAssignmentsInternal(context, course.courseId, 15, 50, false, stopAt));
616
+ let complete = true;
617
+ let listed = false;
618
+ const entries = [];
619
+ const missing = [];
620
+ function add(assignment, course, dueAt, url) {
621
+ const start = Date.parse(dueAt);
622
+ entries.push({
623
+ id: `bb_${course.courseId}:${assignment.contentId}`, kind: 'deadline',
624
+ title: assignment.title, courseTitle: course.title, source: 'Blackboard',
625
+ date: dueAt.slice(0, 10), start, end: start, url
626
+ });
627
+ }
628
+ for (const [i, listing] of listings.entries()) {
629
+ if (listing.status === 'rejected') {
630
+ if (listing.reason?.code === 'authentication_required') throw listing.reason;
631
+ complete = false;
632
+ continue;
633
+ }
634
+ listed = true;
635
+ complete &&= !listing.value.truncated;
636
+ const course = courses[i];
637
+ for (const assignment of listing.value.assignments) {
638
+ let url;
639
+ try { url = reviewUrl(assignment, course.courseId, assignment.contentId); }
640
+ catch (error) { if (!(error instanceof BbError)) throw error; }
641
+ let dueAt;
642
+ for (const line of assignment.dueText) {
643
+ if (!/截止|到期|提交时限|最后提交|\bdue\b|\bdeadline\b/i.test(line)) continue;
644
+ const first = DEADLINE_PATTERN.exec(line);
645
+ // Two timed dates can describe an opening and a deadline. Prefer the labelled detail field.
646
+ if (!first || DEADLINE_PATTERN.test(line.slice(first.index + first[0].length))) continue;
647
+ dueAt = deadline(first[0]);
648
+ if (dueAt) break;
649
+ }
650
+ if (dueAt) add(assignment, course, dueAt, url ?? new URL(course.path, BB_ORIGIN).href);
651
+ else if (url) missing.push({ assignment, course, url });
652
+ else complete = false;
653
+ }
654
+ }
655
+ const details = await mapLimited(missing, 4, async ({ assignment, course, url }) => {
656
+ const page = await fetchPage(context, url, { timeout: REVIEW_TIMEOUT_MS, stopAt });
657
+ const { dueAt } = parseReview(page.text, { assignment });
658
+ if (dueAt) add(assignment, course, dueAt, url);
659
+ });
660
+ for (const detail of details) {
661
+ if (detail.status === 'fulfilled') continue;
662
+ if (detail.reason?.code === 'authentication_required') throw detail.reason;
663
+ complete = false;
664
+ }
665
+ return { state: entries.length ? 'ok' : complete ? 'empty' : listed ? 'partial' : 'unavailable', complete,
666
+ entries: entries.sort((a, b) => a.start - b.start || a.id.localeCompare(b.id)) };
667
+ }
668
+
600
669
  function formValues($, form, name) {
601
670
  return form.find('input[name]')
602
671
  .filter((_, node) => $(node).attr('name') === name)
@@ -1237,6 +1306,10 @@ export function createBb({ withSchoolContext, dataDir, connectReadSession } = {}
1237
1306
  };
1238
1307
 
1239
1308
  const api = {
1309
+ agenda() {
1310
+ return run(readAssignmentAgenda, true);
1311
+ },
1312
+
1240
1313
  async listCourses({ keyword = '', term = '' } = {}) {
1241
1314
  boundedText(keyword, 200, '课程关键字');
1242
1315
  requireValue(!term || /^20\d{2}(?:FA|SP|SU|WI)$/.test(term),
@@ -1273,7 +1346,7 @@ export function createBb({ withSchoolContext, dataDir, connectReadSession } = {}
1273
1346
  return run(async (context) => {
1274
1347
  const assignment = await locate(context, courseId, contentId);
1275
1348
  const target = reviewUrl(assignment, courseId, contentId);
1276
- const page = await fetchPage(context, target, { timeout: HISTORY_TIMEOUT_MS });
1349
+ const page = await fetchPage(context, target, { timeout: REVIEW_TIMEOUT_MS });
1277
1350
  return {
1278
1351
  courseId,
1279
1352
  contentId,