mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
Merge pull request #494 from BetterSEQTA/sync-test
TimeTable P2P Sync Test Idea
This commit is contained in:
50 files changed
+3514
-157
No files matched your search
@@ -21,6 +21,7 @@ import {
|
||||
} from "./background/calendarBackground";
|
||||
import { createCustomThemesHandlers } from "./background/customThemesHandlers";
|
||||
import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos";
|
||||
import { initTimetableClassmatesBackgroundSync } from "./background/timetableClassmatesSync";
|
||||
|
||||
/**
|
||||
* Session-only dev-mode override of the content API base.
|
||||
@@ -750,4 +751,5 @@ browser.runtime.onStartup.addListener(() => {
|
||||
});
|
||||
|
||||
initCloudSettingsAutoSync({ reloadSeqtaPages });
|
||||
initTimetableClassmatesBackgroundSync();
|
||||
void ensureSyncableStorageDefaults();
|
||||
@@ -53,6 +53,7 @@ import {
|
||||
type OutlookCalendarStatus,
|
||||
} from "@/seqta/utils/calendarSync/providerStorage";
|
||||
import browser from "webextension-polyfill";
|
||||
import { isSeqtaTab } from "@/seqta/utils/seqtaTabMatch";
|
||||
|
||||
const WEEKLY_PERIOD_MINUTES = 7 * 24 * 60;
|
||||
|
||||
@@ -510,11 +511,6 @@ export function registerOutlookCalendarMessageHandlers(
|
||||
registerProviderHandlers(handlers, isTrustedSender, OUTLOOK_BACKEND, getOutlookCalendarStatus);
|
||||
}
|
||||
|
||||
function isSeqtaTab(tab: browser.Tabs.Tab): boolean {
|
||||
const title = tab.title ?? "";
|
||||
return title.includes("SEQTA Learn") || title.includes("SEQTA Engage");
|
||||
}
|
||||
|
||||
export async function ensureWeeklySyncAlarm(): Promise<void> {
|
||||
const [connected, enabled] = await Promise.all([isAnyCalendarConnected(), getAutoSyncWeekly()]);
|
||||
if (!connected || !enabled) {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
import { hasAnySyncOptInScope } from "@/plugins/built-in/timetableClassmates/syncScopes";
|
||||
import { isSeqtaTab } from "@/seqta/utils/seqtaTabMatch";
|
||||
|
||||
const ALARM_NAME = "timetable-classmates-sync";
|
||||
const ALARM_PERIOD_MINUTES = 8 * 60;
|
||||
|
||||
let initialized = false;
|
||||
|
||||
async function pingSeqtaTabs(): Promise<void> {
|
||||
const tabs = await browser.tabs.query({});
|
||||
for (const tab of tabs) {
|
||||
if (!isSeqtaTab(tab) || tab.id == null) continue;
|
||||
try {
|
||||
await browser.tabs.sendMessage(tab.id, { type: "timetableClassmatesSync" });
|
||||
} catch {
|
||||
/* content script not ready */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function pingIfOptedIn(): Promise<void> {
|
||||
if (!(await hasAnySyncOptInScope())) return;
|
||||
await pingSeqtaTabs();
|
||||
}
|
||||
|
||||
export function initTimetableClassmatesBackgroundSync(): void {
|
||||
if (initialized) return;
|
||||
initialized = true;
|
||||
|
||||
void browser.alarms.create(ALARM_NAME, { periodInMinutes: ALARM_PERIOD_MINUTES });
|
||||
browser.alarms.onAlarm.addListener((alarm) => {
|
||||
if (alarm.name === ALARM_NAME) void pingIfOptedIn();
|
||||
});
|
||||
}
|
||||
@@ -43,16 +43,16 @@
|
||||
class="flex shrink-0 items-center gap-4 border-b border-zinc-200/60 px-5 py-4 dark:border-zinc-700/50"
|
||||
style="--bs-settings-ease: 0.28s cubic-bezier(0.22, 1, 0.36, 1)"
|
||||
>
|
||||
<button type="button" class="hidden shrink-0 lg:block" onclick={onLogoClick}>
|
||||
<button type="button" class="shrink-0" onclick={onLogoClick} aria-label="BetterSEQTA+">
|
||||
<img
|
||||
src={resolveExtensionAssetUrl(darkLogo)}
|
||||
class="h-11 w-52 object-cover dark:hidden"
|
||||
alt="BetterSEQTA+"
|
||||
class="h-9 max-w-[10.5rem] object-contain object-left dark:hidden sm:h-10"
|
||||
alt=""
|
||||
/>
|
||||
<img
|
||||
src={resolveExtensionAssetUrl(lightLogo)}
|
||||
class="hidden h-11 w-52 object-cover dark:block"
|
||||
alt="BetterSEQTA+"
|
||||
class="hidden h-9 max-w-[10.5rem] object-contain object-left dark:block sm:h-10"
|
||||
alt=""
|
||||
/>
|
||||
</button>
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
import SidebarNav from "../components/SidebarNav.svelte";
|
||||
import StoreHeader from "../components/store/Header.svelte";
|
||||
import { settingsPopup } from "@/seqta/utils/settingsPopup";
|
||||
import { armDevModeUnlock } from "@/seqta/utils/devModeUnlock";
|
||||
import { consumeOpenFeedbackRequest } from "@/seqta/utils/feedback/client";
|
||||
import {
|
||||
consumeSettingsDestination,
|
||||
@@ -53,7 +54,6 @@
|
||||
|
||||
const BACKGROUND_CATEGORY_PREFIX = "background-category:";
|
||||
|
||||
let devModeSequence = "";
|
||||
let compactActiveTab = $state(0);
|
||||
let expanded = $state(settingsState.settingsPopupExpanded === true);
|
||||
let lastExpandedTab: number | null = null;
|
||||
@@ -201,22 +201,7 @@
|
||||
closeExtensionPopup();
|
||||
};
|
||||
|
||||
const handleDevModeToggle = () => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
devModeSequence += event.key.toLowerCase();
|
||||
if (devModeSequence.includes("dev")) {
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
settingsState.devMode = true;
|
||||
alert("Dev mode is now enabled");
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
setTimeout(() => {
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
devModeSequence = "";
|
||||
}, 10000);
|
||||
};
|
||||
const handleDevModeToggle = () => armDevModeUnlock();
|
||||
|
||||
let ColourPickerComponent = $state<Component | null>(null);
|
||||
let FontPickerComponent = $state<Component | null>(null);
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
"64": "resources/icons/icon-64.png"
|
||||
}
|
||||
},
|
||||
"permissions": ["tabs", "notifications", "storage", "alarms"],
|
||||
"permissions": ["tabs", "notifications", "storage", "alarms", "cookies"],
|
||||
"host_permissions": [
|
||||
"https://newsapi.org/",
|
||||
"https://betterseqta.org/",
|
||||
|
||||
@@ -297,6 +297,73 @@ function titleFromEndpoint(
|
||||
return (firstLine || fallback).slice(0, 200);
|
||||
}
|
||||
|
||||
function shouldSkipPassiveEntity(
|
||||
ctx: CapturedContext,
|
||||
entity: unknown,
|
||||
isPeopleSupport: boolean,
|
||||
): boolean {
|
||||
if (!entity || (typeof entity !== "object" && typeof entity !== "string")) {
|
||||
return true;
|
||||
}
|
||||
if (ctx.route.includes("/load/message") && typeof entity === "object") {
|
||||
const subject = (entity as Record<string, unknown>).subject;
|
||||
if (typeof subject === "string" && subject.startsWith("BQ+TIMETABLE:")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return isPeopleSupport && !isPeopleEntityWorthIndexing(entity);
|
||||
}
|
||||
|
||||
function passiveEntityToIndexItem(
|
||||
ctx: CapturedContext,
|
||||
entity: unknown,
|
||||
index: number,
|
||||
category: ReturnType<typeof categoryFromRoute>,
|
||||
isPeopleSupport: boolean,
|
||||
): IndexItem | null {
|
||||
const fallbackId = `${ctx.route}#${index}`;
|
||||
const entityId = pickId(entity, fallbackId);
|
||||
const stableId = `passive-${ctx.route.replace(/\//g, "_")}-${entityId}`;
|
||||
|
||||
const content = extractTextFromValue(entity, {
|
||||
maxChars: MAX_PER_RESPONSE_TEXT_CHARS,
|
||||
});
|
||||
const title = titleFromEndpoint(ctx.route, entity, content, fallbackId);
|
||||
if (!content && (!title || title === fallbackId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const deepLinkHints = pickDeepLinkHints(entity);
|
||||
const sourcePage = sourcePageForRoute(ctx.route);
|
||||
const coursePm = ctx.route.includes("/load/courses")
|
||||
? extractProgrammeMetaclass(ctx.requestBody, entity)
|
||||
: null;
|
||||
|
||||
return buildIndexItem({
|
||||
id: stableId,
|
||||
text: title,
|
||||
category,
|
||||
contentOverride: content,
|
||||
metadata: {
|
||||
route: ctx.route,
|
||||
source: "passive",
|
||||
observedAt: new Date(ctx.observedAt).toISOString(),
|
||||
entityType: category,
|
||||
entityId,
|
||||
icon: "\ueb71",
|
||||
sourcePage,
|
||||
...(isPeopleSupport ? { supportRecord: true, priority: "low" } : {}),
|
||||
...deepLinkHints,
|
||||
...(coursePm
|
||||
? { programme: coursePm.programme, metaclass: coursePm.metaclass }
|
||||
: {}),
|
||||
},
|
||||
actionId: "passive",
|
||||
renderComponentId: "passive",
|
||||
dateAdded: ctx.observedAt,
|
||||
});
|
||||
}
|
||||
|
||||
function synthesizeItems(
|
||||
ctx: CapturedContext,
|
||||
payload: unknown,
|
||||
@@ -307,75 +374,16 @@ function synthesizeItems(
|
||||
if (entities.length === 0) return [];
|
||||
|
||||
const category = categoryFromRoute(ctx.route);
|
||||
const now = ctx.observedAt;
|
||||
const out: IndexItem[] = [];
|
||||
|
||||
const isPeopleSupport = ctx.route.includes("/load/message/people");
|
||||
|
||||
const out: IndexItem[] = [];
|
||||
const limit = Math.min(entities.length, MAX_ITEMS_PER_RESPONSE);
|
||||
|
||||
for (let i = 0; i < limit; i++) {
|
||||
const entity = entities[i];
|
||||
if (!entity || (typeof entity !== "object" && typeof entity !== "string")) {
|
||||
continue;
|
||||
}
|
||||
if (shouldSkipPassiveEntity(ctx, entity, isPeopleSupport)) continue;
|
||||
|
||||
// For the messages compose-people endpoint, skip records that don't
|
||||
// carry a real human name. We never want raw entries like
|
||||
// `/seqta/student/load/message/people#20` becoming titles, and we
|
||||
// explicitly route the rest to /messages so they're treated as support
|
||||
// records, not standalone "people" results.
|
||||
if (isPeopleSupport && !isPeopleEntityWorthIndexing(entity)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fallbackId = `${ctx.route}#${i}`;
|
||||
const entityId = pickId(entity, fallbackId);
|
||||
const stableId = `passive-${ctx.route.replace(/\//g, "_")}-${entityId}`;
|
||||
|
||||
const content = extractTextFromValue(entity, {
|
||||
maxChars: MAX_PER_RESPONSE_TEXT_CHARS,
|
||||
});
|
||||
const title = titleFromEndpoint(ctx.route, entity, content, fallbackId);
|
||||
if (!content && (!title || title === fallbackId)) {
|
||||
// Skip records that produced neither title nor content; they are
|
||||
// structurally noise (e.g. tiny acknowledgement payloads).
|
||||
continue;
|
||||
}
|
||||
|
||||
const deepLinkHints = pickDeepLinkHints(entity);
|
||||
const sourcePage = sourcePageForRoute(ctx.route);
|
||||
const coursePm = ctx.route.includes("/load/courses")
|
||||
? extractProgrammeMetaclass(ctx.requestBody, entity)
|
||||
: null;
|
||||
|
||||
out.push(
|
||||
buildIndexItem({
|
||||
id: stableId,
|
||||
text: title,
|
||||
category,
|
||||
contentOverride: content,
|
||||
metadata: {
|
||||
route: ctx.route,
|
||||
source: "passive",
|
||||
observedAt: new Date(now).toISOString(),
|
||||
entityType: category,
|
||||
entityId,
|
||||
icon: "\ueb71",
|
||||
sourcePage,
|
||||
// Mark message/people as a low-priority support record so the
|
||||
// search ranker can deprioritize it relative to real messages,
|
||||
// assessments, courses, etc.
|
||||
...(isPeopleSupport ? { supportRecord: true, priority: "low" } : {}),
|
||||
...deepLinkHints,
|
||||
...(coursePm
|
||||
? { programme: coursePm.programme, metaclass: coursePm.metaclass }
|
||||
: {}),
|
||||
},
|
||||
actionId: "passive",
|
||||
renderComponentId: "passive",
|
||||
dateAdded: now,
|
||||
}),
|
||||
);
|
||||
const item = passiveEntityToIndexItem(ctx, entity, i, category, isPeopleSupport);
|
||||
if (item) out.push(item);
|
||||
}
|
||||
|
||||
return out;
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { syncCalendarSyncTheme } from "@/plugins/built-in/timetable/calendarSyncUi";
|
||||
import { loadSession } from "./rosterStore";
|
||||
import { openTimetableClassmatesOptInPopup } from "./openTimetableClassmatesPopup";
|
||||
import { runTimetableClassmatesSync } from "./syncOrchestrator";
|
||||
|
||||
let rootEl = $state<HTMLDivElement | null>(null);
|
||||
let busy = $state(false);
|
||||
|
||||
function syncTheme() {
|
||||
const host = rootEl?.closest(".bsplus-friends-sync-mount");
|
||||
if (host instanceof HTMLElement) syncCalendarSyncTheme(host);
|
||||
}
|
||||
|
||||
async function handleClick() {
|
||||
if (busy) return;
|
||||
const session = await loadSession();
|
||||
if (!session.syncOptIn) {
|
||||
openTimetableClassmatesOptInPopup({ onAccepted: () => {} });
|
||||
return;
|
||||
}
|
||||
|
||||
busy = true;
|
||||
try {
|
||||
await runTimetableClassmatesSync();
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
const themeKeys = ["selectedColor", "selectedFont", "DarkMode", "adaptiveThemeColour"] as const;
|
||||
const onThemeChange = () => syncTheme();
|
||||
for (const key of themeKeys) {
|
||||
settingsState.register(key, onThemeChange);
|
||||
}
|
||||
|
||||
const themeObserver = new MutationObserver(onThemeChange);
|
||||
themeObserver.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ["style", "class"],
|
||||
});
|
||||
|
||||
syncTheme();
|
||||
|
||||
return () => {
|
||||
for (const key of themeKeys) {
|
||||
settingsState.unregister(key, onThemeChange);
|
||||
}
|
||||
themeObserver.disconnect();
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="bsplus-friends-sync" bind:this={rootEl}>
|
||||
<button
|
||||
type="button"
|
||||
class="uiButton bsplus-cal-trigger"
|
||||
class:bsplus-cal-trigger--busy={busy}
|
||||
disabled={busy}
|
||||
aria-busy={busy}
|
||||
aria-label="Sync with Friends"
|
||||
onclick={() => void handleClick()}
|
||||
>
|
||||
<span class="bsplus-cal-trigger-content">
|
||||
<span class="bsplus-cal-trigger-icon iconFamily" aria-hidden="true"></span>
|
||||
<span class="bsplus-cal-trigger-text">Sync with Friends</span>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
@@ -0,0 +1,20 @@
|
||||
<script lang="ts">
|
||||
import Switch from "@/interface/components/Switch.svelte";
|
||||
import { loadSession, notifyClassmatesUpdated, patchSession } from "./rosterStore";
|
||||
|
||||
let showAvatars = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
void loadSession().then((session) => {
|
||||
showAvatars = session.showAvatars;
|
||||
});
|
||||
});
|
||||
|
||||
async function onChange(value: boolean) {
|
||||
await patchSession({ showAvatars: value });
|
||||
showAvatars = value;
|
||||
notifyClassmatesUpdated();
|
||||
}
|
||||
</script>
|
||||
|
||||
<Switch state={showAvatars} onChange={(value) => void onChange(value)} />
|
||||
@@ -0,0 +1,175 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import CloudPfpAvatar from "@/interface/components/CloudPfpAvatar.svelte";
|
||||
import { cloudAuth, type CloudUser } from "@/seqta/utils/CloudAuth";
|
||||
import { ACCOUNTS_BASE } from "./constants";
|
||||
import { markResumeOptInAfterCloudLogin } from "./optInResume";
|
||||
import { registerOptIn } from "./syncOrchestrator";
|
||||
|
||||
interface Props {
|
||||
onAccepted: () => void | Promise<void>;
|
||||
onCancel: () => void;
|
||||
onComplete: () => void;
|
||||
}
|
||||
|
||||
let { onAccepted, onCancel, onComplete }: Props = $props();
|
||||
|
||||
let agreeShare = $state(false);
|
||||
let agreeJoin = $state(false);
|
||||
let busy = $state(false);
|
||||
let error = $state("");
|
||||
let cloudLoggedIn = $state(cloudAuth.state.isLoggedIn);
|
||||
let cloudUser = $state<CloudUser | null>(cloudAuth.state.user);
|
||||
|
||||
onMount(() =>
|
||||
cloudAuth.subscribe((s) => {
|
||||
cloudLoggedIn = s.isLoggedIn;
|
||||
cloudUser = s.user;
|
||||
}),
|
||||
);
|
||||
|
||||
function cloudInitials(user: CloudUser | null | undefined): string {
|
||||
if (!user) return "?";
|
||||
if (user.displayName) return user.displayName.slice(0, 2).toUpperCase();
|
||||
if (user.username) return user.username.slice(0, 2).toUpperCase();
|
||||
if (user.email) return user.email.slice(0, 2).toUpperCase();
|
||||
return "?";
|
||||
}
|
||||
|
||||
function cloudDisplayName(user: CloudUser | null | undefined): string {
|
||||
if (!user) return "Cloud account";
|
||||
return user.displayName || user.username || user.email || "Cloud account";
|
||||
}
|
||||
|
||||
function cloudSubtitle(user: CloudUser | null | undefined): string | null {
|
||||
if (!user) return null;
|
||||
if (user.username) return `@${user.username}`;
|
||||
if (user.email) return user.email;
|
||||
return null;
|
||||
}
|
||||
|
||||
const canSubmit = $derived(agreeShare && agreeJoin && cloudLoggedIn && !busy);
|
||||
const checksDisabled = $derived(busy || !cloudLoggedIn);
|
||||
|
||||
async function signInWithCloud() {
|
||||
busy = true;
|
||||
error = "";
|
||||
try {
|
||||
const res = await cloudAuth.startLogin();
|
||||
if (!res.success) {
|
||||
error = res.error ?? "Could not open sign-in.";
|
||||
return;
|
||||
}
|
||||
markResumeOptInAfterCloudLogin();
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function accept() {
|
||||
if (!canSubmit) return;
|
||||
error = "";
|
||||
busy = true;
|
||||
try {
|
||||
const reg = await registerOptIn();
|
||||
if (!reg.ok) {
|
||||
error = reg.error ?? "Could not complete opt-in.";
|
||||
return;
|
||||
}
|
||||
if (reg.error) error = reg.error;
|
||||
await onAccepted();
|
||||
onComplete();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : "Something went wrong.";
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="bsplus-tc-popup">
|
||||
<section class="bsplus-tc-card bsplus-tc-cloud" aria-labelledby="bsplus-tc-cloud-heading">
|
||||
<h2 id="bsplus-tc-cloud-heading">BetterSEQTA Cloud</h2>
|
||||
|
||||
{#if cloudLoggedIn && cloudUser}
|
||||
<div class="bsplus-tc-cloud-user" role="status">
|
||||
<div class="bsplus-tc-cloud-avatar" aria-hidden="true">
|
||||
<span class="bsplus-tc-cloud-avatar-fallback">{cloudInitials(cloudUser)}</span>
|
||||
<CloudPfpAvatar user={cloudUser} class="bsplus-tc-cloud-avatar-img" />
|
||||
</div>
|
||||
<div class="bsplus-tc-cloud-user-meta">
|
||||
<span class="bsplus-tc-cloud-user-name">{cloudDisplayName(cloudUser)}</span>
|
||||
{#if cloudSubtitle(cloudUser)}
|
||||
<span class="bsplus-tc-cloud-user-sub">{cloudSubtitle(cloudUser)}</span>
|
||||
{/if}
|
||||
</div>
|
||||
<span class="bsplus-tc-cloud-check iconFamily" aria-hidden="true"></span>
|
||||
</div>
|
||||
{:else}
|
||||
<p class="bsplus-tc-cloud-lead">
|
||||
Sign in with your free cloud account to join your school's classmate phonebook.
|
||||
</p>
|
||||
<div class="bsplus-tc-cloud-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="bsplus-cal-btn bsplus-cal-btn--primary bsplus-tc-cloud-signin"
|
||||
disabled={busy}
|
||||
onclick={() => void signInWithCloud()}
|
||||
>
|
||||
Sign in with Cloud
|
||||
</button>
|
||||
<a
|
||||
class="bsplus-tc-link"
|
||||
href={`${ACCOUNTS_BASE}/register`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Create free account
|
||||
</a>
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<ul class="bsplus-tc-bullets">
|
||||
<li>Class codes are encrypted in your browser before they reach the relay.</li>
|
||||
<li>Cloud stores a school phonebook (ids + binding), not lesson times or rooms.</li>
|
||||
<li>After you opt in, BetterSEQTA+ syncs automatically when your timetable changes.</li>
|
||||
</ul>
|
||||
|
||||
<div class="bsplus-tc-checks">
|
||||
<label>
|
||||
<input type="checkbox" bind:checked={agreeShare} disabled={checksDisabled} />
|
||||
<span>
|
||||
I understand my class enrollments are shared with opted-in students via the encrypted cloud
|
||||
relay and phonebook.
|
||||
</span>
|
||||
</label>
|
||||
<label>
|
||||
<input type="checkbox" bind:checked={agreeJoin} disabled={checksDisabled} />
|
||||
<span>I agree to participate in timetable classmate sharing on this SEQTA site.</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<p class="bsplus-tc-error">{error}</p>
|
||||
{/if}
|
||||
|
||||
<div class="bsplus-tc-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="bsplus-cal-btn bsplus-cal-btn--ghost"
|
||||
disabled={busy}
|
||||
onclick={() => onCancel()}
|
||||
>
|
||||
Not now
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="bsplus-cal-btn bsplus-cal-btn--primary"
|
||||
disabled={!canSubmit}
|
||||
onclick={() => void accept()}
|
||||
>
|
||||
{busy ? "Enabling & syncing…" : "Enable sharing"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,81 @@
|
||||
<script lang="ts">
|
||||
import { revokeOptIn } from "./syncOrchestrator";
|
||||
|
||||
interface Props {
|
||||
onConfirmed: () => void | Promise<void>;
|
||||
onCancel: () => void;
|
||||
onComplete: () => void;
|
||||
}
|
||||
|
||||
let { onConfirmed, onCancel, onComplete }: Props = $props();
|
||||
|
||||
let agreeUnderstand = $state(false);
|
||||
let busy = $state(false);
|
||||
let error = $state("");
|
||||
|
||||
const canSubmit = $derived(agreeUnderstand && !busy);
|
||||
|
||||
async function confirmOptOut() {
|
||||
if (!canSubmit) return;
|
||||
error = "";
|
||||
busy = true;
|
||||
try {
|
||||
const res = await revokeOptIn();
|
||||
if (!res.ok) {
|
||||
error = res.error ?? "Opt-out failed.";
|
||||
return;
|
||||
}
|
||||
await onConfirmed();
|
||||
onComplete();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : "Something went wrong.";
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="bsplus-tc-popup">
|
||||
<div class="bsplus-tc-card bsplus-tc-warning">
|
||||
<p>
|
||||
You will leave the school phonebook and your encrypted share will be removed from the relay.
|
||||
Classmates will stop seeing you on their timetables after they sync.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ul class="bsplus-tc-bullets">
|
||||
<li>Your local classmate roster cache on this device is cleared for your account.</li>
|
||||
<li>Classmates may still have roster data from before you opted out until their next sync.</li>
|
||||
<li>You can opt in again later — sharing and sync will start fresh from that point.</li>
|
||||
</ul>
|
||||
|
||||
<div class="bsplus-tc-checks">
|
||||
<label>
|
||||
<input type="checkbox" bind:checked={agreeUnderstand} disabled={busy} />
|
||||
<span>I understand and want to stop classmate sharing for this SEQTA site.</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<p class="bsplus-tc-error">{error}</p>
|
||||
{/if}
|
||||
|
||||
<div class="bsplus-tc-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="bsplus-cal-btn bsplus-cal-btn--ghost"
|
||||
disabled={busy}
|
||||
onclick={() => onCancel()}
|
||||
>
|
||||
Keep sharing
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="bsplus-cal-btn bsplus-cal-btn--danger"
|
||||
disabled={!canSubmit}
|
||||
onclick={() => void confirmOptOut()}
|
||||
>
|
||||
{busy ? "Opting out…" : "Stop sharing"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,112 @@
|
||||
<script lang="ts">
|
||||
import Button from "@/interface/components/Button.svelte";
|
||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||
import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup";
|
||||
import { runTimetableClassmatesSync } from "./syncOrchestrator";
|
||||
import { loadSession, resolveClassmatesScope } from "./rosterStore";
|
||||
import { pluginSettingsStore } from "@/interface/pages/settings/pluginSettingsState.svelte";
|
||||
import {
|
||||
openTimetableClassmatesOptInPopup,
|
||||
openTimetableClassmatesOptOutPopup,
|
||||
} from "./openTimetableClassmatesPopup";
|
||||
|
||||
const PLUGIN_ID = "timetable-classmates";
|
||||
const SETTINGS_CLOSE_MS = 320;
|
||||
|
||||
let busy = $state(false);
|
||||
let status = $state("");
|
||||
let error = $state("");
|
||||
let scopeLabel = $state("");
|
||||
let syncOptIn = $state(false);
|
||||
|
||||
async function refreshStatus() {
|
||||
const scope = await resolveClassmatesScope();
|
||||
scopeLabel = scope ? scope.replace("#", " · student ") : "Open SEQTA on your school site";
|
||||
const session = await loadSession();
|
||||
syncOptIn = session.syncOptIn;
|
||||
if (session.lastSyncAt) {
|
||||
status = `Last sync ${new Date(session.lastSyncAt).toLocaleString()}${
|
||||
session.lastPeerCount != null ? ` · ${session.lastPeerCount} peers` : ""
|
||||
}`;
|
||||
} else {
|
||||
status = "";
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
void refreshStatus();
|
||||
});
|
||||
|
||||
function afterSettingsClosed(run: () => void) {
|
||||
closeExtensionPopup();
|
||||
window.setTimeout(run, SETTINGS_CLOSE_MS);
|
||||
}
|
||||
|
||||
function startOptIn() {
|
||||
error = "";
|
||||
afterSettingsClosed(() => {
|
||||
openTimetableClassmatesOptInPopup({
|
||||
onAccepted: async () => {
|
||||
await pluginSettingsStore.update(PLUGIN_ID, "enabled", true);
|
||||
await refreshStatus();
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function startOptOut() {
|
||||
error = "";
|
||||
afterSettingsClosed(() => {
|
||||
openTimetableClassmatesOptOutPopup({
|
||||
onConfirmed: async () => {
|
||||
await refreshStatus();
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function syncNow() {
|
||||
error = "";
|
||||
busy = true;
|
||||
try {
|
||||
const res = await runTimetableClassmatesSync();
|
||||
if (!res.ok) error = res.error ?? "Sync failed";
|
||||
await refreshStatus();
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col items-end gap-2 shrink-0 max-w-[14rem]">
|
||||
<p class="text-xs text-right text-zinc-500 dark:text-zinc-400">{scopeLabel}</p>
|
||||
|
||||
{#if syncOptIn}
|
||||
<p class="text-xs font-medium text-green-600 dark:text-green-400">Opted in on this site</p>
|
||||
<div class="flex flex-wrap gap-2 justify-end">
|
||||
<Button text="Sync now" onClick={() => void syncNow()} disabled={busy} />
|
||||
<button
|
||||
type="button"
|
||||
class="px-3 py-1.5 text-[0.75rem] rounded-lg text-red-600 dark:text-red-400 hover:bg-zinc-200/80 dark:hover:bg-zinc-700/50 disabled:opacity-50 transition-colors duration-200"
|
||||
disabled={busy}
|
||||
onclick={startOptOut}
|
||||
>
|
||||
Opt out…
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-xs text-right text-zinc-500 dark:text-zinc-400">
|
||||
{cloudAuth.state.isLoggedIn
|
||||
? "Not sharing yet"
|
||||
: "Sign in to Cloud in the opt-in guide"}
|
||||
</p>
|
||||
<Button text="Opt in…" onClick={startOptIn} disabled={busy} />
|
||||
{/if}
|
||||
|
||||
{#if status}
|
||||
<p class="text-xs text-right text-zinc-500 dark:text-zinc-400">{status}</p>
|
||||
{/if}
|
||||
{#if error}
|
||||
<p class="text-xs text-right text-red-500">{error}</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,132 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import { getInstanceHostname } from "@/seqta/utils/feedback/client";
|
||||
import { ACCOUNTS_BASE } from "./constants";
|
||||
import type {
|
||||
OptInBindingBody,
|
||||
TimetableClassmatesBindingFields,
|
||||
} from "./identityBinding";
|
||||
|
||||
export type PeersResponse = {
|
||||
self: { seqta_student_id: number; cloud_user_id?: string };
|
||||
peers: Array<{ seqta_student_id: number; cloud_user_id?: string }>;
|
||||
};
|
||||
|
||||
export type RelaySessionResponse = {
|
||||
ws_url: string;
|
||||
relay_token: string;
|
||||
bundle_key_b64: string;
|
||||
share_code: string;
|
||||
relay_protocol: number;
|
||||
};
|
||||
|
||||
const PEER_CLOUD_ID_TTL_MS = 5 * 60_000;
|
||||
let peerCloudIds: Record<string, string> = {};
|
||||
let peerCloudIdsAt = 0;
|
||||
|
||||
function peersToCloudIdMap(data: PeersResponse): Record<string, string> {
|
||||
const map: Record<string, string> = {};
|
||||
if (data.self.cloud_user_id) {
|
||||
map[String(data.self.seqta_student_id)] = data.self.cloud_user_id;
|
||||
}
|
||||
for (const peer of data.peers) {
|
||||
if (peer.cloud_user_id) map[String(peer.seqta_student_id)] = peer.cloud_user_id;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
export function rememberPeerCloudIds(data: PeersResponse): void {
|
||||
peerCloudIds = peersToCloudIdMap(data);
|
||||
peerCloudIdsAt = Date.now();
|
||||
}
|
||||
|
||||
export async function peerCloudIdsForPaint(): Promise<Record<string, string>> {
|
||||
if (Date.now() - peerCloudIdsAt < PEER_CLOUD_ID_TTL_MS && Object.keys(peerCloudIds).length > 0) {
|
||||
return peerCloudIds;
|
||||
}
|
||||
const host = getInstanceHostname();
|
||||
if (!host) return peerCloudIds;
|
||||
const data = await fetchPeers(host);
|
||||
if (data) rememberPeerCloudIds(data);
|
||||
return peerCloudIds;
|
||||
}
|
||||
|
||||
async function getAccessToken(): Promise<string | null> {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
return typeof bsplus_token === "string" && bsplus_token.length > 0 ? bsplus_token : null;
|
||||
}
|
||||
|
||||
async function accountsFetch<T>(
|
||||
path: string,
|
||||
init?: RequestInit,
|
||||
): Promise<{ ok: boolean; status: number; data?: T; error?: string }> {
|
||||
const token = await getAccessToken();
|
||||
if (!token) return { ok: false, status: 401, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
|
||||
const res = await fetch(`${ACCOUNTS_BASE}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
});
|
||||
|
||||
const text = await res.text();
|
||||
let data: T | undefined;
|
||||
try {
|
||||
data = text ? (JSON.parse(text) as T) : undefined;
|
||||
} catch {
|
||||
data = undefined;
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const err =
|
||||
data && typeof data === "object" && "error" in data
|
||||
? String((data as { error?: string }).error)
|
||||
: res.statusText;
|
||||
return { ok: false, status: res.status, error: err };
|
||||
}
|
||||
return { ok: true, status: res.status, data };
|
||||
}
|
||||
|
||||
export async function putOptIn(body: OptInBindingBody): Promise<{ ok: boolean; error?: string }> {
|
||||
const res = await accountsFetch<{ opted_in_at?: string }>(
|
||||
"/api/bsplus/timetable-classmates/opt-in",
|
||||
{ method: "PUT", body: JSON.stringify(body) },
|
||||
);
|
||||
return res.ok ? { ok: true } : { ok: false, error: res.error };
|
||||
}
|
||||
|
||||
export async function deleteOptIn(instanceHost: string): Promise<{ ok: boolean; error?: string }> {
|
||||
const q = encodeURIComponent(instanceHost);
|
||||
const res = await accountsFetch<unknown>(
|
||||
`/api/bsplus/timetable-classmates/opt-in?instance_host=${q}`,
|
||||
{ method: "DELETE" },
|
||||
);
|
||||
return res.ok ? { ok: true } : { ok: false, error: res.error };
|
||||
}
|
||||
|
||||
export async function fetchPeers(instanceHost: string): Promise<PeersResponse | null> {
|
||||
const q = encodeURIComponent(instanceHost);
|
||||
const res = await accountsFetch<PeersResponse>(
|
||||
`/api/bsplus/timetable-classmates/peers?instance_host=${q}`,
|
||||
);
|
||||
return res.ok && res.data ? res.data : null;
|
||||
}
|
||||
|
||||
export async function fetchRelaySession(
|
||||
instanceHost: string,
|
||||
): Promise<RelaySessionResponse | null> {
|
||||
const q = encodeURIComponent(instanceHost);
|
||||
const res = await accountsFetch<RelaySessionResponse>(
|
||||
`/api/bsplus/timetable-classmates/relay-session?instance_host=${q}`,
|
||||
);
|
||||
return res.ok && res.data ? res.data : null;
|
||||
}
|
||||
|
||||
export async function postHeartbeat(body: TimetableClassmatesBindingFields): Promise<void> {
|
||||
await accountsFetch("/api/bsplus/timetable-classmates/heartbeat", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import { resolveCloudPfp, defaultAccountsPfpUrl } from "@/seqta/utils/cloudPfpCache";
|
||||
import { buildAvatarDisplayList, type AvatarListInput } from "./classKeys";
|
||||
import { MAX_VISIBLE_CLASSMATE_AVATARS, maxClassmatesVisibleForWidth } from "./constants";
|
||||
import type { ArchivedMembers, ClassRosterIndex } from "./rosterMerge";
|
||||
import { rosterPeersForClass } from "./rosterMerge";
|
||||
import type { PeopleCache } from "./rosterStore";
|
||||
import { displayNameForSeqtaId } from "./peopleCache";
|
||||
import { openClassmatesRosterPopup } from "./openTimetableClassmatesPopup";
|
||||
|
||||
const STACK = "bsplus-classmate-stack";
|
||||
const AVATAR = "bsplus-classmate-avatar";
|
||||
|
||||
export function isClassmatesPluginMutation(record: MutationRecord): boolean {
|
||||
const inStack = (el: Element | null) => Boolean(el?.closest(`.${STACK}`));
|
||||
if (record.target instanceof Element && inStack(record.target)) return true;
|
||||
for (const node of [...record.addedNodes, ...record.removedNodes]) {
|
||||
const el = node instanceof Element ? node : node.parentElement;
|
||||
if (inStack(el)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function stackSignature(classKey: string, maxVisible: number, overflow: number, peerIds: number[]): string {
|
||||
return `${classKey}|${maxVisible}|${overflow}|${peerIds.join(",")}`;
|
||||
}
|
||||
|
||||
function avatarColumnWidth(host: HTMLElement): number {
|
||||
const scope =
|
||||
(host.classList.contains("entry") ? host : host.closest(".timetablepage .entry.class")) ??
|
||||
host.closest(".timetablepage .quickbar .meta") ??
|
||||
host.closest(".timetablepage .days tbody td");
|
||||
if (!(scope instanceof HTMLElement)) return 0;
|
||||
const w = scope.getBoundingClientRect().width;
|
||||
return w > 0 ? w * 0.5 : 0;
|
||||
}
|
||||
|
||||
function maxVisibleForHost(host: HTMLElement): number {
|
||||
const width = avatarColumnWidth(host);
|
||||
return width > 0 ? maxClassmatesVisibleForWidth(width) : MAX_VISIBLE_CLASSMATE_AVATARS;
|
||||
}
|
||||
|
||||
export function removeClassmateStacks(root: ParentNode = document): void {
|
||||
root.querySelectorAll(`.${STACK}`).forEach((el) => el.remove());
|
||||
}
|
||||
|
||||
function initials(name: string): string {
|
||||
const parts = name.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length === 0) return "?";
|
||||
if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
|
||||
return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
|
||||
}
|
||||
|
||||
function createAvatarChip(
|
||||
peopleCache: PeopleCache,
|
||||
opts: { studentId: number } | { overflow: number; onOpen: () => void },
|
||||
): HTMLElement {
|
||||
const wrap = document.createElement("span");
|
||||
const overflow = "overflow" in opts;
|
||||
wrap.className = overflow ? `${AVATAR} bsplus-classmate-avatar--overflow` : AVATAR;
|
||||
|
||||
const label = overflow
|
||||
? `Show ${opts.overflow} more classmates`
|
||||
: displayNameForSeqtaId(peopleCache, opts.studentId);
|
||||
wrap.title = label;
|
||||
wrap.setAttribute("aria-label", label);
|
||||
|
||||
if (overflow) {
|
||||
wrap.setAttribute("role", "button");
|
||||
wrap.tabIndex = 0;
|
||||
const open = (e: Event) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
opts.onOpen();
|
||||
};
|
||||
wrap.addEventListener("click", open);
|
||||
wrap.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter" || e.key === " ") open(e);
|
||||
});
|
||||
}
|
||||
|
||||
const placeholder = document.createElement("span");
|
||||
placeholder.className = "bsplus-classmate-avatar-placeholder";
|
||||
placeholder.textContent = overflow ? `+${opts.overflow}` : initials(label);
|
||||
wrap.appendChild(placeholder);
|
||||
|
||||
if (!overflow) {
|
||||
const people = peopleCache[String(opts.studentId)];
|
||||
if (people?.house_colour) wrap.style.setProperty("--bsplus-house-color", people.house_colour);
|
||||
}
|
||||
return wrap;
|
||||
}
|
||||
|
||||
async function hydrateAvatarFromCloud(wrap: HTMLElement, cloudUserId: string): Promise<void> {
|
||||
const mark = wrap.dataset.bsplusPfp;
|
||||
if (mark === cloudUserId || mark === `none:${cloudUserId}`) return;
|
||||
try {
|
||||
wrap.dataset.bsplusPfp = cloudUserId;
|
||||
const resolved = await resolveCloudPfp(cloudUserId, defaultAccountsPfpUrl(cloudUserId));
|
||||
if (!resolved?.src) {
|
||||
wrap.dataset.bsplusPfp = `none:${cloudUserId}`;
|
||||
return;
|
||||
}
|
||||
const img = document.createElement("img");
|
||||
img.alt = "";
|
||||
img.loading = "lazy";
|
||||
img.src = resolved.src;
|
||||
wrap.querySelector(".bsplus-classmate-avatar-placeholder")?.remove();
|
||||
wrap.appendChild(img);
|
||||
} catch {
|
||||
wrap.dataset.bsplusPfp = `none:${cloudUserId}`;
|
||||
}
|
||||
}
|
||||
|
||||
function openRosterPopup(classTitle: string, allSorted: AvatarListInput[], peopleCache: PeopleCache): void {
|
||||
openClassmatesRosterPopup(
|
||||
classTitle || "Classmates",
|
||||
allSorted.map((p) => {
|
||||
const displayName = displayNameForSeqtaId(peopleCache, p.seqtaStudentId);
|
||||
const people = peopleCache[String(p.seqtaStudentId)];
|
||||
return {
|
||||
displayName,
|
||||
initials: initials(displayName),
|
||||
houseColour: people?.house_colour,
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function renderClassmateStackForEntry(
|
||||
entry: HTMLElement,
|
||||
classKey: string | null,
|
||||
roster: ClassRosterIndex,
|
||||
peopleCache: PeopleCache,
|
||||
selfSeqtaId: number,
|
||||
archived: ArchivedMembers = {},
|
||||
cloudUserIdByStudentId: Record<string, string> = {},
|
||||
maxVisible = maxVisibleForHost(entry),
|
||||
): Promise<void> {
|
||||
if (!classKey) {
|
||||
entry.querySelector(`.${STACK}`)?.remove();
|
||||
return;
|
||||
}
|
||||
|
||||
const { visible, overflow, allSorted } = buildAvatarDisplayList(
|
||||
rosterPeersForClass(roster, classKey, archived).map((p) => ({
|
||||
seqtaStudentId: p.seqtaStudentId,
|
||||
cloudUserId: p.cloudUserId,
|
||||
updatedAt: p.updatedAt,
|
||||
})),
|
||||
selfSeqtaId,
|
||||
maxVisible,
|
||||
);
|
||||
|
||||
const signature = stackSignature(
|
||||
classKey,
|
||||
maxVisible,
|
||||
overflow,
|
||||
visible.map((p) => p.seqtaStudentId),
|
||||
);
|
||||
const existing = entry.querySelector(`.${STACK}`) as HTMLElement | null;
|
||||
if (visible.length === 0) {
|
||||
existing?.remove();
|
||||
return;
|
||||
}
|
||||
if (existing?.dataset.bsplusPeers === signature) return;
|
||||
existing?.remove();
|
||||
|
||||
const classTitle = entry.querySelector(".title")?.textContent?.trim() ?? "";
|
||||
const stack = document.createElement("div");
|
||||
stack.className = STACK;
|
||||
stack.dataset.bsplusPeers = signature;
|
||||
stack.setAttribute("aria-label", "Classmates in this class");
|
||||
|
||||
for (const peer of visible) {
|
||||
const el = createAvatarChip(peopleCache, { studentId: peer.seqtaStudentId });
|
||||
stack.appendChild(el);
|
||||
const cloudUserId =
|
||||
peer.cloudUserId ?? cloudUserIdByStudentId[String(peer.seqtaStudentId)] ?? null;
|
||||
if (cloudUserId) void hydrateAvatarFromCloud(el, cloudUserId);
|
||||
}
|
||||
|
||||
if (overflow > 0) {
|
||||
stack.appendChild(
|
||||
createAvatarChip(peopleCache, {
|
||||
overflow,
|
||||
onOpen: () => openRosterPopup(classTitle, allSorted, peopleCache),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
entry.appendChild(stack);
|
||||
}
|
||||
|
||||
export function classKeyFromCi(ci: number | null, ciMap: Record<string, string>): string | null {
|
||||
if (ci == null) return null;
|
||||
return ciMap[String(ci)] ?? null;
|
||||
}
|
||||
|
||||
export function findClassEntryByTitle(page: ParentNode, title: string): HTMLElement | null {
|
||||
const normalized = title.trim();
|
||||
if (!normalized) return null;
|
||||
for (const entry of page.querySelectorAll(".entry.class")) {
|
||||
const el = entry as HTMLElement;
|
||||
if ((el.querySelector(".title")?.textContent?.trim() ?? "") === normalized) return el;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
export type ClassRef = {
|
||||
metaID?: number;
|
||||
code?: string;
|
||||
programmeID?: number;
|
||||
};
|
||||
|
||||
export function classRosterKey(ref: ClassRef): string | null {
|
||||
if (ref.metaID != null && Number.isFinite(ref.metaID)) {
|
||||
return `cr:v1:${ref.metaID}`;
|
||||
}
|
||||
const code = ref.code?.trim();
|
||||
if (code && ref.programmeID != null && Number.isFinite(ref.programmeID)) {
|
||||
return `cr:v1:${code}:${ref.programmeID}`;
|
||||
}
|
||||
if (code) return `cr:v1:code:${code}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isSyncableClassLesson(item: {
|
||||
type?: string;
|
||||
metaID?: number;
|
||||
code?: string;
|
||||
}): boolean {
|
||||
const type = item.type?.trim().toLowerCase();
|
||||
if (type && type !== "class") return false;
|
||||
return item.metaID != null || Boolean(item.code?.trim());
|
||||
}
|
||||
|
||||
export function classRefsFromTimetableItems(
|
||||
items: Array<{
|
||||
type?: string;
|
||||
metaID?: number;
|
||||
code?: string;
|
||||
programmeID?: number;
|
||||
}>,
|
||||
): ClassRef[] {
|
||||
const seen = new Set<string>();
|
||||
const out: ClassRef[] = [];
|
||||
for (const item of items) {
|
||||
if (!isSyncableClassLesson(item)) continue;
|
||||
const key = classRosterKey(item);
|
||||
if (!key || seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push({
|
||||
metaID: item.metaID,
|
||||
code: item.code,
|
||||
programmeID: item.programmeID,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export type AvatarListInput = {
|
||||
seqtaStudentId: number;
|
||||
cloudUserId?: string | null;
|
||||
updatedAt: number;
|
||||
};
|
||||
|
||||
export type AvatarListResult = {
|
||||
visible: AvatarListInput[];
|
||||
overflow: number;
|
||||
allSorted: AvatarListInput[];
|
||||
};
|
||||
|
||||
export function buildAvatarDisplayList(
|
||||
peers: AvatarListInput[],
|
||||
selfSeqtaId: number,
|
||||
maxVisible: number,
|
||||
): AvatarListResult {
|
||||
const filtered = peers
|
||||
.filter((p) => p.seqtaStudentId !== selfSeqtaId)
|
||||
.sort((a, b) => {
|
||||
const aCloud = a.cloudUserId ? 1 : 0;
|
||||
const bCloud = b.cloudUserId ? 1 : 0;
|
||||
if (bCloud !== aCloud) return bCloud - aCloud;
|
||||
return b.updatedAt - a.updatedAt;
|
||||
});
|
||||
const visible = filtered.slice(0, maxVisible);
|
||||
return {
|
||||
visible,
|
||||
overflow: Math.max(0, filtered.length - visible.length),
|
||||
allSorted: filtered,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
.timetable-classmates-controls {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.bsplus-friends-sync-mount {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.bsplus-friends-sync {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
font-family: var(--bsplus-cal-font-family, var(--betterseqta-font-family, Rubik), sans-serif);
|
||||
color: var(--bsplus-cal-text, var(--text-primary, #111));
|
||||
}
|
||||
|
||||
.bsplus-friends-sync .bsplus-cal-trigger {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
min-width: auto;
|
||||
height: auto;
|
||||
padding: 0 10px;
|
||||
margin: 0;
|
||||
border-radius: 16px !important;
|
||||
font-family: inherit;
|
||||
background: var(--bsplus-cal-surface, var(--background-primary, #232323)) !important;
|
||||
transition:
|
||||
transform 0.2s ease,
|
||||
opacity 0.2s ease,
|
||||
background-color 0.2s ease;
|
||||
overflow: hidden;
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
.bsplus-friends-sync .bsplus-cal-trigger-content {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.bsplus-friends-sync .bsplus-cal-trigger-icon {
|
||||
font-family: "IconFamily" !important;
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.bsplus-friends-sync .bsplus-cal-trigger-text {
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.bsplus-friends-sync .bsplus-cal-trigger:hover:not(:disabled) {
|
||||
transform: scale(1.03);
|
||||
}
|
||||
|
||||
.bsplus-friends-sync .bsplus-cal-trigger:active:not(:disabled) {
|
||||
transform: scale(0.97);
|
||||
}
|
||||
|
||||
.bsplus-friends-sync .bsplus-cal-trigger--busy {
|
||||
opacity: 0.95;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.bsplus-friends-sync .bsplus-cal-trigger--busy:hover,
|
||||
.bsplus-friends-sync .bsplus-cal-trigger--busy:active {
|
||||
transform: none;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { mount, unmount } from "svelte";
|
||||
import { syncCalendarSyncTheme } from "@/plugins/built-in/timetable/calendarSyncUi";
|
||||
import chipStyles from "./classmatesToolbarChip.css?inline";
|
||||
|
||||
const CONTROLS_CLASS = "timetable-classmates-controls";
|
||||
const HOST_STYLE_ID = "bsplus-timetable-classmates-chip-styles";
|
||||
|
||||
let currentApp: ReturnType<typeof mount> | null = null;
|
||||
|
||||
function ensureHostStyles() {
|
||||
if (document.getElementById(HOST_STYLE_ID)) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = HOST_STYLE_ID;
|
||||
style.textContent = chipStyles;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
function teardown() {
|
||||
if (currentApp) {
|
||||
unmount(currentApp);
|
||||
currentApp = null;
|
||||
}
|
||||
document.querySelector(`.${CONTROLS_CLASS}`)?.remove();
|
||||
document.getElementById(HOST_STYLE_ID)?.remove();
|
||||
}
|
||||
|
||||
function insertControls(toolbar: HTMLElement, controls: HTMLElement) {
|
||||
const calendar = toolbar.querySelector(".timetable-calendar-controls");
|
||||
const zoomControls = toolbar.querySelector(".timetable-zoom-controls");
|
||||
if (calendar?.nextSibling) {
|
||||
toolbar.insertBefore(controls, calendar.nextSibling);
|
||||
} else if (zoomControls) {
|
||||
toolbar.insertBefore(controls, zoomControls);
|
||||
} else {
|
||||
toolbar.appendChild(controls);
|
||||
}
|
||||
}
|
||||
|
||||
export async function mountClassmatesToolbarChip(): Promise<void> {
|
||||
if (document.querySelector(`.${CONTROLS_CLASS}`)) return;
|
||||
|
||||
const toolbar = document.getElementById("toolbar");
|
||||
if (!toolbar) return;
|
||||
|
||||
ensureHostStyles();
|
||||
|
||||
const controls = document.createElement("div");
|
||||
controls.className = CONTROLS_CLASS;
|
||||
insertControls(toolbar, controls);
|
||||
|
||||
const mountRoot = document.createElement("div");
|
||||
mountRoot.className = "bsplus-friends-sync-mount";
|
||||
syncCalendarSyncTheme(mountRoot);
|
||||
controls.appendChild(mountRoot);
|
||||
|
||||
const { default: ClassmatesToolbarChip } = await import("./ClassmatesToolbarChip.svelte");
|
||||
currentApp = mount(ClassmatesToolbarChip, { target: mountRoot });
|
||||
}
|
||||
|
||||
export function unmountClassmatesToolbarChip(): void {
|
||||
teardown();
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
.bsplus-timetable-classmates-popup-host {
|
||||
text-align: left;
|
||||
font-size: 0.95rem;
|
||||
line-height: 1.55;
|
||||
max-height: min(72vh, 540px);
|
||||
overflow-y: auto;
|
||||
padding: 0 0.25rem 0.5rem;
|
||||
}
|
||||
|
||||
.bsplus-tc-popup {
|
||||
--tc-edge: color-mix(in srgb, currentColor 12%, transparent);
|
||||
--tc-surface: color-mix(in srgb, currentColor 6%, transparent);
|
||||
--tc-accent: var(--colour1, #818cf8);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.85rem;
|
||||
}
|
||||
|
||||
.bsplus-tc-card {
|
||||
padding: 0.85rem 1rem;
|
||||
border-radius: 0.75rem;
|
||||
background: var(--tc-surface);
|
||||
border: 1px solid var(--tc-edge);
|
||||
}
|
||||
|
||||
.bsplus-tc-card > p:first-child {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud {
|
||||
border-color: color-mix(in srgb, var(--tc-accent) 35%, transparent);
|
||||
background: linear-gradient(
|
||||
145deg,
|
||||
color-mix(in srgb, var(--tc-accent) 14%, transparent),
|
||||
color-mix(in srgb, var(--tc-accent) 5%, transparent)
|
||||
);
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud h2 {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin: 0 0 0.65rem;
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud-user {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.65rem 0.75rem;
|
||||
border-radius: 0.65rem;
|
||||
background: color-mix(in srgb, currentColor 5%, transparent);
|
||||
border: 1px solid var(--tc-edge);
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud-avatar {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
width: 2.75rem;
|
||||
height: 2.75rem;
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud-avatar-fallback,
|
||||
.bsplus-tc-cloud-avatar-img {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud-avatar-fallback {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.03em;
|
||||
color: color-mix(in srgb, var(--tc-accent) 70%, currentColor);
|
||||
background: color-mix(in srgb, var(--tc-accent) 22%, transparent);
|
||||
border: 1px solid color-mix(in srgb, var(--tc-accent) 35%, transparent);
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud-user-meta {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.1rem;
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud-user-name {
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud-user-sub {
|
||||
font-size: 0.8rem;
|
||||
opacity: 0.72;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud-check {
|
||||
flex-shrink: 0;
|
||||
font-size: 1.35rem;
|
||||
line-height: 1;
|
||||
color: color-mix(in srgb, #4ade80 90%, currentColor);
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud-lead {
|
||||
margin: 0 0 0.75rem;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.45;
|
||||
opacity: 0.88;
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud-actions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.bsplus-tc-cloud-signin {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.bsplus-tc-link {
|
||||
font-size: 0.88rem;
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
opacity: 0.85;
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
|
||||
.bsplus-tc-link:hover {
|
||||
opacity: 1;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
.bsplus-tc-muted {
|
||||
margin-top: 0.35rem;
|
||||
font-size: 0.88rem;
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.bsplus-tc-warning {
|
||||
border-color: color-mix(in srgb, #f87171 45%, transparent);
|
||||
background: color-mix(in srgb, #f87171 10%, transparent);
|
||||
}
|
||||
|
||||
.bsplus-tc-warning > p {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.bsplus-tc-bullets {
|
||||
margin: 0;
|
||||
padding-left: 1.15rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
font-size: 0.9rem;
|
||||
opacity: 0.92;
|
||||
}
|
||||
|
||||
.bsplus-tc-checks {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.bsplus-tc-checks label {
|
||||
display: flex;
|
||||
gap: 0.55rem;
|
||||
align-items: flex-start;
|
||||
cursor: pointer;
|
||||
font-size: 0.92rem;
|
||||
}
|
||||
|
||||
.bsplus-tc-checks input {
|
||||
margin-top: 0.2rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.bsplus-tc-error {
|
||||
color: #f87171;
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.bsplus-tc-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.25rem;
|
||||
padding-top: 0.5rem;
|
||||
}
|
||||
|
||||
.bsplus-timetable-classmates-popup-host .bsplus-cal-btn {
|
||||
min-width: 7.5rem;
|
||||
padding: 0.5rem 0.9rem;
|
||||
border: none;
|
||||
border-radius: 0.55rem;
|
||||
font-size: 0.88rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.bsplus-timetable-classmates-popup-host .bsplus-cal-btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.bsplus-timetable-classmates-popup-host .bsplus-cal-btn--primary {
|
||||
background: var(--tc-accent);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.bsplus-timetable-classmates-popup-host .bsplus-cal-btn--primary:hover:not(:disabled) {
|
||||
filter: brightness(1.06);
|
||||
}
|
||||
|
||||
.bsplus-timetable-classmates-popup-host .bsplus-cal-btn--ghost {
|
||||
background: color-mix(in srgb, currentColor 8%, transparent);
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.bsplus-timetable-classmates-popup-host .bsplus-cal-btn--ghost:hover:not(:disabled) {
|
||||
background: color-mix(in srgb, currentColor 14%, transparent);
|
||||
}
|
||||
|
||||
.bsplus-timetable-classmates-popup-host .bsplus-cal-btn--danger {
|
||||
background: color-mix(in srgb, #ef4444 88%, #000);
|
||||
color: #fff;
|
||||
border: 1px solid color-mix(in srgb, #ef4444 70%, transparent);
|
||||
}
|
||||
|
||||
.bsplus-timetable-classmates-popup-host .bsplus-cal-btn--danger:hover:not(:disabled) {
|
||||
filter: brightness(1.06);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/** Fallback cap when host width is unknown. */
|
||||
export const MAX_VISIBLE_CLASSMATE_AVATARS = 4;
|
||||
|
||||
const AVATAR_SLOT_PX = 22;
|
||||
const OVERFLOW_CHIP_PX = 26;
|
||||
const MAX_CLASSMATES_VISIBLE_CAP = 24;
|
||||
|
||||
/** Fit as many 20px avatars as the host width allows before "+N". */
|
||||
export function maxClassmatesVisibleForWidth(widthPx: number): number {
|
||||
if (!Number.isFinite(widthPx) || widthPx <= 0) return MAX_VISIBLE_CLASSMATE_AVATARS;
|
||||
const fit = Math.floor((widthPx - OVERFLOW_CHIP_PX) / AVATAR_SLOT_PX);
|
||||
return Math.max(1, Math.min(fit, MAX_CLASSMATES_VISIBLE_CAP));
|
||||
}
|
||||
|
||||
/** School-year rolling window (weeks ahead from current week). */
|
||||
export const CLASSMATES_SCHOOL_YEAR_WEEKS = 52;
|
||||
|
||||
/** Re-sync with relay when enrollments unchanged but peers may have updated. */
|
||||
export const CLASSMATES_PEER_REFRESH_MS = 8 * 60 * 60 * 1000;
|
||||
|
||||
/** While timetable is open, re-check enrollments on this interval. */
|
||||
export const CLASSMATES_TIMETABLE_POLL_MS = 15 * 60 * 1000;
|
||||
|
||||
export const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||
|
||||
export const TIMETABLE_CLASSMATES_CONSENT_VERSION = 3;
|
||||
@@ -0,0 +1,120 @@
|
||||
import { resolveLoginPayload } from "./seqtaClient";
|
||||
|
||||
/** Must match `buildIdentityBindingCanonical` in betterseqta-accounts worker. */
|
||||
export function buildIdentityBindingCanonical(input: {
|
||||
version: 1;
|
||||
instanceHost: string;
|
||||
seqtaStudentId: number;
|
||||
seqtaPersonUuid: string;
|
||||
cloudUserId: string;
|
||||
seqtaAccountType?: string;
|
||||
}): string {
|
||||
const lines = [
|
||||
`v=${input.version}`,
|
||||
`instance=${input.instanceHost}`,
|
||||
`student=${input.seqtaStudentId}`,
|
||||
`person=${input.seqtaPersonUuid}`,
|
||||
`cloud=${input.cloudUserId.toLowerCase()}`,
|
||||
];
|
||||
if (input.seqtaAccountType != null && input.seqtaAccountType !== "") {
|
||||
lines.push(`type=${input.seqtaAccountType}`);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
async function sha256Hex(text: string): Promise<string> {
|
||||
const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
||||
return Array.from(new Uint8Array(hash))
|
||||
.map((b) => b.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
|
||||
export type TimetableClassmatesBindingFields = {
|
||||
instance_host: string;
|
||||
seqta_student_id: number;
|
||||
seqta_person_uuid: string;
|
||||
identity_binding_digest: string;
|
||||
identity_binding_version: 1;
|
||||
seqta_account_type?: string;
|
||||
};
|
||||
|
||||
export type OptInBindingBody = TimetableClassmatesBindingFields & {
|
||||
attested_at: string;
|
||||
};
|
||||
|
||||
/** JWT `id` claim — must match server `user.id` when verifying the digest. */
|
||||
export function cloudUserIdFromAccessToken(token: string): string | null {
|
||||
try {
|
||||
const parts = token.split(".");
|
||||
if (parts.length < 2) return null;
|
||||
const b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
||||
const pad = b64.length % 4 === 0 ? b64 : b64 + "=".repeat(4 - (b64.length % 4));
|
||||
const payload = JSON.parse(atob(pad)) as { id?: string; sub?: string };
|
||||
const id = payload.id ?? payload.sub;
|
||||
return typeof id === "string" && id.length > 0 ? id : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function bindingFieldsFromSession(
|
||||
instanceHost: string,
|
||||
cloudUserId: string,
|
||||
): Promise<TimetableClassmatesBindingFields | null> {
|
||||
const login = await resolveLoginPayload();
|
||||
const seqtaStudentId = login?.id ?? login?.student;
|
||||
const personUuidRaw = login?.personUUID;
|
||||
if (
|
||||
typeof seqtaStudentId !== "number" ||
|
||||
!Number.isFinite(seqtaStudentId) ||
|
||||
typeof personUuidRaw !== "string" ||
|
||||
!personUuidRaw.trim()
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const seqtaPersonUuid = personUuidRaw.trim().toLowerCase();
|
||||
const seqtaAccountType = login?.type?.trim();
|
||||
const normalizedAccountType =
|
||||
seqtaAccountType && seqtaAccountType.length <= 64 ? seqtaAccountType : undefined;
|
||||
|
||||
const digest = await sha256Hex(
|
||||
buildIdentityBindingCanonical({
|
||||
version: 1,
|
||||
instanceHost,
|
||||
seqtaStudentId,
|
||||
seqtaPersonUuid,
|
||||
cloudUserId,
|
||||
seqtaAccountType: normalizedAccountType,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
instance_host: instanceHost,
|
||||
seqta_student_id: seqtaStudentId,
|
||||
seqta_person_uuid: seqtaPersonUuid,
|
||||
identity_binding_digest: digest,
|
||||
identity_binding_version: 1,
|
||||
...(normalizedAccountType ? { seqta_account_type: normalizedAccountType } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** SEQTA session + cloud user binding for opt-in (server recomputes digest). */
|
||||
export async function optInIdentityDigest(
|
||||
instanceHost: string,
|
||||
cloudUserId: string,
|
||||
): Promise<OptInBindingBody | null> {
|
||||
const fields = await bindingFieldsFromSession(instanceHost, cloudUserId);
|
||||
if (!fields) return null;
|
||||
return {
|
||||
...fields,
|
||||
attested_at: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Same binding proof as opt-in, for heartbeat (no attested_at). */
|
||||
export async function heartbeatIdentityFields(
|
||||
instanceHost: string,
|
||||
cloudUserId: string,
|
||||
): Promise<TimetableClassmatesBindingFields | null> {
|
||||
return bindingFieldsFromSession(instanceHost, cloudUserId);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import type { Plugin } from "@/plugins/core/types";
|
||||
import browser from "webextension-polyfill";
|
||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||
import { isPluginBlockedByPerformanceMode } from "@/seqta/utils/performanceMode";
|
||||
import { timetableClassmatesSettings } from "./settings";
|
||||
import styles from "./styles.css?inline";
|
||||
import {
|
||||
classKeyFromCi,
|
||||
findClassEntryByTitle,
|
||||
isClassmatesPluginMutation,
|
||||
removeClassmateStacks,
|
||||
renderClassmateStackForEntry,
|
||||
} from "./avatarStack";
|
||||
import {
|
||||
CLASSMATES_UPDATED_EVENT,
|
||||
ensureCiToClassKey,
|
||||
loadArchivedMembers,
|
||||
loadCiToClassKey,
|
||||
loadRosterIndex,
|
||||
loadSession,
|
||||
} from "./rosterStore";
|
||||
import { refreshPeopleCacheIfStale } from "./peopleCache";
|
||||
import { resolveStudentId } from "./seqtaClient";
|
||||
import { peerCloudIdsForPaint } from "./accountsClient";
|
||||
import { fetchSchoolYearEnrollmentSnapshot } from "./timetableYearSnapshot";
|
||||
import { CLASSMATES_TIMETABLE_POLL_MS } from "./constants";
|
||||
import { scheduleClassmatesSyncIfNeeded } from "./syncOrchestrator";
|
||||
import {
|
||||
mountClassmatesToolbarChip,
|
||||
unmountClassmatesToolbarChip,
|
||||
} from "./classmatesToolbarUi";
|
||||
import { maybeResumeTimetableClassmatesOptInPopup } from "./openTimetableClassmatesPopup";
|
||||
|
||||
const timetableClassmatesPlugin: Plugin<typeof timetableClassmatesSettings> = {
|
||||
id: "timetable-classmates",
|
||||
name: "Timetable Classmates",
|
||||
description: "Show opted-in classmates on your timetable via private sync",
|
||||
version: "1.0.0",
|
||||
settings: timetableClassmatesSettings,
|
||||
defaultEnabled: false,
|
||||
styles,
|
||||
|
||||
run: async (api) => {
|
||||
if (isPluginBlockedByPerformanceMode("timetable-classmates")) return () => {};
|
||||
await Promise.all([api.storage.loaded, api.settings.loaded]);
|
||||
void maybeResumeTimetableClassmatesOptInPopup();
|
||||
|
||||
const onSyncMessage = (request: { type?: string }) => {
|
||||
if (request?.type === "timetableClassmatesSync") scheduleClassmatesSyncIfNeeded();
|
||||
return false;
|
||||
};
|
||||
browser.runtime.onMessage.addListener(onSyncMessage);
|
||||
|
||||
let gridObserver: MutationObserver | null = null;
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
let paintTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let painting = false;
|
||||
|
||||
const schedulePaint = () => {
|
||||
if (paintTimer) clearTimeout(paintTimer);
|
||||
paintTimer = setTimeout(() => void paintTimetable(), 120);
|
||||
};
|
||||
|
||||
const paintTimetable = async () => {
|
||||
if (painting) return;
|
||||
painting = true;
|
||||
try {
|
||||
const session = await loadSession();
|
||||
if (!api.settings.enabled || !session.showAvatars) {
|
||||
removeClassmateStacks();
|
||||
return;
|
||||
}
|
||||
|
||||
const page = document.querySelector(".timetablepage");
|
||||
if (!page) return;
|
||||
|
||||
const selfId = await resolveStudentId();
|
||||
if (selfId == null) return;
|
||||
|
||||
const [roster, peopleCache, archived, ciMap, cloudIds] = await Promise.all([
|
||||
loadRosterIndex(),
|
||||
refreshPeopleCacheIfStale(),
|
||||
loadArchivedMembers(),
|
||||
loadCiToClassKey(),
|
||||
peerCloudIdsForPaint(),
|
||||
]);
|
||||
|
||||
const paintHost = (host: HTMLElement, ci: number | null) =>
|
||||
renderClassmateStackForEntry(
|
||||
host,
|
||||
classKeyFromCi(ci, ciMap),
|
||||
roster,
|
||||
peopleCache,
|
||||
selfId,
|
||||
archived,
|
||||
cloudIds,
|
||||
);
|
||||
|
||||
const ciOf = (el: Element | null | undefined) => {
|
||||
const ci = parseInt(el?.getAttribute("data-instance") ?? "", 10);
|
||||
return Number.isNaN(ci) ? null : ci;
|
||||
};
|
||||
|
||||
const paints = [...page.querySelectorAll(".entry.class")].map((entry) =>
|
||||
paintHost(entry as HTMLElement, ciOf(entry)),
|
||||
);
|
||||
|
||||
const quickbar = page.querySelector(".quickbar.visible[data-type='class']");
|
||||
if (quickbar) {
|
||||
const title = quickbar.querySelector(".title")?.textContent?.trim() ?? "";
|
||||
const host =
|
||||
(quickbar.querySelector(".meta") as HTMLElement | null) ?? (quickbar as HTMLElement);
|
||||
paints.push(paintHost(host, ciOf(findClassEntryByTitle(page, title))));
|
||||
}
|
||||
await Promise.all(paints);
|
||||
} finally {
|
||||
painting = false;
|
||||
}
|
||||
};
|
||||
|
||||
const startTimetablePoll = () => {
|
||||
if (pollTimer) return;
|
||||
scheduleClassmatesSyncIfNeeded();
|
||||
pollTimer = setInterval(() => scheduleClassmatesSyncIfNeeded(), CLASSMATES_TIMETABLE_POLL_MS);
|
||||
};
|
||||
|
||||
const handleTimetablePage = async () => {
|
||||
try {
|
||||
await waitForElm(".timetablepage .entry.class", true, 50, 300);
|
||||
} catch {
|
||||
/* entries may appear later */
|
||||
}
|
||||
|
||||
const page = document.querySelector(".timetablepage");
|
||||
if ((await loadSession()).syncOptIn) {
|
||||
void ensureCiToClassKey(() => fetchSchoolYearEnrollmentSnapshot()).catch(() => {});
|
||||
startTimetablePoll();
|
||||
}
|
||||
|
||||
schedulePaint();
|
||||
await paintTimetable();
|
||||
void mountClassmatesToolbarChip();
|
||||
|
||||
if (page && !gridObserver) {
|
||||
gridObserver = new MutationObserver((mutations) => {
|
||||
if (mutations.every(isClassmatesPluginMutation)) return;
|
||||
schedulePaint();
|
||||
});
|
||||
gridObserver.observe(page, { childList: true, subtree: true });
|
||||
|
||||
resizeObserver = new ResizeObserver(() => schedulePaint());
|
||||
resizeObserver.observe(page);
|
||||
}
|
||||
};
|
||||
|
||||
const onUpdated = () => schedulePaint();
|
||||
window.addEventListener(CLASSMATES_UPDATED_EVENT, onUpdated);
|
||||
|
||||
const onClassEntryClick = (e: Event) => {
|
||||
if ((e.target as HTMLElement).closest?.(".timetablepage .entry.class")) schedulePaint();
|
||||
};
|
||||
document.addEventListener("click", onClassEntryClick, true);
|
||||
|
||||
const { unregister: unregisterEnabled } = api.settings.onChange("enabled", schedulePaint);
|
||||
|
||||
const { unregister } = api.seqta.onMount(".timetablepage", handleTimetablePage);
|
||||
if ((await loadSession()).syncOptIn) scheduleClassmatesSyncIfNeeded();
|
||||
|
||||
return () => {
|
||||
unregister();
|
||||
browser.runtime.onMessage.removeListener(onSyncMessage);
|
||||
gridObserver?.disconnect();
|
||||
resizeObserver?.disconnect();
|
||||
if (paintTimer) clearTimeout(paintTimer);
|
||||
if (pollTimer) clearInterval(pollTimer);
|
||||
window.removeEventListener(CLASSMATES_UPDATED_EVENT, onUpdated);
|
||||
document.removeEventListener("click", onClassEntryClick, true);
|
||||
unregisterEnabled();
|
||||
removeClassmateStacks();
|
||||
unmountClassmatesToolbarChip();
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default timetableClassmatesPlugin;
|
||||
@@ -0,0 +1,14 @@
|
||||
import { defineLazyPlugin } from "../../core/dynamicLoader";
|
||||
import { timetableClassmatesSettings } from "./settings";
|
||||
import styles from "./styles.css?inline";
|
||||
|
||||
export default defineLazyPlugin({
|
||||
id: "timetable-classmates",
|
||||
name: "Timetable Classmates",
|
||||
description: "Show opted-in classmates on your timetable via private sync",
|
||||
version: "1.0.0",
|
||||
settings: timetableClassmatesSettings,
|
||||
defaultEnabled: false,
|
||||
styles,
|
||||
loader: () => import("./index"),
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import stringToHTML from "@/seqta/utils/stringToHTML";
|
||||
import { createPopupHeroVideo } from "@/seqta/utils/Openers/attachPopupMediaFullscreen";
|
||||
import { closePopup, openPopup } from "@/seqta/utils/Openers/PopupManager";
|
||||
import { mount, unmount } from "svelte";
|
||||
import TimetableClassmatesOptInPopup from "./TimetableClassmatesOptInPopup.svelte";
|
||||
import TimetableClassmatesOptOutPopup from "./TimetableClassmatesOptOutPopup.svelte";
|
||||
import popupStyles from "./consentPopup.css?inline";
|
||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||
import { loadSession } from "./rosterStore";
|
||||
import {
|
||||
clearResumeOptInAfterCloudLogin,
|
||||
shouldResumeOptInAfterCloudLogin,
|
||||
} from "./optInResume";
|
||||
|
||||
const STYLE_ID = "bsplus-timetable-classmates-popup-styles";
|
||||
const CLASSMATES_VIDEO_URL =
|
||||
"https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Plus/main/src/resources/timetable-classmates-video.webm";
|
||||
|
||||
function ensurePopupStyles(): void {
|
||||
if (document.getElementById(STYLE_ID)) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = STYLE_ID;
|
||||
style.textContent = popupStyles;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
type ConsentPopupOptions = {
|
||||
onDismiss?: () => void;
|
||||
heroVideo?: boolean;
|
||||
};
|
||||
|
||||
function openConsentPopup(
|
||||
title: string,
|
||||
subtitle: string,
|
||||
component: typeof TimetableClassmatesOptInPopup | typeof TimetableClassmatesOptOutPopup,
|
||||
props: Record<string, unknown>,
|
||||
options?: ConsentPopupOptions,
|
||||
): void {
|
||||
if (document.getElementById("whatsnewbk")) return;
|
||||
ensurePopupStyles();
|
||||
|
||||
let app: ReturnType<typeof mount> | null = null;
|
||||
let completed = false;
|
||||
const host = document.createElement("div");
|
||||
host.className = "whatsnewTextContainer bsplus-timetable-classmates-popup-host";
|
||||
|
||||
const header = stringToHTML(/* html */ `
|
||||
<div class="whatsnewHeader"><h1>${title}</h1><p>${subtitle}</p></div>
|
||||
`).firstChild as HTMLElement;
|
||||
|
||||
const hero = options?.heroVideo
|
||||
? createPopupHeroVideo(CLASSMATES_VIDEO_URL, "Timetable classmates preview")
|
||||
: null;
|
||||
|
||||
openPopup({
|
||||
header,
|
||||
content: hero ? [hero, host] : [host],
|
||||
containerClass: "whatsnewContainer--scrollBody",
|
||||
backgroundClass: "bsplus-popup-backdrop--lite",
|
||||
animateSelector: hero
|
||||
? ".whatsnewImgContainer, .bsplus-timetable-classmates-popup-host > *"
|
||||
: ".bsplus-timetable-classmates-popup-host > *",
|
||||
afterClose: () => {
|
||||
if (app) unmount(app);
|
||||
if (!completed) options?.onDismiss?.();
|
||||
},
|
||||
onReady: () => {
|
||||
app = mount(component, {
|
||||
target: host,
|
||||
props: {
|
||||
...props,
|
||||
onCancel: () => void closePopup(),
|
||||
onComplete: () => {
|
||||
completed = true;
|
||||
void closePopup();
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function openTimetableClassmatesOptInPopup(options: {
|
||||
onAccepted: () => void | Promise<void>;
|
||||
onDismiss?: () => void;
|
||||
}): void {
|
||||
openConsentPopup(
|
||||
"Timetable classmates",
|
||||
"Share class lists with opted-in students at your school",
|
||||
TimetableClassmatesOptInPopup,
|
||||
{
|
||||
onAccepted: async () => {
|
||||
clearResumeOptInAfterCloudLogin();
|
||||
await options.onAccepted();
|
||||
},
|
||||
},
|
||||
{
|
||||
onDismiss: () => {
|
||||
clearResumeOptInAfterCloudLogin();
|
||||
options.onDismiss?.();
|
||||
},
|
||||
heroVideo: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function openResumeOptInIfNeeded(): Promise<void> {
|
||||
if (!shouldResumeOptInAfterCloudLogin()) return;
|
||||
if (document.getElementById("whatsnewbk")) return;
|
||||
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return;
|
||||
|
||||
const session = await loadSession();
|
||||
if (session.syncOptIn) {
|
||||
clearResumeOptInAfterCloudLogin();
|
||||
return;
|
||||
}
|
||||
|
||||
openTimetableClassmatesOptInPopup({ onAccepted: () => {} });
|
||||
}
|
||||
|
||||
/** After cloud OAuth refreshes the page, reopen opt-in if the user started sign-in from this flow. */
|
||||
export async function maybeResumeTimetableClassmatesOptInPopup(): Promise<void> {
|
||||
if (!shouldResumeOptInAfterCloudLogin()) return;
|
||||
|
||||
if (await cloudAuth.getStoredToken()) {
|
||||
await openResumeOptInIfNeeded();
|
||||
return;
|
||||
}
|
||||
|
||||
const unsub = cloudAuth.subscribe((state) => {
|
||||
if (!state.isLoggedIn) return;
|
||||
unsub();
|
||||
void openResumeOptInIfNeeded();
|
||||
});
|
||||
}
|
||||
|
||||
export function openTimetableClassmatesOptOutPopup(options: {
|
||||
onConfirmed: () => void | Promise<void>;
|
||||
onDismiss?: () => void;
|
||||
}): void {
|
||||
openConsentPopup(
|
||||
"Stop classmate sharing",
|
||||
"You can turn this back on anytime",
|
||||
TimetableClassmatesOptOutPopup,
|
||||
{ onConfirmed: options.onConfirmed },
|
||||
{ onDismiss: options.onDismiss },
|
||||
);
|
||||
}
|
||||
|
||||
export function openClassmatesRosterPopup(
|
||||
title: string,
|
||||
peers: { displayName: string; initials: string; houseColour?: string }[],
|
||||
): void {
|
||||
if (document.getElementById("whatsnewbk")) return;
|
||||
|
||||
const list = document.createElement("ul");
|
||||
list.className = "bsplus-classmates-roster-list";
|
||||
for (const peer of peers) {
|
||||
const li = document.createElement("li");
|
||||
li.className = "bsplus-classmates-roster-item";
|
||||
const avatar = document.createElement("span");
|
||||
avatar.className = "bsplus-classmates-roster-avatar";
|
||||
if (peer.houseColour) avatar.style.setProperty("--bsplus-house-color", peer.houseColour);
|
||||
avatar.textContent = peer.initials;
|
||||
const name = document.createElement("span");
|
||||
name.className = "bsplus-classmates-roster-name";
|
||||
name.textContent = peer.displayName;
|
||||
li.append(avatar, name);
|
||||
list.append(li);
|
||||
}
|
||||
|
||||
const host = document.createElement("div");
|
||||
host.className = "whatsnewTextContainer bsplus-classmates-roster-popup";
|
||||
host.append(list);
|
||||
|
||||
const header = document.createElement("div");
|
||||
header.className = "whatsnewHeader";
|
||||
const heading = document.createElement("h1");
|
||||
heading.textContent = title;
|
||||
const subtitle = document.createElement("p");
|
||||
subtitle.textContent = `${peers.length} classmate${peers.length === 1 ? "" : "s"} in this class`;
|
||||
header.append(heading, subtitle);
|
||||
|
||||
openPopup({
|
||||
header,
|
||||
content: [host],
|
||||
containerClass: "whatsnewContainer--scrollBody",
|
||||
backgroundClass: "bsplus-popup-backdrop--lite",
|
||||
animateSelector: ".bsplus-classmates-roster-popup",
|
||||
afterClose: () => {},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
const SESSION_KEY = "bsplus-tc-resume-opt-in-after-cloud-login";
|
||||
|
||||
export function markResumeOptInAfterCloudLogin(): void {
|
||||
try {
|
||||
sessionStorage.setItem(SESSION_KEY, "1");
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
}
|
||||
|
||||
export function clearResumeOptInAfterCloudLogin(): void {
|
||||
try {
|
||||
sessionStorage.removeItem(SESSION_KEY);
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
}
|
||||
|
||||
export function shouldResumeOptInAfterCloudLogin(): boolean {
|
||||
try {
|
||||
return sessionStorage.getItem(SESSION_KEY) === "1";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { postSeqtaJson } from "./seqtaClient";
|
||||
import type { PeopleCache } from "./rosterStore";
|
||||
import {
|
||||
loadPeopleCache,
|
||||
loadPeopleCacheFetchedAt,
|
||||
savePeopleCache,
|
||||
savePeopleCacheFetchedAt,
|
||||
} from "./rosterStore";
|
||||
|
||||
const PEOPLE_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
type PeopleApiRow = {
|
||||
id?: number;
|
||||
xx_display?: string;
|
||||
house_colour?: string;
|
||||
};
|
||||
|
||||
export async function refreshPeopleCacheIfStale(): Promise<PeopleCache> {
|
||||
const existing = await loadPeopleCache();
|
||||
const fetchedAt = await loadPeopleCacheFetchedAt();
|
||||
if (fetchedAt != null && Date.now() - fetchedAt < PEOPLE_TTL_MS) return existing;
|
||||
|
||||
const data = await postSeqtaJson<{ payload?: PeopleApiRow[] }>(
|
||||
"/seqta/student/load/message/people",
|
||||
{ mode: "student" },
|
||||
);
|
||||
const rows = Array.isArray(data?.payload) ? data.payload : [];
|
||||
const next: PeopleCache = {};
|
||||
const now = Date.now();
|
||||
for (const row of rows) {
|
||||
if (row.id == null || !row.xx_display) continue;
|
||||
next[String(row.id)] = {
|
||||
xx_display: row.xx_display,
|
||||
house_colour: row.house_colour,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
await savePeopleCache(next);
|
||||
await savePeopleCacheFetchedAt(now);
|
||||
return next;
|
||||
}
|
||||
|
||||
export function displayNameForSeqtaId(cache: PeopleCache, seqtaStudentId: number): string {
|
||||
return cache[String(seqtaStudentId)]?.xx_display ?? `Student ${seqtaStudentId}`;
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import type { RelaySessionResponse } from "./accountsClient";
|
||||
import type { RelayWireBundle } from "./relayCrypto";
|
||||
|
||||
export type RelaySnapshotShare = {
|
||||
seqta_student_id: number;
|
||||
cloud_user_id: string;
|
||||
share_code: string;
|
||||
period: { from: string; until: string };
|
||||
updated_at: number;
|
||||
bundles: RelayWireBundle[];
|
||||
};
|
||||
|
||||
const RELAY_TIMEOUT_MS = 45_000;
|
||||
|
||||
function wsConnectUrl(session: RelaySessionResponse, instanceHost: string): string {
|
||||
const base = session.ws_url.replace(/^http/, "ws");
|
||||
const q = new URLSearchParams({
|
||||
instance_host: instanceHost,
|
||||
relay_token: session.relay_token,
|
||||
});
|
||||
return `${base}?${q.toString()}`;
|
||||
}
|
||||
|
||||
export type RelaySyncHandlers = {
|
||||
onSnapshot: (shares: RelaySnapshotShare[]) => void | Promise<void>;
|
||||
buildPublish: () => Promise<{
|
||||
period: { from: string; until: string };
|
||||
bundles: RelayWireBundle[];
|
||||
}>;
|
||||
};
|
||||
|
||||
export async function runRelayRoundTrip(
|
||||
instanceHost: string,
|
||||
session: RelaySessionResponse,
|
||||
handlers: RelaySyncHandlers,
|
||||
): Promise<{ ok: boolean; error?: string }> {
|
||||
return await new Promise((resolve) => {
|
||||
let settled = false;
|
||||
let published = false;
|
||||
let snapshotCount = 0;
|
||||
|
||||
const finish = (result: { ok: boolean; error?: string }) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
try {
|
||||
ws.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
const url = wsConnectUrl(session, instanceHost);
|
||||
const ws = new WebSocket(url);
|
||||
const timer = setTimeout(() => finish({ ok: false, error: "Relay connection timed out" }), RELAY_TIMEOUT_MS);
|
||||
|
||||
ws.addEventListener("message", (event) => {
|
||||
void (async () => {
|
||||
try {
|
||||
const msg = JSON.parse(String(event.data)) as {
|
||||
v?: number;
|
||||
type?: string;
|
||||
shares?: RelaySnapshotShare[];
|
||||
message?: string;
|
||||
};
|
||||
if (msg.v !== 1) return;
|
||||
if (msg.type === "error") {
|
||||
finish({ ok: false, error: msg.message ?? "Relay error" });
|
||||
return;
|
||||
}
|
||||
if (msg.type !== "snapshot" || !Array.isArray(msg.shares)) return;
|
||||
|
||||
snapshotCount += 1;
|
||||
await handlers.onSnapshot(msg.shares);
|
||||
|
||||
if (!published) {
|
||||
published = true;
|
||||
const publish = await handlers.buildPublish();
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
v: 1,
|
||||
type: "publish",
|
||||
period: publish.period,
|
||||
bundles: publish.bundles,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (snapshotCount >= 2) {
|
||||
finish({ ok: true });
|
||||
}
|
||||
} catch {
|
||||
finish({ ok: false, error: "Invalid relay message" });
|
||||
}
|
||||
})();
|
||||
});
|
||||
|
||||
ws.addEventListener("error", () => finish({ ok: false, error: "Relay WebSocket error" }));
|
||||
ws.addEventListener("close", () => {
|
||||
if (!settled) finish({ ok: false, error: "Relay closed before sync completed" });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function sendRelayRevoke(
|
||||
instanceHost: string,
|
||||
session: RelaySessionResponse,
|
||||
): Promise<void> {
|
||||
await new Promise<void>((resolve) => {
|
||||
const ws = new WebSocket(wsConnectUrl(session, instanceHost));
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
ws.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
resolve();
|
||||
}, 8_000);
|
||||
|
||||
ws.addEventListener("open", () => {
|
||||
ws.send(JSON.stringify({ v: 1, type: "revoke" }));
|
||||
});
|
||||
ws.addEventListener("message", () => {
|
||||
clearTimeout(timer);
|
||||
try {
|
||||
ws.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
ws.addEventListener("error", () => {
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { classRosterKey, type ClassRef } from "./classKeys";
|
||||
import { classBundlePlaintext } from "./relayPayload";
|
||||
|
||||
const IV_BYTES = 12;
|
||||
|
||||
function base64FromBytes(bytes: Uint8Array): string {
|
||||
let binary = "";
|
||||
for (const b of bytes) binary += String.fromCharCode(b);
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
export function decodeBundleKey(bundleKeyB64: string): Uint8Array {
|
||||
const binary = atob(bundleKeyB64);
|
||||
const out = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
||||
return out;
|
||||
}
|
||||
|
||||
async function sha256(data: Uint8Array): Promise<Uint8Array> {
|
||||
const hash = await crypto.subtle.digest("SHA-256", data);
|
||||
return new Uint8Array(hash);
|
||||
}
|
||||
|
||||
async function classAesKey(bundleKey: Uint8Array, classKey: string): Promise<CryptoKey> {
|
||||
const prefix = new TextEncoder().encode(`tq-v1:${classKey}`);
|
||||
const material = new Uint8Array(bundleKey.length + 1 + prefix.length);
|
||||
material.set(bundleKey, 0);
|
||||
material.set([0x7c], bundleKey.length);
|
||||
material.set(prefix, bundleKey.length + 1);
|
||||
const raw = await sha256(material);
|
||||
return crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt", "decrypt"]);
|
||||
}
|
||||
|
||||
async function compressUtf8(json: string): Promise<Uint8Array> {
|
||||
const input = new TextEncoder().encode(json);
|
||||
if (typeof CompressionStream === "undefined") return input;
|
||||
const stream = new Blob([input]).stream().pipeThrough(new CompressionStream("deflate"));
|
||||
const buf = await new Response(stream).arrayBuffer();
|
||||
return new Uint8Array(buf);
|
||||
}
|
||||
|
||||
async function decompressUtf8(bytes: Uint8Array): Promise<string> {
|
||||
if (typeof DecompressionStream === "undefined") {
|
||||
return new TextDecoder().decode(bytes);
|
||||
}
|
||||
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate"));
|
||||
const buf = await new Response(stream).arrayBuffer();
|
||||
return new TextDecoder().decode(buf);
|
||||
}
|
||||
|
||||
export type RelayWireBundle = {
|
||||
class_key: string;
|
||||
iv_b64: string;
|
||||
ct_b64: string;
|
||||
};
|
||||
|
||||
export async function encryptClassBundle(
|
||||
bundleKey: Uint8Array,
|
||||
classKey: string,
|
||||
plaintext: Record<string, unknown>,
|
||||
): Promise<RelayWireBundle> {
|
||||
const key = await classAesKey(bundleKey, classKey);
|
||||
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
|
||||
const compressed = await compressUtf8(JSON.stringify(plaintext));
|
||||
const ct = new Uint8Array(
|
||||
await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, compressed),
|
||||
);
|
||||
return {
|
||||
class_key: classKey,
|
||||
iv_b64: base64FromBytes(iv),
|
||||
ct_b64: base64FromBytes(ct),
|
||||
};
|
||||
}
|
||||
|
||||
export async function decryptClassBundle(
|
||||
bundleKey: Uint8Array,
|
||||
bundle: RelayWireBundle,
|
||||
): Promise<Record<string, unknown> | null> {
|
||||
try {
|
||||
const key = await classAesKey(bundleKey, bundle.class_key);
|
||||
const iv = Uint8Array.from(atob(bundle.iv_b64), (c) => c.charCodeAt(0));
|
||||
const ct = Uint8Array.from(atob(bundle.ct_b64), (c) => c.charCodeAt(0));
|
||||
const plain = new Uint8Array(
|
||||
await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ct),
|
||||
);
|
||||
const json = await decompressUtf8(plain);
|
||||
return JSON.parse(json) as Record<string, unknown>;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function buildEncryptedBundlesForClasses(input: {
|
||||
bundleKey: Uint8Array;
|
||||
seqtaStudentId: number;
|
||||
personUuid: string;
|
||||
cloudUserId: string | null;
|
||||
classes: ClassRef[];
|
||||
}): Promise<RelayWireBundle[]> {
|
||||
const seen = new Set<string>();
|
||||
const bundles: RelayWireBundle[] = [];
|
||||
for (const ref of input.classes) {
|
||||
const classKey = classRosterKey(ref);
|
||||
if (!classKey || seen.has(classKey)) continue;
|
||||
seen.add(classKey);
|
||||
const plaintext = classBundlePlaintext({
|
||||
seqtaStudentId: input.seqtaStudentId,
|
||||
personUuid: input.personUuid,
|
||||
cloudUserId: input.cloudUserId,
|
||||
classRef: ref,
|
||||
});
|
||||
bundles.push(await encryptClassBundle(input.bundleKey, classKey, plaintext));
|
||||
}
|
||||
return bundles;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { ClassRef } from "./classKeys";
|
||||
|
||||
export type TimetableSharePlainV1 = {
|
||||
v: 1;
|
||||
instance: string;
|
||||
sender: {
|
||||
seqtaId: number;
|
||||
personUuid: string;
|
||||
cloudUserId: string | null;
|
||||
};
|
||||
period: { from: string; until: string };
|
||||
classes: ClassRef[];
|
||||
};
|
||||
|
||||
const MAX_CLASSES = 400;
|
||||
|
||||
export function buildSharePayload(input: {
|
||||
instance: string;
|
||||
sender: TimetableSharePlainV1["sender"];
|
||||
period: TimetableSharePlainV1["period"];
|
||||
classes: ClassRef[];
|
||||
}): TimetableSharePlainV1 {
|
||||
return {
|
||||
v: 1,
|
||||
instance: input.instance,
|
||||
sender: input.sender,
|
||||
period: input.period,
|
||||
classes: input.classes.slice(0, MAX_CLASSES),
|
||||
};
|
||||
}
|
||||
|
||||
/** One class per bundle ciphertext on the relay. */
|
||||
export function classBundlePlaintext(input: {
|
||||
seqtaStudentId: number;
|
||||
personUuid: string;
|
||||
cloudUserId: string | null;
|
||||
classRef: ClassRef;
|
||||
}): Record<string, unknown> {
|
||||
return {
|
||||
v: 1,
|
||||
seqta_student_id: input.seqtaStudentId,
|
||||
person_uuid: input.personUuid,
|
||||
cloud_user_id: input.cloudUserId,
|
||||
class: input.classRef,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { TimetableSharePlainV1 } from "./relayPayload";
|
||||
import { classRosterKey, classRefsFromTimetableItems } from "./classKeys";
|
||||
|
||||
export type RosterMember = {
|
||||
seqtaStudentId: number;
|
||||
personUuid?: string;
|
||||
cloudUserId?: string | null;
|
||||
updatedAt: number;
|
||||
};
|
||||
|
||||
export type ClassRosterIndex = Record<string, Record<string, RosterMember>>;
|
||||
|
||||
export function emptyRosterIndex(): ClassRosterIndex {
|
||||
return {};
|
||||
}
|
||||
|
||||
export function mergePayloadIntoRoster(
|
||||
index: ClassRosterIndex,
|
||||
payload: TimetableSharePlainV1,
|
||||
allowedSeqtaIds: ReadonlySet<number>,
|
||||
): ClassRosterIndex {
|
||||
const senderId = payload.sender.seqtaId;
|
||||
if (!allowedSeqtaIds.has(senderId)) return index;
|
||||
|
||||
let next: ClassRosterIndex = { ...index };
|
||||
const refs = classRefsFromTimetableItems(payload.classes);
|
||||
const updatedAt = Date.now();
|
||||
const member: RosterMember = {
|
||||
seqtaStudentId: senderId,
|
||||
personUuid: payload.sender.personUuid,
|
||||
cloudUserId: payload.sender.cloudUserId,
|
||||
updatedAt,
|
||||
};
|
||||
|
||||
for (const ref of refs) {
|
||||
const key = classRosterKey(ref);
|
||||
if (!key) continue;
|
||||
const bucket = { ...(next[key] ?? {}) };
|
||||
bucket[String(senderId)] = member;
|
||||
next[key] = bucket;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export type ArchivedMembers = Record<string, { archivedAt: number }>;
|
||||
|
||||
export function removeMemberFromRoster(
|
||||
index: ClassRosterIndex,
|
||||
seqtaStudentId: number,
|
||||
): ClassRosterIndex {
|
||||
const id = String(seqtaStudentId);
|
||||
const next: ClassRosterIndex = {};
|
||||
for (const [classKey, bucket] of Object.entries(index)) {
|
||||
if (!bucket[id]) {
|
||||
next[classKey] = bucket;
|
||||
continue;
|
||||
}
|
||||
const copy = { ...bucket };
|
||||
delete copy[id];
|
||||
if (Object.keys(copy).length > 0) next[classKey] = copy;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function archiveMember(
|
||||
archived: ArchivedMembers,
|
||||
seqtaStudentId: number,
|
||||
): ArchivedMembers {
|
||||
return {
|
||||
...archived,
|
||||
[String(seqtaStudentId)]: { archivedAt: Date.now() },
|
||||
};
|
||||
}
|
||||
|
||||
export function isMemberArchived(
|
||||
archived: ArchivedMembers,
|
||||
seqtaStudentId: number,
|
||||
): boolean {
|
||||
return Boolean(archived[String(seqtaStudentId)]);
|
||||
}
|
||||
|
||||
export function rosterPeersForClass(
|
||||
index: ClassRosterIndex,
|
||||
classKey: string,
|
||||
archived: ArchivedMembers = {},
|
||||
): RosterMember[] {
|
||||
const bucket = index[classKey];
|
||||
if (!bucket) return [];
|
||||
return Object.values(bucket).filter(
|
||||
(m) => !isMemberArchived(archived, m.seqtaStudentId),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import localforage, { type LocalForage } from "localforage";
|
||||
import { getInstanceHostname } from "@/seqta/utils/feedback/client";
|
||||
import type { ArchivedMembers, ClassRosterIndex } from "./rosterMerge";
|
||||
import { resolveStudentId } from "./seqtaClient";
|
||||
import { TIMETABLE_CLASSMATES_CONSENT_VERSION } from "./constants";
|
||||
|
||||
const ROSTER_KEY = "classRosterIndex";
|
||||
const PEOPLE_CACHE_KEY = "peopleCache";
|
||||
const PEOPLE_CACHE_FETCHED_AT_KEY = "peopleCacheFetchedAt";
|
||||
const CI_MAP_KEY = "ciToClassKey";
|
||||
const ARCHIVED_KEY = "archivedMembers";
|
||||
const SESSION_KEY = "session";
|
||||
|
||||
const storeCache = new Map<string, LocalForage>();
|
||||
|
||||
export type PeopleCacheEntry = {
|
||||
xx_display: string;
|
||||
house_colour?: string;
|
||||
updatedAt: number;
|
||||
};
|
||||
|
||||
export type PeopleCache = Record<string, PeopleCacheEntry>;
|
||||
|
||||
export type ClassmatesSession = {
|
||||
showAvatars: boolean;
|
||||
syncOptIn: boolean;
|
||||
consentAt?: number;
|
||||
consentVersion?: number;
|
||||
lastSyncAt?: number;
|
||||
lastPeerCount?: number;
|
||||
lastHeartbeatAt?: number;
|
||||
lastPublishedEnrollmentHash?: string;
|
||||
};
|
||||
|
||||
const defaultSession = (): ClassmatesSession => ({
|
||||
showAvatars: false,
|
||||
syncOptIn: false,
|
||||
});
|
||||
|
||||
export async function resolveClassmatesScope(): Promise<string | null> {
|
||||
const host = getInstanceHostname()?.toLowerCase();
|
||||
const studentId = await resolveStudentId();
|
||||
if (!host || studentId == null) return null;
|
||||
return `${host}#${studentId}`;
|
||||
}
|
||||
|
||||
function storeNameForScope(scope: string): string {
|
||||
return scope.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 72);
|
||||
}
|
||||
|
||||
function storeForScope(scope: string): LocalForage {
|
||||
const name = storeNameForScope(scope);
|
||||
let instance = storeCache.get(name);
|
||||
if (!instance) {
|
||||
instance = localforage.createInstance({
|
||||
name: "timetable-classmates",
|
||||
storeName: name,
|
||||
});
|
||||
storeCache.set(name, instance);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
async function scopedStore(): Promise<LocalForage | null> {
|
||||
const scope = await resolveClassmatesScope();
|
||||
if (!scope) return null;
|
||||
return storeForScope(scope);
|
||||
}
|
||||
|
||||
export async function loadSession(): Promise<ClassmatesSession> {
|
||||
const store = await scopedStore();
|
||||
if (!store) return defaultSession();
|
||||
const data = await store.getItem<ClassmatesSession>(SESSION_KEY);
|
||||
if (!data || typeof data !== "object") return defaultSession();
|
||||
return {
|
||||
...defaultSession(),
|
||||
...data,
|
||||
};
|
||||
}
|
||||
|
||||
export async function saveSession(session: ClassmatesSession): Promise<void> {
|
||||
const store = await scopedStore();
|
||||
if (!store) return;
|
||||
await store.setItem(SESSION_KEY, session);
|
||||
}
|
||||
|
||||
export async function patchSession(patch: Partial<ClassmatesSession>): Promise<ClassmatesSession> {
|
||||
const next = { ...(await loadSession()), ...patch };
|
||||
await saveSession(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
export async function loadRosterIndex(): Promise<ClassRosterIndex> {
|
||||
const store = await scopedStore();
|
||||
if (!store) return {};
|
||||
const data = await store.getItem<ClassRosterIndex>(ROSTER_KEY);
|
||||
return data && typeof data === "object" ? data : {};
|
||||
}
|
||||
|
||||
export async function saveRosterIndex(index: ClassRosterIndex): Promise<void> {
|
||||
const store = await scopedStore();
|
||||
if (!store) return;
|
||||
await store.setItem(ROSTER_KEY, index);
|
||||
}
|
||||
|
||||
export async function loadPeopleCache(): Promise<PeopleCache> {
|
||||
const store = await scopedStore();
|
||||
if (!store) return {};
|
||||
const data = await store.getItem<PeopleCache>(PEOPLE_CACHE_KEY);
|
||||
return data && typeof data === "object" ? data : {};
|
||||
}
|
||||
|
||||
export async function savePeopleCache(cache: PeopleCache): Promise<void> {
|
||||
const store = await scopedStore();
|
||||
if (!store) return;
|
||||
await store.setItem(PEOPLE_CACHE_KEY, cache);
|
||||
}
|
||||
|
||||
export async function loadPeopleCacheFetchedAt(): Promise<number | null> {
|
||||
const store = await scopedStore();
|
||||
if (!store) return null;
|
||||
const at = await store.getItem<number>(PEOPLE_CACHE_FETCHED_AT_KEY);
|
||||
return typeof at === "number" ? at : null;
|
||||
}
|
||||
|
||||
export async function savePeopleCacheFetchedAt(at: number): Promise<void> {
|
||||
const store = await scopedStore();
|
||||
if (!store) return;
|
||||
await store.setItem(PEOPLE_CACHE_FETCHED_AT_KEY, at);
|
||||
}
|
||||
|
||||
export async function loadCiToClassKey(): Promise<Record<string, string>> {
|
||||
const store = await scopedStore();
|
||||
if (!store) return {};
|
||||
const data = await store.getItem<Record<string, string>>(CI_MAP_KEY);
|
||||
return data && typeof data === "object" ? data : {};
|
||||
}
|
||||
|
||||
export async function saveCiToClassKey(map: Record<string, string>): Promise<void> {
|
||||
const store = await scopedStore();
|
||||
if (!store) return;
|
||||
await store.setItem(CI_MAP_KEY, map);
|
||||
}
|
||||
|
||||
/** Ensures timetable `data-instance` → roster class keys exist for painting. */
|
||||
export async function ensureCiToClassKey(
|
||||
loader: () => Promise<{ ciToClassKey: Record<string, string> }>,
|
||||
): Promise<Record<string, string>> {
|
||||
const existing = await loadCiToClassKey();
|
||||
if (Object.keys(existing).length > 0) return existing;
|
||||
try {
|
||||
const { ciToClassKey } = await loader();
|
||||
if (Object.keys(ciToClassKey).length > 0) {
|
||||
await saveCiToClassKey(ciToClassKey);
|
||||
return ciToClassKey;
|
||||
}
|
||||
} catch {
|
||||
/* SEQTA timetable fetch may fail off-week */
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
export async function loadArchivedMembers(): Promise<ArchivedMembers> {
|
||||
const store = await scopedStore();
|
||||
if (!store) return {};
|
||||
const data = await store.getItem<ArchivedMembers>(ARCHIVED_KEY);
|
||||
return data && typeof data === "object" ? data : {};
|
||||
}
|
||||
|
||||
export async function saveArchivedMembers(archived: ArchivedMembers): Promise<void> {
|
||||
const store = await scopedStore();
|
||||
if (!store) return;
|
||||
await store.setItem(ARCHIVED_KEY, archived);
|
||||
}
|
||||
|
||||
export async function recordConsent(): Promise<void> {
|
||||
await patchSession({
|
||||
consentAt: Date.now(),
|
||||
consentVersion: TIMETABLE_CLASSMATES_CONSENT_VERSION,
|
||||
});
|
||||
}
|
||||
|
||||
export const CLASSMATES_UPDATED_EVENT = "timetable-classmates-updated";
|
||||
|
||||
export function notifyClassmatesUpdated(): void {
|
||||
window.dispatchEvent(new CustomEvent(CLASSMATES_UPDATED_EVENT));
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
export type SeqtaLoginPayload = {
|
||||
id?: number;
|
||||
student?: number;
|
||||
personUUID?: string;
|
||||
type?: string;
|
||||
userDesc?: string;
|
||||
};
|
||||
|
||||
let cachedLogin: SeqtaLoginPayload | null = null;
|
||||
|
||||
export async function postSeqtaJson<T>(
|
||||
path: string,
|
||||
body: Record<string, unknown>,
|
||||
): Promise<T> {
|
||||
const res = await fetch(`${location.origin}${path}`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
Accept: "text/javascript, text/html, application/xml, text/xml, */*",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) throw new Error(`SEQTA request failed (${res.status})`);
|
||||
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 uuid = payload?.personUUID;
|
||||
return typeof uuid === "string" && uuid.length > 0 ? uuid : undefined;
|
||||
}
|
||||
|
||||
export type TimetableApiItem = {
|
||||
date?: string;
|
||||
from?: string;
|
||||
until?: string;
|
||||
description?: string;
|
||||
code?: string;
|
||||
metaID?: number;
|
||||
programmeID?: number;
|
||||
ci?: number;
|
||||
type?: string;
|
||||
};
|
||||
|
||||
export async function fetchStudentTimetableItems(
|
||||
from: string,
|
||||
until: string,
|
||||
): Promise<TimetableApiItem[]> {
|
||||
const studentId = await resolveStudentId();
|
||||
const body: Record<string, unknown> = { from, until };
|
||||
if (studentId != null) body.student = studentId;
|
||||
const data = await postSeqtaJson<{ payload?: { items?: TimetableApiItem[] } }>(
|
||||
"/seqta/student/load/timetable?",
|
||||
body,
|
||||
);
|
||||
return Array.isArray(data?.payload?.items) ? data.payload.items : [];
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { booleanSetting, componentSetting, defineSettings } from "@/plugins/core/settingsHelpers";
|
||||
import TimetableClassmatesAvatarsSwitch from "./TimetableClassmatesAvatarsSwitch.svelte";
|
||||
import TimetableClassmatesSharing from "./TimetableClassmatesSharing.svelte";
|
||||
|
||||
export const timetableClassmatesSettings = defineSettings({
|
||||
enabled: booleanSetting({
|
||||
default: false,
|
||||
title: "Enable timetable classmates",
|
||||
description: "Show opted-in classmates on your timetable via private sync",
|
||||
}),
|
||||
showAvatars: componentSetting({
|
||||
title: "Show classmate avatars",
|
||||
description: "Display avatar stacks on lessons (saved per SEQTA site and student on this device)",
|
||||
component: TimetableClassmatesAvatarsSwitch,
|
||||
}),
|
||||
sharing: componentSetting({
|
||||
title: "Classmate sharing",
|
||||
description:
|
||||
"Encrypted class enrollments sync through BetterSEQTA Cloud. Your full timetable is never stored on our servers.",
|
||||
component: TimetableClassmatesSharing,
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
.bsplus-classmate-stack {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 2px;
|
||||
flex-wrap: nowrap;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.bsplus-classmate-stack .bsplus-classmate-avatar {
|
||||
pointer-events: auto;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.bsplus-classmate-avatar--overflow {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.timetablepage .entry.class:has(> .bsplus-classmate-stack),
|
||||
.timetablepage .quickbar .meta:has(> .bsplus-classmate-stack) {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.timetablepage .entry.class:has(> .bsplus-classmate-stack) {
|
||||
column-gap: 4px;
|
||||
}
|
||||
|
||||
.timetablepage .quickbar .meta:has(> .bsplus-classmate-stack) {
|
||||
column-gap: 6px;
|
||||
}
|
||||
|
||||
.timetablepage .entry.class:has(> .bsplus-classmate-stack) > :not(.bsplus-classmate-stack),
|
||||
.timetablepage .quickbar .meta:has(> .bsplus-classmate-stack) > :not(.bsplus-classmate-stack) {
|
||||
grid-column: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.timetablepage .entry.class:has(> .bsplus-classmate-stack) > .bsplus-classmate-stack,
|
||||
.timetablepage .quickbar .meta:has(> .bsplus-classmate-stack) > .bsplus-classmate-stack {
|
||||
grid-column: 2;
|
||||
grid-row: 1 / -1;
|
||||
align-self: center;
|
||||
justify-self: end;
|
||||
}
|
||||
|
||||
.timetablepage .entry.class {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.bsplus-classmate-avatar {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 9999px;
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
border: 1px solid var(--bsplus-house-color, rgba(255, 255, 255, 0.35));
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
.bsplus-classmate-avatar img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.bsplus-classmate-avatar-placeholder {
|
||||
font-size: 9px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.bsplus-classmate-avatar--overflow .bsplus-classmate-avatar-placeholder {
|
||||
font-size: 8px;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.bsplus-classmates-roster-popup {
|
||||
text-align: left;
|
||||
max-height: min(60vh, 420px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.bsplus-classmates-roster-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.bsplus-classmates-roster-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.65rem;
|
||||
padding: 0.35rem 0.25rem;
|
||||
}
|
||||
|
||||
.bsplus-classmates-roster-avatar {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 9999px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
border: 1px solid var(--bsplus-house-color, rgba(255, 255, 255, 0.35));
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.bsplus-classmates-roster-name {
|
||||
font-size: 0.95rem;
|
||||
line-height: 1.3;
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import { getInstanceHostname } from "@/seqta/utils/feedback/client";
|
||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||
import {
|
||||
deleteOptIn,
|
||||
fetchPeers,
|
||||
fetchRelaySession,
|
||||
postHeartbeat,
|
||||
putOptIn,
|
||||
rememberPeerCloudIds,
|
||||
} from "./accountsClient";
|
||||
import {
|
||||
archiveMember,
|
||||
mergePayloadIntoRoster,
|
||||
removeMemberFromRoster,
|
||||
} from "./rosterMerge";
|
||||
import {
|
||||
loadArchivedMembers,
|
||||
loadRosterIndex,
|
||||
loadSession,
|
||||
notifyClassmatesUpdated,
|
||||
patchSession,
|
||||
recordConsent,
|
||||
resolveClassmatesScope,
|
||||
saveArchivedMembers,
|
||||
saveCiToClassKey,
|
||||
saveRosterIndex,
|
||||
} from "./rosterStore";
|
||||
import { setScopeSyncOptIn } from "./syncScopes";
|
||||
import {
|
||||
cloudUserIdFromAccessToken,
|
||||
heartbeatIdentityFields,
|
||||
optInIdentityDigest,
|
||||
} from "./identityBinding";
|
||||
import { resolvePersonUuid, resolveStudentId } from "./seqtaClient";
|
||||
import {
|
||||
fetchSchoolYearEnrollmentSnapshot,
|
||||
fingerprintEnrollment,
|
||||
type EnrollmentSnapshot,
|
||||
} from "./timetableYearSnapshot";
|
||||
import { buildEncryptedBundlesForClasses, decodeBundleKey, decryptClassBundle } from "./relayCrypto";
|
||||
import { buildSharePayload } from "./relayPayload";
|
||||
import { runRelayRoundTrip, sendRelayRevoke, type RelaySnapshotShare } from "./relayClient";
|
||||
import type { ClassRef } from "./classKeys";
|
||||
import { CLASSMATES_PEER_REFRESH_MS } from "./constants";
|
||||
|
||||
const HEARTBEAT_MIN_MS = 15 * 60 * 1000;
|
||||
|
||||
export type SyncRunResult = { ok: boolean; error?: string; peers?: number };
|
||||
|
||||
let syncChain: Promise<void> = Promise.resolve();
|
||||
|
||||
export function scheduleClassmatesSyncIfNeeded(force = false): void {
|
||||
syncChain = syncChain
|
||||
.then(() => runClassmatesSyncIfNeeded(force))
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
async function runClassmatesSyncIfNeeded(force = false): Promise<void> {
|
||||
const session = await loadSession();
|
||||
if (!session.syncOptIn) return;
|
||||
|
||||
let yearSnap: EnrollmentSnapshot | undefined;
|
||||
if (!force) {
|
||||
const stale =
|
||||
!session.lastSyncAt || Date.now() - session.lastSyncAt > CLASSMATES_PEER_REFRESH_MS;
|
||||
if (!stale) {
|
||||
try {
|
||||
yearSnap = await fetchSchoolYearEnrollmentSnapshot();
|
||||
if (fingerprintEnrollment(yearSnap) === session.lastPublishedEnrollmentHash) return;
|
||||
} catch {
|
||||
/* fetch failed — try full sync */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await runTimetableClassmatesSync(yearSnap);
|
||||
}
|
||||
|
||||
async function resolveCloudUserIdForBinding(): Promise<string | null> {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
const fromToken =
|
||||
typeof bsplus_token === "string" ? cloudUserIdFromAccessToken(bsplus_token) : null;
|
||||
return fromToken ?? cloudAuth.state.user?.id ?? null;
|
||||
}
|
||||
|
||||
export async function registerOptIn(): Promise<{ ok: boolean; error?: string }> {
|
||||
const instanceHost = getInstanceHostname();
|
||||
if (!instanceHost) return { ok: false, error: "Open SEQTA on your school site first." };
|
||||
const cloudUserId = await resolveCloudUserIdForBinding();
|
||||
if (!cloudAuth.state.isLoggedIn || !cloudUserId) {
|
||||
return { ok: false, error: "Sign in to BetterSEQTA Cloud to opt in." };
|
||||
}
|
||||
const body = await optInIdentityDigest(instanceHost, cloudUserId);
|
||||
if (!body) return { ok: false, error: "Could not read your SEQTA login." };
|
||||
await recordConsent();
|
||||
const res = await putOptIn(body);
|
||||
if (!res.ok) return res;
|
||||
const scope = await resolveClassmatesScope();
|
||||
if (scope) await setScopeSyncOptIn(scope, true);
|
||||
await patchSession({ syncOptIn: true, showAvatars: true });
|
||||
const sync = await runTimetableClassmatesSync();
|
||||
if (!sync.ok) {
|
||||
return { ok: true, error: sync.error ?? "Opt-in saved but initial sync failed." };
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
export async function revokeOptIn(): Promise<{ ok: boolean; error?: string }> {
|
||||
const instanceHost = getInstanceHostname();
|
||||
|
||||
if (instanceHost && cloudAuth.state.isLoggedIn) {
|
||||
const session = await fetchRelaySession(instanceHost);
|
||||
if (session) {
|
||||
try {
|
||||
await sendRelayRevoke(instanceHost, session);
|
||||
} catch {
|
||||
/* best-effort */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (instanceHost) {
|
||||
const res = await deleteOptIn(instanceHost);
|
||||
if (!res.ok) return res;
|
||||
}
|
||||
|
||||
const seqtaId = await resolveStudentId();
|
||||
if (seqtaId != null) {
|
||||
const [index, archived] = await Promise.all([loadRosterIndex(), loadArchivedMembers()]);
|
||||
await Promise.all([
|
||||
saveRosterIndex(removeMemberFromRoster(index, seqtaId)),
|
||||
saveArchivedMembers(archiveMember(archived, seqtaId)),
|
||||
]);
|
||||
}
|
||||
|
||||
const scope = await resolveClassmatesScope();
|
||||
if (scope) await setScopeSyncOptIn(scope, false);
|
||||
await patchSession({
|
||||
syncOptIn: false,
|
||||
lastSyncAt: undefined,
|
||||
lastPeerCount: undefined,
|
||||
lastPublishedEnrollmentHash: undefined,
|
||||
});
|
||||
|
||||
notifyClassmatesUpdated();
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
async function maybeHeartbeat(instanceHost: string): Promise<void> {
|
||||
const session = await loadSession();
|
||||
if (session.lastHeartbeatAt && Date.now() - session.lastHeartbeatAt < HEARTBEAT_MIN_MS) return;
|
||||
|
||||
const cloudUserId = await resolveCloudUserIdForBinding();
|
||||
if (!cloudUserId) return;
|
||||
const binding = await heartbeatIdentityFields(instanceHost, cloudUserId);
|
||||
if (!binding) return;
|
||||
|
||||
await postHeartbeat(binding);
|
||||
await patchSession({ lastHeartbeatAt: Date.now() });
|
||||
}
|
||||
|
||||
async function applyRelaySnapshot(
|
||||
instanceHost: string,
|
||||
shares: RelaySnapshotShare[],
|
||||
bundleKey: Uint8Array,
|
||||
allowedSeqtaIds: ReadonlySet<number>,
|
||||
): Promise<void> {
|
||||
let index = await loadRosterIndex();
|
||||
|
||||
for (const share of shares) {
|
||||
if (!allowedSeqtaIds.has(share.seqta_student_id)) continue;
|
||||
|
||||
const classes: ClassRef[] = [];
|
||||
let personUuid = "";
|
||||
let cloudUserId: string | null = share.cloud_user_id;
|
||||
|
||||
for (const bundle of share.bundles) {
|
||||
const plain = await decryptClassBundle(bundleKey, bundle);
|
||||
if (!plain) continue;
|
||||
const cls = plain.class as ClassRef | undefined;
|
||||
if (cls) classes.push(cls);
|
||||
if (typeof plain.person_uuid === "string") personUuid = plain.person_uuid;
|
||||
if (typeof plain.cloud_user_id === "string") cloudUserId = plain.cloud_user_id;
|
||||
}
|
||||
|
||||
if (classes.length === 0) continue;
|
||||
|
||||
index = mergePayloadIntoRoster(
|
||||
index,
|
||||
buildSharePayload({
|
||||
instance: instanceHost,
|
||||
sender: {
|
||||
seqtaId: share.seqta_student_id,
|
||||
personUuid,
|
||||
cloudUserId: cloudUserId ?? share.cloud_user_id,
|
||||
},
|
||||
period: share.period,
|
||||
classes,
|
||||
}),
|
||||
allowedSeqtaIds,
|
||||
);
|
||||
}
|
||||
|
||||
await saveRosterIndex(index);
|
||||
}
|
||||
|
||||
export async function runTimetableClassmatesSync(
|
||||
preloadedYear?: EnrollmentSnapshot,
|
||||
): Promise<SyncRunResult> {
|
||||
const instanceHost = getInstanceHostname();
|
||||
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 personUuid = await resolvePersonUuid();
|
||||
if (seqtaId == null || !personUuid) return { ok: false, error: "SEQTA login required" };
|
||||
|
||||
await maybeHeartbeat(instanceHost);
|
||||
|
||||
const peersData = await fetchPeers(instanceHost);
|
||||
if (!peersData) return { ok: false, error: "Not opted in on this school" };
|
||||
rememberPeerCloudIds(peersData);
|
||||
|
||||
const allowed = new Set<number>([peersData.self.seqta_student_id]);
|
||||
for (const p of peersData.peers) allowed.add(p.seqta_student_id);
|
||||
|
||||
const yearSnap = preloadedYear ?? (await fetchSchoolYearEnrollmentSnapshot());
|
||||
await saveCiToClassKey(yearSnap.ciToClassKey);
|
||||
|
||||
const relaySession = await fetchRelaySession(instanceHost);
|
||||
if (!relaySession) return { ok: false, error: "Relay unavailable — update accounts worker" };
|
||||
|
||||
const bundleKey = decodeBundleKey(relaySession.bundle_key_b64);
|
||||
const cloudUserId = await resolveCloudUserIdForBinding();
|
||||
|
||||
const relayResult = await runRelayRoundTrip(instanceHost, relaySession, {
|
||||
onSnapshot: (shares) => applyRelaySnapshot(instanceHost, shares, bundleKey, allowed),
|
||||
buildPublish: async () => ({
|
||||
period: yearSnap.period,
|
||||
bundles: await buildEncryptedBundlesForClasses({
|
||||
bundleKey,
|
||||
seqtaStudentId: seqtaId,
|
||||
personUuid,
|
||||
cloudUserId,
|
||||
classes: yearSnap.classes,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!relayResult.ok) {
|
||||
return { ok: false, error: relayResult.error ?? "Relay sync failed" };
|
||||
}
|
||||
|
||||
await patchSession({
|
||||
lastSyncAt: Date.now(),
|
||||
lastPeerCount: peersData.peers.length,
|
||||
lastPublishedEnrollmentHash: fingerprintEnrollment(yearSnap),
|
||||
});
|
||||
|
||||
notifyClassmatesUpdated();
|
||||
return { ok: true, peers: peersData.peers.length };
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
const SYNC_SCOPES_KEY = "plugin.timetable-classmates.storage.syncScopes";
|
||||
|
||||
export async function setScopeSyncOptIn(scope: string, optedIn: boolean): Promise<void> {
|
||||
const stored = await browser.storage.local.get(SYNC_SCOPES_KEY);
|
||||
const list = stored[SYNC_SCOPES_KEY];
|
||||
const scopes = new Set<string>(Array.isArray(list) ? list.filter((s) => typeof s === "string") : []);
|
||||
if (optedIn) scopes.add(scope);
|
||||
else scopes.delete(scope);
|
||||
await browser.storage.local.set({ [SYNC_SCOPES_KEY]: [...scopes] });
|
||||
}
|
||||
|
||||
export async function hasAnySyncOptInScope(): Promise<boolean> {
|
||||
const stored = await browser.storage.local.get(SYNC_SCOPES_KEY);
|
||||
const list = stored[SYNC_SCOPES_KEY];
|
||||
return Array.isArray(list) && list.length > 0;
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import {
|
||||
buildAvatarDisplayList,
|
||||
classRefsFromTimetableItems,
|
||||
classRosterKey,
|
||||
} from "./classKeys";
|
||||
import { buildSharePayload } from "./relayPayload";
|
||||
import { buildIdentityBindingCanonical } from "./identityBinding";
|
||||
import {
|
||||
mergePayloadIntoRoster,
|
||||
emptyRosterIndex,
|
||||
removeMemberFromRoster,
|
||||
archiveMember,
|
||||
rosterPeersForClass,
|
||||
isMemberArchived,
|
||||
} from "./rosterMerge";
|
||||
|
||||
describe("identityBinding canonical", () => {
|
||||
it("matches betterseqta-accounts worker v1 format", () => {
|
||||
const canonical = buildIdentityBindingCanonical({
|
||||
version: 1,
|
||||
instanceHost: "learn.example.edu.au",
|
||||
seqtaStudentId: 18,
|
||||
seqtaPersonUuid: "03c5f6e3-b27e-42e1-bece-27c6526205a8",
|
||||
cloudUserId: "550E8400-E29B-41D4-A716-446655440000",
|
||||
seqtaAccountType: "student",
|
||||
});
|
||||
expect(canonical).toBe(
|
||||
[
|
||||
"v=1",
|
||||
"instance=learn.example.edu.au",
|
||||
"student=18",
|
||||
"person=03c5f6e3-b27e-42e1-bece-27c6526205a8",
|
||||
"cloud=550e8400-e29b-41d4-a716-446655440000",
|
||||
"type=student",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("classRosterKey", () => {
|
||||
it("prefers metaID", () => {
|
||||
expect(classRosterKey({ metaID: 14774 })).toBe("cr:v1:14774");
|
||||
});
|
||||
|
||||
it("falls back to code and programmeID", () => {
|
||||
expect(classRosterKey({ code: "AEMAA1", programmeID: 6865 })).toBe(
|
||||
"cr:v1:AEMAA1:6865",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("classRefsFromTimetableItems", () => {
|
||||
it("dedupes and skips non-class types", () => {
|
||||
const refs = classRefsFromTimetableItems([
|
||||
{ type: "class", metaID: 1, code: "A" },
|
||||
{ type: "class", metaID: 1, code: "A" },
|
||||
{ type: "appointment", metaID: 2, code: "B" },
|
||||
]);
|
||||
expect(refs).toHaveLength(1);
|
||||
expect(refs[0].metaID).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("relay share payload", () => {
|
||||
it("builds roster merge input", () => {
|
||||
const payload = buildSharePayload({
|
||||
instance: "school.example.edu.au",
|
||||
sender: { seqtaId: 18, personUuid: "uuid", cloudUserId: null },
|
||||
period: { from: "2026-01-01", until: "2026-12-31" },
|
||||
classes: [{ metaID: 1, code: "X" }],
|
||||
});
|
||||
expect(payload.sender.seqtaId).toBe(18);
|
||||
expect(payload.classes).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rosterMerge", () => {
|
||||
it("only merges allowed senders", () => {
|
||||
const payload = buildSharePayload({
|
||||
instance: "school.example.edu.au",
|
||||
sender: { seqtaId: 99, personUuid: "u", cloudUserId: null },
|
||||
period: { from: "a", until: "b" },
|
||||
classes: [{ metaID: 5 }],
|
||||
});
|
||||
const next = mergePayloadIntoRoster(emptyRosterIndex(), payload, new Set([18]));
|
||||
expect(Object.keys(next)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("merges peer into class bucket", () => {
|
||||
const payload = buildSharePayload({
|
||||
instance: "school.example.edu.au",
|
||||
sender: { seqtaId: 18, personUuid: "u", cloudUserId: "cloud" },
|
||||
period: { from: "a", until: "b" },
|
||||
classes: [{ metaID: 5 }],
|
||||
});
|
||||
const next = mergePayloadIntoRoster(emptyRosterIndex(), payload, new Set([18]));
|
||||
expect(next["cr:v1:5"]?.["18"]?.cloudUserId).toBe("cloud");
|
||||
});
|
||||
});
|
||||
|
||||
describe("removeMemberFromRoster", () => {
|
||||
it("removes student from all class buckets", () => {
|
||||
const index = mergePayloadIntoRoster(
|
||||
emptyRosterIndex(),
|
||||
buildSharePayload({
|
||||
instance: "x",
|
||||
sender: { seqtaId: 2, personUuid: "a", cloudUserId: null },
|
||||
period: { from: "a", until: "b" },
|
||||
classes: [{ metaID: 1 }],
|
||||
}),
|
||||
new Set([2]),
|
||||
);
|
||||
const next = removeMemberFromRoster(index, 2);
|
||||
expect(rosterPeersForClass(next, "cr:v1:1")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("archived members", () => {
|
||||
it("hides archived peers from class roster", () => {
|
||||
const index = mergePayloadIntoRoster(
|
||||
emptyRosterIndex(),
|
||||
buildSharePayload({
|
||||
instance: "x",
|
||||
sender: { seqtaId: 2, personUuid: "a", cloudUserId: null },
|
||||
period: { from: "a", until: "b" },
|
||||
classes: [{ metaID: 1 }],
|
||||
}),
|
||||
new Set([2]),
|
||||
);
|
||||
const archived = archiveMember({}, 2);
|
||||
expect(isMemberArchived(archived, 2)).toBe(true);
|
||||
expect(rosterPeersForClass(index, "cr:v1:1", archived)).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAvatarDisplayList", () => {
|
||||
it("caps visible avatars and counts overflow", () => {
|
||||
const peers = [1, 2, 3, 4, 5, 6].map((id, i) => ({
|
||||
seqtaStudentId: id,
|
||||
updatedAt: i,
|
||||
}));
|
||||
const { visible, overflow } = buildAvatarDisplayList(peers, 0, 4);
|
||||
expect(visible).toHaveLength(4);
|
||||
expect(overflow).toBe(2);
|
||||
});
|
||||
|
||||
it("excludes self", () => {
|
||||
const { visible } = buildAvatarDisplayList(
|
||||
[{ seqtaStudentId: 3, updatedAt: 1 }],
|
||||
3,
|
||||
4,
|
||||
);
|
||||
expect(visible).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { syncWindowRange } from "@/seqta/utils/googleCalendar/syncDateRange";
|
||||
import { classRefsFromTimetableItems, classRosterKey, type ClassRef } from "./classKeys";
|
||||
import { CLASSMATES_SCHOOL_YEAR_WEEKS } from "./constants";
|
||||
import { fetchStudentTimetableItems } from "./seqtaClient";
|
||||
|
||||
export type EnrollmentSnapshot = {
|
||||
period: { from: string; until: string };
|
||||
classes: ClassRef[];
|
||||
ciToClassKey: Record<string, string>;
|
||||
};
|
||||
|
||||
/** Stable hash for “did my enrollments change?” checks. */
|
||||
export function fingerprintEnrollment(snapshot: Pick<EnrollmentSnapshot, "classes" | "ciToClassKey">): string {
|
||||
const classKeys = snapshot.classes
|
||||
.map((c) => classRosterKey(c))
|
||||
.filter((k): k is string => Boolean(k))
|
||||
.sort();
|
||||
const ciPairs = Object.entries(snapshot.ciToClassKey).sort(([a], [b]) => a.localeCompare(b));
|
||||
return JSON.stringify({ classKeys, ciPairs });
|
||||
}
|
||||
|
||||
/** Rolling school-year window from the start of the current week. */
|
||||
export async function fetchSchoolYearEnrollmentSnapshot(): Promise<EnrollmentSnapshot> {
|
||||
const period = syncWindowRange(CLASSMATES_SCHOOL_YEAR_WEEKS);
|
||||
const items = await fetchStudentTimetableItems(period.from, period.until);
|
||||
const classes = classRefsFromTimetableItems(items);
|
||||
const ciToClassKey: Record<string, string> = {};
|
||||
for (const item of items) {
|
||||
if (item.ci == null) continue;
|
||||
const key = classRosterKey(item);
|
||||
if (key) ciToClassKey[String(item.ci)] = key;
|
||||
}
|
||||
return { period, classes, ciToClassKey };
|
||||
}
|
||||
@@ -36,6 +36,7 @@ const PLUGIN_START_PHASES: readonly string[][] = [
|
||||
"assessments-overview",
|
||||
"assessments-average",
|
||||
"messageFolders",
|
||||
"timetable-classmates",
|
||||
"profile-picture",
|
||||
"background-music",
|
||||
// Menu icon is eager; page UI still loads on demand via dynamic import.
|
||||
|
||||
@@ -17,6 +17,7 @@ import enhancedNavigationPluginLazy from "./built-in/enhancedNavigation/lazy";
|
||||
import globalSearchPluginLazy from "./built-in/globalSearch/lazy";
|
||||
import gradeAnalyticsPluginLazy from "./built-in/gradeAnalytics/lazy";
|
||||
import errorPageKittenPlugin from "./built-in/errorPageKitten";
|
||||
import timetableClassmatesPluginLazy from "./built-in/timetableClassmates/lazy";
|
||||
|
||||
// Initialize plugin manager
|
||||
const pluginManager = PluginManager.getInstance();
|
||||
@@ -38,6 +39,7 @@ pluginManager.registerPlugin(enhancedNavigationPluginLazy);
|
||||
pluginManager.registerPlugin(globalSearchPluginLazy);
|
||||
pluginManager.registerPlugin(gradeAnalyticsPluginLazy);
|
||||
pluginManager.registerPlugin(errorPageKittenPlugin);
|
||||
pluginManager.registerPlugin(timetableClassmatesPluginLazy);
|
||||
|
||||
export async function initializePlugins(): Promise<void> {
|
||||
await pluginManager.startAllPlugins();
|
||||
|
||||
@@ -38,4 +38,5 @@ export const SYNCABLE_PLUGIN_SETTING_DEFAULTS: Record<
|
||||
},
|
||||
"grade-analytics": { cacheTtlHours: 24 },
|
||||
"error-page-kitten": {},
|
||||
"timetable-classmates": { enabled: false },
|
||||
};
|
||||
Binary file not shown.
@@ -124,10 +124,34 @@ export function applySidebarStyleClass(
|
||||
);
|
||||
}
|
||||
|
||||
let bodyPositionListenerAttached = false;
|
||||
|
||||
function deferSidebarPositionUntilBody() {
|
||||
if (bodyPositionListenerAttached) return;
|
||||
bodyPositionListenerAttached = true;
|
||||
const apply = () => {
|
||||
bodyPositionListenerAttached = false;
|
||||
const body = document.body;
|
||||
if (!body) return;
|
||||
const position = normalizeSidebarPosition(settingsState.sidebarPosition);
|
||||
body.classList.toggle("bsplus-sidebar-right", position === "right");
|
||||
};
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", apply, { once: true });
|
||||
} else {
|
||||
queueMicrotask(apply);
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply left/right placement on `body` and drill slide direction vars. */
|
||||
export function applySidebarPosition() {
|
||||
const position = normalizeSidebarPosition(settingsState.sidebarPosition);
|
||||
document.body?.classList.toggle("bsplus-sidebar-right", position === "right");
|
||||
const body = document.body;
|
||||
if (body) {
|
||||
body.classList.toggle("bsplus-sidebar-right", position === "right");
|
||||
} else {
|
||||
deferSidebarPositionUntilBody();
|
||||
}
|
||||
const root = document.documentElement;
|
||||
root.style.setProperty("--bsplus-slide-off", position === "right" ? "320px" : "-320px");
|
||||
root.style.setProperty("--bsplus-slide-off-compact", position === "right" ? "70px" : "-70px");
|
||||
@@ -150,17 +174,18 @@ export function applySidebarLook(
|
||||
|
||||
applySidebarPosition();
|
||||
|
||||
const lookKey = `${density}|${indicator}|${width}|${radius}|${blur}|${normalizeSidebarPosition(settingsState.sidebarPosition)}`;
|
||||
if (lookKey === lastSidebarLookKey && menu === lastSidebarLookMenu) return;
|
||||
lastSidebarLookKey = lookKey;
|
||||
lastSidebarLookMenu = menu;
|
||||
|
||||
const root = document.documentElement;
|
||||
root.style.setProperty("--bsplus-sidebar-width", `${SIDEBAR_WIDTH_PX[width]}px`);
|
||||
root.style.setProperty("--bsplus-sidebar-radius", `${radius}px`);
|
||||
root.style.setProperty("--bsplus-sidebar-blur", `${blur}px`);
|
||||
|
||||
if (!menu) return;
|
||||
|
||||
const lookKey = `${density}|${indicator}|${width}|${radius}|${blur}|${normalizeSidebarPosition(settingsState.sidebarPosition)}`;
|
||||
if (lookKey === lastSidebarLookKey && menu === lastSidebarLookMenu) return;
|
||||
lastSidebarLookKey = lookKey;
|
||||
lastSidebarLookMenu = menu;
|
||||
|
||||
setExclusiveClass(menu, DENSITY_CLASS_PREFIX, density, DEFAULT_SIDEBAR_DENSITY);
|
||||
setExclusiveClass(
|
||||
menu,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import stringToHTML from "../stringToHTML";
|
||||
import browser from "webextension-polyfill";
|
||||
import { openPopup } from "./PopupManager";
|
||||
import { attachPopupMediaFullscreen } from "./attachPopupMediaFullscreen";
|
||||
import { createPopupHeroVideo } from "./attachPopupMediaFullscreen";
|
||||
import { createPopupSocialFooter } from "./createPopupSocialFooter";
|
||||
import { renderWhatsNewChangelogHtml } from "./whatsNewChangelog";
|
||||
|
||||
@@ -17,22 +17,6 @@ export function OpenWhatsNewPopup(onDismissed?: () => void) {
|
||||
</div>`,
|
||||
).firstChild as HTMLElement;
|
||||
|
||||
const imageContainer = document.createElement("div");
|
||||
imageContainer.classList.add("whatsnewImgContainer");
|
||||
|
||||
const heroVideo = document.createElement("video");
|
||||
heroVideo.src = UPDATE_VIDEO_URL;
|
||||
heroVideo.classList.add("whatsnewImg");
|
||||
heroVideo.autoplay = true;
|
||||
heroVideo.muted = true;
|
||||
heroVideo.loop = true;
|
||||
heroVideo.playsInline = true;
|
||||
heroVideo.setAttribute("playsinline", "");
|
||||
heroVideo.setAttribute("aria-label", "BetterSEQTA+ update preview");
|
||||
imageContainer.appendChild(heroVideo);
|
||||
attachPopupMediaFullscreen(heroVideo);
|
||||
void heroVideo.play().catch(() => {});
|
||||
|
||||
const text = stringToHTML(/* html */ `
|
||||
<div class="whatsnewTextContainer" style="height: 50%;overflow-y: auto;">
|
||||
|
||||
@@ -44,7 +28,11 @@ export function OpenWhatsNewPopup(onDismissed?: () => void) {
|
||||
|
||||
openPopup({
|
||||
header,
|
||||
content: [imageContainer, text, footer],
|
||||
content: [
|
||||
createPopupHeroVideo(UPDATE_VIDEO_URL, "BetterSEQTA+ update preview"),
|
||||
text,
|
||||
footer,
|
||||
],
|
||||
afterClose: onDismissed,
|
||||
clearJustUpdated: true,
|
||||
});
|
||||
|
||||
@@ -169,3 +169,22 @@ export function attachPopupMediaFullscreenIfPresent(
|
||||
attachPopupMediaFullscreen(el);
|
||||
}
|
||||
}
|
||||
|
||||
/** Autoplay hero video for What's New / feature popups (`whatsnewImgContainer`). */
|
||||
export function createPopupHeroVideo(src: string, ariaLabel: string): HTMLElement {
|
||||
const wrap = document.createElement("div");
|
||||
wrap.classList.add("whatsnewImgContainer");
|
||||
const video = document.createElement("video");
|
||||
video.src = src;
|
||||
video.classList.add("whatsnewImg");
|
||||
video.autoplay = true;
|
||||
video.muted = true;
|
||||
video.loop = true;
|
||||
video.playsInline = true;
|
||||
video.setAttribute("playsinline", "");
|
||||
video.setAttribute("aria-label", ariaLabel);
|
||||
wrap.appendChild(video);
|
||||
attachPopupMediaFullscreen(video);
|
||||
void video.play().catch(() => {});
|
||||
return wrap;
|
||||
}
|
||||
@@ -5,9 +5,10 @@ export type WhatsNewRelease = {
|
||||
|
||||
export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [
|
||||
{
|
||||
"title": "3.7.3 – Performance Mode, Timetable sync into Calendars, Sidebar Customisation, new loading animations & Bugfix Bundle",
|
||||
"title": "3.7.3 – Performance Mode, Timetable syncing with Friends and Calendars, Sidebar Customisation, new loading animations & Bugfix Bundle",
|
||||
"items": [
|
||||
"Added Performance Mode in General settings dramatically improving performance with little sacrifice to looks.",
|
||||
"Added the ability to sync your timetable with your friends and calendars.",
|
||||
"Fixed custom background images and videos not uploading.",
|
||||
"Added combined class groups in Grade Analytics to merge multiple subjects into one trend.",
|
||||
"Fixed icon-only sidebar not expanding when opening a folder.",
|
||||
|
||||
@@ -32,11 +32,42 @@ export function defaultAccountsPfpUrl(userId: string): string {
|
||||
return `${ACCOUNTS_BASE}/api/user/pfp/${userId}`;
|
||||
}
|
||||
|
||||
const NO_PFP_META_TTL_MS = 10 * 60 * 1000;
|
||||
const noPfpMetaUntil = new Map<string, number>();
|
||||
const metaInflight = new Map<string, Promise<string | null>>();
|
||||
|
||||
async function fetchServerHash(userId: string): Promise<string | null> {
|
||||
const res = await fetch(`${ACCOUNTS_BASE}/api/user/pfp/${userId}/meta`);
|
||||
if (!res.ok) return null;
|
||||
const data = (await res.json()) as { pfpHash?: string | null };
|
||||
return data.pfpHash ?? null;
|
||||
const cachedUntil = noPfpMetaUntil.get(userId);
|
||||
if (cachedUntil != null && Date.now() < cachedUntil) return null;
|
||||
|
||||
const inflight = metaInflight.get(userId);
|
||||
if (inflight) return inflight;
|
||||
|
||||
const work = (async () => {
|
||||
try {
|
||||
const res = await fetch(`${ACCOUNTS_BASE}/api/user/pfp/${userId}/meta`);
|
||||
if (!res.ok) {
|
||||
if (res.status === 404) {
|
||||
noPfpMetaUntil.set(userId, Date.now() + NO_PFP_META_TTL_MS);
|
||||
return null;
|
||||
}
|
||||
throw new Error(`pfp meta HTTP ${res.status}`);
|
||||
}
|
||||
const data = (await res.json()) as { pfpHash?: string | null };
|
||||
const hash = data.pfpHash ?? null;
|
||||
if (!hash) {
|
||||
noPfpMetaUntil.set(userId, Date.now() + NO_PFP_META_TTL_MS);
|
||||
return null;
|
||||
}
|
||||
noPfpMetaUntil.delete(userId);
|
||||
return hash;
|
||||
} finally {
|
||||
metaInflight.delete(userId);
|
||||
}
|
||||
})();
|
||||
|
||||
metaInflight.set(userId, work);
|
||||
return work;
|
||||
}
|
||||
|
||||
async function clearLocal(userId: string): Promise<void> {
|
||||
@@ -55,6 +86,56 @@ export type ResolveCloudPfpResult = {
|
||||
fromCache: boolean;
|
||||
};
|
||||
|
||||
function cachedBlobUrl(blob: Blob): ResolveCloudPfpResult {
|
||||
return { src: URL.createObjectURL(blob), fromCache: true };
|
||||
}
|
||||
|
||||
function sessionPfpHash(viewerId: string | null, userId: string): string | null {
|
||||
if (!viewerId || viewerId !== userId) return null;
|
||||
return cloudAuth.state.user?.pfpHash ?? null;
|
||||
}
|
||||
|
||||
function localHashHit(
|
||||
serverHash: string | null | undefined,
|
||||
localHash: string | null | undefined,
|
||||
localBlob: Blob | null | undefined,
|
||||
): ResolveCloudPfpResult | null {
|
||||
if (!serverHash || serverHash !== localHash || !(localBlob instanceof Blob)) {
|
||||
return null;
|
||||
}
|
||||
return cachedBlobUrl(localBlob);
|
||||
}
|
||||
|
||||
async function fetchAndCachePfp(
|
||||
userId: string,
|
||||
pfpUrl: string,
|
||||
serverHash: string,
|
||||
localHash: string | null | undefined,
|
||||
localBlob: Blob | null | undefined,
|
||||
): Promise<ResolveCloudPfpResult | null> {
|
||||
const imageUrl = pfpUrlWithHash(pfpUrl, serverHash);
|
||||
const headers: HeadersInit = {};
|
||||
if (localHash) {
|
||||
headers["If-None-Match"] = `"${localHash}"`;
|
||||
}
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (token) {
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const res = await fetch(imageUrl, { headers });
|
||||
if (res.status === 304 && localBlob instanceof Blob) {
|
||||
await store.setItem(hashKey(userId), serverHash);
|
||||
return cachedBlobUrl(localBlob);
|
||||
}
|
||||
if (!res.ok) return null;
|
||||
|
||||
const blob = await res.blob();
|
||||
await store.setItem(blobKey(userId), blob);
|
||||
await store.setItem(hashKey(userId), serverHash);
|
||||
return { src: URL.createObjectURL(blob), fromCache: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an object URL or direct URL for the cloud profile picture.
|
||||
* Order: session hash match → local blob; else meta → download → store blob then hash.
|
||||
@@ -67,54 +148,29 @@ export async function resolveCloudPfp(
|
||||
return { src: pfpUrl, fromCache: false };
|
||||
}
|
||||
|
||||
const sessionHash = cloudAuth.state.user?.pfpHash ?? null;
|
||||
const viewerId = cloudAuth.state.user?.id ?? null;
|
||||
const localHash = await store.getItem<string>(hashKey(userId));
|
||||
const localBlob = await store.getItem<Blob>(blobKey(userId));
|
||||
|
||||
let serverHash = sessionHash;
|
||||
let serverHash: string | null = sessionPfpHash(viewerId, userId);
|
||||
const sessionHit = localHashHit(serverHash, localHash, localBlob);
|
||||
if (sessionHit) return sessionHit;
|
||||
|
||||
const localMatches =
|
||||
!!serverHash && serverHash === localHash && localBlob instanceof Blob;
|
||||
if (localMatches) {
|
||||
return { src: URL.createObjectURL(localBlob), fromCache: true };
|
||||
}
|
||||
|
||||
if (!serverHash || serverHash !== localHash) {
|
||||
try {
|
||||
serverHash = await fetchServerHash(userId);
|
||||
} catch {
|
||||
return localHashHit(localHash, localHash, localBlob);
|
||||
}
|
||||
|
||||
if (!serverHash) {
|
||||
if (!localHash && !localBlob) return null;
|
||||
await clearLocal(userId);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (serverHash === localHash && localBlob instanceof Blob) {
|
||||
return { src: URL.createObjectURL(localBlob), fromCache: true };
|
||||
}
|
||||
const metaHit = localHashHit(serverHash, localHash, localBlob);
|
||||
if (metaHit) return metaHit;
|
||||
|
||||
await clearLocal(userId);
|
||||
|
||||
const imageUrl = pfpUrlWithHash(pfpUrl, serverHash);
|
||||
const headers: HeadersInit = {};
|
||||
if (localHash) {
|
||||
headers["If-None-Match"] = `"${localHash}"`;
|
||||
}
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (token && isAccountsHostedPfpUrl(pfpUrl)) {
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const res = await fetch(imageUrl, { headers });
|
||||
if (res.status === 304 && localBlob instanceof Blob) {
|
||||
await store.setItem(hashKey(userId), serverHash);
|
||||
return { src: URL.createObjectURL(localBlob), fromCache: true };
|
||||
}
|
||||
|
||||
if (!res.ok) return null;
|
||||
|
||||
const blob = await res.blob();
|
||||
await store.setItem(blobKey(userId), blob);
|
||||
await store.setItem(hashKey(userId), serverHash);
|
||||
|
||||
return { src: URL.createObjectURL(blob), fromCache: false };
|
||||
return fetchAndCachePfp(userId, pfpUrl, serverHash, localHash, localBlob);
|
||||
}
|
||||
@@ -87,6 +87,11 @@ const OMIT_FROM_UPLOAD_EXACT = new Set<string>([
|
||||
"devMode",
|
||||
"devGhReleaseVersionOverride",
|
||||
"devDelayLoadingScreen",
|
||||
"bsplus_dev_api_base",
|
||||
"bsplus_dev_accounts_base",
|
||||
"bsplus_dev_oauth_client_id",
|
||||
"bsplus_dev_oauth_client_secret",
|
||||
"bsplus_dev_oauth_redirect_uri",
|
||||
]);
|
||||
|
||||
const UNSAFE_STORAGE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
|
||||
let sequence = "";
|
||||
let onKeyDown: ((event: KeyboardEvent) => void) | null = null;
|
||||
let disarmTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function disarm(): void {
|
||||
if (onKeyDown) {
|
||||
window.removeEventListener("keydown", onKeyDown, true);
|
||||
onKeyDown = null;
|
||||
}
|
||||
if (disarmTimer) {
|
||||
clearTimeout(disarmTimer);
|
||||
disarmTimer = null;
|
||||
}
|
||||
sequence = "";
|
||||
}
|
||||
|
||||
/** Click BetterSEQTA+ logo in settings, then type `dev` within 10s (works in shadow DOM popout). */
|
||||
export function armDevModeUnlock(): void {
|
||||
disarm();
|
||||
onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
sequence += event.key.toLowerCase();
|
||||
if (sequence.includes("dev")) {
|
||||
disarm();
|
||||
settingsState.devMode = true;
|
||||
alert("Dev mode is now enabled");
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown, true);
|
||||
disarmTimer = setTimeout(disarm, 10_000);
|
||||
}
|
||||
@@ -46,6 +46,11 @@ export const PERFORMANCE_HEAVY_PLUGINS: readonly PerformanceHeavyPlugin[] = [
|
||||
name: "Message Folders",
|
||||
description: "Message DOM tagging and folder indexing",
|
||||
},
|
||||
{
|
||||
id: "timetable-classmates",
|
||||
name: "Timetable Classmates",
|
||||
description: "Classmate avatar sync and SEQTA message polling",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export const PERFORMANCE_HEAVY_PLUGIN_IDS = new Set(
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { Tabs } from "webextension-polyfill";
|
||||
|
||||
/** Same rules as background `isSeqtaOrigin` / ConnectMobileApp `isSeqtaUrl`. */
|
||||
export function isSeqtaHostname(hostname: string): boolean {
|
||||
return hostname.includes("seqta") || hostname.endsWith(".edu.au");
|
||||
}
|
||||
|
||||
export function isSeqtaPageUrl(url: string): boolean {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
if (u.protocol !== "http:" && u.protocol !== "https:") return false;
|
||||
return isSeqtaHostname(u.hostname);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a browser tab is likely SEQTA Learn/Engage (for background `tabs.sendMessage`).
|
||||
* URL check covers custom school hosts; title covers cases where URL is not yet available.
|
||||
*/
|
||||
export function isSeqtaTab(tab: Tabs.Tab): boolean {
|
||||
if (tab.url && isSeqtaPageUrl(tab.url)) return true;
|
||||
const title = tab.title ?? "";
|
||||
return title.includes("SEQTA Learn") || title.includes("SEQTA Engage");
|
||||
}
|
||||
Reference in new issue
Block a user