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
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 grades = createGrades({withSchoolContext:school.withSchoolContext});
|
|
62
|
-
const librarySpaces = createLibrarySpaces({withSchoolContext:school.withSchoolContext});
|
|
63
61
|
const libraryBooking = createLibraryBooking({withSchoolContext:school.withSchoolContext,dataDir:dir});
|
|
64
62
|
const hsLibrary = createHsLibrary({withSchoolContext:school.withSchoolContext});
|
|
65
|
-
const
|
|
66
|
-
|
|
63
|
+
const personal = createAccountData({ dir, school, youth, bb, libraryBooking, hsLibrary,
|
|
64
|
+
createExams: cache => createExams({ withSchoolContext: school.withSchoolContext, cache }) });
|
|
65
|
+
const { exams } = personal;
|
|
66
|
+
const grades = createGrades({withSchoolContext:school.withSchoolContext, cache:personal.cache});
|
|
67
|
+
const librarySpaces = createLibrarySpaces({withSchoolContext:school.withSchoolContext});
|
|
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;
|
|
@@ -218,6 +105,7 @@ export function apply(ctx) {
|
|
|
218
105
|
const approval=libraryApprovals.get(planId);
|
|
219
106
|
if(approval?.busy) return {state:'busy',planId,message:'正在处理此预约,请勿重复提交。'};
|
|
220
107
|
const result=await readBooking(()=>libraryBooking.status({planId}));
|
|
108
|
+
if (result.state === 'verified' && result.plan?.date) personal.refreshReservations('west', result.plan.date);
|
|
221
109
|
if(result.state!=='ready') return result;
|
|
222
110
|
if(!approval || libraryApprovals.get(planId)!==approval || approval.expiry<=Date.now()) {
|
|
223
111
|
return {state:'expired',planId,message:'预约草稿已失效,没有提交。请重新核对时段。'};
|
|
@@ -252,73 +140,62 @@ export function apply(ctx) {
|
|
|
252
140
|
return {state:decision,planId,requestSent:false,message:approval.message};
|
|
253
141
|
}
|
|
254
142
|
try {
|
|
255
|
-
|
|
143
|
+
const result = await libraryBooking.confirm({planId,digest:approval.digest,authorized:true},approvalSignal);
|
|
144
|
+
if (result.state === 'verified' && !approvalSignal.aborted) personal.refreshReservations('west', p.date);
|
|
145
|
+
return result;
|
|
256
146
|
} finally { libraryApprovals.delete(planId); }
|
|
257
147
|
} finally { approval.busy=false; }
|
|
258
148
|
}
|
|
259
149
|
|
|
150
|
+
async function refreshOnVerified(operation, refresh) {
|
|
151
|
+
const epoch = accountEpoch;
|
|
152
|
+
const result = await operation;
|
|
153
|
+
if (epoch === accountEpoch && result.state === 'verified') refresh();
|
|
154
|
+
return result;
|
|
155
|
+
}
|
|
156
|
+
|
|
260
157
|
async function dispatchOwner(op,data) {
|
|
261
158
|
if(op==='agenda-local') return campus.agenda(data);
|
|
262
159
|
if(op==='agenda') {
|
|
160
|
+
campus.validateAgendaRange(data.from, data.through);
|
|
263
161
|
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];
|
|
162
|
+
const { schoolEntries, ...metadata } = await personal.agenda(data);
|
|
271
163
|
if (epoch !== accountEpoch) {
|
|
272
|
-
const unavailable={state:'not_connected',complete:false};
|
|
273
|
-
return { ...
|
|
164
|
+
const unavailable = { state: 'not_connected', complete: false };
|
|
165
|
+
return { ...campus.agenda(data), school: { state: school.status().state, complete: false },
|
|
166
|
+
exams: unavailable, assignments: unavailable, reservations: { count: 0, complete: false },
|
|
167
|
+
youth: { ...unavailable, verifiedCount: 0 }, stale: false, syncing: false, cachedAt: null };
|
|
274
168
|
}
|
|
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}};
|
|
169
|
+
return { ...campus.agenda(data, { schoolEntries }), ...metadata };
|
|
278
170
|
}
|
|
279
|
-
if(op==='item-mutate' && data.action==='remove' && typeof data.id==='string' && /^(?:school|youth)_/.test(data.id)) {
|
|
171
|
+
if(op==='item-mutate' && data.action==='remove' && typeof data.id==='string' && /^(?:school|youth|bb|library)_/.test(data.id)) {
|
|
280
172
|
const epoch = accountEpoch;
|
|
281
173
|
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:[]};
|
|
174
|
+
const { schoolEntries } = await personal.agenda({ from: data.date, through: data.date });
|
|
285
175
|
if(epoch!==accountEpoch) throw new CampusInputError('学校账号已切换,请重新打开日程');
|
|
286
|
-
return campus.mutateItem(data,{schoolEntries
|
|
176
|
+
return campus.mutateItem(data,{schoolEntries,includeSchool:true});
|
|
287
177
|
}
|
|
288
178
|
if(op==='item-find') return campus.findItems(data,{includeSchool:true});
|
|
289
179
|
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
|
-
}
|
|
180
|
+
if(op==='school-logout') return school.logout();
|
|
181
|
+
if(op==='school-login') return school.login({manual:data.manual===true});
|
|
182
|
+
if(op==='school-credentials-save') return school.saveCredentials(data);
|
|
300
183
|
if(op==='bb-requests') return bbActions.list();
|
|
301
184
|
if(op==='bb-status') return bbActions.status(data.id);
|
|
302
185
|
if(op==='grade-terms') return grades.terms();
|
|
303
186
|
if(op==='grade-read') return grades.read(data);
|
|
304
187
|
if(op==='school-exams') return exams.read(data);
|
|
305
|
-
if(op==='campus-shuttle') return transit.read(data);
|
|
188
|
+
if(op==='campus-shuttle') return transit.read({ ...data, autoResolve: true });
|
|
306
189
|
if(op==='library-space-categories') return librarySpaces.categories();
|
|
307
190
|
if(op==='library-space-availability') return librarySpaces.availability(data);
|
|
308
191
|
if(op==='library-booking-prepare') return prepareBooking(data);
|
|
309
192
|
if(op==='library-booking-status') return bookingStatus(data);
|
|
310
193
|
if(op==='library-booking-reservations') return reservations(data);
|
|
311
194
|
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
|
-
}
|
|
195
|
+
if(op==='feed') return queryFeed(data);
|
|
316
196
|
if(op==='refresh') {
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
getYouthEnrollingFeed(data.force === true)
|
|
320
|
-
]);
|
|
321
|
-
return campus.queryFeed({ ...data, courseTitles: cachedSchoolCourseTitles, ...extra });
|
|
197
|
+
await refreshFeed({ force: data.force === true });
|
|
198
|
+
return queryFeed(data);
|
|
322
199
|
}
|
|
323
200
|
if(op==='feed-feedback') return campus.recordFeedFeedback(data);
|
|
324
201
|
if(op==='feed-profile') return campus.feedProfile();
|
|
@@ -333,10 +210,13 @@ export function apply(ctx) {
|
|
|
333
210
|
}
|
|
334
211
|
ctx.provide('ustcCampus', {
|
|
335
212
|
...campus,
|
|
336
|
-
|
|
337
|
-
|
|
213
|
+
queryFeed,
|
|
214
|
+
refresh: refreshFeed
|
|
338
215
|
});
|
|
339
|
-
ctx.provide('ustcSchool', school)
|
|
216
|
+
ctx.provide('ustcSchool', { ...school, async agenda(data) {
|
|
217
|
+
campus.validateAgendaRange(data?.from, data?.through);
|
|
218
|
+
return personal.timetableFor(data);
|
|
219
|
+
} });
|
|
340
220
|
ctx.provide('ustcBb', {listCourses:bb.listCourses,listAssignments:bb.listAssignments,inspectAssignment:bb.inspectAssignment,request:bbActions.request,status:bbActions.status,
|
|
341
221
|
confirm:(data,approve,signal)=>bbActions.confirm(data,approve,AbortSignal.any([signal,accountSignal.signal])),
|
|
342
222
|
submitDirect:(data,signal)=>bbActions.submitDirect(data,signal?AbortSignal.any([signal,accountSignal.signal]):accountSignal.signal)});
|
|
@@ -349,19 +229,21 @@ export function apply(ctx) {
|
|
|
349
229
|
reservations: hsLibrary.reservations,
|
|
350
230
|
prepareBooking: hsLibrary.prepareBooking,
|
|
351
231
|
prepareCancel: hsLibrary.prepareCancel,
|
|
352
|
-
status: hsLibrary.status,
|
|
353
|
-
confirm: (data, approve, signal) =>
|
|
232
|
+
status: data => refreshOnVerified(hsLibrary.status(data), () => personal.refreshReservations('hs')),
|
|
233
|
+
confirm: (data, approve, signal) => refreshOnVerified(
|
|
234
|
+
hsLibrary.confirm(data, approve, AbortSignal.any([signal, accountSignal.signal])), () => personal.refreshReservations('hs'))
|
|
354
235
|
});
|
|
355
236
|
ctx.provide('ustcYouth', youth);
|
|
356
237
|
ctx.provide('ustcYouthActions', {
|
|
357
238
|
prepareEnroll: youthActions.prepareEnroll,
|
|
358
239
|
prepareCancel: youthActions.prepareCancel,
|
|
359
|
-
status: youthActions.status,
|
|
360
|
-
confirm: (data, approve, signal) =>
|
|
240
|
+
status: data => refreshOnVerified(youthActions.status(data), personal.refreshEnrollment),
|
|
241
|
+
confirm: (data, approve, signal) => refreshOnVerified(
|
|
242
|
+
youthActions.confirm(data, approve, AbortSignal.any([signal, accountSignal.signal])), personal.refreshEnrollment)
|
|
361
243
|
});
|
|
362
244
|
ctx.provide('ustcExams', exams);
|
|
363
245
|
ctx.provide('ustcTransit', transit);
|
|
364
|
-
ctx.effect(() => async () => { accountSignal.abort(); campus.close(); await school.close(); });
|
|
246
|
+
ctx.effect(() => async () => { accountSignal.abort(); personal.close(); campus.close(); await school.close(); });
|
|
365
247
|
ctx.inject(['connection'], scope => scope.connection.fetch.register({
|
|
366
248
|
path: '/api/ustc-campus', methods: ['POST'], requestBody: 'streaming',
|
|
367
249
|
async fetch(request) {
|
|
@@ -395,8 +277,6 @@ function dispatch(campus, school, op, data) {
|
|
|
395
277
|
switch (op) {
|
|
396
278
|
case 'import': return campus.importCalendar(data);
|
|
397
279
|
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
280
|
case 'materials': return campus.lookup(data.query);
|
|
401
281
|
case 'save': return campus.saveEvent(data);
|
|
402
282
|
case 'school-status': return school.status();
|
package/src/hs-library.mjs
CHANGED
|
@@ -827,6 +827,46 @@ export function createHsLibrary({
|
|
|
827
827
|
};
|
|
828
828
|
}
|
|
829
829
|
|
|
830
|
+
async function agenda({ from, through }) {
|
|
831
|
+
const res = await runWithContext(async context => {
|
|
832
|
+
const opts = { timeout };
|
|
833
|
+
const session = await ensureHsSession(context, opts);
|
|
834
|
+
if (session.kind !== 'ok') return session;
|
|
835
|
+
const pageSize = 50;
|
|
836
|
+
const entries = new Map();
|
|
837
|
+
let complete = true;
|
|
838
|
+
for (let pageNum = 1; pageNum <= 5; pageNum++) {
|
|
839
|
+
const hist = await hsGet(context, '/desktopAppointment/getAppointmentHistory', { pageSize, pageNum }, opts);
|
|
840
|
+
if (hist.kind !== 'ok' || !Array.isArray(hist.content?.userRecordsList)) {
|
|
841
|
+
if (pageNum === 1) return { kind: hist.kind === 'not_connected' ? hist.kind : 'failure' };
|
|
842
|
+
complete = false;
|
|
843
|
+
break;
|
|
844
|
+
}
|
|
845
|
+
const rows = hist.content.userRecordsList;
|
|
846
|
+
for (const raw of rows) {
|
|
847
|
+
const item = mapHistoryItem(raw);
|
|
848
|
+
if (!item || !ACTIVE_BOOKING_STATES.has(item.stateCode) || item.stateCode === 12) continue;
|
|
849
|
+
if (!isValidDate(item.date)) { complete = false; continue; }
|
|
850
|
+
if ((from && item.date < from) || (through && item.date > through)) continue;
|
|
851
|
+
if (hhmmMinutes(item.startTime) === null || hhmmMinutes(item.endTime) === null || item.endTime <= item.startTime) {
|
|
852
|
+
complete = false;
|
|
853
|
+
continue;
|
|
854
|
+
}
|
|
855
|
+
const id = `library_hs_${item.appointmentId}`;
|
|
856
|
+
entries.set(id, { id, kind: 'reservation', title: item.resourceName || '高新园区图书馆预约', date: item.date,
|
|
857
|
+
startTime: item.startTime, endTime: item.endTime, source: CAMPUS, location: item.partitionName,
|
|
858
|
+
url: HS_LIBRARY_RESULT_LINK.url });
|
|
859
|
+
}
|
|
860
|
+
const total = nonNegativeInt(hist.content.total);
|
|
861
|
+
if (total === null ? rows.length < pageSize : pageNum * pageSize >= total) break;
|
|
862
|
+
if (rows.length < pageSize || pageNum === 5) { complete = false; break; }
|
|
863
|
+
}
|
|
864
|
+
return { kind: 'ok', complete, entries: [...entries.values()] };
|
|
865
|
+
});
|
|
866
|
+
if (res.kind !== 'ok') return { state: res.kind, complete: false, entries: [] };
|
|
867
|
+
return { state: res.entries.length ? 'ok' : 'empty', complete: res.complete, entries: res.entries };
|
|
868
|
+
}
|
|
869
|
+
|
|
830
870
|
function validateSlotAgainstRules(rules, date, startTime, endTime) {
|
|
831
871
|
if (rules.bookableDates.length > 0 && !rules.bookableDates.includes(date)) {
|
|
832
872
|
return { ok: false, state: 'not_bookable', message: '所选日期不在当前可预约日期范围内。' };
|
|
@@ -1428,6 +1468,7 @@ export function createHsLibrary({
|
|
|
1428
1468
|
categories,
|
|
1429
1469
|
availability,
|
|
1430
1470
|
reservations,
|
|
1471
|
+
agenda,
|
|
1431
1472
|
prepareBooking,
|
|
1432
1473
|
prepareCancel,
|
|
1433
1474
|
confirm,
|
package/src/library-booking.mjs
CHANGED
|
@@ -103,6 +103,7 @@ import {
|
|
|
103
103
|
statusOf
|
|
104
104
|
} from './library-spaces.mjs';
|
|
105
105
|
import { LIBRARY_RESULT_LINK } from './result-links.mjs';
|
|
106
|
+
import { shDate } from './calendar.mjs';
|
|
106
107
|
|
|
107
108
|
const CAMPUS = '西区图书馆';
|
|
108
109
|
const TIME_ZONE = 'Asia/Shanghai';
|
|
@@ -599,10 +600,10 @@ async function locateRoom(context, kindId, devId, date) {
|
|
|
599
600
|
return { kind: 'not_found' };
|
|
600
601
|
}
|
|
601
602
|
|
|
602
|
-
function mineUrl(
|
|
603
|
+
function mineUrl(from, through, page) {
|
|
603
604
|
const url = new URL(MINE_PATH, ORIGIN);
|
|
604
|
-
url.searchParams.set('beginDate',
|
|
605
|
-
url.searchParams.set('endDate',
|
|
605
|
+
url.searchParams.set('beginDate', from);
|
|
606
|
+
url.searchParams.set('endDate', through);
|
|
606
607
|
url.searchParams.set('needStatus', '0');
|
|
607
608
|
url.searchParams.set('page', String(page));
|
|
608
609
|
url.searchParams.set('pageNum', String(MINE_PAGE_SIZE));
|
|
@@ -611,12 +612,12 @@ function mineUrl(date, page) {
|
|
|
611
612
|
return officialUrl(url.pathname + url.search);
|
|
612
613
|
}
|
|
613
614
|
|
|
614
|
-
async function readMineAll(context,
|
|
615
|
+
async function readMineAll(context, from, through = from) {
|
|
615
616
|
const rows = [];
|
|
616
617
|
const seen = new Set();
|
|
617
618
|
let total = null;
|
|
618
619
|
for (let page = 1; page <= MAX_MINE_PAGES; page += 1) {
|
|
619
|
-
const result = await getEnvelope(context, mineUrl(
|
|
620
|
+
const result = await getEnvelope(context, mineUrl(from, through, page));
|
|
620
621
|
if (result.kind !== 'ok') return result;
|
|
621
622
|
const data = result.envelope.data;
|
|
622
623
|
if (!Array.isArray(data)) return { kind: 'failure' };
|
|
@@ -1398,6 +1399,33 @@ export function createLibraryBooking({ withSchoolContext, now = () => Date.now()
|
|
|
1398
1399
|
);
|
|
1399
1400
|
},
|
|
1400
1401
|
|
|
1402
|
+
agenda({ from, through }) {
|
|
1403
|
+
return scoped(async context => {
|
|
1404
|
+
const session = await openBookingSession(context);
|
|
1405
|
+
if (session.kind !== 'ok') return { state: upstreamState(session.kind), complete: false, entries: [] };
|
|
1406
|
+
const mine = await readMineAll(context, from, through);
|
|
1407
|
+
if (mine.kind !== 'ok') return { state: upstreamState(mine.kind), complete: false, entries: [] };
|
|
1408
|
+
const entries = [];
|
|
1409
|
+
let complete = true;
|
|
1410
|
+
for (const raw of mine.rows) {
|
|
1411
|
+
const item = publicReservation(raw);
|
|
1412
|
+
const status = Number(item.status);
|
|
1413
|
+
// The official history distinguishes approval, payment and participant confirmation from booking success.
|
|
1414
|
+
if (!(status & (1 | 2 | 4 | 32 | 64 | 1024 | 2048)) || status & (8 | 16 | 128 | 256 | 512 | 8192)) continue;
|
|
1415
|
+
const start = parseTimestamp(item.begin);
|
|
1416
|
+
const end = parseTimestamp(item.end);
|
|
1417
|
+
if (start === null || end === null || end <= start) { complete = false; continue; }
|
|
1418
|
+
const date = shDate(start);
|
|
1419
|
+
if (date < from || date > through) continue;
|
|
1420
|
+
const room = item.resources.map(device => device.devName || device.roomName).filter(Boolean).join(' / ');
|
|
1421
|
+
entries.push({ id: `library_west_${item.id}`, kind: 'reservation', title: room || '西区图书馆预约',
|
|
1422
|
+
date, start, end, source: CAMPUS, location: item.resources[0]?.labName ?? '', url: LIBRARY_RESULT_LINK.url });
|
|
1423
|
+
}
|
|
1424
|
+
return { state: entries.length ? 'ok' : 'empty', complete, entries };
|
|
1425
|
+
}, state => ({ state, complete: false, entries: [] }),
|
|
1426
|
+
result => Array.isArray(result?.entries));
|
|
1427
|
+
},
|
|
1428
|
+
|
|
1401
1429
|
async reservations({date}={}) {
|
|
1402
1430
|
if(!parseDate(date)) return unresolvedResult('invalid',[],{reason:'date',message:'请选择有效日期。'});
|
|
1403
1431
|
return scoped(async context=>{
|
package/src/library-spaces.mjs
CHANGED
|
@@ -44,11 +44,11 @@ const MAX_LIMIT = 50;
|
|
|
44
44
|
const MAX_PAGE = 100;
|
|
45
45
|
const MAX_BODY_BYTES = 2 * 1024 * 1024;
|
|
46
46
|
const REQUEST_TIMEOUT_MS = 20_000;
|
|
47
|
-
const
|
|
47
|
+
const SESSION_TIMEOUT_MS = 8_000;
|
|
48
48
|
const MAX_PAGE_ROWS = 500;
|
|
49
49
|
const MAX_OCCUPIED_INTERVALS = 200;
|
|
50
|
-
const SESSION_POLLS = 60;
|
|
51
50
|
const SESSION_POLL_MS = 250;
|
|
51
|
+
const LOGIN_SETTLE_POLLS = 3;
|
|
52
52
|
|
|
53
53
|
const DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
54
54
|
const CONTROL_PATTERN = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g;
|
|
@@ -289,13 +289,13 @@ function parseEnvelope(text) {
|
|
|
289
289
|
return { kind: 'ok', envelope: body };
|
|
290
290
|
}
|
|
291
291
|
|
|
292
|
-
async function getEnvelope(context, url) {
|
|
292
|
+
async function getEnvelope(context, url, timeout = REQUEST_TIMEOUT_MS) {
|
|
293
293
|
const request = context?.request;
|
|
294
294
|
if (!request || typeof request.get !== 'function') return { kind: 'not_connected' };
|
|
295
295
|
let response;
|
|
296
296
|
try {
|
|
297
297
|
response = await request.get(url, {
|
|
298
|
-
timeout
|
|
298
|
+
timeout,
|
|
299
299
|
maxRedirects: 0,
|
|
300
300
|
failOnStatusCode: false,
|
|
301
301
|
headers: { accept: 'application/json' }
|
|
@@ -384,13 +384,13 @@ function checkPageSite(page) {
|
|
|
384
384
|
return { kind: 'ok' };
|
|
385
385
|
}
|
|
386
386
|
|
|
387
|
-
async function navigateToEntry(page) {
|
|
387
|
+
async function navigateToEntry(page, timeout) {
|
|
388
388
|
if (!page || typeof page.goto !== 'function') return { kind: 'failure' };
|
|
389
389
|
let response;
|
|
390
390
|
try {
|
|
391
391
|
response = await page.goto(ENTRY_URL, {
|
|
392
392
|
waitUntil: 'commit',
|
|
393
|
-
timeout
|
|
393
|
+
timeout
|
|
394
394
|
});
|
|
395
395
|
} catch {
|
|
396
396
|
const failedUrl = currentUrl(page);
|
|
@@ -409,40 +409,41 @@ async function navigateToEntry(page) {
|
|
|
409
409
|
}
|
|
410
410
|
return site;
|
|
411
411
|
}
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
const info = await getEnvelope(context, officialUrl(USER_INFO_PATH));
|
|
412
|
+
async function readUserInfo(context, timeout) {
|
|
413
|
+
const info = await getEnvelope(context, officialUrl(USER_INFO_PATH), timeout);
|
|
415
414
|
if (info.kind !== 'ok') return info;
|
|
416
415
|
const data = info.envelope.data;
|
|
417
416
|
if (!data || typeof data !== 'object' || Array.isArray(data)) return { kind: 'failure' };
|
|
418
417
|
return { kind: 'ok' };
|
|
419
418
|
}
|
|
420
419
|
|
|
421
|
-
async function verifySession(context, page) {
|
|
422
|
-
let
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
420
|
+
async function verifySession(context, page, deadline) {
|
|
421
|
+
let lastUrl;
|
|
422
|
+
let settled = 0;
|
|
423
|
+
let info = { kind: 'not_connected' };
|
|
424
|
+
while (Date.now() < deadline) {
|
|
425
|
+
const url = page && currentUrl(page);
|
|
426
|
+
if (url && IDENTITY_HOSTS.has(url.hostname)) {
|
|
427
|
+
if (typeof page.waitForTimeout !== 'function') return info;
|
|
428
|
+
if (typeof page.locator === 'function') {
|
|
428
429
|
try {
|
|
429
|
-
if (await page.locator('input[type="password"]').count() > 0)
|
|
430
|
-
|
|
431
|
-
}
|
|
432
|
-
} catch { /* ignore */ }
|
|
433
|
-
}
|
|
434
|
-
try {
|
|
435
|
-
await page.waitForTimeout(SESSION_POLL_MS);
|
|
436
|
-
} catch {
|
|
437
|
-
break;
|
|
430
|
+
if (await page.locator('input[type="password"]').count() > 0) return info;
|
|
431
|
+
} catch { /* redirect may replace the document */ }
|
|
438
432
|
}
|
|
439
|
-
|
|
440
|
-
|
|
433
|
+
settled = url.href === lastUrl ? settled + 1 : 1;
|
|
434
|
+
lastUrl = url.href;
|
|
435
|
+
if (settled >= LOGIN_SETTLE_POLLS) return info;
|
|
436
|
+
} else {
|
|
437
|
+
if (page && checkPageSite(page).kind !== 'ok') return { kind: 'failure' };
|
|
438
|
+
const remaining = deadline - Date.now();
|
|
439
|
+
if (remaining <= 0) break;
|
|
440
|
+
info = await readUserInfo(context, Math.min(2_000, remaining));
|
|
441
|
+
if (info.kind !== 'not_connected' || typeof page?.waitForTimeout !== 'function') return info;
|
|
441
442
|
}
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
443
|
+
const remaining = deadline - Date.now();
|
|
444
|
+
if (remaining <= 0) break;
|
|
445
|
+
try { await page.waitForTimeout(Math.min(SESSION_POLL_MS, remaining)); }
|
|
446
|
+
catch { break; }
|
|
446
447
|
}
|
|
447
448
|
return info;
|
|
448
449
|
}
|
|
@@ -457,7 +458,8 @@ async function openSession(context) {
|
|
|
457
458
|
if (active) return active;
|
|
458
459
|
|
|
459
460
|
const run = (async () => {
|
|
460
|
-
|
|
461
|
+
const deadline = Date.now() + SESSION_TIMEOUT_MS;
|
|
462
|
+
if (typeof context.newPage !== 'function') return verifySession(context, null, deadline);
|
|
461
463
|
let page;
|
|
462
464
|
try {
|
|
463
465
|
page = await context.newPage();
|
|
@@ -466,9 +468,11 @@ async function openSession(context) {
|
|
|
466
468
|
}
|
|
467
469
|
try {
|
|
468
470
|
await installNavigationGuard(page);
|
|
469
|
-
const
|
|
471
|
+
const remaining = deadline - Date.now();
|
|
472
|
+
if (remaining <= 0) return { kind: 'failure' };
|
|
473
|
+
const navigation = await navigateToEntry(page, Math.min(3_000, remaining));
|
|
470
474
|
if (navigation.kind !== 'ok') return navigation;
|
|
471
|
-
return await verifySession(context, page);
|
|
475
|
+
return await verifySession(context, page, deadline);
|
|
472
476
|
} finally {
|
|
473
477
|
await closePage(page);
|
|
474
478
|
}
|
|
@@ -753,7 +757,7 @@ export function createLibrarySpaces({ withSchoolContext } = {}) {
|
|
|
753
757
|
const returned = await withSchoolContext(async (context) => {
|
|
754
758
|
captured = await operation(context);
|
|
755
759
|
return captured;
|
|
756
|
-
});
|
|
760
|
+
}, { refreshCas: false });
|
|
757
761
|
if (isResult(returned)) return returned;
|
|
758
762
|
if (isResult(captured)) return captured;
|
|
759
763
|
return fallback('failure');
|