// ApiDataSource: the DataSource over the Rezina Go API. Live spec: /swagger/doc.json. // // What is wired, and how sure we are of it: // verified against the live API public catalog + course outline (GET /catalog/courses, /catalog/courses/{id}) // built from the spec, untested sign-in, profile, progress summary, lesson video URLs, video heartbeat, // notifications, issue reports (all need a signed-in learner) // not on the API yet per-course prices/purchases, translations, categories, teacher, lesson // durations, prerequisites; quizzes are left out until their question shape is known // Screens never see the API's shapes: everything is mapped onto the domain types in ./index. import type { Campaign, Category, Course, DataSource, InboxItem, Issue, IssueStatus, IssueType, LessonProgress, Locale, Settings, Student, Unsub, UserStatus, Viewer, AuditEntry, } from './index'; // ---------------------------------------------------------------- API shapes (the subset we read) type Tier = 'FREE' | 'PREMIUM'; export interface RawCourse { id: number; name: string; description: string; thumbnail: string; access_tier: Tier; chapter_count: number; lesson_count: number; quiz_count: number } export interface RawLesson { id: number; title: string; description: string; thumbnail: string; access_tier: Tier; video_url?: string; sort_order?: number } export interface RawChapter { id: number; name: string; description: string; lessons: RawLesson[]; quizzes: { id: number; title: string; question_count: number }[] } export interface RawOutline extends RawCourse { chapters: RawChapter[] } interface RawAccess { is_accessible: boolean; is_completed: boolean; progress_percent: number } interface RawSummary { courses: { id: number; access: RawAccess; chapters: { id: number; lessons: { id: number; access: RawAccess }[] }[] }[] } interface RawProfile { id: number; first_name?: string; last_name?: string; nick_name?: string; email?: string; phone_number?: string; country?: string; region?: string; preferred_language?: string; status?: string; created_at?: string; updated_at?: string; last_login?: string } interface RawIssue { id: number; issue_type: string; subject: string; description: string; status: string; created_at: string; updated_at: string } interface RawNotification { id: string; is_read: boolean; timestamp: string; type: string; payload?: { headline?: string; message?: string }; metadata?: Record } interface Tokens { access: string; refresh: string; userId: number } // ---------------------------------------------------------------- ids and mapping (pure: covered by api.check.ts) /** Domain ids are strings with a kind prefix, so ids from different API tables can't collide in one record. */ export const ids = { course: (n: number) => `c${n}`, chapter: (n: number) => `ch${n}`, lesson: (n: number) => `l${n}`, quiz: (n: number) => `q${n}`, num: (id: string) => Number(id.replace(/^[a-z]+/, '')), }; /** URL slug: readable name plus the API id, so renaming a course never breaks a shared link (the id wins). */ export function slugify(name: string, id: number): string { const s = name.toLowerCase().normalize('NFKD').replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, ''); return s ? `${s}-${id}` : String(id); } export const absolute = (base: string, url: string | null | undefined) => !url ? null : /^https?:\/\//.test(url) ? url : base.replace(/\/+$/, '') + (url.startsWith('/') ? url : `/${url}`); /** Course outline → domain Course. Text is English-only until the API carries translations. */ export function mapOutline(o: RawOutline, base: string): Course { return { id: ids.course(o.id), slug: slugify(o.name, o.id), categoryId: '', instructorName: '', instructionLocale: 'en', coverAssetId: absolute(base, o.thumbnail), status: 'PUBLISHED', isFeatured: false, isTest: false, sequentialLessons: false, prerequisiteCourseId: null, publishedAt: null, createdAt: '', updatedAt: '', translations: { en: { title: o.name, description: o.description } }, prices: {}, // the API sells subscription plans, not courses: no per-course price yet chapters: o.chapters.map((ch, i) => ({ id: ids.chapter(ch.id), sortOrder: i + 1, translations: { en: { title: ch.name, summary: ch.description || undefined } }, lessons: ch.lessons.map((l, j) => ({ id: ids.lesson(l.id), sortOrder: l.sort_order ?? j + 1, // a FREE lesson (or a lesson in a FREE course) plays for anyone, like our preview lessons isPreview: o.access_tier === 'FREE' || l.access_tier === 'FREE', isPublished: true, durationSec: 0, // not on the API yet videoAssetId: l.video_url || null, videoStatus: 'READY' as const, translations: { en: { title: l.title, description: l.description || undefined } }, })), })), assessments: [], // chapter quizzes exist on the API; their question shape isn't mapped yet }; } const ISSUE_TYPES: IssueType[] = ['BUG', 'PAYMENT', 'VIDEO', 'ACCOUNT', 'CONTENT', 'OTHER']; const ISSUE_STATUSES: IssueStatus[] = ['OPEN', 'IN_PROGRESS', 'RESOLVED', 'CLOSED']; const USER_STATUSES: UserStatus[] = ['PENDING', 'ACTIVE', 'DEACTIVATED']; const LOCALES: Locale[] = ['am', 'en', 'om', 'ti']; const upper = (s: string | undefined) => (s ?? '').toUpperCase().replace(/[\s-]+/g, '_'); export function mapIssue(i: RawIssue): Issue { const type = upper(i.issue_type) as IssueType, status = upper(i.status) as IssueStatus; return { id: String(i.id), type: ISSUE_TYPES.includes(type) ? type : 'OTHER', subject: i.subject, description: i.description, status: ISSUE_STATUSES.includes(status) ? status : 'OPEN', createdAt: i.created_at, updatedAt: i.updated_at, }; } export function mapNotification(n: RawNotification): InboxItem { const link = typeof n.metadata?.link === 'string' ? n.metadata.link : null; return { id: n.id, type: upper(n.type), title: n.payload?.headline ?? '', body: n.payload?.message ?? '', link, readAt: n.is_read ? n.timestamp : null, createdAt: n.timestamp }; } /** Profile + progress summary + issues → the domain Student the screens read. */ export function mapStudent(p: RawProfile, summary: RawSummary | null, issues: RawIssue[], local: Record, now: string): Student { const name = [p.first_name, p.last_name].filter(Boolean).join(' ') || p.nick_name || p.phone_number || p.email || ''; const status = upper(p.status) === 'SUSPENDED' ? 'DEACTIVATED' : (upper(p.status) as UserStatus); const locale = (p.preferred_language ?? '').slice(0, 2) as Locale; const enrollments: Student['enrollments'] = {}; const progress: Record = { ...local }; for (const c of summary?.courses ?? []) { const courseId = ids.course(c.id); if (c.access?.is_accessible) enrollments[courseId] = { courseId, source: 'FREE', createdAt: p.created_at ?? now }; for (const ch of c.chapters ?? []) for (const l of ch.lessons ?? []) { if (!l.access?.is_completed) continue; const id = ids.lesson(l.id); const seen = progress[id]; progress[id] = { positionSec: seen?.positionSec ?? 0, maxPositionSec: seen?.maxPositionSec ?? 0, updatedAt: seen?.updatedAt ?? now, courseId, completedAt: seen?.completedAt ?? now }; } } return { id: String(p.id), name, phone: p.phone_number || undefined, email: p.email || undefined, country: p.country ?? '', city: p.region ?? '', locale: LOCALES.includes(locale) ? locale : 'en', status: USER_STATUSES.includes(status) ? status : 'ACTIVE', createdAt: p.created_at ?? now, updatedAt: p.updated_at ?? now, lastActiveAt: p.last_login, enrollments, orders: {}, progress, issues: Object.fromEntries(issues.map((i) => [String(i.id), mapIssue(i)])), assessments: {}, watchSec: {}, }; } // ---------------------------------------------------------------- HTTP export class ApiError extends Error { readonly status: number; readonly code: string; constructor(status: number, message: string) { super(message); this.status = status; this.code = 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 TOKENS_KEY = 'lms.api.tokens'; 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 */ } }; // ---------------------------------------------------------------- data source type Contact = { phone?: string; email?: string; password?: string }; export class ApiDataSource implements DataSource { readonly kind = 'api' as const; private tokens: Tokens | null = readTokens(); private refreshing: Promise | null = null; private courseCbs = new Set<(c: Course[]) => void>(); private studentCbs = new Map<(s: Student | null) => void, string>(); private inboxCbs = new Set<(i: InboxItem[]) => void>(); /** Positions reported this session; the API only tells us completion, so resume points live here until reload. */ private localProgress: Record = {}; readonly base: string; constructor(base: string) { this.base = base; } // ---- transport private async request(method: string, path: string, body?: unknown, auth = true): Promise { const send = () => fetch(`${this.base.replace(/\/+$/, '')}/api/v1${path}`, { method, headers: { 'content-type': 'application/json', ...(auth && this.tokens ? { authorization: `Bearer ${this.tokens.access}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body), }); let res = await send(); if (res.status === 401 && auth && this.tokens && (await this.refresh())) res = await send(); const json = await res.json().catch(() => null); // Some endpoints answer `success: false` on a 200, so the HTTP status is what counts. if (!res.ok) throw new ApiError(res.status, json?.message || json?.error || res.statusText); return (json && 'data' in json ? json.data : json) as T; } private refresh(): Promise { if (!this.tokens) return Promise.resolve(false); this.refreshing ??= fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/refresh`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ access_token: this.tokens.access, refresh_token: this.tokens.refresh }), }).then(async (r) => { const j = await r.json().catch(() => null); if (!r.ok || !j?.data?.access_token) { this.setTokens(null); return false; } this.setTokens({ access: j.data.access_token, refresh: j.data.refresh_token, userId: j.data.user_id }); return true; }, () => false).finally(() => { this.refreshing = null; }); return this.refreshing; } private setTokens(t: Tokens | null) { this.tokens = t; writeTokens(t); } // ---- auth (the screens reach this through `ds.auth` when it exists; the demo has none) /** * Phone: existing learners get a login code (resend-otp → customer-login with otp_code); new ones get a register * code (sendRegisterCode → verify-otp). Email: password login; an unknown email registers and confirms by code. * The exact endpoint pairing is our reading of the spec and still needs confirming with the backend. */ readonly auth = { signedIn: () => !!this.tokens, /** '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'> => { 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 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.phone && known) { await this.request('POST', '/user/resend-otp', who, false); return 'code'; } if (c.phone) await this.request('POST', '/user/sendRegisterCode', who, false); else await this.request('POST', '/user/register', { email: c.email, password: c.password }, false); return 'code'; }, verify: async (c: Contact, code: string): Promise => { 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); 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); this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id }); this.refreshAll(); }, signOut: async () => { const t = this.tokens; this.setTokens(null); if (t) await this.request('POST', '/auth/logout', { refresh_token: t.refresh }, false).catch(() => { /* already gone server-side */ }); this.localProgress = {}; this.refreshAll(); }, }; private async login(body: Record) { const t = await this.request<{ access_token: string; refresh_token: string; user_id: number }>('POST', '/auth/customer-login', body, false); this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id }); this.refreshAll(); } // ---- reads async viewer(): Promise { const none: Viewer = { id: null, name: '', avatarUrl: '', isOwner: false, canEdit: false }; if (!this.tokens) return none; try { const p = await this.request('GET', '/user/user-profile'); return { id: String(p.id), name: [p.first_name, p.last_name].filter(Boolean).join(' '), avatarUrl: '', isOwner: false, canEdit: true }; } catch { return none; } } async names() { return {}; } private async loadCourses(): Promise { 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('GET', `/catalog/courses/${c.id}`, undefined, false).catch(() => null))); 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) => { // 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); for (const l of r?.lessons ?? []) { 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; } } }))); return courses; } private async loadStudent(): Promise { if (!this.tokens) return null; const [p, summary, issues] = await Promise.all([ this.request('GET', '/user/user-profile'), this.request('GET', '/progress-summary').catch(() => null), this.request<{ issues: RawIssue[] }>('GET', '/issues/me?limit=100').catch(() => ({ issues: [] })), ]); return mapStudent(p, summary, issues.issues ?? [], this.localProgress, new Date().toISOString()); } private async loadInbox(): Promise { if (!this.tokens) return []; const r = await this.request<{ notifications: RawNotification[] }>('GET', '/notifications?limit=100'); return (r.notifications ?? []).map(mapNotification); } /** Re-runs every watcher, e.g. after sign-in, sign-out or a write the server changes state for. */ refreshAll() { if (this.courseCbs.size) this.loadCourses().then((c) => this.courseCbs.forEach((cb) => cb(c)), (e) => console.warn('courses', e)); this.refreshStudent(); if (this.inboxCbs.size) this.loadInbox().then((i) => this.inboxCbs.forEach((cb) => cb(i)), () => this.inboxCbs.forEach((cb) => cb([]))); } private refreshStudent() { if (!this.studentCbs.size) return; this.loadStudent().then((s) => this.studentCbs.forEach((_, cb) => cb(s)), (e) => { console.warn('student', e); this.studentCbs.forEach((_, cb) => cb(null)); }); } watchCourses(cb: (c: Course[]) => void): Unsub { this.courseCbs.add(cb); this.loadCourses().then((c) => { if (this.courseCbs.has(cb)) cb(c); }, (e) => { console.warn('courses', e); if (this.courseCbs.has(cb)) cb([]); }); return () => { this.courseCbs.delete(cb); }; } watchStudent(id: string, cb: (s: Student | null) => void): Unsub { this.studentCbs.set(cb, id); this.loadStudent().then((s) => { if (this.studentCbs.has(cb)) cb(s); }, () => { if (this.studentCbs.has(cb)) cb(null); }); return () => { this.studentCbs.delete(cb); }; } watchInbox(_studentId: string, cb: (i: InboxItem[]) => void): Unsub { this.inboxCbs.add(cb); this.loadInbox().then((i) => { if (this.inboxCbs.has(cb)) cb(i); }, () => { if (this.inboxCbs.has(cb)) cb([]); }); return () => { this.inboxCbs.delete(cb); }; } // Not on the API: categories, app settings (the screens fall back to their defaults) and the admin collections. watchCategories(cb: (c: Category[]) => void): Unsub { cb([]); return () => {}; } watchSettings(cb: (s: Settings | null) => void): Unsub { cb(null); return () => {}; } watchStudents(cb: (s: Student[]) => void): Unsub { cb([]); return () => {}; } watchCampaigns(cb: (c: Campaign[]) => void): Unsub { cb([]); return () => {}; } watchAudit(cb: (a: AuditEntry[]) => void): Unsub { cb([]); return () => {}; } // ---- writes /** Profile setup after a first sign-in. */ async saveStudent(s: Student) { const [first_name, ...rest] = s.name.trim().split(/\s+/); await this.request('PUT', '/user', { first_name, last_name: rest.join(' '), country: s.country, region: s.city, preferred_language: s.locale }); this.refreshStudent(); } /** * The screens write partial student records; each key maps to the endpoint that owns it. * Keys the API has no home for (watch time, notification prefs, last active) stay local. */ async patchStudent(_id: string, patch: Record) { const jobs: Promise[] = []; if (patch.orders) throw notConnected('Buying a course'); const progress = patch.progress as Record | undefined; for (const [lessonId, p] of Object.entries(progress ?? {})) { this.localProgress[lessonId] = { ...this.localProgress[lessonId], ...p }; jobs.push(this.request('POST', '/videos/engagement/heartbeat', { content_id: ids.num(lessonId), content_kind: 'lms_lesson', position_sec: Math.floor(p.positionSec), // durations aren't on the API, so the furthest point reached stands in for the length duration_sec: Math.max(1, Math.floor(p.maxPositionSec ?? p.positionSec)), ended: !!p.completedAt, })); } for (const i of Object.values((patch.issues ?? {}) as Record>)) { if (!i.subject) continue; // status changes are the support team's, not the learner's jobs.push(this.request('POST', '/issues', { subject: i.subject, description: i.description ?? '', issue_type: (i.type ?? 'OTHER').toLowerCase() })); } const profile: Record = {}; if (typeof patch.locale === 'string') profile.preferred_language = patch.locale; if (typeof patch.name === 'string') { const [f, ...r] = patch.name.trim().split(/\s+/); profile.first_name = f; profile.last_name = r.join(' '); } if (typeof patch.country === 'string') profile.country = patch.country; if (typeof patch.city === 'string') profile.region = patch.city; if (Object.keys(profile).length) jobs.push(this.request('PUT', '/user', profile)); await Promise.all(jobs); this.refreshStudent(); } async patchInbox(_studentId: string, id: string, patch: Partial) { if (patch.readAt !== undefined) await this.request('PATCH', `/notifications/${id}/${patch.readAt ? 'read' : 'unread'}`); if (this.inboxCbs.size) this.loadInbox().then((i) => this.inboxCbs.forEach((cb) => cb(i)), () => {}); } /** The server writes its own notifications (payment, issue updates); the client never adds to a learner's inbox. */ async addInbox() {} async saveCourse() { throw notConnected('Course editing'); } async deleteCourse() { throw notConnected('Course editing'); } async saveCategory() { throw notConnected('Categories'); } async deleteCategory() { throw notConnected('Categories'); } async saveSettings() { throw notConnected('Settings'); } async saveCampaign() { throw notConnected('Campaigns'); } async addAudit() {} async uploads() { return null; } assetUrl(id: string) { return absolute(this.base, id) ?? ''; } async download() { return false; } async feedback() { return false; } async feedbackAvailable() { return false; } }