dsh-ustc-campus 0.2.14 → 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 -71
- package/dist/client.js +5946 -1061
- package/package.json +63 -24
- 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 +519 -0
- package/src/exams.mjs +21 -7
- package/src/feed.mjs +525 -137
- package/src/grades.mjs +30 -16
- package/src/host.mjs +52 -81
- package/src/library-spaces.mjs +39 -35
- package/src/material.mjs +2268 -65
- package/src/mcp-host.mjs +56 -5
- package/src/mcp.mjs +136 -27
- package/src/recommender.mjs +1319 -0
- package/src/school.mjs +218 -154
- package/src/snapshot-cache.mjs +98 -0
- package/src/state.mjs +152 -16
- package/src/youth-actions.mjs +52 -58
- package/src/youth.mjs +55 -26
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
|
@@ -4,6 +4,7 @@ import { createSchool } from './school.mjs';
|
|
|
4
4
|
import { localMidnight } from './calendar.mjs';
|
|
5
5
|
import { createSchoolVault } from './school-vault.mjs';
|
|
6
6
|
import { createYouth } from './youth.mjs';
|
|
7
|
+
import { createAccountData } from './account-data.mjs';
|
|
7
8
|
import { createYouthActions } from './youth-actions.mjs';
|
|
8
9
|
import { BbError, createBb } from './bb.mjs';
|
|
9
10
|
import { createBbActions, openBbSession } from './bb-actions.mjs';
|
|
@@ -52,73 +53,39 @@ export const inject = ['profileContext'];
|
|
|
52
53
|
export function apply(ctx) {
|
|
53
54
|
const dir = join(ctx.profileContext.dir, 'ustc-campus');
|
|
54
55
|
const campus = openCampus(dir);
|
|
55
|
-
const school = createSchool({ dir, vault:createSchoolVault(dir) });
|
|
56
|
+
const school = createSchool({ dir, vault:createSchoolVault(dir), invalidateAccountData });
|
|
56
57
|
const bb = createBb({dataDir:join(dir,'bb'),withSchoolContext:school.withSchoolContext,connectReadSession:openBbSession});
|
|
57
58
|
const bbActions=createBbActions({bb});
|
|
58
59
|
const youth = createYouth({withSchoolContext:school.withSchoolContext});
|
|
59
60
|
const youthActions = createYouthActions({withSchoolContext:school.withSchoolContext});
|
|
60
|
-
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});
|
|
61
65
|
const librarySpaces = createLibrarySpaces({withSchoolContext:school.withSchoolContext});
|
|
62
66
|
const libraryBooking = createLibraryBooking({withSchoolContext:school.withSchoolContext,dataDir:dir});
|
|
63
67
|
const hsLibrary = createHsLibrary({withSchoolContext:school.withSchoolContext});
|
|
64
|
-
const
|
|
65
|
-
const transit = createCampusTransit();
|
|
68
|
+
const transit = createCampusTransit({ dir });
|
|
66
69
|
const libraryApprovals = new Map();
|
|
67
70
|
let accountSignal = new AbortController();
|
|
68
|
-
const youthWeeks = new Map();
|
|
69
71
|
let accountEpoch = 0;
|
|
70
72
|
function invalidateAccountData() {
|
|
71
73
|
accountEpoch++;
|
|
72
74
|
accountSignal.abort();
|
|
73
75
|
accountSignal = new AbortController();
|
|
74
|
-
schoolWeeks.clear();
|
|
75
|
-
examWeeks.clear();
|
|
76
|
-
youthWeeks.clear();
|
|
77
76
|
bbActions.clear();
|
|
78
77
|
libraryApprovals.clear();
|
|
79
78
|
hsLibrary.clear();
|
|
79
|
+
youthActions.clear();
|
|
80
|
+
campus.clearExtraFeedData();
|
|
81
|
+
personal.invalidate();
|
|
80
82
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
entry.finished = true;
|
|
88
|
-
if (youthWeeks.get(key) === entry && !result.complete) youthWeeks.delete(key);
|
|
89
|
-
return result;
|
|
90
|
-
}) };
|
|
91
|
-
youthWeeks.set(key,entry);
|
|
92
|
-
return entry.request;
|
|
93
|
-
}
|
|
94
|
-
const schoolWeeks = new Map();
|
|
95
|
-
const examWeeks = new Map();
|
|
96
|
-
function examWeek(from, through, refresh) {
|
|
97
|
-
const key=`${from}/${through}`;
|
|
98
|
-
const cached=examWeeks.get(key);
|
|
99
|
-
if(!refresh && cached && Date.now()-cached.at<5*60_000) return cached.request;
|
|
100
|
-
if(examWeeks.size>=8) examWeeks.delete(examWeeks.keys().next().value);
|
|
101
|
-
const request=exams.read({from,through}).catch(error=>{
|
|
102
|
-
if(examWeeks.get(key)?.request===request) examWeeks.delete(key);
|
|
103
|
-
return {state:error?.code==='not_connected'||error?.code==='authentication_required'?'not_connected':'unavailable',complete:false,entries:[]};
|
|
104
|
-
});
|
|
105
|
-
examWeeks.set(key,{at:Date.now(),request});
|
|
106
|
-
return request;
|
|
107
|
-
}
|
|
108
|
-
async function schoolWeek(from, through, refresh = false) {
|
|
109
|
-
const status = school.status();
|
|
110
|
-
if (status.state === 'pending') return {schoolEntries:[],state:'pending',complete:false};
|
|
111
|
-
if (status.state !== 'connected' && !(await school.credentialStatus()).enabled) return {schoolEntries:[],state:status.state,complete:false};
|
|
112
|
-
const key = `${from}/${through}`;
|
|
113
|
-
const cached = schoolWeeks.get(key);
|
|
114
|
-
if(status.state==='connected' && !refresh && cached && Date.now() - cached.at < 5 * 60_000) return cached.request;
|
|
115
|
-
if (schoolWeeks.size >= 8) schoolWeeks.delete(schoolWeeks.keys().next().value);
|
|
116
|
-
const request = school.agenda({from,through}).then(out => {
|
|
117
|
-
if(out.state!=='ok' && schoolWeeks.get(key)?.request === request) schoolWeeks.delete(key);
|
|
118
|
-
const state = school.status().state === 'pending' ? 'pending' : out.state;
|
|
119
|
-
return {schoolEntries:out.entries,state,complete:out.complete};
|
|
120
|
-
});
|
|
121
|
-
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;
|
|
122
89
|
}
|
|
123
90
|
async function readBooking(read) {
|
|
124
91
|
const epoch=accountEpoch;
|
|
@@ -180,59 +147,65 @@ export function apply(ctx) {
|
|
|
180
147
|
async function dispatchOwner(op,data) {
|
|
181
148
|
if(op==='agenda-local') return campus.agenda(data);
|
|
182
149
|
if(op==='agenda') {
|
|
150
|
+
campus.validateAgendaRange(data.from, data.through);
|
|
183
151
|
const epoch = accountEpoch;
|
|
184
|
-
const
|
|
185
|
-
const refresh = data.refresh === true;
|
|
186
|
-
const schoolData=await schoolWeek(data.from,data.through,refresh);
|
|
187
|
-
const secondary = {state:'not_connected',complete:false,entries:[]};
|
|
188
|
-
const [enrollment, examData] = schoolData.state==='ok'
|
|
189
|
-
? await Promise.all([youthAgenda(data.from,data.through,refresh),examWeek(data.from,data.through,refresh)])
|
|
190
|
-
: [secondary,secondary];
|
|
152
|
+
const { schoolEntries, ...metadata } = await personal.agenda(data);
|
|
191
153
|
if (epoch !== accountEpoch) {
|
|
192
|
-
const unavailable={state:'not_connected',complete:false};
|
|
193
|
-
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 };
|
|
194
157
|
}
|
|
195
|
-
|
|
196
|
-
const merged=schoolEntries.length ? campus.agenda(data,{schoolEntries}) : local;
|
|
197
|
-
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 };
|
|
198
159
|
}
|
|
199
160
|
if(op==='item-mutate' && data.action==='remove' && typeof data.id==='string' && /^(?:school|youth)_/.test(data.id)) {
|
|
200
161
|
const epoch = accountEpoch;
|
|
201
162
|
localMidnight(data.date);
|
|
202
|
-
const
|
|
203
|
-
const enrollment=data.id.startsWith('youth_') ? await youthAgenda(data.date,data.date) : {entries:[]};
|
|
204
|
-
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 });
|
|
205
164
|
if(epoch!==accountEpoch) throw new CampusInputError('学校账号已切换,请重新打开日程');
|
|
206
|
-
return campus.mutateItem(data,{schoolEntries
|
|
165
|
+
return campus.mutateItem(data,{schoolEntries,includeSchool:true});
|
|
207
166
|
}
|
|
208
167
|
if(op==='item-find') return campus.findItems(data,{includeSchool:true});
|
|
209
168
|
if(op==='item-mutate') return campus.mutateItem(data,{includeSchool:true});
|
|
210
|
-
if(op==='school-logout')
|
|
211
|
-
if(op==='school-login') {
|
|
212
|
-
|
|
213
|
-
return school.login({manual:data.manual===true});
|
|
214
|
-
}
|
|
215
|
-
if(op==='school-credentials-save') {
|
|
216
|
-
const result = await school.saveCredentials(data);
|
|
217
|
-
if (result.saved) invalidateAccountData();
|
|
218
|
-
return result;
|
|
219
|
-
}
|
|
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);
|
|
220
172
|
if(op==='bb-requests') return bbActions.list();
|
|
221
173
|
if(op==='bb-status') return bbActions.status(data.id);
|
|
222
174
|
if(op==='grade-terms') return grades.terms();
|
|
223
175
|
if(op==='grade-read') return grades.read(data);
|
|
224
176
|
if(op==='school-exams') return exams.read(data);
|
|
225
|
-
if(op==='campus-shuttle') return transit.read(data);
|
|
177
|
+
if(op==='campus-shuttle') return transit.read({ ...data, autoResolve: true });
|
|
226
178
|
if(op==='library-space-categories') return librarySpaces.categories();
|
|
227
179
|
if(op==='library-space-availability') return librarySpaces.availability(data);
|
|
228
180
|
if(op==='library-booking-prepare') return prepareBooking(data);
|
|
229
181
|
if(op==='library-booking-status') return bookingStatus(data);
|
|
230
182
|
if(op==='library-booking-reservations') return reservations(data);
|
|
231
183
|
if(op==='library-booking-unresolved') return readBooking(libraryBooking.unresolved);
|
|
184
|
+
if(op==='feed') return queryFeed(data);
|
|
185
|
+
if(op==='refresh') {
|
|
186
|
+
await refreshFeed({ force: data.force === true });
|
|
187
|
+
return queryFeed(data);
|
|
188
|
+
}
|
|
189
|
+
if(op==='feed-feedback') return campus.recordFeedFeedback(data);
|
|
190
|
+
if(op==='feed-profile') return campus.feedProfile();
|
|
191
|
+
if(op==='feed-custom-list') return campus.listCustomFeeds();
|
|
192
|
+
if(op==='feed-custom-add') {
|
|
193
|
+
const added = campus.addCustomFeed(data);
|
|
194
|
+
await campus.refresh({ force: false }).catch(() => {});
|
|
195
|
+
return { ...added, subscriptions: campus.listCustomFeeds() };
|
|
196
|
+
}
|
|
197
|
+
if(op==='feed-custom-remove') return { ...campus.removeCustomFeed(data), subscriptions: campus.listCustomFeeds() };
|
|
232
198
|
return dispatch(campus,school,op,data);
|
|
233
199
|
}
|
|
234
|
-
ctx.provide('ustcCampus',
|
|
235
|
-
|
|
200
|
+
ctx.provide('ustcCampus', {
|
|
201
|
+
...campus,
|
|
202
|
+
queryFeed,
|
|
203
|
+
refresh: refreshFeed
|
|
204
|
+
});
|
|
205
|
+
ctx.provide('ustcSchool', { ...school, async agenda(data) {
|
|
206
|
+
campus.validateAgendaRange(data?.from, data?.through);
|
|
207
|
+
return personal.timetableFor(data);
|
|
208
|
+
} });
|
|
236
209
|
ctx.provide('ustcBb', {listCourses:bb.listCourses,listAssignments:bb.listAssignments,inspectAssignment:bb.inspectAssignment,request:bbActions.request,status:bbActions.status,
|
|
237
210
|
confirm:(data,approve,signal)=>bbActions.confirm(data,approve,AbortSignal.any([signal,accountSignal.signal])),
|
|
238
211
|
submitDirect:(data,signal)=>bbActions.submitDirect(data,signal?AbortSignal.any([signal,accountSignal.signal]):accountSignal.signal)});
|
|
@@ -257,7 +230,7 @@ export function apply(ctx) {
|
|
|
257
230
|
});
|
|
258
231
|
ctx.provide('ustcExams', exams);
|
|
259
232
|
ctx.provide('ustcTransit', transit);
|
|
260
|
-
ctx.effect(() => async () => { accountSignal.abort(); campus.close(); await school.close(); });
|
|
233
|
+
ctx.effect(() => async () => { accountSignal.abort(); personal.close(); campus.close(); await school.close(); });
|
|
261
234
|
ctx.inject(['connection'], scope => scope.connection.fetch.register({
|
|
262
235
|
path: '/api/ustc-campus', methods: ['POST'], requestBody: 'streaming',
|
|
263
236
|
async fetch(request) {
|
|
@@ -291,8 +264,6 @@ function dispatch(campus, school, op, data) {
|
|
|
291
264
|
switch (op) {
|
|
292
265
|
case 'import': return campus.importCalendar(data);
|
|
293
266
|
case 'forget': return campus.forgetCalendar(data);
|
|
294
|
-
case 'feed': return campus.queryFeed(data);
|
|
295
|
-
case 'refresh': return campus.refresh({ force: data.force === true }).then(() => campus.queryFeed(data));
|
|
296
267
|
case 'materials': return campus.lookup(data.query);
|
|
297
268
|
case 'save': return campus.saveEvent(data);
|
|
298
269
|
case 'school-status': return school.status();
|
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');
|