diff --git a/package.json b/package.json index c6423dcc..1adf20d1 100644 --- a/package.json +++ b/package.json @@ -109,5 +109,12 @@ }, "overrides": { "glob": "$glob" + }, + "allowScripts": { + "@parcel/watcher": false, + "esbuild": false, + "onnxruntime-node": false, + "protobufjs": false, + "sharp": false } } diff --git a/src/plugins/built-in/assessmentsAverage/utils.ts b/src/plugins/built-in/assessmentsAverage/utils.ts index 5dc235fb..8ed226de 100644 --- a/src/plugins/built-in/assessmentsAverage/utils.ts +++ b/src/plugins/built-in/assessmentsAverage/utils.ts @@ -1,4 +1,4 @@ -import { getUserInfo } from "@/seqta/ui/AddBetterSEQTAElements.ts"; +import { getUserInfo } from "@/seqta/utils/userInfo"; import ReactFiber from "@/seqta/utils/ReactFiber.ts"; import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage"; import { getEngageAssessmentStudentId } from "@/seqta/utils/engageAssessmentStudent"; diff --git a/src/plugins/built-in/assessmentsOverview/api.ts b/src/plugins/built-in/assessmentsOverview/api.ts index f8af990d..0fe3187f 100644 --- a/src/plugins/built-in/assessmentsOverview/api.ts +++ b/src/plugins/built-in/assessmentsOverview/api.ts @@ -10,7 +10,7 @@ interface PrefItem { value: string; } -import { getUserInfo } from "@/seqta/ui/AddBetterSEQTAElements"; +import { getUserInfo } from "@/seqta/utils/userInfo"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { getMockAssessmentsData } from "@/seqta/ui/dev/hideSensitiveContent"; import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage"; diff --git a/src/plugins/built-in/globalSearch/src/indexing/api.ts b/src/plugins/built-in/globalSearch/src/indexing/api.ts index 470f6901..81d58a84 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/api.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/api.ts @@ -137,81 +137,6 @@ export function isSensitiveSeqtaPath(path: string): boolean { return SENSITIVE_PATH_PATTERNS.some((re) => re.test(normalized)); } -/* ------------------------------------------------------------------ */ -/* student / user identity */ -/* ------------------------------------------------------------------ */ - -interface SeqtaUserInfo { - id?: number; - personUUID?: string; - username?: string; - [key: string]: unknown; -} - -let cachedUserInfo: SeqtaUserInfo | null = null; -let inflightUserInfo: Promise | null = null; - -/** - * Resolves the current SEQTA user identity by re-using the same `login` - * handshake that the host page performs. This is the canonical way to - * discover the active student id and avoids the historical hard-coded - * `student: 69` placeholder that was incorrect on every real instance. - * - * Failures are intentionally NOT cached — a transient login glitch on the - * very first call must not poison the cache for the lifetime of the page, - * because every subsequent indexing pass that needs the student id (e.g. - * the assignments job) would skip silently. - */ -export async function getCurrentUserInfo(): Promise { - if (cachedUserInfo) return cachedUserInfo; - if (inflightUserInfo) return inflightUserInfo; - - inflightUserInfo = (async () => { - try { - const res = await fetch(`${location.origin}/seqta/student/login`, { - method: "POST", - credentials: "include", - headers: { "Content-Type": "application/json; charset=utf-8" }, - body: JSON.stringify({ - mode: "normal", - query: null, - redirect_url: location.origin, - }), - }); - if (!res.ok) return null; - const json = (await res.json()) as { payload?: SeqtaUserInfo }; - const payload = json?.payload ?? null; - if (payload && typeof payload === "object") { - cachedUserInfo = payload; - return payload; - } - return null; - } catch (e) { - console.warn( - "[Global Search API] Failed to resolve current user info:", - e, - ); - return null; - } finally { - inflightUserInfo = null; - } - })(); - - return inflightUserInfo; -} - -/** - * Best-effort lookup of the active student id. Returns `undefined` when the - * value cannot be discovered (jobs should fall back gracefully rather than - * fabricating an id). - */ -export async function getCurrentStudentId(): Promise { - const info = await getCurrentUserInfo(); - const id = info?.id; - if (typeof id === "number" && Number.isFinite(id)) return id; - return undefined; -} - /* ------------------------------------------------------------------ */ /* core fetch */ /* ------------------------------------------------------------------ */ diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/assignments.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/assignments.ts index 1ea0bb8d..574af2c5 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/assignments.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/assignments.ts @@ -2,6 +2,7 @@ import type { IndexItem, Job } from "../types"; import { verboseDebug } from '@/utils/verboseLog'; import { delay } from "@/seqta/utils/delay"; +import { getUserInfo } from "@/seqta/utils/userInfo"; const fetchJSON = async (url: string, body: any) => { const res = await fetch(`${location.origin}${url}`, { method: "POST", @@ -12,7 +13,7 @@ const fetchJSON = async (url: string, body: any) => { return res.json(); }; -const fetchUpcomingAssessments = async (student: number = 69) => { +const fetchUpcomingAssessments = async (student: number) => { try { const res = await fetchJSON("/seqta/student/assessment/list/upcoming?", { student, @@ -37,7 +38,7 @@ const fetchSubjects = async () => { } }; -const fetchPastAssessments = async (student: number = 69, subjects: any[]) => { +const fetchPastAssessments = async (student: number, subjects: any[]) => { const map: Record = {}; // Fetch past assessments for all subjects in parallel (like assessmentsOverview does) @@ -128,7 +129,7 @@ export const assignmentsJob: Job = { const existingItems = await ctx.getStoredItems("assignments"); const existingIds = new Set(existingItems.map((i) => i.id)); - const student = 69; // TODO: Get from context if available + const { id: student } = await getUserInfo(); verboseDebug("[Assignments job] Starting indexing - fetching all assessments (upcoming and past)..."); diff --git a/src/plugins/built-in/gradeAnalytics/AnalyticsBarChart.svelte b/src/plugins/built-in/gradeAnalytics/AnalyticsBarChart.svelte index 8f99cfbf..edaf2254 100644 --- a/src/plugins/built-in/gradeAnalytics/AnalyticsBarChart.svelte +++ b/src/plugins/built-in/gradeAnalytics/AnalyticsBarChart.svelte @@ -4,7 +4,7 @@ import { BarChart } from "layerchart"; import * as Chart from "./chart/index"; import { cubicInOut } from "svelte/easing"; - import { getUserInfo } from "@/seqta/ui/AddBetterSEQTAElements"; + import { getUserInfo } from "@/seqta/utils/userInfo"; import type { Assessment } from "./types"; import { getTimeRangeLabel, type CustomTimeRange, type TimeRange } from "./timeRange"; import { diff --git a/src/plugins/built-in/gradeAnalytics/api.test.ts b/src/plugins/built-in/gradeAnalytics/api.test.ts index 111f30df..a704f652 100644 --- a/src/plugins/built-in/gradeAnalytics/api.test.ts +++ b/src/plugins/built-in/gradeAnalytics/api.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, expect, it, jest } from "@jest/globals"; -jest.mock("@/seqta/ui/AddBetterSEQTAElements", () => ({ +jest.mock("@/seqta/utils/userInfo", () => ({ getUserInfo: async () => ({ id: 12 }), })); jest.mock("@/seqta/utils/listeners/SettingsState", () => ({ @@ -22,7 +22,9 @@ beforeEach(() => { value: { origin }, }); }); -afterEach(() => jest.restoreAllMocks()); +afterEach(() => { + jest.restoreAllMocks(); +}); it("removes cached custom rubric percentages when inference is disabled", async () => { jest.spyOn(globalThis, "fetch").mockImplementation(async (url) => diff --git a/src/plugins/built-in/gradeAnalytics/api.ts b/src/plugins/built-in/gradeAnalytics/api.ts index 8856ff3b..fde54fa9 100644 --- a/src/plugins/built-in/gradeAnalytics/api.ts +++ b/src/plugins/built-in/gradeAnalytics/api.ts @@ -1,4 +1,4 @@ -import { getUserInfo } from "@/seqta/ui/AddBetterSEQTAElements"; +import { getUserInfo } from "@/seqta/utils/userInfo"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { getMockGradeAnalyticsData } from "@/seqta/ui/dev/hideSensitiveContent"; import { resolveGradeFromAssessmentPayload } from "./gradeResolution"; diff --git a/src/plugins/built-in/notificationCollector/archive.ts b/src/plugins/built-in/notificationCollector/archive.ts index d3349184..b7fa0c9e 100644 --- a/src/plugins/built-in/notificationCollector/archive.ts +++ b/src/plugins/built-in/notificationCollector/archive.ts @@ -1,4 +1,4 @@ -import { getUserInfo } from "@/seqta/ui/AddBetterSEQTAElements"; +import { getUserInfo } from "@/seqta/utils/userInfo"; type RawNotification = Record; diff --git a/src/plugins/built-in/themes/theme-manager.cloud.test.ts b/src/plugins/built-in/themes/theme-manager.cloud.test.ts index 0c6fa7e8..324a0ab2 100644 --- a/src/plugins/built-in/themes/theme-manager.cloud.test.ts +++ b/src/plugins/built-in/themes/theme-manager.cloud.test.ts @@ -43,7 +43,9 @@ describe("cloud theme restoration", () => { jest.spyOn(console, "warn").mockImplementation(() => {}); }); - afterEach(() => jest.restoreAllMocks()); + afterEach(() => { + jest.restoreAllMocks(); + }); it.each(["themes", "custom-themes"])( "installs a missing %s catalog theme", diff --git a/src/plugins/built-in/timetableClassmates/identityBinding.ts b/src/plugins/built-in/timetableClassmates/identityBinding.ts index e2a0f372..1c116aa7 100644 --- a/src/plugins/built-in/timetableClassmates/identityBinding.ts +++ b/src/plugins/built-in/timetableClassmates/identityBinding.ts @@ -1,4 +1,4 @@ -import { resolveLoginPayload } from "./seqtaClient"; +import { tryGetUserInfo } from "@/seqta/utils/userInfo"; /** Must match `buildIdentityBindingCanonical` in betterseqta-accounts worker. */ export function buildIdentityBindingCanonical(input: { @@ -61,7 +61,7 @@ async function bindingFieldsFromSession( instanceHost: string, cloudUserId: string, ): Promise { - const login = await resolveLoginPayload(); + const login = await tryGetUserInfo(); const seqtaStudentId = login?.id ?? login?.student; const personUuidRaw = login?.personUUID; if ( diff --git a/src/plugins/built-in/timetableClassmates/index.ts b/src/plugins/built-in/timetableClassmates/index.ts index eae4a42b..ae47cb51 100644 --- a/src/plugins/built-in/timetableClassmates/index.ts +++ b/src/plugins/built-in/timetableClassmates/index.ts @@ -21,7 +21,7 @@ import { loadSession, } from "./rosterStore"; import { refreshPeopleCacheIfStale } from "./peopleCache"; -import { resolveStudentId } from "./seqtaClient"; +import { getStudentId } from "@/seqta/utils/userInfo"; import { peerCloudIdsForPaint } from "./accountsClient"; import { fetchSchoolYearEnrollmentSnapshot } from "./timetableYearSnapshot"; import { CLASSMATES_TIMETABLE_POLL_MS } from "./constants"; @@ -101,7 +101,7 @@ const timetableClassmatesPlugin: Plugin = { return; } - const selfId = await resolveStudentId(); + const selfId = await getStudentId(); if (selfId == null) return; const [roster, peopleCache, archived, ciMap, cloudIds] = await Promise.all([ diff --git a/src/plugins/built-in/timetableClassmates/rosterStore.ts b/src/plugins/built-in/timetableClassmates/rosterStore.ts index fdc96d6d..cf98d6a9 100644 --- a/src/plugins/built-in/timetableClassmates/rosterStore.ts +++ b/src/plugins/built-in/timetableClassmates/rosterStore.ts @@ -1,7 +1,7 @@ import localforage, { type LocalForage } from "localforage"; import { getInstanceHostname } from "@/seqta/utils/feedback/client"; import type { ArchivedMembers, ClassRosterIndex } from "./rosterMerge"; -import { resolveStudentId } from "./seqtaClient"; +import { getStudentId } from "@/seqta/utils/userInfo"; import { TIMETABLE_CLASSMATES_CONSENT_VERSION } from "./constants"; const ROSTER_KEY = "classRosterIndex"; @@ -39,7 +39,7 @@ const defaultSession = (): ClassmatesSession => ({ export async function resolveClassmatesScope(): Promise { const host = getInstanceHostname()?.toLowerCase(); - const studentId = await resolveStudentId(); + const studentId = await getStudentId(); if (!host || studentId == null) return null; return `${host}#${studentId}`; } diff --git a/src/plugins/built-in/timetableClassmates/seqtaClient.ts b/src/plugins/built-in/timetableClassmates/seqtaClient.ts index 80c8aae5..8b2edc52 100644 --- a/src/plugins/built-in/timetableClassmates/seqtaClient.ts +++ b/src/plugins/built-in/timetableClassmates/seqtaClient.ts @@ -1,12 +1,4 @@ -export type SeqtaLoginPayload = { - id?: number; - student?: number; - personUUID?: string; - type?: string; - userDesc?: string; -}; - -let cachedLogin: SeqtaLoginPayload | null = null; +import { getStudentId, tryGetUserInfo } from "@/seqta/utils/userInfo"; export async function postSeqtaJson( path: string, @@ -26,30 +18,8 @@ export async function postSeqtaJson( return (await res.json()) as T; } -export async function resolveLoginPayload(): Promise { - if (cachedLogin?.id != null || cachedLogin?.student != null) return cachedLogin; - try { - const json = await postSeqtaJson<{ payload?: SeqtaLoginPayload }>( - "/seqta/student/login", - { mode: "normal", query: null, redirect_url: location.href }, - ); - const payload = json?.payload; - if (!payload) return undefined; - cachedLogin = payload; - return payload; - } catch { - return undefined; - } -} - -export async function resolveStudentId(): Promise { - const payload = await resolveLoginPayload(); - const id = payload?.id ?? payload?.student; - return typeof id === "number" && Number.isFinite(id) ? id : undefined; -} - export async function resolvePersonUuid(): Promise { - const payload = await resolveLoginPayload(); + const payload = await tryGetUserInfo(); const uuid = payload?.personUUID; return typeof uuid === "string" && uuid.length > 0 ? uuid : undefined; } @@ -70,7 +40,7 @@ export async function fetchStudentTimetableItems( from: string, until: string, ): Promise { - const studentId = await resolveStudentId(); + const studentId = await getStudentId(); const body: Record = { from, until }; if (studentId != null) body.student = studentId; const data = await postSeqtaJson<{ payload?: { items?: TimetableApiItem[] } }>( diff --git a/src/plugins/built-in/timetableClassmates/syncOrchestrator.ts b/src/plugins/built-in/timetableClassmates/syncOrchestrator.ts index cd8f30da..4783d60b 100644 --- a/src/plugins/built-in/timetableClassmates/syncOrchestrator.ts +++ b/src/plugins/built-in/timetableClassmates/syncOrchestrator.ts @@ -32,7 +32,8 @@ import { heartbeatIdentityFields, optInIdentityDigest, } from "./identityBinding"; -import { resolvePersonUuid, resolveStudentId } from "./seqtaClient"; +import { resolvePersonUuid } from "./seqtaClient"; +import { getStudentId } from "@/seqta/utils/userInfo"; import { fetchSchoolYearEnrollmentSnapshot, fingerprintEnrollment, @@ -134,7 +135,7 @@ export async function revokeOptIn(): Promise<{ ok: boolean; error?: string }> { if (!res.ok) return res; } - const seqtaId = await resolveStudentId(); + const seqtaId = await getStudentId(); if (seqtaId != null) { const [index, archived] = await Promise.all([loadRosterIndex(), loadArchivedMembers()]); await Promise.all([ @@ -221,7 +222,7 @@ export async function runTimetableClassmatesSync( if (!instanceHost) return { ok: false, error: "Not on a SEQTA page" }; if (!cloudAuth.state.isLoggedIn) return { ok: false, error: "Cloud login required" }; - const seqtaId = await resolveStudentId(); + const seqtaId = await getStudentId(); const personUuid = await resolvePersonUuid(); if (seqtaId == null || !personUuid) return { ok: false, error: "SEQTA login required" }; diff --git a/src/seqta/ui/AddBetterSEQTAElements.ts b/src/seqta/ui/AddBetterSEQTAElements.ts index 0f8b85c3..b5f5c315 100644 --- a/src/seqta/ui/AddBetterSEQTAElements.ts +++ b/src/seqta/ui/AddBetterSEQTAElements.ts @@ -31,28 +31,7 @@ import { runSidebarDrillReturn, getSidebarDrillDepth, } from "@/seqta/ui/sidebar/sidebarDrillReturn"; - -let cachedUserInfo: any = null; -let userInfoFetchPromise: Promise | null = null; -let userInfoCacheListenersAttached = false; - -export function invalidateCachedUserInfo(): void { - cachedUserInfo = null; - userInfoFetchPromise = null; -} - -function attachUserInfoCacheInvalidation(): void { - if (userInfoCacheListenersAttached || typeof window === "undefined") return; - userInfoCacheListenersAttached = true; - - window.addEventListener("pageshow", (event) => { - if (event.persisted) { - invalidateCachedUserInfo(); - } - }); -} - -attachUserInfoCacheInvalidation(); +import { getUserInfo } from "@/seqta/utils/userInfo"; let lightDarkToggleStreak = 0; let sidebarAccessibilityObserver: MutationObserver | null = null; @@ -62,68 +41,6 @@ let sidebarAccessibilityListenersAttached = false; /** Marks menu rows that are off-screen in the drill stack (CSS blocks clicks). */ const BSPLUS_SIDEBAR_OFFSCREEN = "bsplus-sidebar-offscreen"; -export async function getUserInfo(options?: { validateSession?: boolean }) { - if (cachedUserInfo && !options?.validateSession) { - return cachedUserInfo; - } - - if (userInfoFetchPromise && !options?.validateSession) { - return userInfoFetchPromise; - } - - const fetchUserInfo = async () => { - try { - const response = await fetch(`${location.origin}/seqta/student/login`, { - method: "POST", - headers: { - "Content-Type": "application/json; charset=utf-8", - }, - body: JSON.stringify({ - mode: "normal", - query: null, - redirect_url: location.origin, - }), - }); - - if (!response.ok) { - throw new Error(`Failed to get user info: HTTP ${response.status}`); - } - - const payload = (await response.json()).payload; - - if ( - cachedUserInfo && - options?.validateSession && - payload?.id != null && - cachedUserInfo.id != null && - payload.id !== cachedUserInfo.id - ) { - console.warn( - "[BetterSEQTA+] Session user changed; invalidating cached user info", - ); - invalidateCachedUserInfo(); - } - - cachedUserInfo = payload; - return cachedUserInfo; - } catch (error) { - console.error("[BetterSEQTA+] Failed to get user info:", error); - throw error; - } finally { - if (!options?.validateSession) { - userInfoFetchPromise = null; - } - } - }; - - if (options?.validateSession) { - return fetchUserInfo(); - } - - userInfoFetchPromise = fetchUserInfo(); - return userInfoFetchPromise; -} - export async function AddBetterSEQTAElements() { if (isSeqtaEngageExperience()) { await waitForElm("#content"); diff --git a/src/seqta/utils/adaptiveThemeColour.ts b/src/seqta/utils/adaptiveThemeColour.ts index b5ab3872..125f63ff 100644 --- a/src/seqta/utils/adaptiveThemeColour.ts +++ b/src/seqta/utils/adaptiveThemeColour.ts @@ -1,4 +1,4 @@ -import { getUserInfo } from "@/seqta/ui/AddBetterSEQTAElements"; +import { getUserInfo } from "@/seqta/utils/userInfo"; /** * Parses the current page from window.location.hash. diff --git a/src/seqta/utils/calendarSync/remoteEvents.test.ts b/src/seqta/utils/calendarSync/remoteEvents.test.ts index 6b91ba6e..6ca7409d 100644 --- a/src/seqta/utils/calendarSync/remoteEvents.test.ts +++ b/src/seqta/utils/calendarSync/remoteEvents.test.ts @@ -4,7 +4,9 @@ import { listOutlookSyncedEvents, } from "./remoteEvents"; -afterEach(() => jest.restoreAllMocks()); +afterEach(() => { + jest.restoreAllMocks(); +}); it.each([ { provider: "google", body: "invalid JSON" }, diff --git a/src/seqta/utils/googleCalendar/fetchTimetable.test.ts b/src/seqta/utils/googleCalendar/fetchTimetable.test.ts index bde9eb3c..2e116874 100644 --- a/src/seqta/utils/googleCalendar/fetchTimetable.test.ts +++ b/src/seqta/utils/googleCalendar/fetchTimetable.test.ts @@ -53,7 +53,9 @@ describe("calendar source fetches", () => { }); }); - afterEach(() => jest.restoreAllMocks()); + afterEach(() => { + jest.restoreAllMocks(); + }); it("uses the same Engage child for timetable and assessment sync", async () => { document.body.classList.contains = () => true; diff --git a/src/seqta/utils/googleCalendar/fetchTimetable.ts b/src/seqta/utils/googleCalendar/fetchTimetable.ts index 596e4cb4..3eeeefa9 100644 --- a/src/seqta/utils/googleCalendar/fetchTimetable.ts +++ b/src/seqta/utils/googleCalendar/fetchTimetable.ts @@ -1,4 +1,5 @@ import { toISODate } from "@/seqta/utils/loaders/engageParentTimetable"; +import { getStudentId, tryGetUserInfo } from "@/seqta/utils/userInfo"; import type { CalendarSyncAssessment } from "./eventMapper"; import type { SyncDateRange } from "./syncDateRange"; import { isDateInRange, syncWindowRange } from "./syncDateRange"; @@ -71,29 +72,6 @@ function withSubjectColours( }); } -type SeqtaLoginPayload = { - id?: number; - student?: number; - type?: string; -}; - -let cachedLogin: SeqtaLoginPayload | null = null; - -async function resolveLoginPayload(): Promise { - if (cachedLogin?.id != null) return cachedLogin; - try { - const json = await postSeqtaJson<{ payload?: SeqtaLoginPayload }>( - "/seqta/student/login", - { mode: "normal", query: null, redirect_url: location.href }, - ); - const payload = json?.payload; - if (!payload) return undefined; - cachedLogin = payload; - return payload; - } catch { - return undefined; - } -} export async function resolveStudentId(): Promise { if (isEngageParentContext()) { @@ -104,13 +82,11 @@ export async function resolveStudentId(): Promise { const id = Array.isArray(data?.payload) ? Number(data.payload[0]?.id) : NaN; return Number.isFinite(id) && id > 0 ? id : undefined; } - const payload = await resolveLoginPayload(); - const id = payload?.id ?? payload?.student; - return typeof id === "number" && Number.isFinite(id) ? id : undefined; + return getStudentId(); } async function resolvePersonType(): Promise { - const payload = await resolveLoginPayload(); + const payload = await tryGetUserInfo(); const type = payload?.type?.trim().toLowerCase(); return type || "student"; } diff --git a/src/seqta/utils/listeners/SettingsState.master.test.ts b/src/seqta/utils/listeners/SettingsState.master.test.ts index 114716a9..c5ba53df 100644 --- a/src/seqta/utils/listeners/SettingsState.master.test.ts +++ b/src/seqta/utils/listeners/SettingsState.master.test.ts @@ -1,7 +1,9 @@ /** @jest-environment jsdom */ describe("master extension setting", () => { - afterEach(() => jest.useRealTimers()); + afterEach(() => { + jest.useRealTimers(); + }); it.each([false, true])("persists %s and queued preferences before reloading SEQTA tabs", async (enabled) => { jest.useFakeTimers(); diff --git a/src/seqta/utils/loaders/LoadHomePage.ts b/src/seqta/utils/loaders/LoadHomePage.ts index ed9ba5ec..2168dd85 100644 --- a/src/seqta/utils/loaders/LoadHomePage.ts +++ b/src/seqta/utils/loaders/LoadHomePage.ts @@ -13,6 +13,7 @@ import { CreateElement } from "@/seqta/utils/createEnable/CreateElement"; import { FilterUpcomingAssessments } from "@/seqta/utils/FilterUpcomingAssessments"; import { setupFixedTooltips } from "@/seqta/utils/fixedTooltip"; import { verboseInfo } from "@/utils/verboseLog"; +import { getUserInfo } from "@/seqta/utils/userInfo"; import { activeSubjectsFromLearnPayload, activeSubjectForAssessment, @@ -225,15 +226,13 @@ export function registerHomeUpcomingSettingsListeners() { async function GetUpcomingAssessments() { try { - return fetch(`${location.origin}/seqta/student/assessment/list/upcoming?`, { + const { id: student } = await getUserInfo(); + const response = await fetch(`${location.origin}/seqta/student/assessment/list/upcoming?`, { method: "POST", - headers: { - "Content-Type": "application/json; charset=utf-8", - }, - body: JSON.stringify({ student: 69 }), - }) - .then((result) => result.json()) - .then((response) => response.payload); + headers: { "Content-Type": "application/json; charset=utf-8" }, + body: JSON.stringify({ student }), + }); + return (await response.json()).payload; } catch (error) { console.error("[BetterSEQTA+] Failed to get upcoming assessments:", error); return []; @@ -313,10 +312,11 @@ function startOfDay(date: Date): Date { } async function callHomeTimetable(date: string, change?: any) { + const { id: student } = await getUserInfo(); const response = await fetch(`${location.origin}/seqta/student/load/timetable?`, { method: "POST", headers: { "Content-Type": "application/json; charset=utf-8" }, - body: JSON.stringify({ from: date, until: date, student: 69 }), + body: JSON.stringify({ from: date, until: date, student }), }); const serverResponse = await response.json(); @@ -601,6 +601,7 @@ function applyHomeUpcomingLimits(assessments: any[], activeSubjects: any[]) { } async function CreateUpcomingSection(assessments: any, activeSubjects: any) { + const { id: student } = await getUserInfo(); const upcomingitemcontainer = document.querySelector("#upcoming-items"); const upcomingDates = {}; const Today = new Date(); @@ -679,6 +680,7 @@ async function CreateUpcomingSection(assessments: any, activeSubjects: any) { const assessmentDate = createAssessmentDateDiv( date, upcomingDates[date as keyof typeof upcomingDates], + student, specialcase, ); @@ -702,7 +704,7 @@ async function CreateUpcomingSection(assessments: any, activeSubjects: any) { } } -function createAssessmentDateDiv(date: string, value: any, datecase?: any) { +function createAssessmentDateDiv(date: string, value: any, student: number, datecase?: any) { const options = { weekday: "long" as "long", month: "long" as "long", @@ -767,7 +769,7 @@ function createAssessmentDateDiv(date: string, value: any, datecase?: any) { body: JSON.stringify({ assessment: element.id, metaclass: element.metaclassID, - student: 69, + student, }), }) .then((result) => result.json()) @@ -813,13 +815,13 @@ function CheckSpecialDay(date1: Date, date2: Date) { async function GetLessonColours() { try { - return fetch(`${location.origin}/seqta/student/load/prefs?`, { + const { id: user } = await getUserInfo(); + const response = await fetch(`${location.origin}/seqta/student/load/prefs?`, { method: "POST", headers: { "Content-Type": "application/json; charset=utf-8" }, - body: JSON.stringify({ request: "userPrefs", asArray: true, user: 69 }), - }) - .then((result) => result.json()) - .then((response) => response.payload); + body: JSON.stringify({ request: "userPrefs", asArray: true, user }), + }); + return (await response.json()).payload; } catch (error) { console.error("[BetterSEQTA+] Failed to get lesson colours:", error); return []; diff --git a/src/seqta/utils/userInfo.ts b/src/seqta/utils/userInfo.ts new file mode 100644 index 00000000..d9cea059 --- /dev/null +++ b/src/seqta/utils/userInfo.ts @@ -0,0 +1,93 @@ +let cachedUserInfo: any = null; +let userInfoFetchPromise: Promise | null = null; + +function invalidateCachedUserInfo(): void { + cachedUserInfo = null; + userInfoFetchPromise = null; +} + +if (typeof window !== "undefined") { + window.addEventListener("pageshow", (event) => { + if (event.persisted) invalidateCachedUserInfo(); + }); +} + +export async function getUserInfo(options?: { validateSession?: boolean }) { + if (cachedUserInfo && !options?.validateSession) { + return cachedUserInfo; + } + + if (userInfoFetchPromise && !options?.validateSession) { + return userInfoFetchPromise; + } + + const fetchUserInfo = async () => { + try { + const response = await fetch(`${location.origin}/seqta/student/login`, { + method: "POST", + headers: { + "Content-Type": "application/json; charset=utf-8", + }, + body: JSON.stringify({ + mode: "normal", + query: null, + redirect_url: location.origin, + }), + }); + + if (!response.ok) { + throw new Error(`Failed to get user info: HTTP ${response.status}`); + } + + const payload = (await response.json()).payload; + + if ( + cachedUserInfo && + options?.validateSession && + payload?.id != null && + cachedUserInfo.id != null && + payload.id !== cachedUserInfo.id + ) { + console.warn( + "[BetterSEQTA+] Session user changed; invalidating cached user info", + ); + invalidateCachedUserInfo(); + } + + cachedUserInfo = payload; + return cachedUserInfo; + } catch (error) { + console.error("[BetterSEQTA+] Failed to get user info:", error); + throw error; + } finally { + if (!options?.validateSession) { + userInfoFetchPromise = null; + } + } + }; + + if (options?.validateSession) { + return fetchUserInfo(); + } + + userInfoFetchPromise = fetchUserInfo(); + return userInfoFetchPromise; +} + +export type SeqtaUserInfo = { + id?: number; + student?: number; + personUUID?: string; + type?: string; + userDesc?: string; +}; + +export async function tryGetUserInfo(): Promise { + return (await getUserInfo().catch(() => undefined)) ?? undefined; +} + +export async function getStudentId(): Promise { + const info = await tryGetUserInfo(); + const id = info?.id ?? info?.student; + return typeof id === "number" && Number.isFinite(id) ? id : undefined; +}