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/LICENSE +661 -0
- package/README.md +105 -72
- package/dist/client.js +6037 -1061
- package/package.json +63 -60
- package/src/account-data.mjs +279 -0
- package/src/bb-actions.mjs +3 -1
- package/src/bb.mjs +94 -21
- 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 +59 -179
- package/src/hs-library.mjs +41 -0
- package/src/library-booking.mjs +33 -5
- package/src/library-spaces.mjs +39 -35
- package/src/material.mjs +2320 -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 +67 -17
- package/src/week-layout.mjs +10 -1
- package/src/youth-actions.mjs +52 -58
- package/src/youth.mjs +68 -34
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
function unlink(file) {
|
|
4
|
+
try { unlinkSync(file); }
|
|
5
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
// One owner per file. Writes and invalidation are synchronous so no old-account
|
|
9
|
+
// rename can race an unlink. Network readers carry the generation they started in.
|
|
10
|
+
export function createSnapshotCache(file, { now = Date.now, limit = 64, retryMs = 60_000 } = {}) {
|
|
11
|
+
const temporary = file && `${file}.tmp`;
|
|
12
|
+
const entries = new Map();
|
|
13
|
+
const pending = new Map();
|
|
14
|
+
const failures = new Map();
|
|
15
|
+
let generation = 0;
|
|
16
|
+
if (file) {
|
|
17
|
+
try { unlink(temporary); } catch { /* retry on write or explicit clear */ }
|
|
18
|
+
try {
|
|
19
|
+
const stored = JSON.parse(readFileSync(file, 'utf8'));
|
|
20
|
+
if (stored.version === 1 && Array.isArray(stored.entries)) {
|
|
21
|
+
for (const [key, entry] of stored.entries.slice(-limit)) {
|
|
22
|
+
if (typeof key === 'string' && Number.isFinite(entry?.at) && entry.value != null) entries.set(key, entry);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
} catch { /* missing or unreadable cache: refill from the source */ }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function persist() {
|
|
29
|
+
if (!file) return;
|
|
30
|
+
try {
|
|
31
|
+
writeFileSync(temporary, JSON.stringify({ version: 1, entries: [...entries] }), { flag: 'wx', mode: 0o600 });
|
|
32
|
+
renameSync(temporary, file);
|
|
33
|
+
} catch {
|
|
34
|
+
try { unlink(temporary); } catch { /* explicit clear will retry */ }
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function setBounded(map, key, value) {
|
|
39
|
+
map.delete(key);
|
|
40
|
+
if (map.size >= limit) map.delete(map.keys().next().value);
|
|
41
|
+
map.set(key, value);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function refresh(key, load, { maxAge = 0, force = false, accept = () => true, backoff = () => true } = {}) {
|
|
45
|
+
const running = pending.get(key);
|
|
46
|
+
if (running) return running;
|
|
47
|
+
const cached = entries.get(key);
|
|
48
|
+
const time = now();
|
|
49
|
+
if (!force && (time - (cached?.at ?? -Infinity) < maxAge || time - (failures.get(key) ?? -Infinity) < retryMs)) {
|
|
50
|
+
if (cached) return Promise.resolve(cached.value);
|
|
51
|
+
if (failures.has(key)) return Promise.resolve(undefined);
|
|
52
|
+
}
|
|
53
|
+
const epoch = generation;
|
|
54
|
+
const task = Promise.resolve().then(() => epoch === generation ? load() : undefined).then(value => {
|
|
55
|
+
if (epoch !== generation) return undefined;
|
|
56
|
+
if (accept(value)) {
|
|
57
|
+
setBounded(entries, key, { at: now(), value });
|
|
58
|
+
failures.delete(key);
|
|
59
|
+
persist();
|
|
60
|
+
} else if (backoff(value)) {
|
|
61
|
+
setBounded(failures, key, now());
|
|
62
|
+
}
|
|
63
|
+
return value;
|
|
64
|
+
}, error => {
|
|
65
|
+
if (epoch !== generation) return undefined;
|
|
66
|
+
if (backoff(error)) setBounded(failures, key, now());
|
|
67
|
+
throw error;
|
|
68
|
+
}).finally(() => {
|
|
69
|
+
if (pending.get(key) === task) pending.delete(key);
|
|
70
|
+
});
|
|
71
|
+
pending.set(key, task);
|
|
72
|
+
return task;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function cancelPending() {
|
|
76
|
+
generation++;
|
|
77
|
+
pending.clear();
|
|
78
|
+
}
|
|
79
|
+
function clearFailures() {
|
|
80
|
+
failures.clear();
|
|
81
|
+
}
|
|
82
|
+
function clear() {
|
|
83
|
+
cancelPending();
|
|
84
|
+
entries.clear();
|
|
85
|
+
failures.clear();
|
|
86
|
+
if (!file) return;
|
|
87
|
+
try { unlink(file); }
|
|
88
|
+
finally { unlink(temporary); }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return { get: key => entries.get(key), syncing: key => pending.has(key), refresh, clear, clearFailures, cancelPending,
|
|
92
|
+
due(key, maxAge) {
|
|
93
|
+
const time = now();
|
|
94
|
+
return !pending.has(key) && time - (entries.get(key)?.at ?? -Infinity) >= maxAge
|
|
95
|
+
&& time - (failures.get(key) ?? -Infinity) >= retryMs;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
}
|
package/src/state.mjs
CHANGED
|
@@ -11,7 +11,10 @@ import { sanitizeText } from './public-fetch.mjs';
|
|
|
11
11
|
|
|
12
12
|
export const MAX_ICS = 1024 * 1024;
|
|
13
13
|
const MAX_SCHOOL_ENTRIES = 2000;
|
|
14
|
+
const FEED_SNAPSHOT_LIMIT = 12;
|
|
15
|
+
const NO_EXTRA_ITEMS = [];
|
|
14
16
|
const localKinds = new Set(['course', 'exam']);
|
|
17
|
+
const schoolKinds = new Set(['exam', 'event', 'deadline', 'reservation']);
|
|
15
18
|
const readLabels = { schedule: '课表', saved: '收藏', items: '日程', recommender: '推荐偏好', 'custom-feeds': '自定义订阅' };
|
|
16
19
|
export class CampusInputError extends Error {}
|
|
17
20
|
function clockMinutes(value) {
|
|
@@ -41,13 +44,26 @@ export function openCampus(dir, { now = Date.now, fetch = globalThis.fetch } = {
|
|
|
41
44
|
};
|
|
42
45
|
const feed = createFeed({ read, write, now, fetch });
|
|
43
46
|
const customFeeds = createCustomFeeds({ read, write, now, fetch });
|
|
44
|
-
|
|
47
|
+
let feedbackVersion = 0;
|
|
48
|
+
const recommender = createRecommender({ read, now, write(key, value) {
|
|
49
|
+
feedbackVersion++;
|
|
50
|
+
write(key, value);
|
|
51
|
+
} });
|
|
45
52
|
const lastExtraItemsById = new Map();
|
|
46
53
|
const materials = createMaterials({ read, write, now, fetch });
|
|
47
54
|
const localItems = createLocalItems({ read, write, now });
|
|
48
55
|
let schedule = read('schedule') ?? {};
|
|
49
56
|
let saved = read('saved') ?? {};
|
|
50
57
|
let recommendationAgenda;
|
|
58
|
+
const feedSnapshots = new Map();
|
|
59
|
+
let snapshotsVersion;
|
|
60
|
+
let indexedExtras;
|
|
61
|
+
|
|
62
|
+
function clearExtraFeedData() {
|
|
63
|
+
lastExtraItemsById.clear();
|
|
64
|
+
indexedExtras = undefined;
|
|
65
|
+
feedSnapshots.clear();
|
|
66
|
+
}
|
|
51
67
|
const range = (from, through) => {
|
|
52
68
|
let start, last;
|
|
53
69
|
try { start = localMidnight(from); last = localMidnight(through); }
|
|
@@ -118,7 +134,7 @@ export function openCampus(dir, { now = Date.now, fetch = globalThis.fetch } = {
|
|
|
118
134
|
if (!source || /^https?:\/\//i.test(source)) source = '学校教务';
|
|
119
135
|
entries.push({
|
|
120
136
|
id,
|
|
121
|
-
kind: item.kind
|
|
137
|
+
kind: schoolKinds.has(item.kind) ? item.kind : 'course',
|
|
122
138
|
title,
|
|
123
139
|
date,
|
|
124
140
|
start,
|
|
@@ -126,6 +142,8 @@ export function openCampus(dir, { now = Date.now, fetch = globalThis.fetch } = {
|
|
|
126
142
|
allDay: item.allDay === true || (startClock == null && !Number.isFinite(item.start)),
|
|
127
143
|
location,
|
|
128
144
|
source,
|
|
145
|
+
...(item.kind === 'deadline' && { courseTitle: sanitizeText(item.courseTitle, 300) }),
|
|
146
|
+
...(item.url && { url: item.url }),
|
|
129
147
|
school: true,
|
|
130
148
|
external: true,
|
|
131
149
|
});
|
|
@@ -151,10 +169,15 @@ export function openCampus(dir, { now = Date.now, fetch = globalThis.fetch } = {
|
|
|
151
169
|
truncated: report.truncated, warnings: issues });
|
|
152
170
|
if (issues.length || report.truncated) warnings.push(`${item.label}:${report.truncated ? '未完整展开' : '有日历警告'}${issues.length ? `(${issues[0]})` : ''}`);
|
|
153
171
|
}
|
|
172
|
+
const trustedEntries = trusted && typeof trusted === 'object' ? trusted.schoolEntries : undefined;
|
|
173
|
+
const enrolledIds = new Set();
|
|
174
|
+
if (Array.isArray(trustedEntries)) for (const entry of trustedEntries) {
|
|
175
|
+
if (typeof entry?.id === 'string' && entry.id.startsWith('youth_')) enrolledIds.add(entry.id);
|
|
176
|
+
}
|
|
154
177
|
for (const item of Object.values(saved)) {
|
|
178
|
+
if (item.activitySource === 'youth-enrolling' && enrolledIds.has(`youth_${item.id.slice('youth-enrolling:'.length)}`)) continue;
|
|
155
179
|
if (item.start != null ? item.start < end && Math.max(item.end ?? item.start, item.start + 1) > start : item.date >= from && item.date <= through) entries.push({ ...item, saved: true });
|
|
156
180
|
}
|
|
157
|
-
const trustedEntries = trusted && typeof trusted === 'object' ? trusted.schoolEntries : undefined;
|
|
158
181
|
entries.push(...schoolEntryList(trustedEntries, { from, through, hidden, warnings }));
|
|
159
182
|
const personal = localItems.entriesIn(from, through);
|
|
160
183
|
entries.push(...personal.entries);
|
|
@@ -196,12 +219,46 @@ export function openCampus(dir, { now = Date.now, fetch = globalThis.fetch } = {
|
|
|
196
219
|
return customFeeds.getSourceMeta(srcId) ?? null;
|
|
197
220
|
}
|
|
198
221
|
function queryFeed(options = {}) {
|
|
199
|
-
const
|
|
200
|
-
|
|
222
|
+
const nowMs = now();
|
|
223
|
+
const from = shDate(nowMs);
|
|
224
|
+
const recommended = options.sort === 'recommended' || options.sort === 'recommend';
|
|
225
|
+
if (recommended && recommendationAgenda?.from !== from) {
|
|
201
226
|
recommendationAgenda = agenda({ from, through: shDate(localMidnight(from) + 30 * DAY) });
|
|
202
227
|
}
|
|
203
|
-
const coverage =
|
|
204
|
-
const
|
|
228
|
+
const coverage = recommended ? recommendationAgenda : null;
|
|
229
|
+
const hostExtraItems = Array.isArray(options.extraItems) ? options.extraItems : NO_EXTRA_ITEMS;
|
|
230
|
+
if (hostExtraItems !== indexedExtras) {
|
|
231
|
+
clearExtraFeedData();
|
|
232
|
+
indexedExtras = hostExtraItems;
|
|
233
|
+
for (const item of hostExtraItems) if (item?.id) lastExtraItemsById.set(item.id, item);
|
|
234
|
+
}
|
|
235
|
+
const version = `${feed.revision()}/${customFeeds.revision()}/${feedbackVersion}/${Math.floor(nowMs / 60_000)}`;
|
|
236
|
+
if (snapshotsVersion !== version) {
|
|
237
|
+
snapshotsVersion = version;
|
|
238
|
+
feedSnapshots.clear();
|
|
239
|
+
}
|
|
240
|
+
const key = JSON.stringify([options.source, options.category, options.intent, options.keyword, recommended,
|
|
241
|
+
options.interests, options.courseTitles]);
|
|
242
|
+
let snapshot = feedSnapshots.get(key);
|
|
243
|
+
if (!snapshot || snapshot.coverage !== coverage || snapshot.extraSources !== options.extraSources || snapshot.saved !== saved) {
|
|
244
|
+
snapshot = { coverage, extraSources: options.extraSources, saved, result: computeFeed(options, coverage, hostExtraItems) };
|
|
245
|
+
feedSnapshots.delete(key);
|
|
246
|
+
if (feedSnapshots.size >= FEED_SNAPSHOT_LIMIT) feedSnapshots.delete(feedSnapshots.keys().next().value);
|
|
247
|
+
feedSnapshots.set(key, snapshot);
|
|
248
|
+
}
|
|
249
|
+
const { items, sources } = snapshot.result;
|
|
250
|
+
const total = items.length;
|
|
251
|
+
const paginated = options.page != null || options.pageSize != null;
|
|
252
|
+
const rawSize = options.pageSize == null ? 20 : Number(options.pageSize);
|
|
253
|
+
const pageSize = paginated ? Math.min(100, Math.max(1, Number.isNaN(rawSize) ? 20 : Math.trunc(rawSize))) : Math.max(1, total);
|
|
254
|
+
const totalPages = Math.ceil(total / pageSize);
|
|
255
|
+
const page = paginated ? Math.max(1, Math.min(totalPages, Math.trunc(Number(options.page) || 1))) : 1;
|
|
256
|
+
const visible = paginated ? items.slice((page - 1) * pageSize, page * pageSize) : items;
|
|
257
|
+
return { sources, total, page, pageSize, totalPages, hasMore: page < totalPages,
|
|
258
|
+
items: visible.map(item => ({ ...item, saved: Object.hasOwn(saved, item.id) })) };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function computeFeed(options, coverage, hostExtraItems) {
|
|
205
262
|
const importedTitles = (coverage?.entries ?? [])
|
|
206
263
|
.filter(entry => entry.kind === 'course' || entry.kind === 'exam')
|
|
207
264
|
.map(entry => entry.title)
|
|
@@ -211,25 +268,18 @@ export function openCampus(dir, { now = Date.now, fetch = globalThis.fetch } = {
|
|
|
211
268
|
: [];
|
|
212
269
|
const courseTitles = [...new Set([...hostCourseTitles, ...importedTitles])].slice(0, 40);
|
|
213
270
|
const savedTitles = Object.values(saved).map(item => item.title).filter(Boolean).slice(0, 20);
|
|
214
|
-
const hostExtraItems = Array.isArray(options.extraItems) ? options.extraItems : [];
|
|
215
|
-
for (const item of hostExtraItems) {
|
|
216
|
-
if (item && typeof item === 'object' && item.id) {
|
|
217
|
-
if (lastExtraItemsById.size >= 400) lastExtraItemsById.clear();
|
|
218
|
-
lastExtraItemsById.set(item.id, item);
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
271
|
const extraItems = [...customFeeds.getItems(), ...hostExtraItems];
|
|
222
272
|
const extraSources = [
|
|
223
273
|
...customFeeds.getSourceStatuses(),
|
|
224
274
|
...(Array.isArray(options.extraSources) ? options.extraSources : [])
|
|
225
275
|
];
|
|
226
|
-
|
|
276
|
+
return feed.query({
|
|
227
277
|
source: options.source,
|
|
228
278
|
category: options.category,
|
|
229
279
|
intent: options.intent,
|
|
230
280
|
keyword: options.keyword,
|
|
231
281
|
sort: options.sort,
|
|
232
|
-
interests,
|
|
282
|
+
interests: Array.isArray(options.interests) ? options.interests.slice(0, 12).map(x => String(x).slice(0, 64)) : [],
|
|
233
283
|
extraItems,
|
|
234
284
|
extraSources,
|
|
235
285
|
recommender,
|
|
@@ -239,7 +289,6 @@ export function openCampus(dir, { now = Date.now, fetch = globalThis.fetch } = {
|
|
|
239
289
|
...range(coverage.from, coverage.through), complete: coverage.imported.length > 0 && !coverage.truncated && !coverage.warnings.length,
|
|
240
290
|
} : undefined
|
|
241
291
|
});
|
|
242
|
-
return { ...result, items: result.items.map(item => ({ ...item, saved: Object.hasOwn(saved, item.id) })) };
|
|
243
292
|
}
|
|
244
293
|
function saveEvent({ id, action = 'save' } = {}) {
|
|
245
294
|
if (typeof id !== 'string' || !id || id.length > 200 || !['save', 'remove'].includes(action)) throw new CampusInputError('无效的活动 ID 或操作');
|
|
@@ -335,6 +384,7 @@ export function openCampus(dir, { now = Date.now, fetch = globalThis.fetch } = {
|
|
|
335
384
|
}
|
|
336
385
|
return { agenda, importCalendar, forgetCalendar, queryFeed, saveEvent, mutateItem, findItems,
|
|
337
386
|
recordFeedFeedback, feedProfile, listCustomFeeds, addCustomFeed, removeCustomFeed,
|
|
387
|
+
validateAgendaRange: range, clearExtraFeedData,
|
|
338
388
|
refresh: async options => {
|
|
339
389
|
const [feedResult] = await Promise.all([feed.refresh(options), customFeeds.refresh(options)]);
|
|
340
390
|
return feedResult;
|
package/src/week-layout.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const DAY = 86_400_000, MINUTE = 60_000, HOUR = 60;
|
|
2
|
+
const POINT_TARGET = 24;
|
|
2
3
|
|
|
3
4
|
export function layoutWeek(weekUtc, entries) {
|
|
4
5
|
const first = weekUtc - 8 * HOUR * MINUTE;
|
|
@@ -12,6 +13,14 @@ export function layoutWeek(weekUtc, entries) {
|
|
|
12
13
|
if (item.date === date) day.untimed.push(item);
|
|
13
14
|
continue;
|
|
14
15
|
}
|
|
16
|
+
if (item.kind === 'deadline') {
|
|
17
|
+
if (item.start < midnight || item.start >= next) continue;
|
|
18
|
+
const point = (item.start - midnight) / MINUTE;
|
|
19
|
+
const from = Math.min(point, 24 * HOUR - POINT_TARGET);
|
|
20
|
+
start = Math.min(start, Math.floor(from / HOUR) * HOUR);
|
|
21
|
+
day.timed.push({ item, from, through: point, point });
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
15
24
|
const finish = Math.max(item.end ?? item.start, item.start + 1);
|
|
16
25
|
if (item.start >= next || finish <= midnight) continue;
|
|
17
26
|
if (item.allDay) { day.untimed.push(item); continue; }
|
|
@@ -30,7 +39,7 @@ export function layoutWeek(weekUtc, entries) {
|
|
|
30
39
|
for (const block of day.timed) {
|
|
31
40
|
if (block.from >= clusterEnd) finishCluster();
|
|
32
41
|
// Short entries get a readable hit target without obscuring adjacent entries.
|
|
33
|
-
block.visualEnd = Math.min(24 * HOUR, Math.max(block.through, block.from +
|
|
42
|
+
block.visualEnd = Math.min(24 * HOUR, Math.max(block.through, block.from + POINT_TARGET));
|
|
34
43
|
const free = lanes.findIndex(value => value <= block.from);
|
|
35
44
|
block.lane = free < 0 ? lanes.length : free;
|
|
36
45
|
lanes[block.lane] = block.visualEnd;
|
package/src/youth-actions.mjs
CHANGED
|
@@ -33,8 +33,8 @@ import {
|
|
|
33
33
|
|
|
34
34
|
const PLAN_TTL_MS = 15 * 60_000;
|
|
35
35
|
const MAX_PLANS = 32;
|
|
36
|
-
const DEFAULT_VERIFY_ATTEMPTS =
|
|
37
|
-
const DEFAULT_VERIFY_DELAY_MS =
|
|
36
|
+
const DEFAULT_VERIFY_ATTEMPTS = 2;
|
|
37
|
+
const DEFAULT_VERIFY_DELAY_MS = 300;
|
|
38
38
|
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
39
39
|
|
|
40
40
|
function canonicalJson(value) {
|
|
@@ -64,36 +64,32 @@ function sleep(ms, signal) {
|
|
|
64
64
|
});
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
async function findInOwnList(context, token, itemId, opts) {
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
{ queryCatelog: 0, pageNo, pageSize },
|
|
76
|
-
opts
|
|
77
|
-
);
|
|
78
|
-
if (res.kind !== 'ok') return { kind: res.kind };
|
|
79
|
-
const records = Array.isArray(res.value.records) ? res.value.records : null;
|
|
80
|
-
if (!records) return { kind: 'failure' };
|
|
81
|
-
const hit = records.find((row) => cleanId(row?.id ?? row?.itemId) === itemId);
|
|
82
|
-
if (hit) return { kind: 'ok', found: true, record: hit };
|
|
83
|
-
const total = Number(res.value.total);
|
|
84
|
-
if (!Number.isFinite(total) || pageNo * pageSize >= total || records.length === 0) {
|
|
85
|
-
return { kind: 'ok', found: false, record: null };
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
return { kind: 'failure' };
|
|
67
|
+
async function findInOwnList(context, token, itemId, title, opts) {
|
|
68
|
+
const res = await youthQuery(context, token, 'item/scParticipateItem/list', {
|
|
69
|
+
queryCatelog: 0, pageNo: 1, pageSize: 100, ...(title ? { itemName: title } : {})
|
|
70
|
+
}, opts);
|
|
71
|
+
if (res.kind !== 'ok') return res;
|
|
72
|
+
if (!Array.isArray(res.value.records)) return { kind: 'failure' };
|
|
73
|
+
const record = res.value.records.find(row => cleanId(row?.id ?? row?.itemId) === itemId);
|
|
74
|
+
return { kind: 'ok', record: record ?? null };
|
|
89
75
|
}
|
|
90
76
|
|
|
91
|
-
async function readItemState(context, token, itemId, opts) {
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
const
|
|
95
|
-
if (
|
|
96
|
-
return { kind: 'ok'
|
|
77
|
+
async function readItemState(context, token, itemId, opts, { target, title, checkCancelPolicy } = {}) {
|
|
78
|
+
const result = await youthQuery(context, token, 'item/scItem/queryById', { id: itemId }, opts);
|
|
79
|
+
const detail = result.kind === 'ok' && cleanId(result.value.id ?? result.value.itemId) === itemId ? result.value : null;
|
|
80
|
+
const reg = registration(detail);
|
|
81
|
+
if (target !== undefined && reg === target) return { kind: 'verified' };
|
|
82
|
+
if (target === undefined && !detail) return { kind: result.kind === 'ok' ? 'failure' : result.kind };
|
|
83
|
+
if (target === undefined && reg !== null && (!checkCancelPolicy || !reg || detail.cancelSign != null)) {
|
|
84
|
+
return { kind: 'ok', detail, ownFound: reg, ownRecord: reg ? detail : null };
|
|
85
|
+
}
|
|
86
|
+
// Absence from a filtered or truncated list does not prove cancellation.
|
|
87
|
+
if (target === false) return { kind: 'uncertain' };
|
|
88
|
+
const own = await findInOwnList(context, token, itemId, title || cleanText(detail?.itemName ?? detail?.title, 100), opts);
|
|
89
|
+
const found = Boolean(own.record && registration(own.record) !== false);
|
|
90
|
+
if (target === true) return { kind: found ? 'verified' : 'uncertain' };
|
|
91
|
+
if (own.kind !== 'ok') return { kind: own.kind };
|
|
92
|
+
return { kind: 'ok', detail, ownFound: reg === true || found, ownRecord: own.record };
|
|
97
93
|
}
|
|
98
94
|
|
|
99
95
|
function summarizePlanContent(action, itemId, detail) {
|
|
@@ -148,6 +144,7 @@ export function createYouthActions({
|
|
|
148
144
|
}
|
|
149
145
|
|
|
150
146
|
const plans = new Map();
|
|
147
|
+
let generation = 0;
|
|
151
148
|
const clockMs = () => (typeof now === 'function' ? Number(now()) : Date.now());
|
|
152
149
|
|
|
153
150
|
function pruneExpired() {
|
|
@@ -234,6 +231,7 @@ export function createYouthActions({
|
|
|
234
231
|
|
|
235
232
|
async function prepareEnroll({ itemId } = {}) {
|
|
236
233
|
pruneExpired();
|
|
234
|
+
const epoch = generation;
|
|
237
235
|
const id = cleanId(itemId);
|
|
238
236
|
if (!id) {
|
|
239
237
|
return { state: 'invalid', message: '请提供有效的二课活动 ID。', untrustedContent: true };
|
|
@@ -249,6 +247,7 @@ export function createYouthActions({
|
|
|
249
247
|
if (!check.ok) return { kind: 'blocked', check };
|
|
250
248
|
return { kind: 'ok', context, detail: stateRes.detail };
|
|
251
249
|
});
|
|
250
|
+
if (epoch !== generation) return { state: 'not_connected', requestSent: false, message: '学校账号已切换,请重新准备。' };
|
|
252
251
|
|
|
253
252
|
if (res.kind === 'not_connected') {
|
|
254
253
|
return { state: 'not_connected', message: '该功能需要登录学校账号,请在左侧「校园」页右上角登录后再试。', untrustedContent: true };
|
|
@@ -292,6 +291,7 @@ export function createYouthActions({
|
|
|
292
291
|
|
|
293
292
|
async function prepareCancel({ itemId } = {}) {
|
|
294
293
|
pruneExpired();
|
|
294
|
+
const epoch = generation;
|
|
295
295
|
const id = cleanId(itemId);
|
|
296
296
|
if (!id) {
|
|
297
297
|
return { state: 'invalid', message: '请提供有效的二课活动 ID。', untrustedContent: true };
|
|
@@ -301,7 +301,7 @@ export function createYouthActions({
|
|
|
301
301
|
const opts = { now, requestTimeoutMs };
|
|
302
302
|
const session = await obtainYouthSession(context, opts);
|
|
303
303
|
if (session.kind !== 'token') return { kind: session.kind };
|
|
304
|
-
const stateRes = await readItemState(context, session.token, id, opts);
|
|
304
|
+
const stateRes = await readItemState(context, session.token, id, opts, { checkCancelPolicy: true });
|
|
305
305
|
if (stateRes.kind !== 'ok') return { kind: stateRes.kind };
|
|
306
306
|
const reg = registration(stateRes.detail);
|
|
307
307
|
if (!stateRes.ownFound && reg !== true) {
|
|
@@ -313,6 +313,7 @@ export function createYouthActions({
|
|
|
313
313
|
}
|
|
314
314
|
return { kind: 'ok', context, detail: stateRes.detail };
|
|
315
315
|
});
|
|
316
|
+
if (epoch !== generation) return { state: 'not_connected', requestSent: false, message: '学校账号已切换,请重新准备。' };
|
|
316
317
|
|
|
317
318
|
if (res.kind === 'not_connected') {
|
|
318
319
|
return { state: 'not_connected', message: '该功能需要登录学校账号,请在左侧「校园」页右上角登录后再试。', untrustedContent: true };
|
|
@@ -351,21 +352,15 @@ export function createYouthActions({
|
|
|
351
352
|
return view(plan);
|
|
352
353
|
}
|
|
353
354
|
|
|
354
|
-
async function verifyOutcome(context, token,
|
|
355
|
-
const attempts = Math.max(1, verifyAttempts);
|
|
355
|
+
async function verifyOutcome(context, token, content, opts, signal) {
|
|
356
|
+
const attempts = Math.min(2, Math.max(1, verifyAttempts));
|
|
356
357
|
for (let i = 0; i < attempts; i += 1) {
|
|
357
358
|
if (i > 0) await sleep(verifyDelayMs, signal);
|
|
358
359
|
if (signal?.aborted) break;
|
|
359
|
-
const check = await readItemState(context, token, itemId,
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
return { kind: 'verified' };
|
|
364
|
-
}
|
|
365
|
-
if (action === 'cancel' && !check.ownFound && reg === false) {
|
|
366
|
-
return { kind: 'verified' };
|
|
367
|
-
}
|
|
368
|
-
}
|
|
360
|
+
const check = await readItemState(context, token, content.itemId,
|
|
361
|
+
{ ...opts, timeout: Math.min(requestTimeoutMs, 2_500) },
|
|
362
|
+
{ target: content.action === 'enroll', title: content.title });
|
|
363
|
+
if (check.kind === 'verified') return check;
|
|
369
364
|
}
|
|
370
365
|
return { kind: 'uncertain' };
|
|
371
366
|
}
|
|
@@ -418,7 +413,8 @@ export function createYouthActions({
|
|
|
418
413
|
const session = await obtainYouthSession(context, opts);
|
|
419
414
|
if (session.kind !== 'token') return { kind: session.kind };
|
|
420
415
|
|
|
421
|
-
const preflight = await readItemState(context, session.token, plan.content.itemId, opts
|
|
416
|
+
const preflight = await readItemState(context, session.token, plan.content.itemId, opts,
|
|
417
|
+
{ checkCancelPolicy: plan.content.action === 'cancel' });
|
|
422
418
|
if (preflight.kind !== 'ok') return { kind: preflight.kind };
|
|
423
419
|
|
|
424
420
|
if (plan.content.action === 'enroll') {
|
|
@@ -431,7 +427,7 @@ export function createYouthActions({
|
|
|
431
427
|
if (!preflight.ownFound && reg !== true) {
|
|
432
428
|
return { kind: 'state_changed', reason: 'not_enrolled', message: '该活动已不在本人报名列表中,未重复取消。' };
|
|
433
429
|
}
|
|
434
|
-
const policy = deriveCancelPolicy(preflight.detail);
|
|
430
|
+
const policy = deriveCancelPolicy(preflight.detail, { enrolledRow: preflight.ownRecord });
|
|
435
431
|
if (!policy.cancelAllowed) {
|
|
436
432
|
return { kind: 'state_changed', reason: 'not_cancellable', message: policy.cancelRuleNote };
|
|
437
433
|
}
|
|
@@ -441,6 +437,7 @@ export function createYouthActions({
|
|
|
441
437
|
? `item/scItemRegistration/enter/${encodeURIComponent(plan.content.itemId)}`
|
|
442
438
|
: `item/scItemRegistration/cancellRegistration/${encodeURIComponent(plan.content.itemId)}`;
|
|
443
439
|
|
|
440
|
+
if (signal?.aborted || plans.get(planId) !== plan) return { kind: 'state_changed', message: '确认已失效,没有提交。' };
|
|
444
441
|
plan.state = 'executing';
|
|
445
442
|
plan.requestSent = true;
|
|
446
443
|
const post = await youthPost(context, session.token, endpoint, {}, opts);
|
|
@@ -454,16 +451,18 @@ export function createYouthActions({
|
|
|
454
451
|
return { kind: 'uncertain', accepted: null, message: '暂未收到平台明确回执,请用 youth_action_status 查询最新状态。' };
|
|
455
452
|
}
|
|
456
453
|
|
|
457
|
-
const verified = await verifyOutcome(context, session.token, plan.content
|
|
454
|
+
const verified = await verifyOutcome(context, session.token, plan.content, opts, signal);
|
|
458
455
|
if (verified.kind === 'verified') {
|
|
459
456
|
return { kind: 'verified', serverMessage: post.message };
|
|
460
457
|
}
|
|
461
458
|
return {
|
|
462
459
|
kind: 'uncertain',
|
|
463
460
|
accepted: true,
|
|
464
|
-
message: '
|
|
461
|
+
message: '请求已受理,尚未在官方记录中核实,请稍后用 youth_action_status 查询。'
|
|
465
462
|
};
|
|
466
463
|
});
|
|
464
|
+
if (plans.get(planId) !== plan) return { state: 'expired', planId, requestSent: plan.requestSent,
|
|
465
|
+
message: '学校账号已切换,无法继续核对此计划。' };
|
|
467
466
|
|
|
468
467
|
if (execRes.kind === 'not_connected') {
|
|
469
468
|
if (!plan.requestSent) {
|
|
@@ -524,17 +523,11 @@ export function createYouthActions({
|
|
|
524
523
|
const opts = { now, requestTimeoutMs };
|
|
525
524
|
const session = await obtainYouthSession(context, opts);
|
|
526
525
|
if (session.kind !== 'token') return { kind: session.kind };
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
if (plan.content.action === 'enroll' && (check.ownFound || reg === true)) {
|
|
531
|
-
return { kind: 'verified' };
|
|
532
|
-
}
|
|
533
|
-
if (plan.content.action === 'cancel' && !check.ownFound && reg === false) {
|
|
534
|
-
return { kind: 'verified' };
|
|
535
|
-
}
|
|
536
|
-
return { kind: 'still_uncertain' };
|
|
526
|
+
if (context !== plan.owner) return { kind: 'still_uncertain' };
|
|
527
|
+
return readItemState(context, session.token, plan.content.itemId, opts,
|
|
528
|
+
{ target: plan.content.action === 'enroll', title: plan.content.title });
|
|
537
529
|
});
|
|
530
|
+
if (plans.get(planId) !== plan) return { state: 'not_found', planId, message: '找不到此二课操作计划,或计划已过期。' };
|
|
538
531
|
|
|
539
532
|
if (res.kind === 'verified') {
|
|
540
533
|
plan.state = 'verified';
|
|
@@ -550,6 +543,7 @@ export function createYouthActions({
|
|
|
550
543
|
prepareEnroll,
|
|
551
544
|
prepareCancel,
|
|
552
545
|
confirm,
|
|
553
|
-
status
|
|
546
|
+
status,
|
|
547
|
+
clear() { generation++; plans.clear(); }
|
|
554
548
|
});
|
|
555
549
|
}
|