@robertying/thu-learn-lib 5.0.0 → 6.0.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/README.md +94 -227
- package/lib/auth.d.ts +15 -4
- package/lib/auth.d.ts.map +1 -1
- package/lib/auth.js +65 -55
- package/lib/auth.js.map +1 -1
- package/lib/calendar.d.ts +12 -5
- package/lib/calendar.d.ts.map +1 -1
- package/lib/calendar.js +118 -20
- package/lib/calendar.js.map +1 -1
- package/lib/contents.d.ts.map +1 -1
- package/lib/contents.js +10 -6
- package/lib/contents.js.map +1 -1
- package/lib/courses.d.ts.map +1 -1
- package/lib/courses.js +15 -29
- package/lib/courses.js.map +1 -1
- package/lib/discussions.d.ts.map +1 -1
- package/lib/discussions.js +8 -19
- package/lib/discussions.js.map +1 -1
- package/lib/favorites.d.ts +1 -0
- package/lib/favorites.d.ts.map +1 -1
- package/lib/favorites.js +25 -60
- package/lib/favorites.js.map +1 -1
- package/lib/files.d.ts +4 -4
- package/lib/files.d.ts.map +1 -1
- package/lib/files.js +112 -134
- package/lib/files.js.map +1 -1
- package/lib/homework.d.ts +35 -5
- package/lib/homework.d.ts.map +1 -1
- package/lib/homework.js +150 -92
- package/lib/homework.js.map +1 -1
- package/lib/index.d.ts +45 -20
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +52 -17
- package/lib/index.js.map +1 -1
- package/lib/notices.d.ts +4 -4
- package/lib/notices.d.ts.map +1 -1
- package/lib/notices.js +13 -33
- package/lib/notices.js.map +1 -1
- package/lib/questionnaires.d.ts +6 -3
- package/lib/questionnaires.d.ts.map +1 -1
- package/lib/questionnaires.js +26 -24
- package/lib/questionnaires.js.map +1 -1
- package/lib/request.d.ts +64 -20
- package/lib/request.d.ts.map +1 -1
- package/lib/request.js +174 -64
- package/lib/request.js.map +1 -1
- package/lib/timetable.d.ts +26 -0
- package/lib/timetable.d.ts.map +1 -0
- package/lib/timetable.js +110 -0
- package/lib/timetable.js.map +1 -0
- package/lib/types.d.ts +117 -76
- package/lib/types.d.ts.map +1 -1
- package/lib/types.js +3 -0
- package/lib/types.js.map +1 -1
- package/lib/urls.d.ts +10 -20
- package/lib/urls.d.ts.map +1 -1
- package/lib/urls.js +11 -56
- package/lib/urls.js.map +1 -1
- package/lib/user.d.ts +7 -2
- package/lib/user.d.ts.map +1 -1
- package/lib/user.js +20 -6
- package/lib/user.js.map +1 -1
- package/lib/utils.d.ts +42 -4
- package/lib/utils.d.ts.map +1 -1
- package/lib/utils.js +80 -29
- package/lib/utils.js.map +1 -1
- package/package.json +9 -8
- package/src/auth.ts +72 -70
- package/src/calendar.ts +136 -24
- package/src/contents.ts +13 -6
- package/src/courses.ts +21 -37
- package/src/discussions.ts +10 -21
- package/src/favorites.ts +44 -80
- package/src/files.ts +124 -142
- package/src/homework.ts +207 -135
- package/src/index.ts +79 -48
- package/src/notices.ts +29 -42
- package/src/questionnaires.ts +62 -45
- package/src/request.ts +192 -69
- package/src/timetable.ts +121 -0
- package/src/types.ts +123 -87
- package/src/urls.ts +13 -64
- package/src/user.ts +22 -7
- package/src/utils.ts +97 -29
package/src/auth.ts
CHANGED
|
@@ -3,39 +3,35 @@
|
|
|
3
3
|
import { sm2 } from 'sm-crypto';
|
|
4
4
|
|
|
5
5
|
import type { Session } from './request.ts';
|
|
6
|
-
import {
|
|
7
|
-
import type {
|
|
8
|
-
import { FailReason, Language } from './types.ts';
|
|
6
|
+
import { discard, isConnectionError } from './request.ts';
|
|
7
|
+
import type { Credential } from './types.ts';
|
|
8
|
+
import { CourseType, FailReason, Language } from './types.ts';
|
|
9
9
|
import * as URLS from './urls.ts';
|
|
10
|
+
import { $, apiError } from './utils.ts';
|
|
11
|
+
|
|
12
|
+
/** a `Credential` with everything an SSO login needs */
|
|
13
|
+
export type CompleteCredential = Credential & { username: string; password: string; fingerPrint: string };
|
|
14
|
+
|
|
15
|
+
/** whether `credential` has a username, a password and a fingerprint */
|
|
16
|
+
export const isComplete = (credential: Credential | undefined): credential is CompleteCredential =>
|
|
17
|
+
!!credential?.username && !!credential.password && !!credential.fingerPrint;
|
|
10
18
|
|
|
11
19
|
/**
|
|
12
20
|
* If using alternative cookie management systems,
|
|
13
21
|
* be sure to clear id.tsinghua.edu.cn cookies before calling this function
|
|
14
22
|
*/
|
|
15
|
-
export async function getRoamingTicket(
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
password: string,
|
|
19
|
-
fingerPrint: string,
|
|
20
|
-
fingerGenPrint: string = '',
|
|
21
|
-
fingerGenPrint3: string = '',
|
|
22
|
-
) {
|
|
23
|
-
// Make sure we always start with the form page
|
|
24
|
-
// More code is needed to handle the case where the user is already logged in (i.e. cookies are set)
|
|
25
|
-
// It won't be a problem if it is always the same user,
|
|
26
|
-
// but if the current cookies are from a different user than the one trying to log in,
|
|
27
|
-
// it will cause problems.
|
|
23
|
+
export async function getRoamingTicket(s: Session, credential: CompleteCredential): Promise<string> {
|
|
24
|
+
const { username, password, fingerPrint, fingerGenPrint = '', fingerGenPrint3 = '' } = credential;
|
|
25
|
+
// start from the login form without an id.tsinghua.edu.cn session: one left in the cookies may be another user's
|
|
28
26
|
try {
|
|
29
27
|
await s.cookieJar.setCookie('JSESSIONID=; path=/; HttpOnly', URLS.ID_PREFIX);
|
|
30
28
|
} catch (err) {
|
|
31
|
-
throw
|
|
32
|
-
reason: FailReason.ERROR_SETTING_COOKIES,
|
|
33
|
-
extra: err,
|
|
34
|
-
} as ApiError;
|
|
29
|
+
throw apiError(FailReason.ERROR_SETTING_COOKIES, err);
|
|
35
30
|
}
|
|
36
31
|
|
|
32
|
+
let page: string;
|
|
37
33
|
try {
|
|
38
|
-
const loginForm = await s.rawFetch(URLS.ID_LOGIN
|
|
34
|
+
const loginForm = await s.rawFetch(URLS.ID_LOGIN);
|
|
39
35
|
const body = $(await loginForm.text());
|
|
40
36
|
const sm2publicKey = body('#sm2publicKey').text().trim();
|
|
41
37
|
|
|
@@ -44,78 +40,84 @@ export async function getRoamingTicket(
|
|
|
44
40
|
formData.append('i_pass', '04' + sm2.doEncrypt(password, sm2publicKey));
|
|
45
41
|
formData.append('singleLogin', 'on');
|
|
46
42
|
formData.append('fingerPrint', fingerPrint);
|
|
47
|
-
formData.append('fingerGenPrint', fingerGenPrint
|
|
48
|
-
formData.append('fingerGenPrint3', fingerGenPrint3
|
|
43
|
+
formData.append('fingerGenPrint', fingerGenPrint);
|
|
44
|
+
formData.append('fingerGenPrint3', fingerGenPrint3);
|
|
49
45
|
formData.append('i_captcha', '');
|
|
50
|
-
const checkResponse = await s.rawFetch(URLS.ID_LOGIN_CHECK
|
|
46
|
+
const checkResponse = await s.rawFetch(URLS.ID_LOGIN_CHECK, {
|
|
51
47
|
method: 'POST',
|
|
52
48
|
body: formData,
|
|
53
49
|
});
|
|
54
50
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
51
|
+
if (!checkResponse.ok) {
|
|
52
|
+
throw { code: checkResponse.status, text: checkResponse.statusText };
|
|
53
|
+
}
|
|
54
|
+
page = await checkResponse.text();
|
|
59
55
|
} catch (err) {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
} as ApiError;
|
|
56
|
+
// no answer at all: the device is offline or id.tsinghua.edu.cn is unreachable, not a refused login
|
|
57
|
+
if (isConnectionError(err)) throw err;
|
|
58
|
+
throw apiError(FailReason.ERROR_FETCH_FROM_ID, err);
|
|
64
59
|
}
|
|
60
|
+
|
|
61
|
+
// id.tsinghua.edu.cn answers with a page whose only link is the roaming URL (with the ticket), or with the login form
|
|
62
|
+
// again (with its links to the password reset, guides, phone and mail) for a wrong password
|
|
63
|
+
const body = $(page);
|
|
64
|
+
const ticket = ticketOf(body('a[href*="ticket="]').attr('href'));
|
|
65
|
+
if (ticket) return ticket;
|
|
66
|
+
if (body('#theform, form[action*="/auth/login/check"]').length > 0 && body('#i_pass').length > 0) {
|
|
67
|
+
throw apiError(FailReason.BAD_CREDENTIAL, textOf(body('#msg_note, .alert-danger')) || undefined);
|
|
68
|
+
}
|
|
69
|
+
// something else, e.g. a second factor, a locked account or maintenance: not a wrong password
|
|
70
|
+
throw apiError(
|
|
71
|
+
FailReason.ERROR_FETCH_FROM_ID,
|
|
72
|
+
textOf(body('body').clone().find('script, style').remove().end()).slice(0, 200),
|
|
73
|
+
);
|
|
65
74
|
}
|
|
66
75
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
): Promise<void> {
|
|
76
|
-
if (!username || !password || !fingerPrint) {
|
|
77
|
-
if (!s.provider)
|
|
78
|
-
return Promise.reject({
|
|
79
|
-
reason: FailReason.NO_CREDENTIAL,
|
|
80
|
-
});
|
|
81
|
-
const credential = await s.provider();
|
|
82
|
-
username = credential.username;
|
|
83
|
-
password = credential.password;
|
|
84
|
-
fingerPrint = credential.fingerPrint;
|
|
85
|
-
fingerGenPrint = credential.fingerGenPrint;
|
|
86
|
-
fingerGenPrint3 = credential.fingerGenPrint3;
|
|
87
|
-
if (!username || !password || !fingerPrint) {
|
|
88
|
-
return Promise.reject({
|
|
89
|
-
reason: FailReason.NO_CREDENTIAL,
|
|
90
|
-
});
|
|
91
|
-
}
|
|
76
|
+
const textOf = (el: { text(): string }) => el.text().replace(/\s+/g, ' ').trim();
|
|
77
|
+
|
|
78
|
+
const ticketOf = (href: string | undefined): string | undefined => {
|
|
79
|
+
if (!href) return undefined;
|
|
80
|
+
try {
|
|
81
|
+
return new URL(href, URLS.ID_PREFIX).searchParams.get('ticket') || undefined;
|
|
82
|
+
} catch {
|
|
83
|
+
return undefined;
|
|
92
84
|
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/** log in with the `CredentialProvider`; `NO_CREDENTIAL` without one, or when it gives an incomplete credential */
|
|
88
|
+
export async function loginWithProvider(s: Session): Promise<void> {
|
|
89
|
+
const credential = await s.provider?.();
|
|
90
|
+
if (!isComplete(credential)) throw apiError(FailReason.NO_CREDENTIAL);
|
|
91
|
+
return login(s, credential);
|
|
92
|
+
}
|
|
93
93
|
|
|
94
|
-
|
|
95
|
-
|
|
94
|
+
/** log in through id.tsinghua.edu.cn, then read the CSRF token and the website language from the homepage */
|
|
95
|
+
export async function login(s: Session, credential: CompleteCredential): Promise<void> {
|
|
96
|
+
const ticket = await getRoamingTicket(s, credential);
|
|
97
|
+
const { fingerPrint, fingerGenPrint = '', fingerGenPrint3 = '' } = credential;
|
|
98
|
+
s.fingerprints = { fingerPrint, fingerGenPrint, fingerGenPrint3 };
|
|
96
99
|
|
|
97
100
|
const loginResponse = await s.rawFetch(URLS.LEARN_AUTH_ROAM(ticket));
|
|
101
|
+
// only the status matters
|
|
102
|
+
discard(loginResponse);
|
|
98
103
|
if (!loginResponse.ok) {
|
|
99
|
-
|
|
100
|
-
reason: FailReason.ERROR_ROAMING,
|
|
101
|
-
});
|
|
104
|
+
throw apiError(FailReason.ERROR_ROAMING);
|
|
102
105
|
}
|
|
103
|
-
const courseListPageSource: string = await (await s.rawFetch(URLS.
|
|
106
|
+
const courseListPageSource: string = await (await s.rawFetch(URLS.LEARN_HOMEPAGE(CourseType.STUDENT))).text();
|
|
104
107
|
const tokenRegex = /^.*&_csrf=(\S*)".*$/gm;
|
|
105
108
|
const tokenMatches = [...courseListPageSource.matchAll(tokenRegex)];
|
|
106
109
|
if (tokenMatches.length === 0) {
|
|
107
|
-
|
|
108
|
-
reason: FailReason.INVALID_RESPONSE,
|
|
109
|
-
extra: 'cannot fetch CSRF token from source',
|
|
110
|
-
});
|
|
110
|
+
throw apiError(FailReason.INVALID_RESPONSE, 'cannot fetch CSRF token from source');
|
|
111
111
|
}
|
|
112
112
|
s.csrfToken = tokenMatches[0][1];
|
|
113
|
-
|
|
113
|
+
// the homepage loads e.g. `/f/wlxt/common/languagejs?lang=zh_CN&v=845`
|
|
114
|
+
const langRegex = /\/f\/wlxt\/common\/languagejs\?lang=(zh|en)/g;
|
|
114
115
|
const langMatches = [...courseListPageSource.matchAll(langRegex)];
|
|
115
116
|
if (langMatches.length !== 0) s.lang = langMatches[0][1] === 'en' ? Language.EN : Language.ZH;
|
|
116
117
|
}
|
|
117
118
|
|
|
118
|
-
/** logout (to make everyone happy) */
|
|
119
|
+
/** logout (to make everyone happy); the CSRF token is cleared, so the next request logs in again */
|
|
119
120
|
export async function logout(s: Session): Promise<void> {
|
|
120
|
-
await s.rawFetch(URLS.LEARN_LOGOUT
|
|
121
|
+
discard(await s.rawFetch(URLS.LEARN_LOGOUT, { method: 'POST' }));
|
|
122
|
+
s.csrfToken = '';
|
|
121
123
|
}
|
package/src/calendar.ts
CHANGED
|
@@ -1,21 +1,30 @@
|
|
|
1
|
-
// Course calendar from the registrar (
|
|
1
|
+
// Course calendar from the registrar (zhjw.cic.tsinghua.edu.cn).
|
|
2
2
|
|
|
3
3
|
import type { Session } from './request.ts';
|
|
4
|
-
import
|
|
4
|
+
import { discard } from './request.ts';
|
|
5
|
+
import type { ApiError, CalendarEvent, CalendarOptions, CalendarRange, CalendarResult } from './types.ts';
|
|
5
6
|
import { FailReason } from './types.ts';
|
|
6
7
|
import * as URLS from './urls.ts';
|
|
7
|
-
import { JSONP_EXTRACTOR_NAME, extractJSONPResult } from './utils.ts';
|
|
8
|
+
import { $, JSONP_EXTRACTOR_NAME, apiError, extractJSONPResult } from './utils.ts';
|
|
8
9
|
|
|
9
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* The registrar often fails for ranges longer than about a month, so longer ranges are fetched in windows of this many
|
|
12
|
+
* days.
|
|
13
|
+
*/
|
|
10
14
|
export const CALENDAR_WINDOW_DAYS = 28;
|
|
11
15
|
|
|
12
16
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
13
17
|
|
|
18
|
+
/** after this many windows in a row time out, `getCalendar` gives up on the rest (they go to `failedRanges`) */
|
|
19
|
+
const MAX_CONSECUTIVE_TIMEOUTS = 2;
|
|
20
|
+
|
|
21
|
+
const isTimeout = (err: unknown) => (err as ApiError | undefined)?.reason === FailReason.REQUEST_TIMEOUT;
|
|
22
|
+
|
|
14
23
|
const parseDate = (date: string): number => {
|
|
15
24
|
const match = /^(\d{4})(\d{2})(\d{2})$/.exec(date);
|
|
16
25
|
const time = match ? Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])) : NaN;
|
|
17
26
|
if (Number.isNaN(time) || formatDate(time) !== date) {
|
|
18
|
-
throw
|
|
27
|
+
throw new RangeError(`invalid date ${date}, expected yyyymmdd`);
|
|
19
28
|
}
|
|
20
29
|
return time;
|
|
21
30
|
};
|
|
@@ -34,18 +43,112 @@ export function splitCalendarRange(startDate: string, endDate: string, days = CA
|
|
|
34
43
|
return ranges;
|
|
35
44
|
}
|
|
36
45
|
|
|
46
|
+
const FINGERPRINT_FIELDS = ['fingerPrint', 'fingerGenPrint', 'fingerGenPrint3'] as const;
|
|
47
|
+
const isFingerprintField = (name: string): name is (typeof FINGERPRINT_FIELDS)[number] =>
|
|
48
|
+
(FINGERPRINT_FIELDS as readonly string[]).includes(name);
|
|
49
|
+
|
|
50
|
+
/** `extra.step` of an `ERROR_REGISTRAR_AUTH` that id.tsinghua.edu.cn turned down (rather than the registrar failing) */
|
|
51
|
+
const ID_STEP = 'id.tsinghua.edu.cn';
|
|
52
|
+
|
|
53
|
+
const isIdRefusal = (err: unknown) =>
|
|
54
|
+
(err as ApiError | undefined)?.reason === FailReason.ERROR_REGISTRAR_AUTH &&
|
|
55
|
+
((err as ApiError).extra as { step?: string } | undefined)?.step === ID_STEP;
|
|
56
|
+
|
|
57
|
+
/** an id.tsinghua.edu.cn login form (`/do/off/ui/auth/login/check`, `.../checkSingle`) */
|
|
58
|
+
const isIdLoginPage = (res: Response, page: string) =>
|
|
59
|
+
res.url.startsWith(URLS.ID_PREFIX) || /action="[^"]*\/do\/off\/ui\/auth\/login\//.test(page);
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The body of a sign-in step, or '' when there is no text. The registrar's own pages are GBK, which React Native's
|
|
63
|
+
* fetch can't decode: its `text()` then gives `undefined` instead of a string. Only id.tsinghua.edu.cn pages (UTF-8)
|
|
64
|
+
* are looked into here, so an undecodable registrar page is as good as an empty one.
|
|
65
|
+
*/
|
|
66
|
+
const readText = async (res: Response): Promise<string> => {
|
|
67
|
+
const text: unknown = await res.text();
|
|
68
|
+
return typeof text === 'string' ? text : '';
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Sign in to the registrar with a Web Learning ticket.
|
|
73
|
+
*
|
|
74
|
+
* Registrar requests use `rawFetch`, without the Web Learning login check: a 403 or login page from the registrar says
|
|
75
|
+
* nothing about the Web Learning session, and logging in there again wouldn't renew the registrar ticket. They don't
|
|
76
|
+
* carry Web Learning's CSRF token either: the registrar (and WebVPN in front of it off campus) has no use for it.
|
|
77
|
+
*
|
|
78
|
+
* Off campus the registrar is only reachable through WebVPN (webvpn.tsinghua.edu.cn): the auth URL redirects there,
|
|
79
|
+
* and WebVPN signs in through id.tsinghua.edu.cn OAuth. As the id.tsinghua.edu.cn session of the Web Learning login is
|
|
80
|
+
* still there, id.tsinghua.edu.cn answers with a form (`#logined`) that a browser submits right away with its device
|
|
81
|
+
* fingerprints. Submitting it answers with a page that links (by script) to the OAuth callback, which signs in to WebVPN
|
|
82
|
+
* and redirects back to the auth URL, so following the link ends on the registrar.
|
|
83
|
+
*/
|
|
84
|
+
async function authenticateRegistrar(s: Session, ticket: string): Promise<void> {
|
|
85
|
+
let res = await s.rawFetch(URLS.REGISTRAR_AUTH(ticket));
|
|
86
|
+
let page = await readText(res);
|
|
87
|
+
|
|
88
|
+
const form = $(page)('form#logined');
|
|
89
|
+
if (form.length > 0) {
|
|
90
|
+
const fingerprints = s.fingerprints ?? (await s.provider?.());
|
|
91
|
+
const data = new FormData();
|
|
92
|
+
form.find('input[name]').each((_, input) => {
|
|
93
|
+
const name = input.attribs.name;
|
|
94
|
+
const known = isFingerprintField(name) ? fingerprints?.[name] : undefined;
|
|
95
|
+
data.append(name, known ?? input.attribs.value ?? '');
|
|
96
|
+
});
|
|
97
|
+
const action = new URL(form.attr('action') ?? '', res.url || URLS.ID_PREFIX).href;
|
|
98
|
+
const check = await s.rawFetch(action, { method: 'POST', body: data });
|
|
99
|
+
const link = check.ok ? $(await readText(check))('a').attr('href') : undefined;
|
|
100
|
+
if (!link) {
|
|
101
|
+
discard(check);
|
|
102
|
+
throw apiError(FailReason.ERROR_REGISTRAR_AUTH, { step: ID_STEP, code: check.status });
|
|
103
|
+
}
|
|
104
|
+
res = await s.rawFetch(new URL(link, check.url || action).href);
|
|
105
|
+
page = await readText(res);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (isIdLoginPage(res, page)) {
|
|
109
|
+
throw apiError(FailReason.ERROR_REGISTRAR_AUTH, { step: ID_STEP, code: res.status, url: res.url.split('?')[0] });
|
|
110
|
+
}
|
|
111
|
+
if (!res.ok) {
|
|
112
|
+
throw apiError(FailReason.ERROR_REGISTRAR_AUTH, { code: res.status, url: res.url.split('?')[0] });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Get a registrar ticket and sign in to the registrar with it. When id.tsinghua.edu.cn turns the sign-in down (its
|
|
118
|
+
* session from the last login has expired, e.g. in a session resumed from saved cookies) and there is a
|
|
119
|
+
* `CredentialProvider`, log in to Web Learning again (a new id.tsinghua.edu.cn session) and try once more.
|
|
120
|
+
*/
|
|
121
|
+
async function signInToRegistrar(s: Session): Promise<void> {
|
|
122
|
+
const signIn = async () => {
|
|
123
|
+
const ticket = await s.fetchTextWithToken(URLS.REGISTRAR_TICKET, {
|
|
124
|
+
method: 'POST',
|
|
125
|
+
body: URLS.REGISTRAR_TICKET_FORM_DATA(),
|
|
126
|
+
});
|
|
127
|
+
await authenticateRegistrar(s, ticket.substring(1, ticket.length - 1));
|
|
128
|
+
};
|
|
129
|
+
try {
|
|
130
|
+
await signIn();
|
|
131
|
+
} catch (err) {
|
|
132
|
+
if (!s.provider || !isIdRefusal(err)) throw err;
|
|
133
|
+
await s.autoRelogin();
|
|
134
|
+
await signIn();
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
37
138
|
async function fetchWindow(s: Session, range: CalendarRange, graduate: boolean): Promise<CalendarEvent[]> {
|
|
38
|
-
const response = await s.
|
|
139
|
+
const response = await s.rawFetch(
|
|
39
140
|
URLS.REGISTRAR_CALENDAR(range.startDate, range.endDate, graduate, JSONP_EXTRACTOR_NAME),
|
|
40
141
|
);
|
|
41
142
|
|
|
42
143
|
if (!response.ok) {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
});
|
|
144
|
+
discard(response);
|
|
145
|
+
throw apiError(FailReason.INVALID_RESPONSE, { code: response.status, text: response.statusText });
|
|
46
146
|
}
|
|
47
147
|
|
|
48
|
-
const result = extractJSONPResult(await response.text())
|
|
148
|
+
const result: unknown = extractJSONPResult(await response.text());
|
|
149
|
+
if (!Array.isArray(result)) {
|
|
150
|
+
throw apiError(FailReason.INVALID_RESPONSE, result);
|
|
151
|
+
}
|
|
49
152
|
|
|
50
153
|
return result.map<CalendarEvent>((i) => ({
|
|
51
154
|
location: i.dd,
|
|
@@ -60,10 +163,14 @@ async function fetchWindow(s: Session, range: CalendarRange, graduate: boolean):
|
|
|
60
163
|
/**
|
|
61
164
|
* Get calendar items during the specified period (in yyyymmdd format, both inclusive).
|
|
62
165
|
*
|
|
63
|
-
* Ranges longer than `CALENDAR_WINDOW_DAYS` are fetched in consecutive windows (one at a time, each retried once
|
|
64
|
-
* merged in date order. Windows that still fail are listed in `failedRanges`, so callers can
|
|
65
|
-
* retry only those
|
|
66
|
-
*
|
|
166
|
+
* Ranges longer than `CALENDAR_WINDOW_DAYS` are fetched in consecutive windows (one at a time, each retried once
|
|
167
|
+
* unless it timed out) and merged in date order. Windows that still fail are listed in `failedRanges`, so callers can
|
|
168
|
+
* show partial data and retry only those; after two windows in a row time out, the rest are listed there without a
|
|
169
|
+
* request. If every window fails, this rejects with the last error instead (usually `FailReason.INVALID_RESPONSE`).
|
|
170
|
+
* The result might be empty if the period is too far away from now. Throws a `RangeError` for a date that is not a
|
|
171
|
+
* valid yyyymmdd, and rejects with `FailReason.ERROR_REGISTRAR_AUTH` if signing in to the registrar fails. Off campus
|
|
172
|
+
* this goes through WebVPN and needs the id.tsinghua.edu.cn session of the last `login`; when that has expired, a
|
|
173
|
+
* helper with a `CredentialProvider` logs in again and tries once more.
|
|
67
174
|
*/
|
|
68
175
|
export async function getCalendar(
|
|
69
176
|
s: Session,
|
|
@@ -75,25 +182,30 @@ export async function getCalendar(
|
|
|
75
182
|
const ranges = splitCalendarRange(startDate, endDate);
|
|
76
183
|
if (ranges.length === 0) return { events: [], failedRanges: [] };
|
|
77
184
|
|
|
78
|
-
|
|
79
|
-
method: 'POST',
|
|
80
|
-
body: URLS.REGISTRAR_TICKET_FORM_DATA(),
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
let ticket = await ticketResponse.text();
|
|
84
|
-
ticket = ticket.substring(1, ticket.length - 1);
|
|
85
|
-
|
|
86
|
-
await s.fetch(URLS.REGISTRAR_AUTH(ticket));
|
|
185
|
+
await signInToRegistrar(s);
|
|
87
186
|
|
|
88
187
|
const events: CalendarEvent[] = [];
|
|
89
188
|
const failedRanges: CalendarRange[] = [];
|
|
90
189
|
let lastError: unknown;
|
|
190
|
+
let timeouts = 0;
|
|
91
191
|
for (const range of ranges) {
|
|
192
|
+
// after this many timed-out windows in a row the registrar is taken as down, and the rest are not tried
|
|
193
|
+
if (timeouts >= MAX_CONSECUTIVE_TIMEOUTS) {
|
|
194
|
+
failedRanges.push(range);
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
92
197
|
try {
|
|
93
|
-
|
|
198
|
+
// a timed-out window is not retried: the registrar is slow, not flaky, and each try takes `requestTimeout`
|
|
199
|
+
events.push(
|
|
200
|
+
...(await fetchWindow(s, range, graduate).catch((err: unknown) =>
|
|
201
|
+
isTimeout(err) ? Promise.reject(err) : fetchWindow(s, range, graduate),
|
|
202
|
+
)),
|
|
203
|
+
);
|
|
204
|
+
timeouts = 0;
|
|
94
205
|
} catch (e) {
|
|
95
206
|
lastError = e;
|
|
96
207
|
failedRanges.push(range);
|
|
208
|
+
timeouts = isTimeout(e) ? timeouts + 1 : 0;
|
|
97
209
|
}
|
|
98
210
|
}
|
|
99
211
|
|
package/src/contents.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import type { Session } from './request.ts';
|
|
4
4
|
import type { AllContentsOptions, AllContentsResult, ContentTypeMap, CourseContent } from './types.ts';
|
|
5
|
+
import { apiError } from './utils.ts';
|
|
5
6
|
import { ContentType, CourseType, FailReason } from './types.ts';
|
|
6
7
|
import { getAnsweredQuestionList, getDiscussionList } from './discussions.ts';
|
|
7
8
|
import { getFileList } from './files.ts';
|
|
@@ -20,7 +21,7 @@ export async function getAllContents<T extends ContentType>(
|
|
|
20
21
|
options: AllContentsOptions<T> = {},
|
|
21
22
|
): Promise<AllContentsResult<T>> {
|
|
22
23
|
const courseType = options.courseType ?? CourseType.STUDENT;
|
|
23
|
-
const fetchContentForCourse = (id: string): Promise<ContentTypeMap[T][]> => {
|
|
24
|
+
const fetchContentForCourse = async (id: string): Promise<ContentTypeMap[T][]> => {
|
|
24
25
|
switch (type) {
|
|
25
26
|
case ContentType.NOTIFICATION:
|
|
26
27
|
return getNotificationList(s, id, courseType, {
|
|
@@ -29,6 +30,13 @@ export async function getAllContents<T extends ContentType>(
|
|
|
29
30
|
case ContentType.FILE:
|
|
30
31
|
return getFileList(s, id, courseType) as Promise<ContentTypeMap[T][]>;
|
|
31
32
|
case ContentType.HOMEWORK:
|
|
33
|
+
if (courseType === CourseType.TEACHER) {
|
|
34
|
+
// the teacher list has another shape (`HomeworkTA`); use `getHomeworkList(id, CourseType.TEACHER)`
|
|
35
|
+
throw apiError(
|
|
36
|
+
FailReason.NOT_IMPLEMENTED,
|
|
37
|
+
'homework of a teacher course; use getHomeworkList(courseID, CourseType.TEACHER)',
|
|
38
|
+
);
|
|
39
|
+
}
|
|
32
40
|
return getHomeworkList(s, id, CourseType.STUDENT, {
|
|
33
41
|
details: (options as AllContentsOptions<ContentType.HOMEWORK>).details,
|
|
34
42
|
}) as Promise<ContentTypeMap[T][]>;
|
|
@@ -37,12 +45,11 @@ export async function getAllContents<T extends ContentType>(
|
|
|
37
45
|
case ContentType.QUESTION:
|
|
38
46
|
return getAnsweredQuestionList(s, id, courseType) as Promise<ContentTypeMap[T][]>;
|
|
39
47
|
case ContentType.QUESTIONNAIRE:
|
|
40
|
-
return getQuestionnaireList(s, id
|
|
48
|
+
return getQuestionnaireList(s, id, {
|
|
49
|
+
details: (options as AllContentsOptions<ContentType.QUESTIONNAIRE>).details,
|
|
50
|
+
}) as Promise<ContentTypeMap[T][]>;
|
|
41
51
|
default:
|
|
42
|
-
|
|
43
|
-
reason: FailReason.NOT_IMPLEMENTED,
|
|
44
|
-
extra: 'Unknown content type',
|
|
45
|
-
});
|
|
52
|
+
throw apiError(FailReason.NOT_IMPLEMENTED, 'Unknown content type');
|
|
46
53
|
}
|
|
47
54
|
};
|
|
48
55
|
|
package/src/courses.ts
CHANGED
|
@@ -1,31 +1,25 @@
|
|
|
1
1
|
// Semesters and courses.
|
|
2
2
|
|
|
3
3
|
import type { Session } from './request.ts';
|
|
4
|
-
import type {
|
|
4
|
+
import type { CourseInfo, CourseListOptions, SemesterInfo } from './types.ts';
|
|
5
5
|
import { CourseType, FailReason } from './types.ts';
|
|
6
6
|
import * as URLS from './urls.ts';
|
|
7
|
-
import { decodeHTML, parseSemesterType } from './utils.ts';
|
|
7
|
+
import { apiError, decodeHTML, expectSuccess, parseSemesterType } from './utils.ts';
|
|
8
8
|
|
|
9
9
|
export async function getSemesterIdList(s: Session): Promise<string[]> {
|
|
10
|
-
const json = await
|
|
10
|
+
const json = await s.fetchJsonWithToken(URLS.LEARN_SEMESTER_LIST);
|
|
11
11
|
if (!Array.isArray(json)) {
|
|
12
|
-
|
|
13
|
-
reason: FailReason.INVALID_RESPONSE,
|
|
14
|
-
extra: json,
|
|
15
|
-
});
|
|
12
|
+
throw apiError(FailReason.INVALID_RESPONSE, json);
|
|
16
13
|
}
|
|
17
14
|
const semesters = json as string[];
|
|
18
|
-
//
|
|
15
|
+
// the list can contain null entries
|
|
19
16
|
return semesters.filter((semester) => semester != null);
|
|
20
17
|
}
|
|
21
18
|
|
|
22
19
|
export async function getCurrentSemester(s: Session): Promise<SemesterInfo> {
|
|
23
|
-
const json = await
|
|
20
|
+
const json = await s.fetchJsonWithToken(URLS.LEARN_CURRENT_SEMESTER);
|
|
24
21
|
if (json.message !== 'success') {
|
|
25
|
-
|
|
26
|
-
reason: FailReason.INVALID_RESPONSE,
|
|
27
|
-
extra: json,
|
|
28
|
-
});
|
|
22
|
+
throw apiError(FailReason.INVALID_RESPONSE, json);
|
|
29
23
|
}
|
|
30
24
|
const result = json.result;
|
|
31
25
|
return {
|
|
@@ -46,14 +40,11 @@ export async function getCourseList(
|
|
|
46
40
|
lang = s.lang,
|
|
47
41
|
options: CourseListOptions = {},
|
|
48
42
|
): Promise<CourseInfo[]> {
|
|
49
|
-
const json = await
|
|
43
|
+
const json = await s.fetchJsonWithToken(URLS.LEARN_COURSE_LIST(semesterID, courseType, lang));
|
|
50
44
|
if (json.message !== 'success' || !Array.isArray(json.resultList)) {
|
|
51
|
-
|
|
52
|
-
reason: FailReason.INVALID_RESPONSE,
|
|
53
|
-
extra: json,
|
|
54
|
-
});
|
|
45
|
+
throw apiError(FailReason.INVALID_RESPONSE, json);
|
|
55
46
|
}
|
|
56
|
-
const result =
|
|
47
|
+
const result = json.resultList as any[];
|
|
57
48
|
|
|
58
49
|
return Promise.all(
|
|
59
50
|
result.map(async (c) => {
|
|
@@ -62,7 +53,7 @@ export async function getCourseList(
|
|
|
62
53
|
try {
|
|
63
54
|
timeAndLocation = await getCourseTimeAndLocation(s, c.wlkcid);
|
|
64
55
|
} catch {
|
|
65
|
-
|
|
56
|
+
// left out, so a failure doesn't look like a course without a schedule; see `getCourseTimeAndLocation`
|
|
66
57
|
}
|
|
67
58
|
}
|
|
68
59
|
return {
|
|
@@ -85,27 +76,20 @@ export async function getCourseList(
|
|
|
85
76
|
/** get the time and location of one course (1 request) */
|
|
86
77
|
export async function getCourseTimeAndLocation(s: Session, courseID: string): Promise<string[]> {
|
|
87
78
|
// see https://github.com/Harry-Chen/Learn-Helper/issues/145
|
|
88
|
-
const json = await
|
|
79
|
+
const json = await s.fetchJsonWithToken(URLS.LEARN_COURSE_TIME_LOCATION(courseID));
|
|
89
80
|
if (!Array.isArray(json)) {
|
|
90
|
-
throw
|
|
81
|
+
throw apiError(FailReason.INVALID_RESPONSE, json);
|
|
91
82
|
}
|
|
92
83
|
return json as string[];
|
|
93
84
|
}
|
|
94
85
|
|
|
95
86
|
export async function sortCourses(s: Session, courseIDs: string[]): Promise<void> {
|
|
96
|
-
const json = await (
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
).json();
|
|
105
|
-
if (json.result !== 'success') {
|
|
106
|
-
return Promise.reject({
|
|
107
|
-
reason: FailReason.OPERATION_FAILED,
|
|
108
|
-
extra: json,
|
|
109
|
-
});
|
|
110
|
-
}
|
|
87
|
+
const json = await s.fetchJsonWithToken(URLS.LEARN_SORT_COURSES, {
|
|
88
|
+
method: 'POST',
|
|
89
|
+
body: JSON.stringify(courseIDs.map((id, index) => ({ wlkcid: id, xh: index + 1 }))),
|
|
90
|
+
headers: {
|
|
91
|
+
'Content-Type': 'application/json',
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
expectSuccess(json, FailReason.OPERATION_FAILED);
|
|
111
95
|
}
|
package/src/discussions.ts
CHANGED
|
@@ -3,11 +3,10 @@
|
|
|
3
3
|
import { Base64 } from 'js-base64';
|
|
4
4
|
|
|
5
5
|
import type { Session } from './request.ts';
|
|
6
|
-
import {
|
|
7
|
-
import type { Discussion, IDiscussionBase, Question } from './types.ts';
|
|
6
|
+
import type { Discussion, DiscussionBase, Question } from './types.ts';
|
|
8
7
|
import { CourseType, FailReason } from './types.ts';
|
|
9
8
|
import * as URLS from './urls.ts';
|
|
10
|
-
import { decodeHTML } from './utils.ts';
|
|
9
|
+
import { YES, decodeHTML, expectSuccess, toRequiredServerTime } from './utils.ts';
|
|
11
10
|
|
|
12
11
|
/** Get all discussions (课程讨论) of the specified course. */
|
|
13
12
|
export async function getDiscussionList(
|
|
@@ -15,13 +14,8 @@ export async function getDiscussionList(
|
|
|
15
14
|
courseID: string,
|
|
16
15
|
courseType: CourseType = CourseType.STUDENT,
|
|
17
16
|
): Promise<Discussion[]> {
|
|
18
|
-
const json = await
|
|
19
|
-
|
|
20
|
-
return Promise.reject({
|
|
21
|
-
reason: FailReason.INVALID_RESPONSE,
|
|
22
|
-
extra: json,
|
|
23
|
-
});
|
|
24
|
-
}
|
|
17
|
+
const json = await s.fetchJsonWithToken(URLS.LEARN_DISCUSSION_LIST(courseID, courseType));
|
|
18
|
+
expectSuccess(json, FailReason.INVALID_RESPONSE);
|
|
25
19
|
|
|
26
20
|
const result = (json.object?.resultsList ?? []) as any[];
|
|
27
21
|
|
|
@@ -44,13 +38,8 @@ export async function getAnsweredQuestionList(
|
|
|
44
38
|
courseID: string,
|
|
45
39
|
courseType: CourseType = CourseType.STUDENT,
|
|
46
40
|
): Promise<Question[]> {
|
|
47
|
-
const json = await
|
|
48
|
-
|
|
49
|
-
return Promise.reject({
|
|
50
|
-
reason: FailReason.INVALID_RESPONSE,
|
|
51
|
-
extra: json,
|
|
52
|
-
});
|
|
53
|
-
}
|
|
41
|
+
const json = await s.fetchJsonWithToken(URLS.LEARN_QUESTION_LIST_ANSWERED(courseID, courseType));
|
|
42
|
+
expectSuccess(json, FailReason.INVALID_RESPONSE);
|
|
54
43
|
|
|
55
44
|
const result = (json.object?.resultsList ?? []) as any[];
|
|
56
45
|
|
|
@@ -58,19 +47,19 @@ export async function getAnsweredQuestionList(
|
|
|
58
47
|
(q) =>
|
|
59
48
|
({
|
|
60
49
|
...parseDiscussionBase(q),
|
|
61
|
-
question: Base64.decode(q.wtnr),
|
|
50
|
+
question: Base64.decode(q.wtnr ?? ''),
|
|
62
51
|
url: URLS.LEARN_QUESTION_DETAIL(q.wlkcid, q.id, courseType),
|
|
63
52
|
}) satisfies Question,
|
|
64
53
|
);
|
|
65
54
|
}
|
|
66
55
|
|
|
67
|
-
function parseDiscussionBase(d: any):
|
|
56
|
+
function parseDiscussionBase(d: any): DiscussionBase {
|
|
68
57
|
return {
|
|
69
58
|
id: d.id,
|
|
70
59
|
title: decodeHTML(d.bt),
|
|
71
60
|
publisherName: d.fbrxm,
|
|
72
|
-
publishTime: d.fbsj,
|
|
73
|
-
lastReplyTime: d.zhhfsj,
|
|
61
|
+
publishTime: toRequiredServerTime(d.fbsj),
|
|
62
|
+
lastReplyTime: toRequiredServerTime(d.zhhfsj),
|
|
74
63
|
lastReplierName: d.zhhfrxm,
|
|
75
64
|
visitCount: d.djs ?? 0, // teacher cannot fetch this
|
|
76
65
|
replyCount: d.hfcs,
|