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/src/youth.mjs CHANGED
@@ -13,10 +13,9 @@
13
13
  * - `https://young.ustc.edu.cn/login/sc-wisdom-group-learning/` is the
14
14
  * registered CAS service used by the platform's own login page;
15
15
  * - `cas/client/checkSsoLogin` exchanges a CAS ticket over GET;
16
- * - `item/scParticipateItem/list` is the enrolled list, filtered by the
17
- * token on the server side;
18
- * - `item/scItem/queryById` confirms the viewer's enrollment when the
19
- * listing does not carry an explicit registration flag.
16
+ * - `item/scParticipateItem/list?queryCatelog=0` is the signed-in user's
17
+ * «已参与项目» list; membership comes from that list, not its rows' flags;
18
+ * - `item/scItem/queryById` can supply missing event times.
20
19
  * The names and envelope were cross-checked against pyustc v1.2.1 and the
21
20
  * platform's own browser bundle; no upstream source is copied here.
22
21
  *
@@ -27,11 +26,12 @@
27
26
  * The returned object has exactly three fields: `{ state, entries, complete }`.
28
27
  * `state` is one of `ok`, `empty`, `not_connected` or `failure`. A row is
29
28
  * returned only when its upstream ID, title and both times are present and
30
- * unambiguous; anything else is dropped and marks `complete` false.
29
+ * unambiguous; undated rows are not scheduled.
31
30
  */
32
31
 
33
32
  import { createCipheriv } from 'node:crypto';
34
33
  import { shanghaiEpoch } from './public-fetch.mjs';
34
+ import { mapLimited } from './concurrency.mjs';
35
35
 
36
36
  export const YOUTH_ORIGIN = 'https://young.ustc.edu.cn';
37
37
  export const YOUTH_LOGIN_URL = `${YOUTH_ORIGIN}/login`;
@@ -46,9 +46,9 @@ const DEFAULT_TOKEN = 'kPBNkx0sSO3aIBaKDt9d2GJURVJfzFuP';
46
46
  const MAX_REDIRECT_HOPS = 8;
47
47
  const MAX_BODY_CHARS = 2_000_000;
48
48
  const MAX_RESPONSE_ROWS = 5_000;
49
- const DEFAULT_PAGE_SIZE = 50;
50
- const DEFAULT_MAX_PAGES = 4;
51
- const MAX_DETAIL_CHECKS = 12;
49
+ const DEFAULT_PAGE_SIZE = 100;
50
+ const DEFAULT_MAX_PAGES = 20;
51
+ const MAX_DETAIL_CHECKS = 24;
52
52
  const DETAIL_TIMEOUT_MS = 2_000;
53
53
  const DEFAULT_MAX_TOTAL = 2_000;
54
54
  const DEFAULT_TIMEOUT_MS = 20_000;
@@ -547,6 +547,11 @@ function registration(record) {
547
547
  }
548
548
  }
549
549
 
