mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
refactor: use real student id, share user lookup and deny install scripts
This commit is contained in:
23 files changed
+161
-259
No files matched your search
@@ -109,5 +109,12 @@
|
||||
},
|
||||
"overrides": {
|
||||
"glob": "$glob"
|
||||
},
|
||||
"allowScripts": {
|
||||
"@parcel/watcher": false,
|
||||
"esbuild": false,
|
||||
"onnxruntime-node": false,
|
||||
"protobufjs": false,
|
||||
"sharp": false
|
||||
}
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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<SeqtaUserInfo | null> | 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<SeqtaUserInfo | null> {
|
||||
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<number | undefined> {
|
||||
const info = await getCurrentUserInfo();
|
||||
const id = info?.id;
|
||||
if (typeof id === "number" && Number.isFinite(id)) return id;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* core fetch */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
@@ -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<number, any> = {};
|
||||
|
||||
// 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)...");
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getUserInfo } from "@/seqta/ui/AddBetterSEQTAElements";
|
||||
import { getUserInfo } from "@/seqta/utils/userInfo";
|
||||
|
||||
type RawNotification = Record<string, unknown>;
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<TimetableClassmatesBindingFields | null> {
|
||||
const login = await resolveLoginPayload();
|
||||
const login = await tryGetUserInfo();
|
||||
const seqtaStudentId = login?.id ?? login?.student;
|
||||
const personUuidRaw = login?.personUUID;
|
||||
if (
|
||||
|
||||
@@ -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<typeof timetableClassmatesSettings> = {
|
||||
return;
|
||||
}
|
||||
|
||||
const selfId = await resolveStudentId();
|
||||
const selfId = await getStudentId();
|
||||
if (selfId == null) return;
|
||||
|
||||
const [roster, peopleCache, archived, ciMap, cloudIds] = await Promise.all([
|
||||
|
||||
@@ -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<string | null> {
|
||||
const host = getInstanceHostname()?.toLowerCase();
|
||||
const studentId = await resolveStudentId();
|
||||
const studentId = await getStudentId();
|
||||
if (!host || studentId == null) return null;
|
||||
return `${host}#${studentId}`;
|
||||
}
|
||||
|
||||
@@ -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<T>(
|
||||
path: string,
|
||||
@@ -26,30 +18,8 @@ export async function postSeqtaJson<T>(
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
export async function resolveLoginPayload(): Promise<SeqtaLoginPayload | undefined> {
|
||||
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<number | undefined> {
|
||||
const payload = await resolveLoginPayload();
|
||||
const id = payload?.id ?? payload?.student;
|
||||
return typeof id === "number" && Number.isFinite(id) ? id : undefined;
|
||||
}
|
||||
|
||||
export async function resolvePersonUuid(): Promise<string | undefined> {
|
||||
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<TimetableApiItem[]> {
|
||||
const studentId = await resolveStudentId();
|
||||
const studentId = await getStudentId();
|
||||
const body: Record<string, unknown> = { from, until };
|
||||
if (studentId != null) body.student = studentId;
|
||||
const data = await postSeqtaJson<{ payload?: { items?: TimetableApiItem[] } }>(
|
||||
|
||||
@@ -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" };
|
||||
|
||||
|
||||
@@ -31,28 +31,7 @@ import {
|
||||
runSidebarDrillReturn,
|
||||
getSidebarDrillDepth,
|
||||
} from "@/seqta/ui/sidebar/sidebarDrillReturn";
|
||||
|
||||
let cachedUserInfo: any = null;
|
||||
let userInfoFetchPromise: Promise<any> | 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");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getUserInfo } from "@/seqta/ui/AddBetterSEQTAElements";
|
||||
import { getUserInfo } from "@/seqta/utils/userInfo";
|
||||
|
||||
/**
|
||||
* Parses the current page from window.location.hash.
|
||||
|
||||
@@ -4,7 +4,9 @@ import {
|
||||
listOutlookSyncedEvents,
|
||||
} from "./remoteEvents";
|
||||
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ provider: "google", body: "invalid JSON" },
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<SeqtaLoginPayload | undefined> {
|
||||
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<number | undefined> {
|
||||
if (isEngageParentContext()) {
|
||||
@@ -104,13 +82,11 @@ export async function resolveStudentId(): Promise<number | undefined> {
|
||||
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<string> {
|
||||
const payload = await resolveLoginPayload();
|
||||
const payload = await tryGetUserInfo();
|
||||
const type = payload?.type?.trim().toLowerCase();
|
||||
return type || "student";
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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 [];
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
let cachedUserInfo: any = null;
|
||||
let userInfoFetchPromise: Promise<any> | 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<SeqtaUserInfo | undefined> {
|
||||
return (await getUserInfo().catch(() => undefined)) ?? undefined;
|
||||
}
|
||||
|
||||
export async function getStudentId(): Promise<number | undefined> {
|
||||
const info = await tryGetUserInfo();
|
||||
const id = info?.id ?? info?.student;
|
||||
return typeof id === "number" && Number.isFinite(id) ? id : undefined;
|
||||
}
|
||||
Reference in new issue
Block a user