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
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export async function mapLimited(items, concurrency, worker) {
|
|
2
|
+
const results = new Array(items.length);
|
|
3
|
+
let next = 0;
|
|
4
|
+
async function run() {
|
|
5
|
+
while (next < items.length) {
|
|
6
|
+
const index = next++;
|
|
7
|
+
try { results[index] = { status: 'fulfilled', value: await worker(items[index], index) }; }
|
|
8
|
+
catch (reason) { results[index] = { status: 'rejected', reason }; }
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, run));
|
|
12
|
+
return results;
|
|
13
|
+
}
|
package/src/custom-feeds.mjs
CHANGED
|
@@ -340,12 +340,14 @@ export function createCustomFeeds(options = {}) {
|
|
|
340
340
|
const now = typeof options.now === 'function' ? options.now : Date.now;
|
|
341
341
|
|
|
342
342
|
const store = loadStore(read);
|
|
343
|
+
let revision = 0;
|
|
343
344
|
let refreshing = null;
|
|
344
345
|
let lastAttempt = 0;
|
|
345
346
|
let closed = false;
|
|
346
347
|
let controller = null;
|
|
347
348
|
|
|
348
349
|
function persist() {
|
|
350
|
+
revision++;
|
|
349
351
|
try {
|
|
350
352
|
write(STORE_KEY, store);
|
|
351
353
|
} catch {
|
|
@@ -507,6 +509,7 @@ export function createCustomFeeds(options = {}) {
|
|
|
507
509
|
add,
|
|
508
510
|
remove,
|
|
509
511
|
refresh,
|
|
512
|
+
revision: () => revision,
|
|
510
513
|
getItems,
|
|
511
514
|
getSourceStatuses,
|
|
512
515
|
getItemById,
|
package/src/exams.mjs
CHANGED
|
@@ -526,7 +526,7 @@ export function parseExamTable(html, { from, through } = {}) {
|
|
|
526
526
|
};
|
|
527
527
|
}
|
|
528
528
|
|
|
529
|
-
export function createExams({ withSchoolContext } = {}) {
|
|
529
|
+
export function createExams({ withSchoolContext, cache } = {}) {
|
|
530
530
|
if (typeof withSchoolContext !== 'function') {
|
|
531
531
|
throw new TypeError('withSchoolContext must be a function');
|
|
532
532
|
}
|
|
@@ -567,8 +567,7 @@ export function createExams({ withSchoolContext } = {}) {
|
|
|
567
567
|
return value;
|
|
568
568
|
}
|
|
569
569
|
|
|
570
|
-
|
|
571
|
-
const range = readRange(input);
|
|
570
|
+
function load() {
|
|
572
571
|
return run(async (context) => {
|
|
573
572
|
const studentId = await discoverStudentId(context);
|
|
574
573
|
const path = `${EXAM_INFO_PREFIX}${studentId}`;
|
|
@@ -578,11 +577,9 @@ export function createExams({ withSchoolContext } = {}) {
|
|
|
578
577
|
(candidate) => candidate === path,
|
|
579
578
|
'考试安排'
|
|
580
579
|
);
|
|
581
|
-
const parsed = parseExamTable(page.text
|
|
580
|
+
const parsed = parseExamTable(page.text);
|
|
582
581
|
return {
|
|
583
582
|
state: parsed.entries.length > 0 ? 'ok' : 'empty',
|
|
584
|
-
from: range.from,
|
|
585
|
-
through: range.through,
|
|
586
583
|
timezone: 'Asia/Shanghai',
|
|
587
584
|
source: EXAM_SOURCE,
|
|
588
585
|
scope: 'current_semester',
|
|
@@ -601,5 +598,22 @@ export function createExams({ withSchoolContext } = {}) {
|
|
|
601
598
|
});
|
|
602
599
|
}
|
|
603
600
|
|
|
604
|
-
|
|
601
|
+
function snapshot({ force = false } = {}) {
|
|
602
|
+
return cache ? cache.refresh('exams', load, {
|
|
603
|
+
maxAge: 2 * 60 * 60_000,
|
|
604
|
+
force,
|
|
605
|
+
backoff: error => !['not_connected', 'authentication_required', 'SCHOOL_NOT_CONNECTED'].includes(error?.code)
|
|
606
|
+
}) : load();
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
async function read(input = {}) {
|
|
610
|
+
const range = readRange(input);
|
|
611
|
+
const all = await snapshot();
|
|
612
|
+
if (!all) fail('学校会话已变化或暂不可用,请重新查询考试安排。', 'not_connected');
|
|
613
|
+
const entries = all.entries.filter(({ date }) => date >= range.from && date <= range.through);
|
|
614
|
+
return { ...all, ...range, state: entries.length ? 'ok' : 'empty', entries,
|
|
615
|
+
count: entries.length, outsideRange: all.entries.length - entries.length };
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
return Object.freeze({ read, snapshot });
|
|
605
619
|
}
|
package/src/feed.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
shanghaiEpoch
|
|
9
9
|
} from './public-fetch.mjs';
|
|
10
10
|
import { createRecommender } from './recommender.mjs';
|
|
11
|
+
import { mapLimited } from './concurrency.mjs';
|
|
11
12
|
|
|
12
13
|
export const FEED_CATEGORY_LABELS = Object.freeze({
|
|
13
14
|
campus: '学校要闻与综合公告',
|
|
@@ -1273,44 +1274,6 @@ function buildReason(item, interests, agenda, coverage, nowMs) {
|
|
|
1273
1274
|
return reasons.join(';');
|
|
1274
1275
|
}
|
|
1275
1276
|
|
|
1276
|
-
function scoreItem(item, interests, agenda, nowMs) {
|
|
1277
|
-
const haystack = `${item.title} ${item.location ?? ''}`.toLowerCase();
|
|
1278
|
-
let score = 0;
|
|
1279
|
-
for (const term of interests) {
|
|
1280
|
-
if (haystack.includes(term.toLowerCase())) score += 30;
|
|
1281
|
-
}
|
|
1282
|
-
|
|
1283
|
-
if (itemKindOf(item) === 'event') {
|
|
1284
|
-
if (item.past) {
|
|
1285
|
-
score -= 100;
|
|
1286
|
-
} else if (item.start != null) {
|
|
1287
|
-
score += 20;
|
|
1288
|
-
if (item.start - nowMs <= 7 * 24 * 60 * 60 * 1000) score += 10;
|
|
1289
|
-
if (overlapsAgenda(item, agenda)) score -= 50;
|
|
1290
|
-
} else {
|
|
1291
|
-
score -= 5;
|
|
1292
|
-
}
|
|
1293
|
-
} else {
|
|
1294
|
-
score += 5;
|
|
1295
|
-
}
|
|
1296
|
-
return score;
|
|
1297
|
-
}
|
|
1298
|
-
|
|
1299
|
-
function sortItems(items, sort, interests, agenda, nowMs) {
|
|
1300
|
-
if (sort === 'recommend') {
|
|
1301
|
-
const withScore = items.map((item) => ({
|
|
1302
|
-
item,
|
|
1303
|
-
score: scoreItem(item, interests, agenda, nowMs)
|
|
1304
|
-
}));
|
|
1305
|
-
withScore.sort((a, b) => {
|
|
1306
|
-
if (b.score !== a.score) return b.score - a.score;
|
|
1307
|
-
return compareChronological(a.item, b.item);
|
|
1308
|
-
});
|
|
1309
|
-
return withScore.map((entry) => entry.item);
|
|
1310
|
-
}
|
|
1311
|
-
|
|
1312
|
-
return [...items].sort(compareChronological);
|
|
1313
|
-
}
|
|
1314
1277
|
|
|
1315
1278
|
function publicItem(item, interests, agenda, nowMs, coverage, sourceMeta = null) {
|
|
1316
1279
|
const past = computePast(item, nowMs);
|
|
@@ -1352,33 +1315,13 @@ function memoryStore() {
|
|
|
1352
1315
|
|
|
1353
1316
|
const REFRESH_CONCURRENCY = 6;
|
|
1354
1317
|
|
|
1355
|
-
async function mapWithConcurrency(items, concurrency, worker) {
|
|
1356
|
-
const results = new Array(items.length);
|
|
1357
|
-
let nextIndex = 0;
|
|
1358
|
-
async function runWorker() {
|
|
1359
|
-
while (nextIndex < items.length) {
|
|
1360
|
-
const idx = nextIndex;
|
|
1361
|
-
nextIndex += 1;
|
|
1362
|
-
try {
|
|
1363
|
-
const value = await worker(items[idx], idx);
|
|
1364
|
-
results[idx] = { status: 'fulfilled', value };
|
|
1365
|
-
} catch (reason) {
|
|
1366
|
-
results[idx] = { status: 'rejected', reason };
|
|
1367
|
-
}
|
|
1368
|
-
}
|
|
1369
|
-
}
|
|
1370
|
-
const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => runWorker());
|
|
1371
|
-
await Promise.all(workers);
|
|
1372
|
-
return results;
|
|
1373
|
-
}
|
|
1374
1318
|
|
|
1375
1319
|
/**
|
|
1376
1320
|
* createFeed({read, write, fetch, now})
|
|
1377
1321
|
*
|
|
1378
1322
|
* `read`/`write` are synchronous key/value storage supplied by the host,
|
|
1379
|
-
* `fetch` and `now` are injectable for tests.
|
|
1380
|
-
*
|
|
1381
|
-
* background (call `refresh({force:true})` when the caller wants to await it).
|
|
1323
|
+
* `fetch` and `now` are injectable for tests. `query` is strictly local;
|
|
1324
|
+
* callers use `refresh` when they want to check the network.
|
|
1382
1325
|
*/
|
|
1383
1326
|
export function createFeed(options = {}) {
|
|
1384
1327
|
const fallback = memoryStore();
|
|
@@ -1388,6 +1331,7 @@ export function createFeed(options = {}) {
|
|
|
1388
1331
|
const now = typeof options.now === 'function' ? options.now : Date.now;
|
|
1389
1332
|
|
|
1390
1333
|
const cache = loadCache(read);
|
|
1334
|
+
let revision = 0;
|
|
1391
1335
|
let fallbackRecommender = null;
|
|
1392
1336
|
let refreshing = null;
|
|
1393
1337
|
let lastAttempt = 0;
|
|
@@ -1395,6 +1339,7 @@ export function createFeed(options = {}) {
|
|
|
1395
1339
|
let controller = null;
|
|
1396
1340
|
|
|
1397
1341
|
function writeCache() {
|
|
1342
|
+
revision++;
|
|
1398
1343
|
try {
|
|
1399
1344
|
write(CACHE_KEY, cache);
|
|
1400
1345
|
} catch {
|
|
@@ -1438,7 +1383,7 @@ export function createFeed(options = {}) {
|
|
|
1438
1383
|
lastAttempt = refreshNow;
|
|
1439
1384
|
const signal = controller.signal;
|
|
1440
1385
|
|
|
1441
|
-
const results = await
|
|
1386
|
+
const results = await mapLimited(SOURCE_IDS, REFRESH_CONCURRENCY, async (id) => {
|
|
1442
1387
|
const source = FEED_SOURCES[id];
|
|
1443
1388
|
const html = await fetchText(source.url, {
|
|
1444
1389
|
fetch: fetchImpl,
|
|
@@ -1528,14 +1473,6 @@ export function createFeed(options = {}) {
|
|
|
1528
1473
|
return refreshing;
|
|
1529
1474
|
}
|
|
1530
1475
|
|
|
1531
|
-
function maybeAutoRefresh(selectedIds) {
|
|
1532
|
-
if (closed || refreshing) return;
|
|
1533
|
-
if (!selectedIds.some((id) => isStale(id))) return;
|
|
1534
|
-
if (lastAttempt > 0 && now() - lastAttempt < RETRY_AFTER_FAILURE_MS) return;
|
|
1535
|
-
refresh().catch(() => {
|
|
1536
|
-
/* surfaced through source metadata on the next query */
|
|
1537
|
-
});
|
|
1538
|
-
}
|
|
1539
1476
|
|
|
1540
1477
|
function getItemById(id) {
|
|
1541
1478
|
for (const srcId of SOURCE_IDS) {
|
|
@@ -1555,7 +1492,6 @@ export function createFeed(options = {}) {
|
|
|
1555
1492
|
|
|
1556
1493
|
function query(queryOptions = {}) {
|
|
1557
1494
|
const selectedIds = normalizeSourceFilter(queryOptions?.source, queryOptions?.category);
|
|
1558
|
-
maybeAutoRefresh(selectedIds);
|
|
1559
1495
|
|
|
1560
1496
|
const sourceTokens = filterTokens(queryOptions?.source);
|
|
1561
1497
|
const categoryTokens = filterTokens(queryOptions?.category);
|
|
@@ -1594,6 +1530,8 @@ export function createFeed(options = {}) {
|
|
|
1594
1530
|
if (categoryTokens && !categoryTokens.includes(cat)) continue;
|
|
1595
1531
|
items.push(extra);
|
|
1596
1532
|
}
|
|
1533
|
+
const seenIds = new Set();
|
|
1534
|
+
items = items.filter(item => !seenIds.has(item.id) && seenIds.add(item.id));
|
|
1597
1535
|
|
|
1598
1536
|
if (keyword) {
|
|
1599
1537
|
items = items.filter((item) => {
|
|
@@ -1630,7 +1568,7 @@ export function createFeed(options = {}) {
|
|
|
1630
1568
|
}
|
|
1631
1569
|
});
|
|
1632
1570
|
} else {
|
|
1633
|
-
sorted =
|
|
1571
|
+
sorted = projected.sort(compareChronological);
|
|
1634
1572
|
}
|
|
1635
1573
|
|
|
1636
1574
|
return {
|
|
@@ -1650,5 +1588,5 @@ export function createFeed(options = {}) {
|
|
|
1650
1588
|
refreshing = null;
|
|
1651
1589
|
}
|
|
1652
1590
|
|
|
1653
|
-
return { query, refresh, close, getItemById };
|
|
1591
|
+
return { query, refresh, close, getItemById, revision: () => revision };
|
|
1654
1592
|
}
|
package/src/grades.mjs
CHANGED
|
@@ -141,14 +141,13 @@ function parseOverview(value) {
|
|
|
141
141
|
};
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
-
function parseGradeRows(data,
|
|
144
|
+
function parseGradeRows(data, allowedSemesterIds) {
|
|
145
145
|
requireValue(isPlainObject(data), '成绩接口结构已变化。', 'incompatible');
|
|
146
146
|
requireValue(Array.isArray(data.semesters), '成绩学期列表结构已变化。', 'incompatible');
|
|
147
147
|
|
|
148
148
|
const rows = [];
|
|
149
149
|
let totalInScope = 0;
|
|
150
150
|
let skipped = 0;
|
|
151
|
-
const needle = keyword.toLowerCase();
|
|
152
151
|
|
|
153
152
|
for (const semester of data.semesters) {
|
|
154
153
|
if (!isPlainObject(semester) || !validId(semester.id) || !Array.isArray(semester.scores)) {
|
|
@@ -174,7 +173,6 @@ function parseGradeRows(data, keyword, allowedSemesterIds) {
|
|
|
174
173
|
continue;
|
|
175
174
|
}
|
|
176
175
|
totalInScope += 1;
|
|
177
|
-
if (needle && !courseName.toLowerCase().includes(needle)) continue;
|
|
178
176
|
|
|
179
177
|
const visible = score.canSee !== false;
|
|
180
178
|
const row = {
|
|
@@ -395,7 +393,7 @@ function emptyRead(type, selected, keyword, includeDetails) {
|
|
|
395
393
|
};
|
|
396
394
|
}
|
|
397
395
|
|
|
398
|
-
export function createGrades({ withSchoolContext } = {}) {
|
|
396
|
+
export function createGrades({ withSchoolContext, cache } = {}) {
|
|
399
397
|
if (typeof withSchoolContext !== 'function') {
|
|
400
398
|
throw new TypeError('withSchoolContext must be a function');
|
|
401
399
|
}
|
|
@@ -436,8 +434,21 @@ export function createGrades({ withSchoolContext } = {}) {
|
|
|
436
434
|
return value;
|
|
437
435
|
}
|
|
438
436
|
|
|
439
|
-
async function
|
|
440
|
-
|
|
437
|
+
async function cached(key, load) {
|
|
438
|
+
const maxAge = 2 * 60 * 60_000;
|
|
439
|
+
const backoff = error => !['not_connected', 'authentication_required', 'SCHOOL_NOT_CONNECTED'].includes(error?.code);
|
|
440
|
+
const snapshot = cache?.get(key);
|
|
441
|
+
if (snapshot) {
|
|
442
|
+
if (cache.due(key, maxAge)) cache.refresh(key, load, { maxAge, backoff }).catch(() => {});
|
|
443
|
+
return snapshot.value;
|
|
444
|
+
}
|
|
445
|
+
const result = await (cache ? cache.refresh(key, load, { maxAge, backoff }) : load());
|
|
446
|
+
if (!result) fail('学校会话已变化或暂不可用,请重新查询成绩。', 'not_connected');
|
|
447
|
+
return result;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function terms() {
|
|
451
|
+
return cached('grade-terms', () => run(async (context) => {
|
|
441
452
|
const { semesters, types, defaultTrainTypeId } = await discover(context);
|
|
442
453
|
return {
|
|
443
454
|
semesters,
|
|
@@ -445,7 +456,7 @@ export function createGrades({ withSchoolContext } = {}) {
|
|
|
445
456
|
defaultTrainTypeId,
|
|
446
457
|
contentIsUntrusted: true
|
|
447
458
|
};
|
|
448
|
-
});
|
|
459
|
+
}));
|
|
449
460
|
}
|
|
450
461
|
|
|
451
462
|
async function read(input = {}) {
|
|
@@ -466,7 +477,8 @@ export function createGrades({ withSchoolContext } = {}) {
|
|
|
466
477
|
requireValue(!CONTROL_CHAR.test(rawKeyword), '课程关键词包含无效字符。');
|
|
467
478
|
const keyword = cleanText(rawKeyword, MAX_KEYWORD_CHARS);
|
|
468
479
|
|
|
469
|
-
|
|
480
|
+
const key = `grades:${JSON.stringify([semesterId, trainTypeId])}`;
|
|
481
|
+
const result = await cached(key, () => run(async (context) => {
|
|
470
482
|
const { semesters, types, defaultTrainTypeId } = await discover(context);
|
|
471
483
|
|
|
472
484
|
const type = trainTypeId == null
|
|
@@ -480,7 +492,7 @@ export function createGrades({ withSchoolContext } = {}) {
|
|
|
480
492
|
}
|
|
481
493
|
|
|
482
494
|
const selected = selectSemesters(semesters, semesterId);
|
|
483
|
-
if (selected.length === 0) return emptyRead(type, selected,
|
|
495
|
+
if (selected.length === 0) return emptyRead(type, selected, '', true);
|
|
484
496
|
|
|
485
497
|
const selectedIds = selected.map((semester) => semester.id);
|
|
486
498
|
const semesterIds = selectedIds.join(',');
|
|
@@ -491,9 +503,7 @@ export function createGrades({ withSchoolContext } = {}) {
|
|
|
491
503
|
trainTypeId: type.id,
|
|
492
504
|
semesterIds
|
|
493
505
|
});
|
|
494
|
-
const { rows, totalInScope, skipped } = parseGradeRows(
|
|
495
|
-
data, keyword, new Set(selectedIds)
|
|
496
|
-
);
|
|
506
|
+
const { rows, totalInScope, skipped } = parseGradeRows(data, new Set(selectedIds));
|
|
497
507
|
return {
|
|
498
508
|
state: rows.length > 0 ? 'ok' : 'empty',
|
|
499
509
|
trainTypeId: type.id,
|
|
@@ -501,15 +511,19 @@ export function createGrades({ withSchoolContext } = {}) {
|
|
|
501
511
|
semesters: selected.map(({ id, name }) => ({ id, name })),
|
|
502
512
|
overview: parseOverview(data.overview),
|
|
503
513
|
overviewScope: '所请求学期的完整成绩;关键词只筛选课程行。',
|
|
504
|
-
keyword,
|
|
514
|
+
keyword: '',
|
|
505
515
|
count: rows.length,
|
|
506
516
|
totalInScope,
|
|
507
|
-
detailsOmitted:
|
|
508
|
-
grades:
|
|
517
|
+
detailsOmitted: false,
|
|
518
|
+
grades: rows,
|
|
509
519
|
complete: skipped === 0,
|
|
510
520
|
contentIsUntrusted: true
|
|
511
521
|
};
|
|
512
|
-
});
|
|
522
|
+
}));
|
|
523
|
+
const needle = keyword.toLowerCase();
|
|
524
|
+
const rows = needle ? result.grades.filter(row => row.courseName.toLowerCase().includes(needle)) : result.grades;
|
|
525
|
+
return { ...result, keyword, state: rows.length ? 'ok' : 'empty', count: rows.length,
|
|
526
|
+
detailsOmitted: !includeDetails, grades: includeDetails ? rows : [] };
|
|
513
527
|
}
|
|
514
528
|
|
|
515
529
|
return Object.freeze({ terms, read });
|
package/src/host.mjs
CHANGED
|
@@ -3,8 +3,8 @@ import { CampusInputError, MAX_ICS, openCampus } from './state.mjs';
|
|
|
3
3
|
import { createSchool } from './school.mjs';
|
|
4
4
|
import { localMidnight } from './calendar.mjs';
|
|
5
5
|
import { createSchoolVault } from './school-vault.mjs';
|
|
6
|
-
import { createYouth
|
|
7
|
-
import {
|
|
6
|
+
import { createYouth } from './youth.mjs';
|
|
7
|
+
import { createAccountData } from './account-data.mjs';
|
|
8
8
|
import { createYouthActions } from './youth-actions.mjs';
|
|
9
9
|
import { BbError, createBb } from './bb.mjs';
|
|
10
10
|
import { createBbActions, openBbSession } from './bb-actions.mjs';
|
|
@@ -53,152 +53,39 @@ export const inject = ['profileContext'];
|
|
|
53
53
|
export function apply(ctx) {
|
|
54
54
|
const dir = join(ctx.profileContext.dir, 'ustc-campus');
|
|
55
55
|
const campus = openCampus(dir);
|
|
56
|
-
const school = createSchool({ dir, vault:createSchoolVault(dir) });
|
|
56
|
+
const school = createSchool({ dir, vault:createSchoolVault(dir), invalidateAccountData });
|
|
57
57
|
const bb = createBb({dataDir:join(dir,'bb'),withSchoolContext:school.withSchoolContext,connectReadSession:openBbSession});
|
|
58
58
|
const bbActions=createBbActions({bb});
|
|
59
59
|
const youth = createYouth({withSchoolContext:school.withSchoolContext});
|
|
60
60
|
const youthActions = createYouthActions({withSchoolContext:school.withSchoolContext});
|
|
61
|
-
const
|
|
61
|
+
const personal = createAccountData({ dir, school, youth,
|
|
62
|
+
createExams: cache => createExams({ withSchoolContext: school.withSchoolContext, cache }) });
|
|
63
|
+
const { exams } = personal;
|
|
64
|
+
const grades = createGrades({withSchoolContext:school.withSchoolContext, cache:personal.cache});
|
|
62
65
|
const librarySpaces = createLibrarySpaces({withSchoolContext:school.withSchoolContext});
|
|
63
66
|
const libraryBooking = createLibraryBooking({withSchoolContext:school.withSchoolContext,dataDir:dir});
|
|
64
67
|
const hsLibrary = createHsLibrary({withSchoolContext:school.withSchoolContext});
|
|
65
|
-
const
|
|
66
|
-
const transit = createCampusTransit();
|
|
68
|
+
const transit = createCampusTransit({ dir });
|
|
67
69
|
const libraryApprovals = new Map();
|
|
68
70
|
let accountSignal = new AbortController();
|
|
69
|
-
const youthWeeks = new Map();
|
|
70
|
-
let youthEnrollingCache = { at: 0, items: [], source: null, inFlight: null };
|
|
71
|
-
let cachedSchoolCourseTitles = [];
|
|
72
71
|
let accountEpoch = 0;
|
|
73
72
|
function invalidateAccountData() {
|
|
74
73
|
accountEpoch++;
|
|
75
74
|
accountSignal.abort();
|
|
76
75
|
accountSignal = new AbortController();
|
|
77
|
-
schoolWeeks.clear();
|
|
78
|
-
examWeeks.clear();
|
|
79
|
-
youthWeeks.clear();
|
|
80
|
-
youthEnrollingCache = { at: 0, items: [], source: null, inFlight: null };
|
|
81
|
-
cachedSchoolCourseTitles = [];
|
|
82
76
|
bbActions.clear();
|
|
83
77
|
libraryApprovals.clear();
|
|
84
78
|
hsLibrary.clear();
|
|
79
|
+
youthActions.clear();
|
|
80
|
+
campus.clearExtraFeedData();
|
|
81
|
+
personal.invalidate();
|
|
85
82
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
const epoch = shanghaiEpoch(y, mo, d, h, mi, m[3] ? Number(m[3]) : 0);
|
|
93
|
-
return { date: m[1], time: m[2], epoch };
|
|
94
|
-
}
|
|
95
|
-
async function getYouthEnrollingFeed(forceRefresh = false) {
|
|
96
|
-
if (school.status().state !== 'connected') {
|
|
97
|
-
return { extraItems: [], extraSources: [] };
|
|
98
|
-
}
|
|
99
|
-
const nowMs = Date.now();
|
|
100
|
-
if (!forceRefresh && youthEnrollingCache.source && nowMs - youthEnrollingCache.at < 5 * 60_000) {
|
|
101
|
-
return { extraItems: youthEnrollingCache.items, extraSources: [youthEnrollingCache.source] };
|
|
102
|
-
}
|
|
103
|
-
if (youthEnrollingCache.inFlight) return youthEnrollingCache.inFlight;
|
|
104
|
-
const epoch = accountEpoch;
|
|
105
|
-
youthEnrollingCache.inFlight = youth.listActivities({ mode: 'enrolling', page: 1, pageSize: 50 })
|
|
106
|
-
.then((res) => {
|
|
107
|
-
if (epoch !== accountEpoch || !res || res.state !== 'ok' || !Array.isArray(res.activities)) {
|
|
108
|
-
return { extraItems: youthEnrollingCache.items, extraSources: youthEnrollingCache.source ? [youthEnrollingCache.source] : [] };
|
|
109
|
-
}
|
|
110
|
-
const items = res.activities.map((act) => {
|
|
111
|
-
const st = parseHoldDateTime(act.holdStart);
|
|
112
|
-
const et = parseHoldDateTime(act.holdEnd);
|
|
113
|
-
const timeStr = st.time ? (et.time ? `${st.time}-${et.time}` : st.time) : null;
|
|
114
|
-
return {
|
|
115
|
-
id: `youth-enrolling:${act.id}`,
|
|
116
|
-
youthItemId: act.id,
|
|
117
|
-
source: 'youth-enrolling',
|
|
118
|
-
category: 'activity',
|
|
119
|
-
intent: 'activity',
|
|
120
|
-
requiresRegistration: true,
|
|
121
|
-
title: act.title,
|
|
122
|
-
url: YOUTH_SERVICE,
|
|
123
|
-
date: st.date,
|
|
124
|
-
time: timeStr,
|
|
125
|
-
location: act.location ?? null,
|
|
126
|
-
start: st.epoch,
|
|
127
|
-
end: et.epoch,
|
|
128
|
-
secondClassroom: true,
|
|
129
|
-
organizer: act.organizer ?? null,
|
|
130
|
-
enrollmentRatio: act.enrollmentRatio ?? null,
|
|
131
|
-
remainingSlots: act.remainingSlots ?? null,
|
|
132
|
-
hours: act.hours ?? null,
|
|
133
|
-
registered: act.registered ?? null,
|
|
134
|
-
reason: '',
|
|
135
|
-
past: false
|
|
136
|
-
};
|
|
137
|
-
});
|
|
138
|
-
const source = {
|
|
139
|
-
id: 'youth-enrolling',
|
|
140
|
-
label: '青春科大 · 报名中二课',
|
|
141
|
-
category: 'activity',
|
|
142
|
-
fetchedAt: Date.now(),
|
|
143
|
-
error: null
|
|
144
|
-
};
|
|
145
|
-
youthEnrollingCache = { at: Date.now(), items, source, inFlight: null };
|
|
146
|
-
return { extraItems: items, extraSources: [source] };
|
|
147
|
-
})
|
|
148
|
-
.catch(() => ({
|
|
149
|
-
extraItems: youthEnrollingCache.items,
|
|
150
|
-
extraSources: youthEnrollingCache.source ? [youthEnrollingCache.source] : []
|
|
151
|
-
}))
|
|
152
|
-
.finally(() => {
|
|
153
|
-
if (youthEnrollingCache) youthEnrollingCache.inFlight = null;
|
|
154
|
-
});
|
|
155
|
-
return youthEnrollingCache.inFlight;
|
|
156
|
-
}
|
|
157
|
-
function youthAgenda(from, through, refresh=false) {
|
|
158
|
-
const key = `${from}/${through}`;
|
|
159
|
-
const cached = youthWeeks.get(key);
|
|
160
|
-
if (cached && (!cached.finished || (!refresh && Date.now() - cached.at < 5 * 60_000))) return cached.request;
|
|
161
|
-
if (youthWeeks.size >= 8) youthWeeks.delete(youthWeeks.keys().next().value);
|
|
162
|
-
const entry = { at: Date.now(), finished:false, request: youth.read({from,through}).then(result => {
|
|
163
|
-
entry.finished = true;
|
|
164
|
-
if (youthWeeks.get(key) === entry && !result.complete) youthWeeks.delete(key);
|
|
165
|
-
return result;
|
|
166
|
-
}) };
|
|
167
|
-
youthWeeks.set(key,entry);
|
|
168
|
-
return entry.request;
|
|
169
|
-
}
|
|
170
|
-
const schoolWeeks = new Map();
|
|
171
|
-
const examWeeks = new Map();
|
|
172
|
-
function examWeek(from, through, refresh) {
|
|
173
|
-
const key=`${from}/${through}`;
|
|
174
|
-
const cached=examWeeks.get(key);
|
|
175
|
-
if(!refresh && cached && Date.now()-cached.at<5*60_000) return cached.request;
|
|
176
|
-
if(examWeeks.size>=8) examWeeks.delete(examWeeks.keys().next().value);
|
|
177
|
-
const request=exams.read({from,through}).catch(error=>{
|
|
178
|
-
if(examWeeks.get(key)?.request===request) examWeeks.delete(key);
|
|
179
|
-
return {state:error?.code==='not_connected'||error?.code==='authentication_required'?'not_connected':'unavailable',complete:false,entries:[]};
|
|
180
|
-
});
|
|
181
|
-
examWeeks.set(key,{at:Date.now(),request});
|
|
182
|
-
return request;
|
|
183
|
-
}
|
|
184
|
-
async function schoolWeek(from, through, refresh = false) {
|
|
185
|
-
const status = school.status();
|
|
186
|
-
if (status.state === 'pending') return {schoolEntries:[],state:'pending',complete:false};
|
|
187
|
-
if (status.state !== 'connected' && !(await school.credentialStatus()).enabled) return {schoolEntries:[],state:status.state,complete:false};
|
|
188
|
-
const key = `${from}/${through}`;
|
|
189
|
-
const cached = schoolWeeks.get(key);
|
|
190
|
-
if(status.state==='connected' && !refresh && cached && Date.now() - cached.at < 5 * 60_000) return cached.request;
|
|
191
|
-
if (schoolWeeks.size >= 8) schoolWeeks.delete(schoolWeeks.keys().next().value);
|
|
192
|
-
const request = school.agenda({from,through}).then(out => {
|
|
193
|
-
if(out.state!=='ok' && schoolWeeks.get(key)?.request === request) schoolWeeks.delete(key);
|
|
194
|
-
if(out.state==='ok' && Array.isArray(out.entries)) {
|
|
195
|
-
const titles = out.entries.map(e => typeof e?.title === 'string' ? e.title.trim() : '').filter(Boolean);
|
|
196
|
-
if (titles.length > 0) cachedSchoolCourseTitles = [...new Set([...cachedSchoolCourseTitles, ...titles])].slice(0, 40);
|
|
197
|
-
}
|
|
198
|
-
const state = school.status().state === 'pending' ? 'pending' : out.state;
|
|
199
|
-
return {schoolEntries:out.entries,state,complete:out.complete};
|
|
200
|
-
});
|
|
201
|
-
schoolWeeks.set(key,{at:Date.now(),request}); return request;
|
|
83
|
+
const queryFeed = (data = {}) => campus.queryFeed({ ...data, courseTitles: personal.courseTitles(), ...personal.feed() });
|
|
84
|
+
async function refreshFeed(options = {}) {
|
|
85
|
+
const [result] = await Promise.all([
|
|
86
|
+
campus.refresh(options), personal.refreshFeed(options.force === true)
|
|
87
|
+
]);
|
|
88
|
+
return result;
|
|
202
89
|
}
|
|
203
90
|
async function readBooking(read) {
|
|
204
91
|
const epoch=accountEpoch;
|
|
@@ -260,65 +147,44 @@ export function apply(ctx) {
|
|
|
260
147
|
async function dispatchOwner(op,data) {
|
|
261
148
|
if(op==='agenda-local') return campus.agenda(data);
|
|
262
149
|
if(op==='agenda') {
|
|
150
|
+
campus.validateAgendaRange(data.from, data.through);
|
|
263
151
|
const epoch = accountEpoch;
|
|
264
|
-
const
|
|
265
|
-
const refresh = data.refresh === true;
|
|
266
|
-
const schoolData=await schoolWeek(data.from,data.through,refresh);
|
|
267
|
-
const secondary = {state:'not_connected',complete:false,entries:[]};
|
|
268
|
-
const [enrollment, examData] = schoolData.state==='ok'
|
|
269
|
-
? await Promise.all([youthAgenda(data.from,data.through,refresh),examWeek(data.from,data.through,refresh)])
|
|
270
|
-
: [secondary,secondary];
|
|
152
|
+
const { schoolEntries, ...metadata } = await personal.agenda(data);
|
|
271
153
|
if (epoch !== accountEpoch) {
|
|
272
|
-
const unavailable={state:'not_connected',complete:false};
|
|
273
|
-
return { ...
|
|
154
|
+
const unavailable = { state: 'not_connected', complete: false };
|
|
155
|
+
return { ...campus.agenda(data), school: { state: school.status().state, complete: false },
|
|
156
|
+
exams: unavailable, youth: { ...unavailable, verifiedCount: 0 }, stale: false, syncing: false, cachedAt: null };
|
|
274
157
|
}
|
|
275
|
-
|
|
276
|
-
const merged=schoolEntries.length ? campus.agenda(data,{schoolEntries}) : local;
|
|
277
|
-
return {...merged, school:{state:schoolData.state,complete:schoolData.complete}, exams:{state:examData.state,complete:examData.complete}, youth:{state:enrollment.state,complete:enrollment.complete,verifiedCount:enrollment.entries.length}};
|
|
158
|
+
return { ...campus.agenda(data, { schoolEntries }), ...metadata };
|
|
278
159
|
}
|
|
279
160
|
if(op==='item-mutate' && data.action==='remove' && typeof data.id==='string' && /^(?:school|youth)_/.test(data.id)) {
|
|
280
161
|
const epoch = accountEpoch;
|
|
281
162
|
localMidnight(data.date);
|
|
282
|
-
const
|
|
283
|
-
const enrollment=data.id.startsWith('youth_') ? await youthAgenda(data.date,data.date) : {entries:[]};
|
|
284
|
-
const examData=rows.state==='ok' && data.id.startsWith('school_') && !rows.schoolEntries.some(row=>row.id===data.id) ? await examWeek(data.date,data.date,false) : {entries:[]};
|
|
163
|
+
const { schoolEntries } = await personal.agenda({ from: data.date, through: data.date });
|
|
285
164
|
if(epoch!==accountEpoch) throw new CampusInputError('学校账号已切换,请重新打开日程');
|
|
286
|
-
return campus.mutateItem(data,{schoolEntries
|
|
165
|
+
return campus.mutateItem(data,{schoolEntries,includeSchool:true});
|
|
287
166
|
}
|
|
288
167
|
if(op==='item-find') return campus.findItems(data,{includeSchool:true});
|
|
289
168
|
if(op==='item-mutate') return campus.mutateItem(data,{includeSchool:true});
|
|
290
|
-
if(op==='school-logout')
|
|
291
|
-
if(op==='school-login') {
|
|
292
|
-
|
|
293
|
-
return school.login({manual:data.manual===true});
|
|
294
|
-
}
|
|
295
|
-
if(op==='school-credentials-save') {
|
|
296
|
-
const result = await school.saveCredentials(data);
|
|
297
|
-
if (result.saved) invalidateAccountData();
|
|
298
|
-
return result;
|
|
299
|
-
}
|
|
169
|
+
if(op==='school-logout') return school.logout();
|
|
170
|
+
if(op==='school-login') return school.login({manual:data.manual===true});
|
|
171
|
+
if(op==='school-credentials-save') return school.saveCredentials(data);
|
|
300
172
|
if(op==='bb-requests') return bbActions.list();
|
|
301
173
|
if(op==='bb-status') return bbActions.status(data.id);
|
|
302
174
|
if(op==='grade-terms') return grades.terms();
|
|
303
175
|
if(op==='grade-read') return grades.read(data);
|
|
304
176
|
if(op==='school-exams') return exams.read(data);
|
|
305
|
-
if(op==='campus-shuttle') return transit.read(data);
|
|
177
|
+
if(op==='campus-shuttle') return transit.read({ ...data, autoResolve: true });
|
|
306
178
|
if(op==='library-space-categories') return librarySpaces.categories();
|
|
307
179
|
if(op==='library-space-availability') return librarySpaces.availability(data);
|
|
308
180
|
if(op==='library-booking-prepare') return prepareBooking(data);
|
|
309
181
|
if(op==='library-booking-status') return bookingStatus(data);
|
|
310
182
|
if(op==='library-booking-reservations') return reservations(data);
|
|
311
183
|
if(op==='library-booking-unresolved') return readBooking(libraryBooking.unresolved);
|
|
312
|
-
if(op==='feed')
|
|
313
|
-
const extra = await getYouthEnrollingFeed(false);
|
|
314
|
-
return campus.queryFeed({ ...data, courseTitles: cachedSchoolCourseTitles, ...extra });
|
|
315
|
-
}
|
|
184
|
+
if(op==='feed') return queryFeed(data);
|
|
316
185
|
if(op==='refresh') {
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
getYouthEnrollingFeed(data.force === true)
|
|
320
|
-
]);
|
|
321
|
-
return campus.queryFeed({ ...data, courseTitles: cachedSchoolCourseTitles, ...extra });
|
|
186
|
+
await refreshFeed({ force: data.force === true });
|
|
187
|
+
return queryFeed(data);
|
|
322
188
|
}
|
|
323
189
|
if(op==='feed-feedback') return campus.recordFeedFeedback(data);
|
|
324
190
|
if(op==='feed-profile') return campus.feedProfile();
|
|
@@ -333,10 +199,13 @@ export function apply(ctx) {
|
|
|
333
199
|
}
|
|
334
200
|
ctx.provide('ustcCampus', {
|
|
335
201
|
...campus,
|
|
336
|
-
|
|
337
|
-
|
|
202
|
+
queryFeed,
|
|
203
|
+
refresh: refreshFeed
|
|
338
204
|
});
|
|
339
|
-
ctx.provide('ustcSchool', school)
|
|
205
|
+
ctx.provide('ustcSchool', { ...school, async agenda(data) {
|
|
206
|
+
campus.validateAgendaRange(data?.from, data?.through);
|
|
207
|
+
return personal.timetableFor(data);
|
|
208
|
+
} });
|
|
340
209
|
ctx.provide('ustcBb', {listCourses:bb.listCourses,listAssignments:bb.listAssignments,inspectAssignment:bb.inspectAssignment,request:bbActions.request,status:bbActions.status,
|
|
341
210
|
confirm:(data,approve,signal)=>bbActions.confirm(data,approve,AbortSignal.any([signal,accountSignal.signal])),
|
|
342
211
|
submitDirect:(data,signal)=>bbActions.submitDirect(data,signal?AbortSignal.any([signal,accountSignal.signal]):accountSignal.signal)});
|
|
@@ -361,7 +230,7 @@ export function apply(ctx) {
|
|
|
361
230
|
});
|
|
362
231
|
ctx.provide('ustcExams', exams);
|
|
363
232
|
ctx.provide('ustcTransit', transit);
|
|
364
|
-
ctx.effect(() => async () => { accountSignal.abort(); campus.close(); await school.close(); });
|
|
233
|
+
ctx.effect(() => async () => { accountSignal.abort(); personal.close(); campus.close(); await school.close(); });
|
|
365
234
|
ctx.inject(['connection'], scope => scope.connection.fetch.register({
|
|
366
235
|
path: '/api/ustc-campus', methods: ['POST'], requestBody: 'streaming',
|
|
367
236
|
async fetch(request) {
|
|
@@ -395,8 +264,6 @@ function dispatch(campus, school, op, data) {
|
|
|
395
264
|
switch (op) {
|
|
396
265
|
case 'import': return campus.importCalendar(data);
|
|
397
266
|
case 'forget': return campus.forgetCalendar(data);
|
|
398
|
-
case 'feed': return campus.queryFeed(data);
|
|
399
|
-
case 'refresh': return campus.refresh({ force: data.force === true }).then(() => campus.queryFeed(data));
|
|
400
267
|
case 'materials': return campus.lookup(data.query);
|
|
401
268
|
case 'save': return campus.saveEvent(data);
|
|
402
269
|
case 'school-status': return school.status();
|