|
|
|
@ -118,12 +118,24 @@ export class ApiError extends Error {
|
|
|
|
constructor(status: number, message: string) {
|
|
|
|
constructor(status: number, message: string) {
|
|
|
|
super(message);
|
|
|
|
super(message);
|
|
|
|
this.status = status;
|
|
|
|
this.status = status;
|
|
|
|
this.code = status === 401 ? 'unauthenticated' : status === 403 ? 'not_granted' : 'api_error';
|
|
|
|
this.code = status === 0 ? 'network' : status === 401 ? 'unauthenticated' : status === 403 ? 'not_granted' : 'api_error';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
const notConnected = (what: string) => Object.assign(new Error(`${what} isn't connected to the API yet.`), { code: 'not_granted' });
|
|
|
|
const notConnected = (what: string) => Object.assign(new Error(`${what} isn't connected to the API yet.`), { code: 'not_granted' });
|
|
|
|
|
|
|
|
|
|
|
|
const TOKENS_KEY = 'lms.api.tokens';
|
|
|
|
const TOKENS_KEY = 'lms.api.tokens';
|
|
|
|
|
|
|
|
const REQUEST_TIMEOUT_MS = 12000;
|
|
|
|
|
|
|
|
const REQUEST_RETRIES = 2;
|
|
|
|
|
|
|
|
const PARALLEL = 3; // the catalog fans out one call per course/chapter; a smaller burst is gentler on the server
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/** Like Promise.all over `items`, with at most `limit` calls in flight. */
|
|
|
|
|
|
|
|
async function mapLimit<T, R>(items: T[], limit: number, fn: (x: T) => Promise<R>): Promise<R[]> {
|
|
|
|
|
|
|
|
const out: R[] = new Array(items.length); let next = 0;
|
|
|
|
|
|
|
|
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
|
|
|
|
|
|
while (next < items.length) { const i = next++; out[i] = await fn(items[i]); }
|
|
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
return out;
|
|
|
|
|
|
|
|
}
|
|
|
|
const readTokens = (): Tokens | null => { try { return JSON.parse(localStorage.getItem(TOKENS_KEY) ?? 'null'); } catch { return null; } };
|
|
|
|
const readTokens = (): Tokens | null => { try { return JSON.parse(localStorage.getItem(TOKENS_KEY) ?? 'null'); } catch { return null; } };
|
|
|
|
const writeTokens = (t: Tokens | null) => { try { t ? localStorage.setItem(TOKENS_KEY, JSON.stringify(t)) : localStorage.removeItem(TOKENS_KEY); } catch { /* storage blocked: session-only */ } };
|
|
|
|
const writeTokens = (t: Tokens | null) => { try { t ? localStorage.setItem(TOKENS_KEY, JSON.stringify(t)) : localStorage.removeItem(TOKENS_KEY); } catch { /* storage blocked: session-only */ } };
|
|
|
|
|
|
|
|
|
|
|
|
@ -146,11 +158,24 @@ export class ApiDataSource implements DataSource {
|
|
|
|
|
|
|
|
|
|
|
|
// ---- transport
|
|
|
|
// ---- transport
|
|
|
|
|
|
|
|
|
|
|
|
private async request<T>(method: string, path: string, body?: unknown, auth = true): Promise<T> {
|
|
|
|
/**
|
|
|
|
const send = () => fetch(`${this.base.replace(/\/+$/, '')}/api/v1${path}`, {
|
|
|
|
* One API call. Every attempt gives up after REQUEST_TIMEOUT_MS: the server has been seen dropping new connections
|
|
|
|
|
|
|
|
* (they hang instead of failing), and a hung sign-in looks like a broken button. Calls that are safe to repeat
|
|
|
|
|
|
|
|
* (reads, the account lookup, password login) retry; ones with side effects (sending a code, verifying it) never do,
|
|
|
|
|
|
|
|
* so a learner can't get two texts or burn a code.
|
|
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
private async request<T>(method: string, path: string, body?: unknown, auth = true, retry = method === 'GET'): Promise<T> {
|
|
|
|
|
|
|
|
const attempt = () => fetch(`${this.base.replace(/\/+$/, '')}/api/v1${path}`, {
|
|
|
|
method, headers: { 'content-type': 'application/json', ...(auth && this.tokens ? { authorization: `Bearer ${this.tokens.access}` } : {}) },
|
|
|
|
method, headers: { 'content-type': 'application/json', ...(auth && this.tokens ? { authorization: `Bearer ${this.tokens.access}` } : {}) },
|
|
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
|
|
|
|
|
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
const send = async () => {
|
|
|
|
|
|
|
|
for (let i = 0; ; i++) {
|
|
|
|
|
|
|
|
try { return await attempt(); }
|
|
|
|
|
|
|
|
catch { if (!retry || i >= REQUEST_RETRIES) throw new ApiError(0, "Couldn't reach the server."); }
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
};
|
|
|
|
let res = await send();
|
|
|
|
let res = await send();
|
|
|
|
if (res.status === 401 && auth && this.tokens && (await this.refresh())) res = await send();
|
|
|
|
if (res.status === 401 && auth && this.tokens && (await this.refresh())) res = await send();
|
|
|
|
const json = await res.json().catch(() => null);
|
|
|
|
const json = await res.json().catch(() => null);
|
|
|
|
@ -164,6 +189,7 @@ export class ApiDataSource implements DataSource {
|
|
|
|
this.refreshing ??= fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/refresh`, {
|
|
|
|
this.refreshing ??= fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/refresh`, {
|
|
|
|
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
|
|
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
|
|
body: JSON.stringify({ access_token: this.tokens.access, refresh_token: this.tokens.refresh }),
|
|
|
|
body: JSON.stringify({ access_token: this.tokens.access, refresh_token: this.tokens.refresh }),
|
|
|
|
|
|
|
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
|
|
}).then(async (r) => {
|
|
|
|
}).then(async (r) => {
|
|
|
|
const j = await r.json().catch(() => null);
|
|
|
|
const j = await r.json().catch(() => null);
|
|
|
|
if (!r.ok || !j?.data?.access_token) { this.setTokens(null); return false; }
|
|
|
|
if (!r.ok || !j?.data?.access_token) { this.setTokens(null); return false; }
|
|
|
|
@ -187,7 +213,7 @@ export class ApiDataSource implements DataSource {
|
|
|
|
/** 'code' when the learner must enter a one-time code next; 'done' when they're signed in already. */
|
|
|
|
/** 'code' when the learner must enter a one-time code next; 'done' when they're signed in already. */
|
|
|
|
start: async (c: Contact): Promise<'code' | 'done'> => {
|
|
|
|
start: async (c: Contact): Promise<'code' | 'done'> => {
|
|
|
|
const who = c.phone ? { phone_number: c.phone } : { email: c.email };
|
|
|
|
const who = c.phone ? { phone_number: c.phone } : { email: c.email };
|
|
|
|
const exists = await this.request<{ email_exist: boolean; phone_number_exist: boolean }>('POST', '/user/checkPhoneEmailExist', who, false);
|
|
|
|
const exists = await this.request<{ email_exist: boolean; phone_number_exist: boolean }>('POST', '/user/checkPhoneEmailExist', who, false, true);
|
|
|
|
const known = c.phone ? exists.phone_number_exist : exists.email_exist;
|
|
|
|
const known = c.phone ? exists.phone_number_exist : exists.email_exist;
|
|
|
|
if (c.email && known) { await this.login({ email: c.email, password: c.password }); return 'done'; }
|
|
|
|
if (c.email && known) { await this.login({ email: c.email, password: c.password }); return 'done'; }
|
|
|
|
if (c.phone && known) { await this.request('POST', '/user/resend-otp', who, false); return 'code'; }
|
|
|
|
if (c.phone && known) { await this.request('POST', '/user/resend-otp', who, false); return 'code'; }
|
|
|
|
@ -197,7 +223,7 @@ export class ApiDataSource implements DataSource {
|
|
|
|
},
|
|
|
|
},
|
|
|
|
verify: async (c: Contact, code: string): Promise<void> => {
|
|
|
|
verify: async (c: Contact, code: string): Promise<void> => {
|
|
|
|
const who = c.phone ? { phone_number: c.phone } : { email: c.email };
|
|
|
|
const who = c.phone ? { phone_number: c.phone } : { email: c.email };
|
|
|
|
const exists = await this.request<{ email_exist: boolean; phone_number_exist: boolean }>('POST', '/user/checkPhoneEmailExist', who, false);
|
|
|
|
const exists = await this.request<{ email_exist: boolean; phone_number_exist: boolean }>('POST', '/user/checkPhoneEmailExist', who, false, true);
|
|
|
|
if (c.phone && exists.phone_number_exist) { await this.login({ phone_number: c.phone, otp_code: code }); return; }
|
|
|
|
if (c.phone && exists.phone_number_exist) { await this.login({ phone_number: c.phone, otp_code: code }); return; }
|
|
|
|
const t = await this.request<{ access_token: string; refresh_token: string; user_id: number }>('POST', '/user/verify-otp', { ...who, otp: code }, false);
|
|
|
|
const t = await this.request<{ access_token: string; refresh_token: string; user_id: number }>('POST', '/user/verify-otp', { ...who, otp: code }, false);
|
|
|
|
this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id });
|
|
|
|
this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id });
|
|
|
|
@ -213,7 +239,7 @@ export class ApiDataSource implements DataSource {
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
private async login(body: Record<string, unknown>) {
|
|
|
|
private async login(body: Record<string, unknown>) {
|
|
|
|
const t = await this.request<{ access_token: string; refresh_token: string; user_id: number }>('POST', '/auth/customer-login', body, false);
|
|
|
|
const t = await this.request<{ access_token: string; refresh_token: string; user_id: number }>('POST', '/auth/customer-login', body, false, !body.otp_code); // a code is single-use: no retry
|
|
|
|
this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id });
|
|
|
|
this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id });
|
|
|
|
this.refreshAll();
|
|
|
|
this.refreshAll();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
@ -232,16 +258,16 @@ export class ApiDataSource implements DataSource {
|
|
|
|
|
|
|
|
|
|
|
|
private async loadCourses(): Promise<Course[]> {
|
|
|
|
private async loadCourses(): Promise<Course[]> {
|
|
|
|
const page = await this.request<{ courses: RawCourse[]; total_count: number }>('GET', '/catalog/courses?limit=100', undefined, false);
|
|
|
|
const page = await this.request<{ courses: RawCourse[]; total_count: number }>('GET', '/catalog/courses?limit=100', undefined, false);
|
|
|
|
const outlines = await Promise.all(page.courses.map((c) => this.request<RawOutline>('GET', `/catalog/courses/${c.id}`, undefined, false).catch(() => null)));
|
|
|
|
const outlines = await mapLimit(page.courses, PARALLEL, (c) => this.request<RawOutline>('GET', `/catalog/courses/${c.id}`, undefined, false).catch(() => null));
|
|
|
|
const courses = outlines.filter((o): o is RawOutline => !!o).map((o) => mapOutline(o, this.base));
|
|
|
|
const courses = outlines.filter((o): o is RawOutline => !!o).map((o) => mapOutline(o, this.base));
|
|
|
|
if (this.tokens) await Promise.all(courses.flatMap((c) => c.chapters.map(async (ch) => {
|
|
|
|
if (this.tokens) await mapLimit(courses.flatMap((c) => c.chapters), PARALLEL, async (ch) => {
|
|
|
|
// Signed in: lesson video URLs (and sort order) only come from the authenticated lesson list.
|
|
|
|
// Signed in: lesson video URLs (and sort order) only come from the authenticated lesson list.
|
|
|
|
const r = await this.request<{ lessons: RawLesson[] }>('GET', `/chapters/${ids.num(ch.id)}/lessons?limit=200`).catch(() => null);
|
|
|
|
const r = await this.request<{ lessons: RawLesson[] }>('GET', `/chapters/${ids.num(ch.id)}/lessons?limit=200`).catch(() => null);
|
|
|
|
for (const l of r?.lessons ?? []) {
|
|
|
|
for (const l of r?.lessons ?? []) {
|
|
|
|
const m = ch.lessons.find((x) => x.id === ids.lesson(l.id));
|
|
|
|
const m = ch.lessons.find((x) => x.id === ids.lesson(l.id));
|
|
|
|
if (m) { m.videoAssetId = l.video_url || m.videoAssetId; if (l.sort_order != null) m.sortOrder = l.sort_order; }
|
|
|
|
if (m) { m.videoAssetId = l.video_url || m.videoAssetId; if (l.sort_order != null) m.sortOrder = l.sort_order; }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})));
|
|
|
|
});
|
|
|
|
return courses;
|
|
|
|
return courses;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|