mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
feat: test timetable syncing
This commit is contained in:
1 parent
242e4f3ff8
commit
7eac66b2b0
50 files changed
+2942
-97
No files matched your search
@@ -21,6 +21,7 @@ import {
|
|||||||
} from "./background/calendarBackground";
|
} from "./background/calendarBackground";
|
||||||
import { createCustomThemesHandlers } from "./background/customThemesHandlers";
|
import { createCustomThemesHandlers } from "./background/customThemesHandlers";
|
||||||
import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos";
|
import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos";
|
||||||
|
import { initTimetableClassmatesBackgroundSync } from "./background/timetableClassmatesSync";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Session-only dev-mode override of the content API base.
|
* Session-only dev-mode override of the content API base.
|
||||||
@@ -750,4 +751,5 @@ browser.runtime.onStartup.addListener(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
initCloudSettingsAutoSync({ reloadSeqtaPages });
|
initCloudSettingsAutoSync({ reloadSeqtaPages });
|
||||||
|
initTimetableClassmatesBackgroundSync();
|
||||||
void ensureSyncableStorageDefaults();
|
void ensureSyncableStorageDefaults();
|
||||||
@@ -53,6 +53,7 @@ import {
|
|||||||
type OutlookCalendarStatus,
|
type OutlookCalendarStatus,
|
||||||
} from "@/seqta/utils/calendarSync/providerStorage";
|
} from "@/seqta/utils/calendarSync/providerStorage";
|
||||||
import browser from "webextension-polyfill";
|
import browser from "webextension-polyfill";
|
||||||
|
import { isSeqtaTab } from "@/seqta/utils/seqtaTabMatch";
|
||||||
|
|
||||||
const WEEKLY_PERIOD_MINUTES = 7 * 24 * 60;
|
const WEEKLY_PERIOD_MINUTES = 7 * 24 * 60;
|
||||||
|
|
||||||
@@ -510,11 +511,6 @@ export function registerOutlookCalendarMessageHandlers(
|
|||||||
registerProviderHandlers(handlers, isTrustedSender, OUTLOOK_BACKEND, getOutlookCalendarStatus);
|
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> {
|
export async function ensureWeeklySyncAlarm(): Promise<void> {
|
||||||
const [connected, enabled] = await Promise.all([isAnyCalendarConnected(), getAutoSyncWeekly()]);
|
const [connected, enabled] = await Promise.all([isAnyCalendarConnected(), getAutoSyncWeekly()]);
|
||||||
if (!connected || !enabled) {
|
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();
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -41,16 +41,16 @@
|
|||||||
class="flex shrink-0 items-center gap-4 border-b border-zinc-200/60 px-5 py-4 dark:border-zinc-700/50"
|
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)"
|
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
|
<img
|
||||||
src={resolveExtensionAssetUrl(darkLogo)}
|
src={resolveExtensionAssetUrl(darkLogo)}
|
||||||
class="h-11 w-52 object-cover dark:hidden"
|
class="h-9 max-w-[10.5rem] object-contain object-left dark:hidden sm:h-10"
|
||||||
alt="BetterSEQTA+"
|
alt=""
|
||||||
/>
|
/>
|
||||||
<img
|
<img
|
||||||
src={resolveExtensionAssetUrl(lightLogo)}
|
src={resolveExtensionAssetUrl(lightLogo)}
|
||||||
class="hidden h-11 w-52 object-cover dark:block"
|
class="hidden h-9 max-w-[10.5rem] object-contain object-left dark:block sm:h-10"
|
||||||
alt="BetterSEQTA+"
|
alt=""
|
||||||
/>
|
/>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte'
|
import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte'
|
||||||
import ThemePlaceholderCover from '@/interface/components/themes/ThemePlaceholderCover.svelte'
|
import ThemePlaceholderCover from '@/interface/components/themes/ThemePlaceholderCover.svelte'
|
||||||
import { filterThemesByMode, isLocalCustomTheme, type ThemeListMode } from '@/interface/utils/themeListFilters'
|
import { filterThemesByMode, isLocalCustomTheme, type ThemeListMode } from '@/interface/utils/themeListFilters'
|
||||||
import { closeExtensionPopup, SettingsClicked } from '@/seqta/utils/Closers/closeExtensionPopup'
|
import { closeExtensionPopup } from '@/seqta/utils/Closers/closeExtensionPopup'
|
||||||
import { formatCustomThemeApiError } from '@/seqta/utils/customThemes/apiErrors'
|
import { formatCustomThemeApiError } from '@/seqta/utils/customThemes/apiErrors'
|
||||||
|
|
||||||
const themeManager = ThemeManager.getInstance();
|
const themeManager = ThemeManager.getInstance();
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
import SidebarNav from "../components/SidebarNav.svelte";
|
import SidebarNav from "../components/SidebarNav.svelte";
|
||||||
import StoreHeader from "../components/store/Header.svelte";
|
import StoreHeader from "../components/store/Header.svelte";
|
||||||
import { settingsPopup } from "@/seqta/utils/settingsPopup";
|
import { settingsPopup } from "@/seqta/utils/settingsPopup";
|
||||||
|
import { armDevModeUnlock } from "@/seqta/utils/devModeUnlock";
|
||||||
import { consumeOpenFeedbackRequest } from "@/seqta/utils/feedback/client";
|
import { consumeOpenFeedbackRequest } from "@/seqta/utils/feedback/client";
|
||||||
import {
|
import {
|
||||||
consumeSettingsDestination,
|
consumeSettingsDestination,
|
||||||
@@ -52,7 +53,6 @@
|
|||||||
|
|
||||||
const BACKGROUND_CATEGORY_PREFIX = "background-category:";
|
const BACKGROUND_CATEGORY_PREFIX = "background-category:";
|
||||||
|
|
||||||
let devModeSequence = "";
|
|
||||||
let compactActiveTab = $state(0);
|
let compactActiveTab = $state(0);
|
||||||
let activePage = $state<PageId>("settings");
|
let activePage = $state<PageId>("settings");
|
||||||
let activeSection = $state("general");
|
let activeSection = $state("general");
|
||||||
@@ -194,22 +194,7 @@
|
|||||||
closeExtensionPopup();
|
closeExtensionPopup();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDevModeToggle = () => {
|
const handleDevModeToggle = () => armDevModeUnlock();
|
||||||
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);
|
|
||||||
};
|
|
||||||
|
|
||||||
let ColourPickerComponent = $state<Component | null>(null);
|
let ColourPickerComponent = $state<Component | null>(null);
|
||||||
let FontPickerComponent = $state<Component | null>(null);
|
let FontPickerComponent = $state<Component | null>(null);
|
||||||
|
|||||||
@@ -15,7 +15,7 @@
|
|||||||
"64": "resources/icons/icon-64.png"
|
"64": "resources/icons/icon-64.png"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"permissions": ["tabs", "notifications", "storage", "alarms"],
|
"permissions": ["tabs", "notifications", "storage", "alarms", "cookies"],
|
||||||
"host_permissions": [
|
"host_permissions": [
|
||||||
"https://newsapi.org/",
|
"https://newsapi.org/",
|
||||||
"https://betterseqta.org/",
|
"https://betterseqta.org/",
|
||||||
|
|||||||
@@ -319,6 +319,17 @@ function synthesizeItems(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
ctx.route.includes("/load/message") &&
|
||||||
|
entity &&
|
||||||
|
typeof entity === "object"
|
||||||
|
) {
|
||||||
|
const subject = (entity as Record<string, unknown>).subject;
|
||||||
|
if (typeof subject === "string" && subject.startsWith("BQ+TIMETABLE:")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// For the messages compose-people endpoint, skip records that don't
|
// For the messages compose-people endpoint, skip records that don't
|
||||||
// carry a real human name. We never want raw entries like
|
// carry a real human name. We never want raw entries like
|
||||||
// `/seqta/student/load/message/people#20` becoming titles, and we
|
// `/seqta/student/load/message/people#20` becoming titles, and we
|
||||||
|
|||||||
@@ -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,140 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from "svelte";
|
||||||
|
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||||
|
import { ACCOUNTS_BASE } from "./constants";
|
||||||
|
import { recordConsent } from "./rosterStore";
|
||||||
|
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 cloudName = $state(
|
||||||
|
cloudAuth.state.user?.displayName ?? cloudAuth.state.user?.username ?? "",
|
||||||
|
);
|
||||||
|
|
||||||
|
onMount(() =>
|
||||||
|
cloudAuth.subscribe((s) => {
|
||||||
|
cloudLoggedIn = s.isLoggedIn;
|
||||||
|
cloudName = s.user?.displayName ?? s.user?.username ?? "";
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
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.";
|
||||||
|
} 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;
|
||||||
|
}
|
||||||
|
await recordConsent();
|
||||||
|
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}
|
||||||
|
<p class="bsplus-tc-cloud-ok">
|
||||||
|
Signed in{cloudName ? ` as ${cloudName}` : ""}. We link this account to your SEQTA student id
|
||||||
|
on this site.
|
||||||
|
</p>
|
||||||
|
{:else}
|
||||||
|
<p class="bsplus-tc-muted">Sign in with a free cloud account to join your school phonebook.</p>
|
||||||
|
<div class="bsplus-tc-cloud-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-btn bsplus-cal-btn--primary"
|
||||||
|
disabled={busy}
|
||||||
|
onclick={() => void signInWithCloud()}
|
||||||
|
>
|
||||||
|
Sign in
|
||||||
|
</button>
|
||||||
|
<a
|
||||||
|
class="bsplus-tc-link"
|
||||||
|
href={`${ACCOUNTS_BASE}/register`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
>
|
||||||
|
Create 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,136 @@
|
|||||||
|
.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) 40%, transparent);
|
||||||
|
background: color-mix(in srgb, var(--tc-accent) 10%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-tc-cloud h2 {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin: 0 0 0.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-tc-cloud p {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-tc-cloud-ok {
|
||||||
|
color: color-mix(in srgb, #4ade80 88%, currentColor);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-tc-cloud-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.65rem;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-tc-link {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-weight: 600;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
.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,177 @@
|
|||||||
|
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";
|
||||||
|
|
||||||
|
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]);
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
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);
|
||||||
|
document.addEventListener(
|
||||||
|
"click",
|
||||||
|
(e) => {
|
||||||
|
if ((e.target as HTMLElement).closest?.(".timetablepage .entry.class")) schedulePaint();
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
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);
|
||||||
|
removeClassmateStacks();
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
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,144 @@
|
|||||||
|
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";
|
||||||
|
|
||||||
|
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: options.onAccepted },
|
||||||
|
{ onDismiss: options.onDismiss, heroVideo: true },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = stringToHTML(/* html */ `
|
||||||
|
<div class="whatsnewHeader">
|
||||||
|
<h1>${title}</h1>
|
||||||
|
<p>${peers.length} classmate${peers.length === 1 ? "" : "s"} in this class</p>
|
||||||
|
</div>
|
||||||
|
`).firstChild as HTMLElement;
|
||||||
|
|
||||||
|
openPopup({
|
||||||
|
header,
|
||||||
|
content: [host],
|
||||||
|
containerClass: "whatsnewContainer--scrollBody",
|
||||||
|
backgroundClass: "bsplus-popup-backdrop--lite",
|
||||||
|
animateSelector: ".bsplus-classmates-roster-popup",
|
||||||
|
afterClose: () => {},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { postSeqtaJson } from "./seqtaClient";
|
||||||
|
import type { PeopleCache } from "./rosterStore";
|
||||||
|
import { loadPeopleCache, savePeopleCache } 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 any = Object.values(existing)[0];
|
||||||
|
if (any && Date.now() - any.updatedAt < 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);
|
||||||
|
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,173 @@
|
|||||||
|
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 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 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,258 @@
|
|||||||
|
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,
|
||||||
|
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." };
|
||||||
|
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();
|
||||||
|
return sync.ok ? res : { ok: false, error: sync.error ?? "Opt-in saved but initial sync failed." };
|
||||||
|
}
|
||||||
|
|
||||||
|
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-overview",
|
||||||
"assessments-average",
|
"assessments-average",
|
||||||
"messageFolders",
|
"messageFolders",
|
||||||
|
"timetable-classmates",
|
||||||
"profile-picture",
|
"profile-picture",
|
||||||
"background-music",
|
"background-music",
|
||||||
// Menu icon is eager; page UI still loads on demand via dynamic import.
|
// 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 globalSearchPluginLazy from "./built-in/globalSearch/lazy";
|
||||||
import gradeAnalyticsPluginLazy from "./built-in/gradeAnalytics/lazy";
|
import gradeAnalyticsPluginLazy from "./built-in/gradeAnalytics/lazy";
|
||||||
import errorPageKittenPlugin from "./built-in/errorPageKitten";
|
import errorPageKittenPlugin from "./built-in/errorPageKitten";
|
||||||
|
import timetableClassmatesPluginLazy from "./built-in/timetableClassmates/lazy";
|
||||||
|
|
||||||
// Initialize plugin manager
|
// Initialize plugin manager
|
||||||
const pluginManager = PluginManager.getInstance();
|
const pluginManager = PluginManager.getInstance();
|
||||||
@@ -38,6 +39,7 @@ pluginManager.registerPlugin(enhancedNavigationPluginLazy);
|
|||||||
pluginManager.registerPlugin(globalSearchPluginLazy);
|
pluginManager.registerPlugin(globalSearchPluginLazy);
|
||||||
pluginManager.registerPlugin(gradeAnalyticsPluginLazy);
|
pluginManager.registerPlugin(gradeAnalyticsPluginLazy);
|
||||||
pluginManager.registerPlugin(errorPageKittenPlugin);
|
pluginManager.registerPlugin(errorPageKittenPlugin);
|
||||||
|
pluginManager.registerPlugin(timetableClassmatesPluginLazy);
|
||||||
|
|
||||||
export async function initializePlugins(): Promise<void> {
|
export async function initializePlugins(): Promise<void> {
|
||||||
await pluginManager.startAllPlugins();
|
await pluginManager.startAllPlugins();
|
||||||
|
|||||||
@@ -38,4 +38,5 @@ export const SYNCABLE_PLUGIN_SETTING_DEFAULTS: Record<
|
|||||||
},
|
},
|
||||||
"grade-analytics": { cacheTtlHours: 24 },
|
"grade-analytics": { cacheTtlHours: 24 },
|
||||||
"error-page-kitten": {},
|
"error-page-kitten": {},
|
||||||
|
"timetable-classmates": { enabled: false },
|
||||||
};
|
};
|
||||||
Binary file not shown.
@@ -1,8 +1,5 @@
|
|||||||
import {
|
import { closeExtensionPopup } from "../Closers/closeExtensionPopup";
|
||||||
changeSettingsClicked,
|
import { isExtensionSettingsOpen } from "../settingsPopupAnimation";
|
||||||
closeExtensionPopup,
|
|
||||||
SettingsClicked,
|
|
||||||
} from "../Closers/closeExtensionPopup";
|
|
||||||
|
|
||||||
let isSettingsRendered = false;
|
let isSettingsRendered = false;
|
||||||
let settingsLoadPromise: Promise<void> | null = null;
|
let settingsLoadPromise: Promise<void> | null = null;
|
||||||
@@ -10,7 +7,7 @@ let resizerAttached = false;
|
|||||||
|
|
||||||
function extensionOutsideClickHandler(extensionPopup: HTMLElement) {
|
function extensionOutsideClickHandler(extensionPopup: HTMLElement) {
|
||||||
return (event: MouseEvent) => {
|
return (event: MouseEvent) => {
|
||||||
if (!SettingsClicked) return;
|
if (!isExtensionSettingsOpen()) return;
|
||||||
|
|
||||||
const target = event.target;
|
const target = event.target;
|
||||||
if (!(target instanceof Node)) return;
|
if (!(target instanceof Node)) return;
|
||||||
@@ -20,7 +17,7 @@ function extensionOutsideClickHandler(extensionPopup: HTMLElement) {
|
|||||||
if (target instanceof HTMLElement && target.closest("#AddedSettings")) return;
|
if (target instanceof HTMLElement && target.closest("#AddedSettings")) return;
|
||||||
if (target === extensionPopup) return;
|
if (target === extensionPopup) return;
|
||||||
|
|
||||||
changeSettingsClicked(closeExtensionPopup());
|
closeExtensionPopup();
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
import { settingsPopup } from "@/seqta/utils/settingsPopup";
|
import { settingsPopup } from "@/seqta/utils/settingsPopup";
|
||||||
import { animateSettingsClose } from "@/seqta/utils/settingsPopupAnimation";
|
import { animateSettingsClose } from "@/seqta/utils/settingsPopupAnimation";
|
||||||
|
|
||||||
export let SettingsClicked = false;
|
let settingsOpenGeneration = 0;
|
||||||
|
|
||||||
|
export function getSettingsOpenGeneration(): number {
|
||||||
|
return settingsOpenGeneration;
|
||||||
|
}
|
||||||
|
|
||||||
export const closeExtensionPopup = (extensionPopup?: HTMLElement) => {
|
export const closeExtensionPopup = (extensionPopup?: HTMLElement) => {
|
||||||
|
settingsOpenGeneration += 1;
|
||||||
|
|
||||||
if (!extensionPopup) extensionPopup = document.getElementById("ExtensionPopup")!;
|
if (!extensionPopup) extensionPopup = document.getElementById("ExtensionPopup")!;
|
||||||
|
|
||||||
if (extensionPopup) {
|
if (extensionPopup) {
|
||||||
@@ -11,9 +17,4 @@ export const closeExtensionPopup = (extensionPopup?: HTMLElement) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
settingsPopup.triggerClose();
|
settingsPopup.triggerClose();
|
||||||
return (SettingsClicked = false);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export function changeSettingsClicked(newVal: boolean) {
|
|
||||||
SettingsClicked = newVal;
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import stringToHTML from "../stringToHTML";
|
import stringToHTML from "../stringToHTML";
|
||||||
import browser from "webextension-polyfill";
|
import browser from "webextension-polyfill";
|
||||||
import { openPopup } from "./PopupManager";
|
import { openPopup } from "./PopupManager";
|
||||||
import { attachPopupMediaFullscreen } from "./attachPopupMediaFullscreen";
|
import { createPopupHeroVideo } from "./attachPopupMediaFullscreen";
|
||||||
import { createPopupSocialFooter } from "./createPopupSocialFooter";
|
import { createPopupSocialFooter } from "./createPopupSocialFooter";
|
||||||
import { renderWhatsNewChangelogHtml } from "./whatsNewChangelog";
|
import { renderWhatsNewChangelogHtml } from "./whatsNewChangelog";
|
||||||
|
|
||||||
@@ -17,22 +17,6 @@ export function OpenWhatsNewPopup(onDismissed?: () => void) {
|
|||||||
</div>`,
|
</div>`,
|
||||||
).firstChild as HTMLElement;
|
).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 */ `
|
const text = stringToHTML(/* html */ `
|
||||||
<div class="whatsnewTextContainer" style="height: 50%;overflow-y: auto;">
|
<div class="whatsnewTextContainer" style="height: 50%;overflow-y: auto;">
|
||||||
|
|
||||||
@@ -44,7 +28,11 @@ export function OpenWhatsNewPopup(onDismissed?: () => void) {
|
|||||||
|
|
||||||
openPopup({
|
openPopup({
|
||||||
header,
|
header,
|
||||||
content: [imageContainer, text, footer],
|
content: [
|
||||||
|
createPopupHeroVideo(UPDATE_VIDEO_URL, "BetterSEQTA+ update preview"),
|
||||||
|
text,
|
||||||
|
footer,
|
||||||
|
],
|
||||||
afterClose: onDismissed,
|
afterClose: onDismissed,
|
||||||
clearJustUpdated: true,
|
clearJustUpdated: true,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -169,3 +169,22 @@ export function attachPopupMediaFullscreenIfPresent(
|
|||||||
attachPopupMediaFullscreen(el);
|
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;
|
||||||
|
}
|
||||||
@@ -32,11 +32,39 @@ export function defaultAccountsPfpUrl(userId: string): string {
|
|||||||
return `${ACCOUNTS_BASE}/api/user/pfp/${userId}`;
|
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> {
|
async function fetchServerHash(userId: string): Promise<string | null> {
|
||||||
const res = await fetch(`${ACCOUNTS_BASE}/api/user/pfp/${userId}/meta`);
|
const cachedUntil = noPfpMetaUntil.get(userId);
|
||||||
if (!res.ok) return null;
|
if (cachedUntil != null && Date.now() < cachedUntil) return null;
|
||||||
const data = (await res.json()) as { pfpHash?: string | null };
|
|
||||||
return data.pfpHash ?? 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) {
|
||||||
|
noPfpMetaUntil.set(userId, Date.now() + NO_PFP_META_TTL_MS);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
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> {
|
async function clearLocal(userId: string): Promise<void> {
|
||||||
@@ -67,23 +95,21 @@ export async function resolveCloudPfp(
|
|||||||
return { src: pfpUrl, fromCache: false };
|
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 localHash = await store.getItem<string>(hashKey(userId));
|
||||||
const localBlob = await store.getItem<Blob>(blobKey(userId));
|
const localBlob = await store.getItem<Blob>(blobKey(userId));
|
||||||
|
|
||||||
let serverHash = sessionHash;
|
let serverHash: string | null =
|
||||||
|
viewerId && viewerId === userId ? (cloudAuth.state.user?.pfpHash ?? null) : null;
|
||||||
|
|
||||||
const localMatches =
|
if (serverHash && serverHash === localHash && localBlob instanceof Blob) {
|
||||||
!!serverHash && serverHash === localHash && localBlob instanceof Blob;
|
|
||||||
if (localMatches) {
|
|
||||||
return { src: URL.createObjectURL(localBlob), fromCache: true };
|
return { src: URL.createObjectURL(localBlob), fromCache: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!serverHash || serverHash !== localHash) {
|
serverHash = await fetchServerHash(userId);
|
||||||
serverHash = await fetchServerHash(userId);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!serverHash) {
|
if (!serverHash) {
|
||||||
|
if (!localHash && !localBlob) return null;
|
||||||
await clearLocal(userId);
|
await clearLocal(userId);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -85,6 +85,11 @@ const OMIT_FROM_UPLOAD_EXACT = new Set<string>([
|
|||||||
"devMode",
|
"devMode",
|
||||||
"devGhReleaseVersionOverride",
|
"devGhReleaseVersionOverride",
|
||||||
"devDelayLoadingScreen",
|
"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"]);
|
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);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import browser from "webextension-polyfill";
|
import browser from "webextension-polyfill";
|
||||||
import { getApiBase } from "@/seqta/utils/DevApiBase";
|
import { getApiBase } from "@/seqta/utils/DevApiBase";
|
||||||
import { SettingsClicked } from "@/seqta/utils/Closers/closeExtensionPopup";
|
import { isExtensionSettingsOpen } from "@/seqta/utils/settingsPopupAnimation";
|
||||||
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
||||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
import {
|
import {
|
||||||
@@ -291,6 +291,6 @@ export function consumeOpenFeedbackRequest(): string | null {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function openExtensionSettingsPopup(): void {
|
export function openExtensionSettingsPopup(): void {
|
||||||
if (SettingsClicked) return;
|
if (isExtensionSettingsOpen()) return;
|
||||||
document.getElementById("AddedSettings")?.click();
|
document.getElementById("AddedSettings")?.click();
|
||||||
}
|
}
|
||||||
@@ -46,6 +46,11 @@ export const PERFORMANCE_HEAVY_PLUGINS: readonly PerformanceHeavyPlugin[] = [
|
|||||||
name: "Message Folders",
|
name: "Message Folders",
|
||||||
description: "Message DOM tagging and folder indexing",
|
description: "Message DOM tagging and folder indexing",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "timetable-classmates",
|
||||||
|
name: "Timetable Classmates",
|
||||||
|
description: "Classmate avatar sync and SEQTA message polling",
|
||||||
|
},
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export const PERFORMANCE_HEAVY_PLUGIN_IDS = new Set(
|
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");
|
||||||
|
}
|
||||||
@@ -1,9 +1,20 @@
|
|||||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
|
|
||||||
const HOST_OPEN_CLASS = "bsplus-settings-host--open";
|
export const HOST_OPEN_CLASS = "bsplus-settings-host--open";
|
||||||
const HOST_CLOSING_CLASS = "bsplus-settings-host--closing";
|
const HOST_CLOSING_CLASS = "bsplus-settings-host--closing";
|
||||||
const PANEL_OPEN_CLASS = "bsplus-settings-panel--open";
|
const PANEL_OPEN_CLASS = "bsplus-settings-panel--open";
|
||||||
|
|
||||||
|
/** True when the settings host is shown (not fully hidden). */
|
||||||
|
export function isSettingsHostVisiblyOpen(host: HTMLElement | null | undefined): boolean {
|
||||||
|
if (!host) return false;
|
||||||
|
if (host.classList.contains("hide")) return false;
|
||||||
|
return host.classList.contains(HOST_OPEN_CLASS);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isExtensionSettingsOpen(): boolean {
|
||||||
|
return isSettingsHostVisiblyOpen(document.getElementById("ExtensionPopup"));
|
||||||
|
}
|
||||||
|
|
||||||
function settingsPanel(host: HTMLElement): HTMLElement | null {
|
function settingsPanel(host: HTMLElement): HTMLElement | null {
|
||||||
return host.shadowRoot?.querySelector<HTMLElement>("[data-settings-panel]") ?? null;
|
return host.shadowRoot?.querySelector<HTMLElement>("[data-settings-panel]") ?? null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,5 @@
|
|||||||
import {
|
import { closeExtensionPopup, getSettingsOpenGeneration } from "./Closers/closeExtensionPopup";
|
||||||
changeSettingsClicked,
|
import { animateSettingsOpen, isExtensionSettingsOpen, prefetchSettingsShell } from "./settingsPopupAnimation";
|
||||||
closeExtensionPopup,
|
|
||||||
SettingsClicked,
|
|
||||||
} from "./Closers/closeExtensionPopup";
|
|
||||||
import {
|
|
||||||
animateSettingsOpen,
|
|
||||||
prefetchSettingsShell,
|
|
||||||
} from "./settingsPopupAnimation";
|
|
||||||
import { renderSettingsIfNeeded } from "./Adders/AddExtensionSettings";
|
import { renderSettingsIfNeeded } from "./Adders/AddExtensionSettings";
|
||||||
|
|
||||||
export function setupSettingsButton() {
|
export function setupSettingsButton() {
|
||||||
@@ -18,8 +11,9 @@ export function setupSettingsButton() {
|
|||||||
|
|
||||||
prefetchSettingsShell();
|
prefetchSettingsShell();
|
||||||
|
|
||||||
AddedSettings.addEventListener("click", async () => {
|
AddedSettings.addEventListener("click", async (event) => {
|
||||||
if (SettingsClicked) {
|
event.stopPropagation();
|
||||||
|
if (isExtensionSettingsOpen()) {
|
||||||
closeExtensionPopup();
|
closeExtensionPopup();
|
||||||
} else {
|
} else {
|
||||||
await openSettingsPopup();
|
await openSettingsPopup();
|
||||||
@@ -27,18 +21,33 @@ export function setupSettingsButton() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let openSettingsInFlight: Promise<void> | null = null;
|
||||||
|
|
||||||
export async function openSettingsPopup(): Promise<void> {
|
export async function openSettingsPopup(): Promise<void> {
|
||||||
if (SettingsClicked && document.getElementById("ExtensionPopup")) return;
|
if (isExtensionSettingsOpen()) return;
|
||||||
|
if (openSettingsInFlight) return openSettingsInFlight;
|
||||||
|
|
||||||
let extensionPopup = document.getElementById("ExtensionPopup");
|
const gen = getSettingsOpenGeneration();
|
||||||
if (!extensionPopup) {
|
|
||||||
const { addExtensionSettings } = await import("./Adders/AddExtensionSettings");
|
|
||||||
addExtensionSettings();
|
|
||||||
extensionPopup = document.getElementById("ExtensionPopup");
|
|
||||||
}
|
|
||||||
if (!extensionPopup) return;
|
|
||||||
|
|
||||||
await renderSettingsIfNeeded();
|
openSettingsInFlight = (async () => {
|
||||||
animateSettingsOpen(extensionPopup);
|
try {
|
||||||
changeSettingsClicked(true);
|
let host = document.getElementById("ExtensionPopup");
|
||||||
|
if (!host) {
|
||||||
|
const { addExtensionSettings } = await import("./Adders/AddExtensionSettings");
|
||||||
|
addExtensionSettings();
|
||||||
|
host = document.getElementById("ExtensionPopup");
|
||||||
|
}
|
||||||
|
if (!host) return;
|
||||||
|
|
||||||
|
await renderSettingsIfNeeded();
|
||||||
|
if (gen !== getSettingsOpenGeneration()) return;
|
||||||
|
|
||||||
|
host = document.getElementById("ExtensionPopup");
|
||||||
|
if (host) animateSettingsOpen(host);
|
||||||
|
} finally {
|
||||||
|
openSettingsInFlight = null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return openSettingsInFlight;
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user