Merge branch 'main' into various-bugfixes

This commit is contained in:
StroepWafel
2026-06-27 15:42:51 +09:30
committed by GitHub
54 changed files with 5073 additions and 42 deletions
@@ -0,0 +1,236 @@
import { verboseLog } from "@/utils/verboseLog";
import {
getStoredEventId,
lessonDateFromSeqtaKey,
normalizeEventMapEntry,
} from "@/seqta/utils/googleCalendar/eventMapEntry";
import {
isDateInRange,
syncWindowRange,
} from "@/seqta/utils/googleCalendar/syncDateRange";
import type {
GoogleCalendarSyncOptions,
GoogleCalendarSyncProgress,
GoogleCalendarSyncResult,
} from "@/seqta/utils/googleCalendar/types";
export const EVENT_MAP_PERSIST_EVERY = 10;
export type EventMapRecord = Record<string, string | { id: string; date: string }>;
export type MappedLessonEvent = {
seqtaKey: string;
startDateTime: string;
};
export function reportSyncProgress(
onProgress: GoogleCalendarSyncOptions["onProgress"],
progress: GoogleCalendarSyncProgress,
) {
onProgress?.(progress);
}
export function lessonDateForEvent(startDateTime: string, seqtaKey: string): string {
return startDateTime.slice(0, 10) || lessonDateFromSeqtaKey(seqtaKey) || "";
}
export function originEventMapEntries(
eventMap: EventMapRecord,
origin: string,
): Array<[string, string]> {
const prefix = `${origin}::`;
const entries: Array<[string, string]> = [];
for (const [key, value] of Object.entries(eventMap)) {
if (!key.startsWith(prefix)) continue;
const id = getStoredEventId(value);
if (id) entries.push([key, id]);
}
return entries;
}
function shouldPruneEntry(
mode: "full" | "incremental",
entry: { id: string; date: string },
mapKey: string,
window: ReturnType<typeof syncWindowRange>,
currentMapKeys: Set<string>,
): boolean {
if (mode === "incremental") return false;
if (entry.date) return !isDateInRange(entry.date, window);
return !currentMapKeys.has(mapKey);
}
export function entriesToPrune(
eventMap: EventMapRecord,
origin: string,
mode: "full" | "incremental",
weeksAhead: number,
currentMapKeys: Set<string>,
): Array<[string, string]> {
const window = syncWindowRange(weeksAhead);
const prefix = `${origin}::`;
const entries: Array<[string, string]> = [];
for (const [mapKey, raw] of Object.entries(eventMap)) {
if (!mapKey.startsWith(prefix)) continue;
const entry = normalizeEventMapEntry(raw);
if (!entry) continue;
if (shouldPruneEntry(mode, entry, mapKey, window, currentMapKeys)) {
entries.push([mapKey, entry.id]);
}
}
return entries;
}
export function notConfiguredSyncResult(error: string): GoogleCalendarSyncResult {
return { success: false, configured: false, error };
}
export function notConnectedSyncResult(error: string): GoogleCalendarSyncResult {
return { success: false, configured: true, connected: false, error };
}
export function emptyLessonsSyncResult(): GoogleCalendarSyncResult {
return {
success: false,
configured: true,
connected: true,
error: "No timetable classes found to sync for the selected range.",
};
}
export function buildLessonSyncResult(
created: number,
updated: number,
deleted: number,
failed: number,
lastSyncAt: number,
): GoogleCalendarSyncResult {
return {
success: failed === 0,
configured: true,
connected: true,
created,
updated,
deleted,
skipped: 0,
failed,
lastSyncAt,
error:
failed > 0
? `Synced with ${failed} error${failed === 1 ? "" : "s"}. Check the console for details.`
: undefined,
};
}
export async function persistFinalSyncState(
writeState: (patch: {
eventMap: EventMapRecord;
lastSyncAt: number;
lastSyncOrigin: string;
}) => Promise<unknown>,
eventMap: EventMapRecord,
lastSyncAt: number,
origin: string,
staleDeleted: number,
staleEntryCount: number,
eventCount: number,
): Promise<void> {
if (staleDeleted > 0 || staleEntryCount > 0 || eventCount > 0) {
await writeState({ eventMap, lastSyncAt, lastSyncOrigin: origin });
}
}
type UpsertLessonEventsParams<TEvent extends MappedLessonEvent> = {
events: TEvent[];
eventMap: EventMapRecord;
origin: string;
staleEntryCount: number;
totalSteps: number;
lastSyncAt: number;
initialFailed: number;
getAccessToken: () => Promise<string>;
mapKey: (origin: string, seqtaKey: string) => string;
upsert: (
accessToken: string,
existingId: string | undefined,
event: TEvent,
refreshAccessToken: () => Promise<string>,
) => Promise<string>;
writeState: (patch: {
eventMap: EventMapRecord;
lastSyncAt: number;
lastSyncOrigin: string;
}) => Promise<unknown>;
onProgress?: GoogleCalendarSyncOptions["onProgress"];
logLabel: string;
};
export async function upsertLessonEvents<TEvent extends MappedLessonEvent>(
params: UpsertLessonEventsParams<TEvent>,
): Promise<{ created: number; updated: number; failed: number; accessToken: string }> {
const {
events,
eventMap,
origin,
staleEntryCount,
totalSteps,
lastSyncAt,
initialFailed,
getAccessToken,
mapKey,
upsert,
writeState,
onProgress,
logLabel,
} = params;
let accessToken = await getAccessToken();
let created = 0;
let updated = 0;
let failed = initialFailed;
for (let i = 0; i < events.length; i++) {
const event = events[i];
const key = mapKey(origin, event.seqtaKey);
const existingId = getStoredEventId(eventMap[key]);
const progressCurrent = staleEntryCount + i + 1;
const progressMessage = `Syncing events (${i + 1}/${events.length})…`;
try {
const remoteId = await upsert(accessToken, existingId, event, async () => {
accessToken = await getAccessToken();
return accessToken;
});
if (existingId) updated += 1;
else created += 1;
eventMap[key] = {
id: remoteId,
date: lessonDateForEvent(event.startDateTime, event.seqtaKey),
};
reportSyncProgress(onProgress, {
phase: "upserting",
current: progressCurrent,
total: totalSteps,
message: progressMessage,
});
if ((i + 1) % EVENT_MAP_PERSIST_EVERY === 0 || i === events.length - 1) {
await writeState({ eventMap, lastSyncAt, lastSyncOrigin: origin });
}
} catch (err) {
verboseLog(`[BetterSEQTA+] ${logLabel} event sync failed:`, err);
failed += 1;
reportSyncProgress(onProgress, {
phase: "upserting",
current: progressCurrent,
total: totalSteps,
message: progressMessage,
});
}
}
return { created, updated, failed, accessToken };
}
+65
View File
@@ -0,0 +1,65 @@
import {
GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT,
GOOGLE_CALENDAR_SYNC_WEEKS_MAX,
GOOGLE_CALENDAR_SYNC_WEEKS_MIN,
} from "@/config/googleCalendar";
import { readOutlookCalendarState } from "@/seqta/utils/outlookCalendar/storage";
import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/storage";
import {
readSharedCalendarSyncSettings,
WEEKLY_SYNC_INTERVAL_MS,
writeSharedCalendarSyncSettings,
} from "./sharedSettings";
export { CALENDAR_WEEKLY_ALARM, WEEKLY_SYNC_INTERVAL_MS } from "./sharedSettings";
export function clampSyncWeeks(weeks: number): number {
if (!Number.isFinite(weeks)) return GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT;
return Math.min(
GOOGLE_CALENDAR_SYNC_WEEKS_MAX,
Math.max(GOOGLE_CALENDAR_SYNC_WEEKS_MIN, Math.round(weeks)),
);
}
export async function getSyncWeeksAhead(): Promise<number> {
const settings = await readSharedCalendarSyncSettings();
return clampSyncWeeks(settings.syncWeeksAhead ?? GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT);
}
export async function getAutoSyncWeekly(): Promise<boolean> {
const settings = await readSharedCalendarSyncSettings();
return settings.autoSyncWeekly !== false;
}
async function isAnyCalendarConnected(): Promise<boolean> {
const [google, outlook] = await Promise.all([
readGoogleCalendarState(),
readOutlookCalendarState(),
]);
return !!(
google.refreshToken ||
google.accessToken ||
outlook.refreshToken ||
outlook.accessToken
);
}
export async function shouldRunWeeklySync(): Promise<boolean> {
const settings = await readSharedCalendarSyncSettings();
if (settings.autoSyncWeekly === false) return false;
if (!(await isAnyCalendarConnected())) return false;
if (settings.pendingWeeklySync) return true;
const last = settings.lastWeeklySyncAt ?? 0;
return Date.now() - last >= WEEKLY_SYNC_INTERVAL_MS;
}
export async function markWeeklySyncComplete(): Promise<void> {
await writeSharedCalendarSyncSettings({
lastWeeklySyncAt: Date.now(),
pendingWeeklySync: false,
});
}
export async function markWeeklySyncPending(): Promise<void> {
await writeSharedCalendarSyncSettings({ pendingWeeklySync: true });
}
@@ -0,0 +1,48 @@
import browser from "webextension-polyfill";
import {
GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT,
} from "@/config/googleCalendar";
import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/storage";
export const BSPLUS_CALENDAR_SYNC_SETTINGS_KEY = "bsplus_calendar_sync_settings";
export const CALENDAR_WEEKLY_ALARM = "bsplus_calendar_weekly";
export const WEEKLY_SYNC_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
export interface SharedCalendarSyncSettings {
syncWeeksAhead?: number;
autoSyncWeekly?: boolean;
lastWeeklySyncAt?: number;
pendingWeeklySync?: boolean;
}
export async function readSharedCalendarSyncSettings(): Promise<SharedCalendarSyncSettings> {
const got = await browser.storage.local.get(BSPLUS_CALENDAR_SYNC_SETTINGS_KEY);
const raw = got[BSPLUS_CALENDAR_SYNC_SETTINGS_KEY];
const shared =
raw && typeof raw === "object" && !Array.isArray(raw)
? (raw as SharedCalendarSyncSettings)
: {};
if (Object.keys(shared).length > 0) return shared;
const legacy = await readGoogleCalendarState();
return {
syncWeeksAhead: legacy.syncWeeksAhead,
autoSyncWeekly: legacy.autoSyncWeekly,
lastWeeklySyncAt: legacy.lastWeeklySyncAt,
pendingWeeklySync: legacy.pendingWeeklySync,
};
}
export async function writeSharedCalendarSyncSettings(
patch: Partial<SharedCalendarSyncSettings>,
): Promise<SharedCalendarSyncSettings> {
const current = await readSharedCalendarSyncSettings();
const next = { ...current, ...patch };
await browser.storage.local.set({ [BSPLUS_CALENDAR_SYNC_SETTINGS_KEY]: next });
return next;
}
export function defaultSyncWeeksAhead(): number {
return GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT;
}
@@ -0,0 +1,51 @@
import type { GoogleCalendarSyncResult } from "@/seqta/utils/googleCalendar/types";
import { formatSyncResultMessage } from "@/seqta/utils/googleCalendar/syncRunner";
import { formatOutlookSyncResultMessage } from "@/seqta/utils/outlookCalendar/syncRunner";
type ProviderCalendarState = {
refreshToken?: string;
accessToken?: string;
};
function isProviderConnected(state: ProviderCalendarState): boolean {
return Boolean(state.refreshToken || state.accessToken);
}
function providerHadChanges(result: GoogleCalendarSyncResult): boolean {
return (
(result.created ?? 0) + (result.updated ?? 0) + (result.deleted ?? 0) > 0
);
}
export function weeklySyncErrorMessage(
results: GoogleCalendarSyncResult[],
): string | undefined {
const failed = results.find((result) => !result.success);
if (!failed) return undefined;
return failed.error ?? "Weekly calendar sync failed.";
}
export function formatWeeklySyncMessages(
google: ProviderCalendarState,
outlook: ProviderCalendarState,
results: GoogleCalendarSyncResult[],
): string[] {
const messages: string[] = [];
let index = 0;
if (isProviderConnected(google)) {
const result = results[index++];
if (result && providerHadChanges(result)) {
messages.push(formatSyncResultMessage(result));
}
}
if (isProviderConnected(outlook)) {
const result = results[index++];
if (result && providerHadChanges(result)) {
messages.push(formatOutlookSyncResultMessage(result));
}
}
return messages;
}
+2
View File
@@ -37,6 +37,7 @@ export const KEYS_OMITTED_FROM_CLOUD_UPLOAD = [
"bsplus_user",
"cloudAccessToken",
"cloudUsername",
"bsplus_google_calendar",
] as const;
/**
@@ -67,6 +68,7 @@ const AUTH_KEYS_TO_PRESERVE = [
"bsplus_refresh_token",
"bsplus_client_id",
"bsplus_user",
"bsplus_google_calendar",
] as const;
const OMIT_FROM_UPLOAD_EXACT = new Set<string>([
@@ -0,0 +1,76 @@
import {
GOOGLE_CALENDAR_ACCOUNTS_NOT_READY_HINT,
GOOGLE_CALENDAR_REFRESH_URL,
GOOGLE_CALENDAR_TOKEN_URL,
} from "@/config/googleCalendar";
type GoogleTokenPayload = {
access_token: string;
refresh_token?: string;
expires_in?: number;
};
async function parseAccountsJson(res: Response): Promise<Record<string, unknown>> {
const text = await res.text();
try {
return text ? (JSON.parse(text) as Record<string, unknown>) : {};
} catch {
return {};
}
}
function extractTokens(json: Record<string, unknown>): GoogleTokenPayload {
const access_token = json.access_token;
if (typeof access_token !== "string" || !access_token) {
throw new Error("Token response missing access_token");
}
return {
access_token,
refresh_token: typeof json.refresh_token === "string" ? json.refresh_token : undefined,
expires_in: typeof json.expires_in === "number" ? json.expires_in : undefined,
};
}
function formatAccountsTokenError(res: Response, json: Record<string, unknown>): string {
if (res.status === 404 || res.status === 501) {
return GOOGLE_CALENDAR_ACCOUNTS_NOT_READY_HINT;
}
const err = typeof json.error === "string" ? json.error : "";
return err || `Accounts token API failed (${res.status})`;
}
export async function exchangeGoogleCodeViaAccounts(
code: string,
redirectUri: string,
codeVerifier: string,
): Promise<GoogleTokenPayload> {
const res = await fetch(GOOGLE_CALENDAR_TOKEN_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier,
}),
});
const json = await parseAccountsJson(res);
if (!res.ok) {
throw new Error(formatAccountsTokenError(res, json));
}
return extractTokens(json);
}
export async function refreshGoogleTokenViaAccounts(
refreshToken: string,
): Promise<GoogleTokenPayload> {
const res = await fetch(GOOGLE_CALENDAR_REFRESH_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refresh_token: refreshToken }),
});
const json = await parseAccountsJson(res);
if (!res.ok) {
throw new Error(formatAccountsTokenError(res, json));
}
return extractTokens(json);
}
@@ -0,0 +1,84 @@
import browser from "webextension-polyfill";
import {
markWeeklySyncComplete,
shouldRunWeeklySync,
} from "@/seqta/utils/calendarSync/settings";
import {
formatWeeklySyncMessages,
weeklySyncErrorMessage,
} from "@/seqta/utils/calendarSync/weeklySyncMessages";
import { runGoogleCalendarSync } from "@/seqta/utils/googleCalendar/syncRunner";
import { runOutlookCalendarSync } from "@/seqta/utils/outlookCalendar/syncRunner";
import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/storage";
import { readOutlookCalendarState } from "@/seqta/utils/outlookCalendar/storage";
import type { GoogleCalendarSyncResult } from "@/seqta/utils/googleCalendar/types";
let listenerRegistered = false;
async function runWeeklySyncForConnectedProviders(): Promise<GoogleCalendarSyncResult[]> {
const [google, outlook] = await Promise.all([
readGoogleCalendarState(),
readOutlookCalendarState(),
]);
const results: GoogleCalendarSyncResult[] = [];
if (google.refreshToken || google.accessToken) {
results.push(await runGoogleCalendarSync({ mode: "incremental", silent: true }));
}
if (outlook.refreshToken || outlook.accessToken) {
results.push(await runOutlookCalendarSync({ mode: "incremental", silent: true }));
}
if (results.some((r) => r.success)) {
await markWeeklySyncComplete();
}
return results;
}
export function registerCalendarContentHandlers(): void {
if (listenerRegistered) return;
listenerRegistered = true;
browser.runtime.onMessage.addListener((request, _sender, sendResponse) => {
if (request?.type === "calendarRunWeeklySync" || request?.type === "googleCalendarRunWeeklySync") {
void runWeeklySyncForConnectedProviders()
.then((results) => sendResponse({ success: true, results }))
.catch((err: unknown) => {
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Weekly sync failed",
});
});
return true;
}
return false;
});
}
export async function maybeRunDueWeeklySync(
onComplete?: (message: string, isError?: boolean) => void,
): Promise<void> {
if (!(await shouldRunWeeklySync())) return;
const [google, outlook] = await Promise.all([
readGoogleCalendarState(),
readOutlookCalendarState(),
]);
const results = await runWeeklySyncForConnectedProviders();
if (!onComplete) return;
const errorMessage = weeklySyncErrorMessage(results);
if (errorMessage) {
onComplete(errorMessage, true);
return;
}
const messages = formatWeeklySyncMessages(google, outlook, results);
if (messages.length > 0) {
onComplete(messages.join(" "));
}
}
/** @deprecated use registerCalendarContentHandlers */
export const registerGoogleCalendarContentHandlers = registerCalendarContentHandlers;
@@ -0,0 +1,29 @@
export interface GoogleCalendarEventMapEntry {
id: string;
date: string;
}
export function normalizeEventMapEntry(
value: string | GoogleCalendarEventMapEntry | undefined,
): GoogleCalendarEventMapEntry | undefined {
if (value == null) return undefined;
if (typeof value === "string") return { id: value, date: "" };
if (typeof value.id === "string" && value.id.length > 0) {
return { id: value.id, date: value.date ?? "" };
}
return undefined;
}
export function getStoredEventId(
value: string | GoogleCalendarEventMapEntry | undefined,
): string | undefined {
return normalizeEventMapEntry(value)?.id;
}
export function lessonDateFromSeqtaKey(seqtaKey: string): string | undefined {
const parts = seqtaKey.split(":");
for (const part of parts) {
if (/^\d{4}-\d{2}-\d{2}$/.test(part)) return part;
}
return undefined;
}
@@ -0,0 +1,64 @@
import { describe, expect, it } from "@jest/globals";
import {
lessonToGoogleEvent,
mapLessonsToGoogleEvents,
seqtaLessonKey,
shouldSyncLesson,
} from "./eventMapper";
import type { SeqtaTimetableLesson } from "./types";
const ORIGIN = "https://school.seqta.com.au";
const baseLesson: SeqtaTimetableLesson = {
date: "2026-06-27",
from: "09:00:00",
until: "10:00:00",
description: "10 Mathematics",
staff: "Mr Smith",
room: "MA1",
code: "10MAT",
type: "class",
calendarid: 12345,
};
describe("shouldSyncLesson", () => {
it("accepts normal class rows", () => {
expect(shouldSyncLesson(baseLesson)).toBe(true);
});
it("rejects holidays and rows without times", () => {
expect(shouldSyncLesson({ ...baseLesson, type: "holiday" })).toBe(false);
expect(shouldSyncLesson({ ...baseLesson, from: "" })).toBe(false);
});
});
describe("seqtaLessonKey", () => {
it("prefers calendarid when present", () => {
expect(seqtaLessonKey(ORIGIN, baseLesson)).toBe(`${ORIGIN}:cal:12345`);
});
});
describe("lessonToGoogleEvent", () => {
it("maps SEQTA lesson fields to Google event input", () => {
const event = lessonToGoogleEvent(ORIGIN, baseLesson, "Australia/Perth");
expect(event).toMatchObject({
summary: "10 Mathematics",
location: "MA1",
startDateTime: "2026-06-27T09:00:00",
endDateTime: "2026-06-27T10:00:00",
timeZone: "Australia/Perth",
});
expect(event?.description).toContain("Mr Smith");
});
});
describe("mapLessonsToGoogleEvents", () => {
it("deduplicates by seqta key", () => {
const events = mapLessonsToGoogleEvents(
ORIGIN,
[baseLesson, { ...baseLesson }],
"Australia/Perth",
);
expect(events).toHaveLength(1);
});
});
@@ -0,0 +1,95 @@
import { BSPLUS_GOOGLE_CALENDAR_EVENT_PROP } from "@/config/googleCalendar";
import type { GoogleCalendarEventInput, SeqtaTimetableLesson } from "./types";
const SKIP_TYPES = new Set(["note", "holiday", "assembly-note"]);
function normalizeTime(value: string): string {
const trimmed = value.trim();
if (/^\d{1,2}:\d{2}:\d{2}$/.test(trimmed)) return trimmed.slice(0, 5);
if (/^\d{1,2}:\d{2}$/.test(trimmed)) return trimmed;
return trimmed;
}
export function seqtaLessonKey(origin: string, lesson: SeqtaTimetableLesson): string {
if (lesson.calendarid != null && String(lesson.calendarid).length > 0) {
return `${origin}:cal:${lesson.calendarid}`;
}
if (lesson.ci != null) {
return `${origin}:ci:${lesson.ci}:${lesson.date}:${normalizeTime(lesson.from)}`;
}
return [
origin,
lesson.date,
normalizeTime(lesson.from),
lesson.code ?? "",
lesson.description ?? "",
].join(":");
}
export function shouldSyncLesson(lesson: SeqtaTimetableLesson): boolean {
if (!lesson.date || !lesson.from || !lesson.until) return false;
if (lesson.type && SKIP_TYPES.has(lesson.type.toLowerCase())) return false;
const title = (lesson.description ?? lesson.code ?? "").trim();
if (!title) return false;
return true;
}
export function lessonToGoogleEvent(
origin: string,
lesson: SeqtaTimetableLesson,
timeZone: string,
): GoogleCalendarEventInput | null {
if (!shouldSyncLesson(lesson)) return null;
const from = normalizeTime(lesson.from);
const until = normalizeTime(lesson.until);
const summary = (lesson.description ?? lesson.code ?? "Class").trim();
const staff = lesson.staff?.trim();
const room = lesson.room?.trim();
const descriptionLines = ["Synced by BetterSEQTA+"];
if (staff) descriptionLines.push(`Teacher: ${staff}`);
if (lesson.code) descriptionLines.push(`Code: ${lesson.code}`);
if (lesson.period) descriptionLines.push(`Period: ${lesson.period}`);
return {
seqtaKey: seqtaLessonKey(origin, lesson),
summary,
location: room || undefined,
description: descriptionLines.join("\n"),
startDateTime: `${lesson.date}T${from}:00`,
endDateTime: `${lesson.date}T${until}:00`,
timeZone,
};
}
export function mapLessonsToGoogleEvents(
origin: string,
lessons: SeqtaTimetableLesson[],
timeZone: string,
): GoogleCalendarEventInput[] {
const out: GoogleCalendarEventInput[] = [];
const seen = new Set<string>();
for (const lesson of lessons) {
const mapped = lessonToGoogleEvent(origin, lesson, timeZone);
if (!mapped || seen.has(mapped.seqtaKey)) continue;
seen.add(mapped.seqtaKey);
out.push(mapped);
}
return out;
}
export function googleApiEventBody(event: GoogleCalendarEventInput): Record<string, unknown> {
return {
summary: event.summary,
location: event.location,
description: event.description,
start: { dateTime: event.startDateTime, timeZone: event.timeZone },
end: { dateTime: event.endDateTime, timeZone: event.timeZone },
extendedProperties: {
private: {
[BSPLUS_GOOGLE_CALENDAR_EVENT_PROP]: event.seqtaKey,
},
},
};
}
@@ -0,0 +1,80 @@
import type { SyncDateRange } from "./syncDateRange";
import { syncWindowRange } from "./syncDateRange";
import type { SeqtaTimetableLesson } from "./types";
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 resolveStudentId(): Promise<number | undefined> {
try {
const json = await postSeqtaJson<{ payload?: { id?: number; student?: number } }>(
"/seqta/student/login",
{ mode: "normal", query: null, redirect_url: location.origin },
);
const id = json?.payload?.id ?? json?.payload?.student;
return typeof id === "number" && Number.isFinite(id) ? id : undefined;
} catch {
return undefined;
}
}
function isEngageParentContext(): boolean {
return (
location.pathname.includes("/parent/") ||
location.hash.includes("/parent/") ||
document.body.classList.contains("parent")
);
}
export async function fetchTimetableLessons(
range: SyncDateRange,
): Promise<SeqtaTimetableLesson[]> {
const { from, until } = range;
if (isEngageParentContext()) {
const listJson = await postSeqtaJson<{ payload?: { id?: string | number }[] }>(
"/seqta/parent/load/timetable",
{ list: true },
);
const firstChild = Array.isArray(listJson?.payload) ? listJson.payload[0] : undefined;
const studentId = firstChild?.id;
if (studentId == null) {
throw new Error("No student found on this parent account.");
}
const data = await postSeqtaJson<{ payload?: { items?: SeqtaTimetableLesson[] } }>(
"/seqta/parent/load/timetable",
{ from, until, student: studentId },
);
return Array.isArray(data?.payload?.items) ? data.payload.items : [];
}
const studentId = await resolveStudentId();
const body: Record<string, unknown> = { from, until };
if (studentId != null) body.student = studentId;
const data = await postSeqtaJson<{ payload?: { items?: SeqtaTimetableLesson[] } }>(
"/seqta/student/load/timetable?",
body,
);
return Array.isArray(data?.payload?.items) ? data.payload.items : [];
}
export async function fetchTimetableForSync(weeksAhead?: number): Promise<SeqtaTimetableLesson[]> {
return fetchTimetableLessons(syncWindowRange(weeksAhead));
}
export { syncWindowRange, trailingWeekRange, droppedWeekRange } from "./syncDateRange";
+44
View File
@@ -0,0 +1,44 @@
import browser from "webextension-polyfill";
import type { GoogleCalendarEventMapEntry } from "./eventMapEntry";
/** Never uploaded to BetterSEQTA Cloud (OAuth tokens + per-device event map). */
export const BSPLUS_GOOGLE_CALENDAR_STORAGE_KEY = "bsplus_google_calendar";
export interface GoogleCalendarStoredState {
accessToken?: string;
refreshToken?: string;
expiresAt?: number;
connectedAt?: number;
lastSyncAt?: number;
lastWeeklySyncAt?: number;
lastSyncOrigin?: string;
syncWeeksAhead?: number;
autoSyncWeekly?: boolean;
pendingWeeklySync?: boolean;
/** `${origin}::${seqtaKey}` → Google event id (+ lesson date when known) */
eventMap?: Record<string, string | GoogleCalendarEventMapEntry>;
}
export async function readGoogleCalendarState(): Promise<GoogleCalendarStoredState> {
const got = await browser.storage.local.get(BSPLUS_GOOGLE_CALENDAR_STORAGE_KEY);
const raw = got[BSPLUS_GOOGLE_CALENDAR_STORAGE_KEY];
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
return raw as GoogleCalendarStoredState;
}
export async function writeGoogleCalendarState(
patch: Partial<GoogleCalendarStoredState>,
): Promise<GoogleCalendarStoredState> {
const current = await readGoogleCalendarState();
const next: GoogleCalendarStoredState = { ...current, ...patch };
await browser.storage.local.set({ [BSPLUS_GOOGLE_CALENDAR_STORAGE_KEY]: next });
return next;
}
export async function clearGoogleCalendarState(): Promise<void> {
await browser.storage.local.remove(BSPLUS_GOOGLE_CALENDAR_STORAGE_KEY);
}
export function eventMapKey(origin: string, seqtaKey: string): string {
return `${origin}::${seqtaKey}`;
}
@@ -0,0 +1,31 @@
import { describe, expect, it } from "@jest/globals";
import {
droppedWeekRange,
syncWindowRange,
trailingWeekRange,
} from "./syncDateRange";
describe("syncDateRange", () => {
it("builds a 12-week rolling window from the current week", () => {
const range = syncWindowRange(12);
expect(range.from <= range.until).toBe(true);
const start = new Date(`${range.from}T12:00:00`);
const end = new Date(`${range.until}T12:00:00`);
const days = Math.round((end.getTime() - start.getTime()) / 86_400_000) + 1;
expect(days).toBe(12 * 7);
});
it("places the trailing week at the end of the window", () => {
const window = syncWindowRange(12);
const trailing = trailingWeekRange(12);
expect(trailing.from >= window.from).toBe(true);
expect(trailing.until <= window.until).toBe(true);
});
it("places the dropped week before the window start", () => {
const window = syncWindowRange(12);
const dropped = droppedWeekRange(12);
expect(dropped.until < window.from).toBe(true);
});
});
@@ -0,0 +1,45 @@
import {
GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT,
} from "@/config/googleCalendar";
import { toISODate, weekRangeContaining } from "@/seqta/utils/Loaders/engageParentTimetable";
export interface SyncDateRange {
from: string;
until: string;
}
function parseLocalDate(iso: string): Date {
return new Date(`${iso}T12:00:00`);
}
/** Full rolling sync window from the start of the current week. */
export function syncWindowRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT): SyncDateRange {
const { from } = weekRangeContaining(new Date());
const end = parseLocalDate(from);
end.setDate(end.getDate() + weeksAhead * 7 - 1);
return { from, until: toISODate(end) };
}
/** The trailing week at the end of the sync window (added each weekly roll). */
export function trailingWeekRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT): SyncDateRange {
const { from: windowStart } = syncWindowRange(weeksAhead);
const start = parseLocalDate(windowStart);
start.setDate(start.getDate() + (weeksAhead - 1) * 7);
const end = new Date(start);
end.setDate(end.getDate() + 6);
return { from: toISODate(start), until: toISODate(end) };
}
/** The week that rolled off when the window advances (removed each weekly roll). */
export function droppedWeekRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT): SyncDateRange {
const { from: windowStart } = syncWindowRange(weeksAhead);
const end = parseLocalDate(windowStart);
end.setDate(end.getDate() - 1);
const start = new Date(end);
start.setDate(start.getDate() - 6);
return { from: toISODate(start), until: toISODate(end) };
}
export function isDateInRange(date: string, range: SyncDateRange): boolean {
return date >= range.from && date <= range.until;
}
@@ -0,0 +1,152 @@
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
import type { SeqtaTimetableLesson } from "./types";
jest.mock("@/config/googleCalendar", () => ({
isGoogleCalendarConfigured: jest.fn(() => true),
}));
jest.mock("@/utils/verboseLog", () => ({
verboseLog: jest.fn(),
}));
jest.mock("@/seqta/utils/googleCalendar/storage", () => ({
eventMapKey: (origin: string, seqtaKey: string) => `${origin}::${seqtaKey}`,
readGoogleCalendarState: jest.fn(),
writeGoogleCalendarState: jest.fn(async (patch: unknown) => patch),
}));
jest.mock("@/seqta/utils/calendarSync/settings", () => ({
getSyncWeeksAhead: jest.fn(async () => 12),
}));
jest.mock("@/seqta/utils/googleCalendar/upsertEvent", () => ({
upsertGoogleCalendarEvent: jest.fn(),
deleteGoogleCalendarEvent: jest.fn(),
}));
import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/storage";
import {
deleteGoogleCalendarEvent,
upsertGoogleCalendarEvent,
} from "@/seqta/utils/googleCalendar/upsertEvent";
import { deleteSyncedEventsFromGoogleCalendar, syncLessonsToGoogleCalendar } from "./syncEngine";
const ORIGIN = "https://school.seqta.com.au";
const getAccessToken = async () => "test-token";
const baseLesson: SeqtaTimetableLesson = {
date: "2026-06-27",
from: "09:00:00",
until: "10:00:00",
description: "10 Mathematics",
staff: "Mr Smith",
room: "MA1",
code: "10MAT",
type: "class",
calendarid: 12345,
};
describe("syncLessonsToGoogleCalendar", () => {
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(readGoogleCalendarState).mockResolvedValue({
refreshToken: "refresh",
eventMap: {
[`${ORIGIN}::${ORIGIN}:cal:12345`]: { id: "google-existing", date: "2026-06-27" },
[`${ORIGIN}::${ORIGIN}:cal:99999`]: { id: "google-stale", date: "2020-01-06" },
},
});
jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-existing");
jest.mocked(deleteGoogleCalendarEvent).mockResolvedValue(undefined);
});
it("updates existing events and removes stale tracked events on full sync", async () => {
const result = await syncLessonsToGoogleCalendar(
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
getAccessToken,
);
expect(deleteGoogleCalendarEvent).toHaveBeenCalled();
expect(upsertGoogleCalendarEvent).toHaveBeenCalledTimes(1);
expect(result).toMatchObject({
success: true,
created: 0,
updated: 1,
failed: 0,
});
});
it("creates events that are not yet tracked", async () => {
jest.mocked(readGoogleCalendarState).mockResolvedValue({
refreshToken: "refresh",
eventMap: {},
});
jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-new");
const result = await syncLessonsToGoogleCalendar(
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
getAccessToken,
);
expect(deleteGoogleCalendarEvent).not.toHaveBeenCalled();
expect(result).toMatchObject({
success: true,
created: 1,
updated: 0,
deleted: 0,
});
});
it("does not delete events during incremental sync", async () => {
const result = await syncLessonsToGoogleCalendar(
{ origin: ORIGIN, lessons: [baseLesson], mode: "incremental" },
getAccessToken,
);
expect(deleteGoogleCalendarEvent).not.toHaveBeenCalled();
expect(result).toMatchObject({
success: true,
deleted: 0,
});
});
it("reports progress while syncing", async () => {
const progress: Array<{ phase: string; current: number; total: number }> = [];
await syncLessonsToGoogleCalendar(
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
getAccessToken,
{
onProgress: (entry) => progress.push(entry),
},
);
expect(progress.some((entry) => entry.phase === "upserting")).toBe(true);
expect(progress.at(-1)?.phase).toBe("done");
});
});
describe("deleteSyncedEventsFromGoogleCalendar", () => {
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(readGoogleCalendarState).mockResolvedValue({
refreshToken: "refresh",
eventMap: {
[`${ORIGIN}::${ORIGIN}:cal:12345`]: { id: "google-1", date: "2026-06-27" },
[`${ORIGIN}::${ORIGIN}:cal:99999`]: { id: "google-2", date: "2026-06-28" },
"https://other.seqta.com.au::other:key": { id: "google-other", date: "2026-06-28" },
},
});
jest.mocked(deleteGoogleCalendarEvent).mockResolvedValue(undefined);
});
it("deletes only events for the requested origin", async () => {
const result = await deleteSyncedEventsFromGoogleCalendar(ORIGIN, getAccessToken);
expect(deleteGoogleCalendarEvent).toHaveBeenCalledTimes(2);
expect(result).toMatchObject({
success: true,
deleted: 2,
failed: 0,
});
});
});
@@ -0,0 +1,250 @@
import { verboseLog } from "@/utils/verboseLog";
import { isGoogleCalendarConfigured } from "@/config/googleCalendar";
import { googleApiEventBody, mapLessonsToGoogleEvents } from "@/seqta/utils/googleCalendar/eventMapper";
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
import {
buildLessonSyncResult,
emptyLessonsSyncResult,
entriesToPrune,
EVENT_MAP_PERSIST_EVERY,
notConfiguredSyncResult,
notConnectedSyncResult,
originEventMapEntries,
persistFinalSyncState,
reportSyncProgress,
upsertLessonEvents,
} from "@/seqta/utils/calendarSync/lessonSyncShared";
import {
eventMapKey,
readGoogleCalendarState,
writeGoogleCalendarState,
} from "@/seqta/utils/googleCalendar/storage";
import type {
GoogleCalendarDeleteResult,
GoogleCalendarSyncOptions,
GoogleCalendarSyncRequest,
GoogleCalendarSyncResult,
} from "@/seqta/utils/googleCalendar/types";
import {
deleteGoogleCalendarEvent,
upsertGoogleCalendarEvent,
} from "@/seqta/utils/googleCalendar/upsertEvent";
const CALENDAR_ID = "primary";
type DeleteTrackedEventsResult = {
deleted: number;
failed: number;
};
async function deleteTrackedEventsFromGoogle(
entries: Array<[string, string]>,
eventMap: Record<string, string | { id: string; date: string }>,
getAccessToken: () => Promise<string>,
persistProgress = false,
onProgress?: GoogleCalendarSyncOptions["onProgress"],
progressOffset = 0,
progressTotal = 0,
): Promise<DeleteTrackedEventsResult> {
if (entries.length === 0) return { deleted: 0, failed: 0 };
let accessToken = await getAccessToken();
let deleted = 0;
let failed = 0;
for (let i = 0; i < entries.length; i++) {
const [mapKey, eventId] = entries[i];
try {
await deleteGoogleCalendarEvent(accessToken, CALENDAR_ID, eventId, async () => {
accessToken = await getAccessToken();
return accessToken;
});
delete eventMap[mapKey];
deleted += 1;
reportSyncProgress(onProgress, {
phase: "deleting",
current: progressOffset + deleted + failed,
total: progressTotal,
message: `Removing old events (${deleted + failed}/${entries.length})…`,
});
if (persistProgress && (deleted + failed) % EVENT_MAP_PERSIST_EVERY === 0) {
await writeGoogleCalendarState({ eventMap });
}
} catch (err) {
verboseLog("[BetterSEQTA+] Google Calendar event delete failed:", err);
failed += 1;
reportSyncProgress(onProgress, {
phase: "deleting",
current: progressOffset + deleted + failed,
total: progressTotal,
message: `Removing old events (${deleted + failed}/${entries.length})…`,
});
}
}
return { deleted, failed };
}
/** Runs in the content script tab so long syncs are not killed by the MV3 service worker. */
export async function syncLessonsToGoogleCalendar(
request: GoogleCalendarSyncRequest,
getAccessToken: () => Promise<string>,
options: GoogleCalendarSyncOptions = {},
): Promise<GoogleCalendarSyncResult> {
if (!isGoogleCalendarConfigured()) {
return notConfiguredSyncResult(
"Google Calendar is not configured in this extension build.",
);
}
const state = await readGoogleCalendarState();
if (!state.refreshToken && !state.accessToken) {
return notConnectedSyncResult("Connect Google Calendar first.");
}
const mode = request.mode ?? "full";
const weeksAhead = request.weeksAhead ?? (await getSyncWeeksAhead());
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
const events = mapLessonsToGoogleEvents(request.origin, request.lessons, timeZone);
if (events.length === 0 && mode === "full") {
return emptyLessonsSyncResult();
}
reportSyncProgress(options.onProgress, {
phase: "preparing",
current: 0,
total: Math.max(events.length, 1),
message: mode === "incremental" ? "Preparing weekly sync…" : "Preparing sync…",
});
const eventMap = { ...(state.eventMap ?? {}) };
const currentMapKeys = new Set(events.map((event) => eventMapKey(request.origin, event.seqtaKey)));
const staleEntries = entriesToPrune(eventMap, request.origin, mode, weeksAhead, currentMapKeys);
const totalSteps = staleEntries.length + events.length;
const lastSyncAt = Date.now();
const staleResult = await deleteTrackedEventsFromGoogle(
staleEntries,
eventMap,
getAccessToken,
false,
options.onProgress,
0,
totalSteps,
);
const upsertResult = await upsertLessonEvents({
events,
eventMap,
origin: request.origin,
staleEntryCount: staleEntries.length,
totalSteps,
lastSyncAt,
initialFailed: staleResult.failed,
getAccessToken,
mapKey: eventMapKey,
upsert: (accessToken, existingId, event, refreshAccessToken) =>
upsertGoogleCalendarEvent(
accessToken,
CALENDAR_ID,
existingId,
googleApiEventBody(event),
refreshAccessToken,
),
writeState: writeGoogleCalendarState,
onProgress: options.onProgress,
logLabel: "Google Calendar",
});
await persistFinalSyncState(
writeGoogleCalendarState,
eventMap,
lastSyncAt,
request.origin,
staleResult.deleted,
staleEntries.length,
events.length,
);
reportSyncProgress(options.onProgress, {
phase: "done",
current: totalSteps,
total: totalSteps,
message: "Sync complete",
});
return buildLessonSyncResult(
upsertResult.created,
upsertResult.updated,
staleResult.deleted,
upsertResult.failed,
lastSyncAt,
);
}
/** Delete all tracked BetterSEQTA+ events for this SEQTA origin from Google Calendar. */
export async function deleteSyncedEventsFromGoogleCalendar(
origin: string,
getAccessToken: () => Promise<string>,
options: GoogleCalendarSyncOptions = {},
): Promise<GoogleCalendarDeleteResult> {
if (!isGoogleCalendarConfigured()) {
return {
success: false,
configured: false,
error: "Google Calendar is not configured in this extension build.",
};
}
const state = await readGoogleCalendarState();
if (!state.refreshToken && !state.accessToken) {
return { success: false, configured: true, connected: false, error: "Connect Google Calendar first." };
}
const entries = originEventMapEntries(state.eventMap ?? {}, origin);
if (entries.length === 0) {
return { success: true, configured: true, connected: true, deleted: 0, failed: 0 };
}
reportSyncProgress(options.onProgress, {
phase: "preparing",
current: 0,
total: entries.length,
message: "Preparing removal…",
});
const eventMap = { ...(state.eventMap ?? {}) };
const { deleted, failed } = await deleteTrackedEventsFromGoogle(
entries,
eventMap,
getAccessToken,
true,
options.onProgress,
0,
entries.length,
);
await writeGoogleCalendarState({ eventMap });
reportSyncProgress(options.onProgress, {
phase: "done",
current: entries.length,
total: entries.length,
message: "Removal complete",
});
return {
success: failed === 0,
configured: true,
connected: true,
deleted,
failed,
error:
failed > 0
? `Removed ${deleted} event${deleted === 1 ? "" : "s"} with ${failed} error${failed === 1 ? "" : "s"}.`
: undefined,
};
}
@@ -0,0 +1,76 @@
import browser from "webextension-polyfill";
import {
fetchTimetableForSync,
fetchTimetableLessons,
trailingWeekRange,
} from "@/seqta/utils/googleCalendar/fetchTimetable";
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
import { syncLessonsToGoogleCalendar } from "@/seqta/utils/googleCalendar/syncEngine";
import type {
GoogleCalendarSyncOptions,
GoogleCalendarSyncProgress,
GoogleCalendarSyncResult,
} from "@/seqta/utils/googleCalendar/types";
export type GoogleCalendarRunMode = "full" | "incremental";
export interface RunGoogleCalendarSyncParams {
mode?: GoogleCalendarRunMode;
silent?: boolean;
onProgress?: (progress: GoogleCalendarSyncProgress) => void;
}
async function getAccessTokenFromBackground(): Promise<string> {
const res = (await browser.runtime.sendMessage({
type: "googleCalendarGetAccessToken",
})) as { success?: boolean; accessToken?: string; error?: string };
if (!res?.success || !res.accessToken) {
throw new Error(res?.error ?? "Could not get Google Calendar access token.");
}
return res.accessToken;
}
export async function runGoogleCalendarSync(
params: RunGoogleCalendarSyncParams = {},
): Promise<GoogleCalendarSyncResult> {
const mode = params.mode ?? "full";
const weeksAhead = await getSyncWeeksAhead();
params.onProgress?.({
phase: "preparing",
current: 0,
total: 1,
message: mode === "incremental" ? "Fetching new week…" : "Fetching timetable…",
});
const lessons =
mode === "incremental"
? await fetchTimetableLessons(trailingWeekRange(weeksAhead))
: await fetchTimetableForSync(weeksAhead);
const options: GoogleCalendarSyncOptions = { onProgress: params.onProgress };
const result = await syncLessonsToGoogleCalendar(
{
origin: location.origin,
lessons,
mode,
weeksAhead,
},
getAccessTokenFromBackground,
options,
);
return result;
}
export function formatSyncResultMessage(result: GoogleCalendarSyncResult): string {
const created = result.created ?? 0;
const updated = result.updated ?? 0;
const deleted = result.deleted ?? 0;
const parts: string[] = [];
if (created > 0) parts.push(`${created} new`);
if (updated > 0) parts.push(`${updated} updated`);
if (deleted > 0) parts.push(`${deleted} removed`);
if (parts.length === 0) return "Google Calendar is up to date.";
return `Google Calendar updated (${parts.join(", ")}).`;
}
@@ -0,0 +1,10 @@
export {
CALENDAR_WEEKLY_ALARM as GOOGLE_CALENDAR_WEEKLY_ALARM,
WEEKLY_SYNC_INTERVAL_MS,
clampSyncWeeks,
getAutoSyncWeekly,
getSyncWeeksAhead,
markWeeklySyncComplete,
markWeeklySyncPending,
shouldRunWeeklySync,
} from "@/seqta/utils/calendarSync/settings";
+75
View File
@@ -0,0 +1,75 @@
export interface SeqtaTimetableLesson {
date: string;
from: string;
until: string;
description: string;
staff?: string;
room?: string;
code?: string;
type?: string;
period?: string;
calendarid?: string | number;
ci?: number;
}
export interface GoogleCalendarEventInput {
seqtaKey: string;
summary: string;
location?: string;
description?: string;
startDateTime: string;
endDateTime: string;
timeZone: string;
}
export interface GoogleCalendarSyncRequest {
origin: string;
lessons: SeqtaTimetableLesson[];
mode?: "full" | "incremental";
weeksAhead?: number;
}
export type GoogleCalendarSyncPhase = "preparing" | "deleting" | "upserting" | "done";
export interface GoogleCalendarSyncProgress {
phase: GoogleCalendarSyncPhase;
current: number;
total: number;
message: string;
}
export interface GoogleCalendarSyncOptions {
onProgress?: (progress: GoogleCalendarSyncProgress) => void;
}
export interface GoogleCalendarSyncResult {
success: boolean;
connected?: boolean;
configured?: boolean;
created?: number;
updated?: number;
deleted?: number;
skipped?: number;
failed?: number;
lastSyncAt?: number;
error?: string;
}
export interface GoogleCalendarStatus {
configured: boolean;
connected: boolean;
lastSyncAt?: number;
lastWeeklySyncAt?: number;
lastSyncOrigin?: string;
syncWeeksAhead?: number;
autoSyncWeekly?: boolean;
}
export interface GoogleCalendarDeleteResult {
success: boolean;
configured?: boolean;
connected?: boolean;
deleted?: number;
failed?: number;
error?: string;
}
@@ -0,0 +1,63 @@
import { GOOGLE_CALENDAR_API } from "@/config/googleCalendar";
export async function upsertGoogleCalendarEvent(
accessToken: string,
calendarId: string,
existingEventId: string | undefined,
body: Record<string, unknown>,
refreshAccessToken?: () => Promise<string>,
): Promise<string> {
const headers = {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
};
if (existingEventId) {
const res = await fetch(
`${GOOGLE_CALENDAR_API}/calendars/${encodeURIComponent(calendarId)}/events/${encodeURIComponent(existingEventId)}`,
{ method: "PATCH", headers, body: JSON.stringify(body) },
);
if (res.status === 401 && refreshAccessToken) {
const nextToken = await refreshAccessToken();
return upsertGoogleCalendarEvent(nextToken, calendarId, existingEventId, body);
}
if (res.ok) return existingEventId;
if (res.status !== 404) {
const err = (await res.json().catch(() => ({}))) as { error?: { message?: string } };
throw new Error(err?.error?.message ?? `Google Calendar update failed (${res.status})`);
}
}
const res = await fetch(
`${GOOGLE_CALENDAR_API}/calendars/${encodeURIComponent(calendarId)}/events`,
{ method: "POST", headers, body: JSON.stringify(body) },
);
if (res.status === 401 && refreshAccessToken) {
const nextToken = await refreshAccessToken();
return upsertGoogleCalendarEvent(nextToken, calendarId, undefined, body);
}
const json = (await res.json().catch(() => ({}))) as { id?: string; error?: { message?: string } };
if (!res.ok || !json.id) {
throw new Error(json?.error?.message ?? `Google Calendar create failed (${res.status})`);
}
return json.id;
}
export async function deleteGoogleCalendarEvent(
accessToken: string,
calendarId: string,
eventId: string,
refreshAccessToken?: () => Promise<string>,
): Promise<void> {
const res = await fetch(
`${GOOGLE_CALENDAR_API}/calendars/${encodeURIComponent(calendarId)}/events/${encodeURIComponent(eventId)}`,
{ method: "DELETE", headers: { Authorization: `Bearer ${accessToken}` } },
);
if (res.status === 401 && refreshAccessToken) {
const nextToken = await refreshAccessToken();
return deleteGoogleCalendarEvent(nextToken, calendarId, eventId);
}
if (res.ok || res.status === 404 || res.status === 410) return;
const err = (await res.json().catch(() => ({}))) as { error?: { message?: string } };
throw new Error(err?.error?.message ?? `Google Calendar delete failed (${res.status})`);
}
@@ -0,0 +1,77 @@
import {
OUTLOOK_CALENDAR_ACCOUNTS_NOT_READY_HINT,
OUTLOOK_CALENDAR_REFRESH_URL,
OUTLOOK_CALENDAR_TOKEN_URL,
} from "@/config/outlookCalendar";
type OutlookTokenPayload = {
access_token: string;
refresh_token?: string;
expires_in?: number;
};
async function parseAccountsJson(res: Response): Promise<Record<string, unknown>> {
const text = await res.text();
try {
return text ? (JSON.parse(text) as Record<string, unknown>) : {};
} catch {
return {};
}
}
function extractTokens(json: Record<string, unknown>): OutlookTokenPayload {
const access_token = json.access_token;
if (typeof access_token !== "string" || !access_token) {
throw new Error("Token response missing access_token");
}
return {
access_token,
refresh_token: typeof json.refresh_token === "string" ? json.refresh_token : undefined,
expires_in: typeof json.expires_in === "number" ? json.expires_in : undefined,
};
}
function formatAccountsTokenError(res: Response, json: Record<string, unknown>): string {
if (res.status === 404 || res.status === 501) {
return OUTLOOK_CALENDAR_ACCOUNTS_NOT_READY_HINT;
}
const err = typeof json.error === "string" ? json.error : "";
const desc = typeof json.error_description === "string" ? json.error_description : "";
return desc || err || `Accounts token API failed (${res.status})`;
}
export async function exchangeOutlookCodeViaAccounts(
code: string,
redirectUri: string,
codeVerifier: string,
): Promise<OutlookTokenPayload> {
const res = await fetch(OUTLOOK_CALENDAR_TOKEN_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier,
}),
});
const json = await parseAccountsJson(res);
if (!res.ok) {
throw new Error(formatAccountsTokenError(res, json));
}
return extractTokens(json);
}
export async function refreshOutlookTokenViaAccounts(
refreshToken: string,
): Promise<OutlookTokenPayload> {
const res = await fetch(OUTLOOK_CALENDAR_REFRESH_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refresh_token: refreshToken }),
});
const json = await parseAccountsJson(res);
if (!res.ok) {
throw new Error(formatAccountsTokenError(res, json));
}
return extractTokens(json);
}
@@ -0,0 +1,36 @@
import { BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY } from "@/config/outlookCalendar";
import type {
GoogleCalendarEventInput,
SeqtaTimetableLesson,
} from "@/seqta/utils/googleCalendar/types";
import {
lessonToGoogleEvent,
mapLessonsToGoogleEvents,
} from "@/seqta/utils/googleCalendar/eventMapper";
export { mapLessonsToGoogleEvents, lessonToGoogleEvent, seqtaLessonKey } from "@/seqta/utils/googleCalendar/eventMapper";
export function outlookGraphEventBody(event: GoogleCalendarEventInput): Record<string, unknown> {
const body: Record<string, unknown> = {
subject: event.summary,
body: {
contentType: "text",
content: event.description ?? "Synced by BetterSEQTA+",
},
start: { dateTime: event.startDateTime, timeZone: event.timeZone },
end: { dateTime: event.endDateTime, timeZone: event.timeZone },
categories: [BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY],
};
if (event.location) {
body.location = { displayName: event.location };
}
return body;
}
export function mapLessonsToOutlookEvents(
origin: string,
lessons: SeqtaTimetableLesson[],
timeZone: string,
): GoogleCalendarEventInput[] {
return mapLessonsToGoogleEvents(origin, lessons, timeZone);
}
@@ -0,0 +1,38 @@
import browser from "webextension-polyfill";
import type { GoogleCalendarEventMapEntry } from "@/seqta/utils/googleCalendar/eventMapEntry";
export const BSPLUS_OUTLOOK_CALENDAR_STORAGE_KEY = "bsplus_outlook_calendar";
export interface OutlookCalendarStoredState {
accessToken?: string;
refreshToken?: string;
expiresAt?: number;
connectedAt?: number;
lastSyncAt?: number;
lastSyncOrigin?: string;
eventMap?: Record<string, string | GoogleCalendarEventMapEntry>;
}
export async function readOutlookCalendarState(): Promise<OutlookCalendarStoredState> {
const got = await browser.storage.local.get(BSPLUS_OUTLOOK_CALENDAR_STORAGE_KEY);
const raw = got[BSPLUS_OUTLOOK_CALENDAR_STORAGE_KEY];
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
return raw as OutlookCalendarStoredState;
}
export async function writeOutlookCalendarState(
patch: Partial<OutlookCalendarStoredState>,
): Promise<OutlookCalendarStoredState> {
const current = await readOutlookCalendarState();
const next: OutlookCalendarStoredState = { ...current, ...patch };
await browser.storage.local.set({ [BSPLUS_OUTLOOK_CALENDAR_STORAGE_KEY]: next });
return next;
}
export async function clearOutlookCalendarState(): Promise<void> {
await browser.storage.local.remove(BSPLUS_OUTLOOK_CALENDAR_STORAGE_KEY);
}
export function outlookEventMapKey(origin: string, seqtaKey: string): string {
return `${origin}::${seqtaKey}`;
}
@@ -0,0 +1,249 @@
import { verboseLog } from "@/utils/verboseLog";
import { isOutlookCalendarConfigured } from "@/config/outlookCalendar";
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
import {
buildLessonSyncResult,
emptyLessonsSyncResult,
entriesToPrune,
EVENT_MAP_PERSIST_EVERY,
notConfiguredSyncResult,
notConnectedSyncResult,
originEventMapEntries,
persistFinalSyncState,
reportSyncProgress,
upsertLessonEvents,
} from "@/seqta/utils/calendarSync/lessonSyncShared";
import type {
GoogleCalendarDeleteResult,
GoogleCalendarSyncOptions,
GoogleCalendarSyncRequest,
GoogleCalendarSyncResult,
} from "@/seqta/utils/googleCalendar/types";
import {
mapLessonsToOutlookEvents,
outlookGraphEventBody,
} from "@/seqta/utils/outlookCalendar/eventMapper";
import {
outlookEventMapKey,
readOutlookCalendarState,
writeOutlookCalendarState,
} from "@/seqta/utils/outlookCalendar/storage";
import {
deleteOutlookCalendarEvent,
upsertOutlookCalendarEvent,
} from "@/seqta/utils/outlookCalendar/upsertEvent";
type DeleteTrackedEventsResult = {
deleted: number;
failed: number;
};
async function deleteTrackedEventsFromOutlook(
entries: Array<[string, string]>,
eventMap: Record<string, string | { id: string; date: string }>,
getAccessToken: () => Promise<string>,
persistProgress = false,
onProgress?: GoogleCalendarSyncOptions["onProgress"],
progressOffset = 0,
progressTotal = 0,
): Promise<DeleteTrackedEventsResult> {
if (entries.length === 0) return { deleted: 0, failed: 0 };
let accessToken = await getAccessToken();
let deleted = 0;
let failed = 0;
for (const [mapKey, eventId] of entries) {
try {
await deleteOutlookCalendarEvent(accessToken, eventId, async () => {
accessToken = await getAccessToken();
return accessToken;
});
delete eventMap[mapKey];
deleted += 1;
reportSyncProgress(onProgress, {
phase: "deleting",
current: progressOffset + deleted + failed,
total: progressTotal,
message: `Removing old events (${deleted + failed}/${entries.length})…`,
});
if (persistProgress && (deleted + failed) % EVENT_MAP_PERSIST_EVERY === 0) {
await writeOutlookCalendarState({ eventMap });
}
} catch (err) {
verboseLog("[BetterSEQTA+] Outlook Calendar event delete failed:", err);
failed += 1;
reportSyncProgress(onProgress, {
phase: "deleting",
current: progressOffset + deleted + failed,
total: progressTotal,
message: `Removing old events (${deleted + failed}/${entries.length})…`,
});
}
}
return { deleted, failed };
}
export async function syncLessonsToOutlookCalendar(
request: GoogleCalendarSyncRequest,
getAccessToken: () => Promise<string>,
options: GoogleCalendarSyncOptions = {},
): Promise<GoogleCalendarSyncResult> {
if (!isOutlookCalendarConfigured()) {
return notConfiguredSyncResult(
"Outlook Calendar is not configured in this extension build.",
);
}
const state = await readOutlookCalendarState();
if (!state.refreshToken && !state.accessToken) {
return notConnectedSyncResult("Connect Outlook Calendar first.");
}
const mode = request.mode ?? "full";
const weeksAhead = request.weeksAhead ?? (await getSyncWeeksAhead());
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
const events = mapLessonsToOutlookEvents(request.origin, request.lessons, timeZone);
if (events.length === 0 && mode === "full") {
return emptyLessonsSyncResult();
}
reportSyncProgress(options.onProgress, {
phase: "preparing",
current: 0,
total: Math.max(events.length, 1),
message: mode === "incremental" ? "Preparing weekly sync…" : "Preparing sync…",
});
const eventMap = { ...(state.eventMap ?? {}) };
const currentMapKeys = new Set(
events.map((event) => outlookEventMapKey(request.origin, event.seqtaKey)),
);
const staleEntries = entriesToPrune(eventMap, request.origin, mode, weeksAhead, currentMapKeys);
const totalSteps = staleEntries.length + events.length;
const lastSyncAt = Date.now();
const staleResult = await deleteTrackedEventsFromOutlook(
staleEntries,
eventMap,
getAccessToken,
false,
options.onProgress,
0,
totalSteps,
);
const upsertResult = await upsertLessonEvents({
events,
eventMap,
origin: request.origin,
staleEntryCount: staleEntries.length,
totalSteps,
lastSyncAt,
initialFailed: staleResult.failed,
getAccessToken,
mapKey: outlookEventMapKey,
upsert: (accessToken, existingId, event, refreshAccessToken) =>
upsertOutlookCalendarEvent(
accessToken,
existingId,
outlookGraphEventBody(event),
refreshAccessToken,
),
writeState: writeOutlookCalendarState,
onProgress: options.onProgress,
logLabel: "Outlook Calendar",
});
await persistFinalSyncState(
writeOutlookCalendarState,
eventMap,
lastSyncAt,
request.origin,
staleResult.deleted,
staleEntries.length,
events.length,
);
reportSyncProgress(options.onProgress, {
phase: "done",
current: totalSteps,
total: totalSteps,
message: "Sync complete",
});
return buildLessonSyncResult(
upsertResult.created,
upsertResult.updated,
staleResult.deleted,
upsertResult.failed,
lastSyncAt,
);
}
export async function deleteSyncedEventsFromOutlookCalendar(
origin: string,
getAccessToken: () => Promise<string>,
options: GoogleCalendarSyncOptions = {},
): Promise<GoogleCalendarDeleteResult> {
if (!isOutlookCalendarConfigured()) {
return {
success: false,
configured: false,
error: "Outlook Calendar is not configured in this extension build.",
};
}
const state = await readOutlookCalendarState();
if (!state.refreshToken && !state.accessToken) {
return { success: false, configured: true, connected: false, error: "Connect Outlook Calendar first." };
}
const entries = originEventMapEntries(state.eventMap ?? {}, origin);
if (entries.length === 0) {
return { success: true, configured: true, connected: true, deleted: 0, failed: 0 };
}
reportSyncProgress(options.onProgress, {
phase: "preparing",
current: 0,
total: entries.length,
message: "Preparing removal…",
});
const eventMap = { ...(state.eventMap ?? {}) };
const { deleted, failed } = await deleteTrackedEventsFromOutlook(
entries,
eventMap,
getAccessToken,
true,
options.onProgress,
0,
entries.length,
);
await writeOutlookCalendarState({ eventMap });
reportSyncProgress(options.onProgress, {
phase: "done",
current: entries.length,
total: entries.length,
message: "Removal complete",
});
return {
success: failed === 0,
configured: true,
connected: true,
deleted,
failed,
error:
failed > 0
? `Removed ${deleted} event${deleted === 1 ? "" : "s"} with ${failed} error${failed === 1 ? "" : "s"}.`
: undefined,
};
}
@@ -0,0 +1,76 @@
import browser from "webextension-polyfill";
import {
fetchTimetableForSync,
fetchTimetableLessons,
trailingWeekRange,
} from "@/seqta/utils/googleCalendar/fetchTimetable";
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
import { syncLessonsToOutlookCalendar } from "@/seqta/utils/outlookCalendar/syncEngine";
import type {
GoogleCalendarSyncOptions,
GoogleCalendarSyncProgress,
GoogleCalendarSyncResult,
} from "@/seqta/utils/googleCalendar/types";
export type OutlookCalendarRunMode = "full" | "incremental";
export interface RunOutlookCalendarSyncParams {
mode?: OutlookCalendarRunMode;
silent?: boolean;
onProgress?: (progress: GoogleCalendarSyncProgress) => void;
}
async function getAccessTokenFromBackground(): Promise<string> {
const res = (await browser.runtime.sendMessage({
type: "outlookCalendarGetAccessToken",
})) as { success?: boolean; accessToken?: string; error?: string };
if (!res?.success || !res.accessToken) {
throw new Error(res?.error ?? "Could not get Outlook Calendar access token.");
}
return res.accessToken;
}
export async function runOutlookCalendarSync(
params: RunOutlookCalendarSyncParams = {},
): Promise<GoogleCalendarSyncResult> {
const mode = params.mode ?? "full";
const weeksAhead = await getSyncWeeksAhead();
params.onProgress?.({
phase: "preparing",
current: 0,
total: 1,
message: mode === "incremental" ? "Fetching new week…" : "Fetching timetable…",
});
const lessons =
mode === "incremental"
? await fetchTimetableLessons(trailingWeekRange(weeksAhead))
: await fetchTimetableForSync(weeksAhead);
const options: GoogleCalendarSyncOptions = { onProgress: params.onProgress };
const result = await syncLessonsToOutlookCalendar(
{
origin: location.origin,
lessons,
mode,
weeksAhead,
},
getAccessTokenFromBackground,
options,
);
return result;
}
export function formatOutlookSyncResultMessage(result: GoogleCalendarSyncResult): string {
const created = result.created ?? 0;
const updated = result.updated ?? 0;
const deleted = result.deleted ?? 0;
const parts: string[] = [];
if (created > 0) parts.push(`${created} new`);
if (updated > 0) parts.push(`${updated} updated`);
if (deleted > 0) parts.push(`${deleted} removed`);
if (parts.length === 0) return "Outlook Calendar is up to date.";
return `Outlook Calendar updated (${parts.join(", ")}).`;
}
+6
View File
@@ -0,0 +1,6 @@
export interface OutlookCalendarStatus {
configured: boolean;
connected: boolean;
lastSyncAt?: number;
lastSyncOrigin?: string;
}
@@ -0,0 +1,48 @@
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
import { upsertOutlookCalendarEvent, deleteOutlookCalendarEvent } from "./upsertEvent";
const fetchMock = jest.fn();
global.fetch = fetchMock as unknown as typeof fetch;
describe("upsertOutlookCalendarEvent", () => {
beforeEach(() => {
fetchMock.mockReset();
});
it("creates a new event when no existing id", async () => {
fetchMock.mockResolvedValue({
ok: true,
status: 200,
json: async () => ({ id: "evt-1" }),
});
const id = await upsertOutlookCalendarEvent("token", undefined, { subject: "Math" });
expect(id).toBe("evt-1");
expect(fetchMock).toHaveBeenCalledWith(
"https://graph.microsoft.com/v1.0/me/events",
expect.objectContaining({ method: "POST" }),
);
});
it("patches when an existing id is provided", async () => {
fetchMock.mockResolvedValue({ ok: true, status: 200, json: async () => ({}) });
const id = await upsertOutlookCalendarEvent("token", "evt-1", { subject: "Math" });
expect(id).toBe("evt-1");
expect(fetchMock).toHaveBeenCalledWith(
"https://graph.microsoft.com/v1.0/me/events/evt-1",
expect.objectContaining({ method: "PATCH" }),
);
});
});
describe("deleteOutlookCalendarEvent", () => {
beforeEach(() => {
fetchMock.mockReset();
});
it("treats 404 as success", async () => {
fetchMock.mockResolvedValue({ ok: false, status: 404, json: async () => ({}) });
await expect(deleteOutlookCalendarEvent("token", "evt-1")).resolves.toBeUndefined();
});
});
@@ -0,0 +1,68 @@
import { OUTLOOK_GRAPH_API } from "@/config/outlookCalendar";
export async function upsertOutlookCalendarEvent(
accessToken: string,
existingEventId: string | undefined,
body: Record<string, unknown>,
refreshAccessToken?: () => Promise<string>,
): Promise<string> {
const headers = {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
};
if (existingEventId) {
const res = await fetch(`${OUTLOOK_GRAPH_API}/me/events/${encodeURIComponent(existingEventId)}`, {
method: "PATCH",
headers,
body: JSON.stringify(body),
});
if (res.status === 401 && refreshAccessToken) {
const nextToken = await refreshAccessToken();
return upsertOutlookCalendarEvent(nextToken, existingEventId, body);
}
if (res.ok) return existingEventId;
if (res.status !== 404) {
const err = (await res.json().catch(() => ({}))) as {
error?: { message?: string };
};
throw new Error(err?.error?.message ?? `Outlook Calendar update failed (${res.status})`);
}
}
const res = await fetch(`${OUTLOOK_GRAPH_API}/me/events`, {
method: "POST",
headers,
body: JSON.stringify(body),
});
if (res.status === 401 && refreshAccessToken) {
const nextToken = await refreshAccessToken();
return upsertOutlookCalendarEvent(nextToken, undefined, body);
}
const json = (await res.json().catch(() => ({}))) as {
id?: string;
error?: { message?: string };
};
if (!res.ok || !json.id) {
throw new Error(json?.error?.message ?? `Outlook Calendar create failed (${res.status})`);
}
return json.id;
}
export async function deleteOutlookCalendarEvent(
accessToken: string,
eventId: string,
refreshAccessToken?: () => Promise<string>,
): Promise<void> {
const res = await fetch(`${OUTLOOK_GRAPH_API}/me/events/${encodeURIComponent(eventId)}`, {
method: "DELETE",
headers: { Authorization: `Bearer ${accessToken}` },
});
if (res.status === 401 && refreshAccessToken) {
const nextToken = await refreshAccessToken();
return deleteOutlookCalendarEvent(nextToken, eventId);
}
if (res.ok || res.status === 404 || res.status === 410) return;
const err = (await res.json().catch(() => ({}))) as { error?: { message?: string } };
throw new Error(err?.error?.message ?? `Outlook Calendar delete failed (${res.status})`);
}