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.
@@ -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
+ }
@@ -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
- async function read(input = {}) {
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, range);
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
- return Object.freeze({ read });
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. `query` is synchronous and
1380
- * returns the last good cache immediately; a stale cache is refreshed in the
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 mapWithConcurrency(SOURCE_IDS, REFRESH_CONCURRENCY, async (id) => {
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 = sortItems(projected, sort, interests, agenda, nowMs);
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, keyword, allowedSemesterIds) {
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 terms() {
440
- return run(async (context) => {
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
- return run(async (context) => {
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, keyword, includeDetails);
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: !includeDetails,
508
- grades: includeDetails ? rows : [],
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 });