550
+ function activeParticipation(record) {
551
+ return String(record.examineStatus) !== '-3'
552
+ && ![record.itemStatus_dictText, record.applyStatus_dictText].some(label => /已取消|取消报名|已终止/.test(label ?? ''));
553
+ }
554
+
550
555
  function enrolledRow(record) {
551
556
  if (!record || typeof record !== 'object' || Array.isArray(record)) return null;
552
557
 
@@ -554,7 +559,7 @@ function enrolledRow(record) {
554
559
  const title = cleanText(record.itemName ?? record.title, 200);
555
560
  if (!id || !title) return null;
556
561
 
557
- if (registration(record) !== true) return null;
562
+ if (String(record.itemCategory) === '1' || !activeParticipation(record)) return null;
558
563
 
559
564
  const start = localTime(record.st ?? record.startTime);
560
565
  const end = localTime(record.et ?? record.endTime);
@@ -572,6 +577,12 @@ function enrolledRow(record) {
572
577
  };
573
578
  }
574
579
 
580
+ function explicitlyEnded(record, now) {
581
+ const end = localTime(record.et ?? record.endTime);
582
+ return (end && end.epoch < now) || /已结束|已终止|已取消|已完结/.test(record.itemStatus_dictText ?? record.applyStatus_dictText ?? '')
583
+ || String(record.examineStatus) === '-3';
584
+ }
585
+
575
586
  function sortRows(rows) {
576
587
  return rows.sort((left, right) => (
577
588
  left.start - right.start
@@ -589,11 +600,10 @@ function sortRows(rows) {
589
600
  * never accepts a token, cookie or username from its caller.
590
601
  *
591
602
  * @param {object} options
592
- * @param {object} options.context dedicated authenticated browser context
593
603
  * @param {Function} [options.now] clock seam returning epoch milliseconds
594
604
  * @param {number} [options.requestTimeoutMs]
595
- * @param {number} [options.pageSize] 1..100, default 50
596
- * @param {number} [options.maxPages] 1..10, default 4
605
+ * @param {number} [options.pageSize] 1..100, default 100
606
+ * @param {number} [options.maxPages] 1..100, default 20
597
607
  * @param {number} [options.maxTotal] safety cap for upstream `total`
598
608
  * @param {string} [options.from] inclusive Shanghai date of the first requested day
599
609
  * @param {string} [options.through] inclusive Shanghai date of the last requested day
@@ -613,7 +623,7 @@ export async function readEnrolled({
613
623
  now: typeof now === 'function' ? now : Date.now,
614
624
  timeout: boundedInteger(requestTimeoutMs, DEFAULT_TIMEOUT_MS, 1_000, 120_000),
615
625
  pageSize: boundedInteger(pageSize, DEFAULT_PAGE_SIZE, 1, 100),
616
- maxPages: boundedInteger(maxPages, DEFAULT_MAX_PAGES, 1, 10),
626
+ maxPages: boundedInteger(maxPages, DEFAULT_MAX_PAGES, 1, 100),
617
627
  maxTotal: boundedInteger(maxTotal, DEFAULT_MAX_TOTAL, 1, 10_000)
618
628
  };
619
629
 
@@ -639,7 +649,11 @@ export async function readEnrolled({
639
649
  let lastPage = 1;
640
650
  let complete = true;
641
651
  let page = 1;
642
- let detailChecks = 0;
652
+ const missingTimes = [];
653
+ const nowMs = clockValue(options.now);
654
+ const collect = row => {
655
+ if (row && (!from || row.date >= from) && (!through || row.date <= through)) entries.push(row);
656
+ };
643
657
 
644
658
  while (page <= options.maxPages) {
645
659
  let pageResult;
@@ -650,8 +664,9 @@ export async function readEnrolled({
650
664
  }
651
665
 
652
666
  if (pageResult.kind !== 'page') {
653
- if (entries.length > 0) return result('ok', sortRows(entries), false);
654
- return result(pageResult.kind === 'not_connected' ? 'not_connected' : 'failure');
667
+ if (total === null) return result(pageResult.kind === 'not_connected' ? 'not_connected' : 'failure');
668
+ complete = false;
669
+ break;
655
670
  }
656
671
 
657
672
  if (total === null) {
@@ -663,25 +678,17 @@ export async function readEnrolled({
663
678
  lastPage = Math.max(lastPage, Math.ceil(pageResult.total / options.pageSize));
664
679
  if (pageResult.records.length !== Math.min(options.pageSize, Math.max(0, pageResult.total - (page - 1) * options.pageSize))) complete = false;
665
680
 
666
- for (let record of pageResult.records) {
681
+ for (const record of pageResult.records) {
667
682
  const id = cleanId(record?.id ?? record?.itemId);
668
683
  if (!id || seen.has(id)) { complete = false; continue; }
669
684
  seen.add(id);
685
+ if (String(record.itemCategory) === '1' || !activeParticipation(record)) continue;
670
686
  const start = localTime(record.st ?? record.startTime);
671
687
  if (start && ((from && start.date < from) || (through && start.date > through))) continue;
672
- if (registration(record) === false) continue;
673
- if (registration(record) == null && detailChecks < MAX_DETAIL_CHECKS) {
674
- detailChecks += 1;
675
- const detail = await youthQuery(context, token, 'item/scItem/queryById', {id}, detailOptions);
676
- if (detail.kind === 'ok' && cleanId(detail.value.id) === id && registration(detail.value) !== null) {
677
- record = { ...record, ...detail.value };
678
- }
679
- }
680
- if (registration(record) === false) continue;
681
688
  const row = enrolledRow(record);
682
- if (!row) { complete = false; continue; }
683
- if ((from && row.date < from) || (through && row.date > through)) continue;
684
- entries.push(row);
689
+ if (row) collect(row);
690
+ else if (missingTimes.length < MAX_DETAIL_CHECKS && !explicitlyEnded(record, nowMs)
691
+ && (!start || !localTime(record.et ?? record.endTime))) missingTimes.push({ id, record });
685
692
  }
686
693
 
687
694
  if (page >= lastPage) break;
@@ -692,9 +699,15 @@ export async function readEnrolled({
692
699
  page += 1;
693
700
  }
694
701
 
702
+ const details = await mapLimited(missingTimes, 4, async ({ id, record }) => {
703
+ const detail = await youthQuery(context, token, 'item/scItem/queryById', { id }, detailOptions);
704
+ if (detail.kind === 'ok' && cleanId(detail.value.id ?? detail.value.itemId) === id) {
705
+ return enrolledRow({ ...record, ...detail.value });
706
+ }
707
+ });
708
+ for (const detail of details) if (detail.status === 'fulfilled') collect(detail.value);
695
709
  complete &&= seen.size === total;
696
710
  if (total === 0) return complete ? result('empty') : result('failure');
697
- if (entries.length === 0 && !complete) return result('failure');
698
711
  return result('ok', sortRows(entries), complete);
699
712
  }
700
713
 
@@ -770,7 +783,7 @@ function deriveCheckInInfo(record) {
770
783
  };
771
784
  }
772
785
 
773
- function mapActivitySummary(record) {
786
+ function mapActivitySummary(record, ownParticipation = false) {
774
787
  if (!record || typeof record !== 'object' || Array.isArray(record)) return null;
775
788
  const id = cleanId(record.id ?? record.itemId);
776
789
  const title = cleanText(record.itemName ?? record.title, 200);
@@ -805,7 +818,7 @@ function mapActivitySummary(record) {
805
818
  remainingSlots: enrolledCount !== null && capacity !== null && capacity > 0
806
819
  ? Math.max(0, capacity - enrolledCount)
807
820
  : null,
808
- registered: registration(record),
821
+ registered: ownParticipation ? activeParticipation(record) : registration(record),
809
822
  isSeries,
810
823
  marathon: Number(record.marathon) === 1,
811
824
  needSignInfo: String(record.needSignInfo) === '1'
@@ -845,6 +858,10 @@ export async function listYouthActivities({
845
858
  const opts = { now, timeout: boundedInteger(requestTimeoutMs, DEFAULT_TIMEOUT_MS, 1_000, 120_000) };
846
859
 
847
860
  const session = await obtainYouthSession(context, opts);
861
+ return listActivityPage(context, session, normalizedMode, kw, pageNo, size, opts);
862
+ }
863
+
864
+ async function listActivityPage(context, session, normalizedMode, kw, pageNo, size, opts) {
848
865
  if (session.kind !== 'token') {
849
866
  const isNotConn = session.kind === 'not_connected';
850
867
  return {
@@ -878,7 +895,8 @@ export async function listYouthActivities({
878
895
  if (!records || records.length > MAX_RESPONSE_ROWS) {
879
896
  return { state: 'failure', mode: normalizedMode, items: [], message: '暂时无法读取青春科大活动列表,请稍后重试。', untrustedContent: true };
880
897
  }
881
- const items = records.map(mapActivitySummary).filter(Boolean).slice(0, size);
898
+ const ownParticipation = normalizedMode === 'enrolled';
899
+ const items = records.map(record => mapActivitySummary(record, ownParticipation)).filter(Boolean).slice(0, size);
882
900
  return {
883
901
  state: items.length > 0 ? 'ok' : 'empty',
884
902
  mode: normalizedMode,
@@ -886,7 +904,7 @@ export async function listYouthActivities({
886
904
  pageSize: size,
887
905
  total: total ?? items.length,
888
906
  items,
889
- note: '列表中的 applyStart/applyEnd 为报名起止时间;若未含举办时间,查看详情可获取具体时间。',
907
+ note: 'applyStart/applyEnd 为报名起止时间;举办时间缺失时请看详情。公开列表的 enrolledCount / remainingSlots 为上游缓存,余量以详情或报名草稿的实时校验为准。',
890
908
  untrustedContent: true
891
909
  };
892
910
  }
@@ -1144,6 +1162,19 @@ export function createYouth({ withSchoolContext, acquireContext, ...options } =
1144
1162
  return fn(context);
1145
1163
  }
1146
1164
 
1165
+ async function enrollmentPages(context) {
1166
+ const opts = { now: options.now ?? Date.now, timeout: options.requestTimeoutMs ?? DEFAULT_TIMEOUT_MS };
1167
+ const session = await obtainYouthSession(context, opts);
1168
+ const size = 50;
1169
+ const read = page => listActivityPage(context, session, 'enrolling', '', page, size, opts);
1170
+ const first = await read(1);
1171
+ if (first.state !== 'ok' || first.total <= size) return first;
1172
+ const pages = Array.from({ length: Math.min(50, Math.ceil(first.total / size)) - 1 }, (_, i) => i + 2);
1173
+ const results = await mapLimited(pages, 4, read);
1174
+ if (results.some(r => r.status !== 'fulfilled' || !['ok', 'empty'].includes(r.value.state))) return result('failure');
1175
+ return { ...first, items: first.items.concat(...results.map(r => r.value.items)) };
1176
+ }
1177
+
1147
1178
  return Object.freeze({
1148
1179
  read({ from, through } = {}) {
1149
1180
  return runScoped(
@@ -1151,6 +1182,9 @@ export function createYouth({ withSchoolContext, acquireContext, ...options } =
1151
1182
  (state) => result(state)
1152
1183
  );
1153
1184
  },
1185
+ enrollingFeed() {
1186
+ return runScoped(enrollmentPages, state => result(state));
1187
+ },
1154
1188
  listActivities(args = {}) {
1155
1189
  return runScoped(
1156
1190
  (context) => listYouthActivities({ context, ...options, ...args }),