refactor: consolidate and debloat calendar sync implementation

Merge duplicated Google/Outlook engines, background handlers, and API
layers into shared calendarSync modules to cut complexity without changing
user-facing sync behavior.
This commit is contained in:
SethBurkart123
2026-06-28 10:45:45 +10:00
parent f4230e02b9
commit 7779edb063
52 changed files with 1965 additions and 3258 deletions
@@ -1,10 +1,4 @@
import {
OUTLOOK_CALENDAR_ACCOUNTS_NOT_READY_HINT,
OUTLOOK_CALENDAR_REFRESH_URL,
OUTLOOK_CALENDAR_TOKEN_URL,
} from "@/config/outlookCalendar";
type OutlookTokenPayload = {
export type AccountsTokenPayload = {
access_token: string;
refresh_token?: string;
expires_in?: number;
@@ -19,7 +13,7 @@ async function parseAccountsJson(res: Response): Promise<Record<string, unknown>
}
}
function extractTokens(json: Record<string, unknown>): OutlookTokenPayload {
function extractTokens(json: Record<string, unknown>): AccountsTokenPayload {
const access_token = json.access_token;
if (typeof access_token !== "string" || !access_token) {
throw new Error("Token response missing access_token");
@@ -31,21 +25,30 @@ function extractTokens(json: Record<string, unknown>): OutlookTokenPayload {
};
}
function formatAccountsTokenError(res: Response, json: Record<string, unknown>): string {
if (res.status === 404 || res.status === 501) {
return OUTLOOK_CALENDAR_ACCOUNTS_NOT_READY_HINT;
}
function formatAccountsTokenError(
res: Response,
json: Record<string, unknown>,
notReadyHint: string,
includeErrorDescription: boolean,
): string {
if (res.status === 404 || res.status === 501) return notReadyHint;
const err = typeof json.error === "string" ? json.error : "";
const desc = typeof json.error_description === "string" ? json.error_description : "";
const desc =
includeErrorDescription && typeof json.error_description === "string"
? json.error_description
: "";
return desc || err || `Accounts token API failed (${res.status})`;
}
export async function exchangeOutlookCodeViaAccounts(
export async function exchangeAccountsCode(
tokenUrl: string,
code: string,
redirectUri: string,
codeVerifier: string,
): Promise<OutlookTokenPayload> {
const res = await fetch(OUTLOOK_CALENDAR_TOKEN_URL, {
notReadyHint: string,
includeErrorDescription = false,
): Promise<AccountsTokenPayload> {
const res = await fetch(tokenUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
@@ -56,22 +59,25 @@ export async function exchangeOutlookCodeViaAccounts(
});
const json = await parseAccountsJson(res);
if (!res.ok) {
throw new Error(formatAccountsTokenError(res, json));
throw new Error(formatAccountsTokenError(res, json, notReadyHint, includeErrorDescription));
}
return extractTokens(json);
}
export async function refreshOutlookTokenViaAccounts(
export async function refreshAccountsToken(
refreshUrl: string,
refreshToken: string,
): Promise<OutlookTokenPayload> {
const res = await fetch(OUTLOOK_CALENDAR_REFRESH_URL, {
notReadyHint: string,
includeErrorDescription = false,
): Promise<AccountsTokenPayload> {
const res = await fetch(refreshUrl, {
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));
throw new Error(formatAccountsTokenError(res, json, notReadyHint, includeErrorDescription));
}
return extractTokens(json);
}
+58
View File
@@ -0,0 +1,58 @@
import browser from "webextension-polyfill";
export interface EventMapEntry {
id: string;
date: string;
}
export type EventMapRecord = Record<string, string | EventMapEntry>;
export function eventMapKey(origin: string, seqtaKey: string): string {
return `${origin}::${seqtaKey}`;
}
export function normalizeEventMapEntry(
value: string | EventMapEntry | undefined,
): EventMapEntry | 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 | EventMapEntry | undefined,
): string | undefined {
return normalizeEventMapEntry(value)?.id;
}
export function lessonDateFromSeqtaKey(seqtaKey: string): string | undefined {
for (const part of seqtaKey.split(":")) {
if (/^\d{4}-\d{2}-\d{2}$/.test(part)) return part;
}
return undefined;
}
export function createCalendarStateStorage<T extends object>(storageKey: string) {
async function read(): Promise<T> {
const got = await browser.storage.local.get(storageKey);
const raw = got[storageKey];
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {} as T;
return raw as T;
}
async function write(patch: Partial<T>): Promise<T> {
const current = await read();
const next = { ...current, ...patch };
await browser.storage.local.set({ [storageKey]: next });
return next;
}
async function clear(): Promise<void> {
await browser.storage.local.remove(storageKey);
}
return { read, write, clear };
}
@@ -1,138 +1,26 @@
import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals";
import { describe, expect, it, jest } from "@jest/globals";
jest.mock("@/utils/verboseLog", () => ({
verboseLog: jest.fn(),
}));
import {
reportSyncProgress,
resetSyncProgressThrottle,
SYNC_PROGRESS_THROTTLE_MS,
} from "./lessonSyncShared";
import { reportSyncProgress } from "./lessonSyncShared";
import type { GoogleCalendarSyncProgress } from "@/seqta/utils/googleCalendar/types";
describe("reportSyncProgress", () => {
beforeEach(() => {
jest.useFakeTimers();
jest.setSystemTime(new Date("2026-06-28T12:00:00.000Z"));
});
afterEach(() => {
jest.useRealTimers();
});
it("reports preparing and done immediately", () => {
it("calls onProgress when provided", () => {
const onProgress = jest.fn();
const preparing: GoogleCalendarSyncProgress = {
phase: "preparing",
current: 0,
total: 10,
message: "Preparing…",
};
const done: GoogleCalendarSyncProgress = {
phase: "done",
current: 10,
total: 10,
message: "Done",
const progress: GoogleCalendarSyncProgress = {
phase: "upserting",
current: 1,
total: 5,
message: "Syncing events (1/5)…",
};
reportSyncProgress(onProgress, preparing);
reportSyncProgress(onProgress, done);
expect(onProgress).toHaveBeenCalledTimes(2);
expect(onProgress).toHaveBeenNthCalledWith(1, preparing);
expect(onProgress).toHaveBeenNthCalledWith(2, done);
});
it("throttles upserting progress to at most once per second", () => {
const onProgress = jest.fn();
for (let i = 1; i <= 5; i++) {
reportSyncProgress(onProgress, {
phase: "upserting",
current: i,
total: 5,
message: `Syncing events (${i}/5)…`,
});
}
expect(onProgress).toHaveBeenCalledTimes(1);
expect(onProgress).toHaveBeenCalledWith({
phase: "upserting",
current: 1,
total: 5,
message: "Syncing events (1/5)…",
});
jest.advanceTimersByTime(SYNC_PROGRESS_THROTTLE_MS);
expect(onProgress).toHaveBeenCalledTimes(2);
expect(onProgress).toHaveBeenLastCalledWith({
phase: "upserting",
current: 5,
total: 5,
message: "Syncing events (5/5)…",
});
});
it("flushes pending progress before reporting done", () => {
const onProgress = jest.fn();
reportSyncProgress(onProgress, {
phase: "upserting",
current: 1,
total: 5,
message: "Syncing events (1/5)…",
});
reportSyncProgress(onProgress, {
phase: "upserting",
current: 4,
total: 5,
message: "Syncing events (4/5)…",
});
reportSyncProgress(onProgress, {
phase: "done",
current: 5,
total: 5,
message: "Sync complete",
});
expect(onProgress).toHaveBeenCalledTimes(3);
expect(onProgress).toHaveBeenNthCalledWith(1, {
phase: "upserting",
current: 1,
total: 5,
message: "Syncing events (1/5)…",
});
expect(onProgress).toHaveBeenNthCalledWith(2, {
phase: "upserting",
current: 4,
total: 5,
message: "Syncing events (4/5)…",
});
expect(onProgress).toHaveBeenNthCalledWith(3, {
phase: "done",
current: 5,
total: 5,
message: "Sync complete",
});
});
it("resetSyncProgressThrottle clears queued updates", () => {
const onProgress = jest.fn();
reportSyncProgress(onProgress, {
phase: "upserting",
current: 1,
total: 3,
message: "Syncing events (1/3)…",
});
resetSyncProgressThrottle(onProgress);
jest.advanceTimersByTime(SYNC_PROGRESS_THROTTLE_MS);
reportSyncProgress(onProgress, progress);
reportSyncProgress(undefined, progress);
expect(onProgress).toHaveBeenCalledTimes(1);
expect(onProgress).toHaveBeenCalledWith(progress);
});
});
+109 -128
View File
@@ -3,109 +3,31 @@ import {
getStoredEventId,
lessonDateFromSeqtaKey,
normalizeEventMapEntry,
} from "@/seqta/utils/googleCalendar/eventMapEntry";
type EventMapRecord,
} from "@/seqta/utils/calendarSync/eventMap";
import {
isDateInRange,
syncWindowRange,
} from "@/seqta/utils/googleCalendar/syncDateRange";
import type {
GoogleCalendarDeleteResult,
GoogleCalendarSyncOptions,
GoogleCalendarSyncProgress,
GoogleCalendarSyncResult,
} from "@/seqta/utils/googleCalendar/types";
export const EVENT_MAP_PERSIST_EVERY = 10;
/** Max UI progress refresh rate during bulk delete/upsert (reduces Svelte re-renders). */
export const SYNC_PROGRESS_THROTTLE_MS = 1000;
export type EventMapRecord = Record<string, string | { id: string; date: string }>;
export type MappedLessonEvent = {
seqtaKey: string;
startDateTime: string;
};
type ProgressThrottleState = {
lastReportAt: number;
pending: GoogleCalendarSyncProgress | null;
timer: ReturnType<typeof setTimeout> | null;
};
const progressThrottleByCallback = new WeakMap<
NonNullable<GoogleCalendarSyncOptions["onProgress"]>,
ProgressThrottleState
>();
function getProgressThrottleState(
onProgress: NonNullable<GoogleCalendarSyncOptions["onProgress"]>,
): ProgressThrottleState {
let state = progressThrottleByCallback.get(onProgress);
if (!state) {
state = { lastReportAt: 0, pending: null, timer: null };
progressThrottleByCallback.set(onProgress, state);
}
return state;
}
function flushPendingSyncProgress(
onProgress: NonNullable<GoogleCalendarSyncOptions["onProgress"]>,
state: ProgressThrottleState,
) {
if (state.timer) {
clearTimeout(state.timer);
state.timer = null;
}
if (!state.pending) return;
onProgress(state.pending);
state.pending = null;
state.lastReportAt = Date.now();
}
/** Clears any queued progress for a callback (e.g. when a sync run ends). */
export function resetSyncProgressThrottle(
onProgress: GoogleCalendarSyncOptions["onProgress"],
) {
if (!onProgress) return;
const state = progressThrottleByCallback.get(onProgress);
if (!state) return;
if (state.timer) {
clearTimeout(state.timer);
state.timer = null;
}
state.pending = null;
}
export function reportSyncProgress(
onProgress: GoogleCalendarSyncOptions["onProgress"],
progress: GoogleCalendarSyncProgress,
) {
if (!onProgress) return;
const state = getProgressThrottleState(onProgress);
if (progress.phase === "preparing" || progress.phase === "done") {
flushPendingSyncProgress(onProgress, state);
onProgress(progress);
state.lastReportAt = Date.now();
if (progress.phase === "done") {
resetSyncProgressThrottle(onProgress);
}
return;
}
state.pending = progress;
const elapsed = Date.now() - state.lastReportAt;
if (elapsed >= SYNC_PROGRESS_THROTTLE_MS) {
flushPendingSyncProgress(onProgress, state);
return;
}
if (state.timer) return;
state.timer = setTimeout(() => {
state.timer = null;
flushPendingSyncProgress(onProgress, state);
}, SYNC_PROGRESS_THROTTLE_MS - elapsed);
onProgress?.(progress);
}
export function lessonDateForEvent(startDateTime: string, seqtaKey: string): string {
@@ -126,18 +48,6 @@ export function originEventMapEntries(
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,
@@ -145,6 +55,8 @@ export function entriesToPrune(
weeksAhead: number,
currentMapKeys: Set<string>,
): Array<[string, string]> {
if (mode === "incremental") return [];
const window = syncWindowRange(weeksAhead);
const prefix = `${origin}::`;
const entries: Array<[string, string]> = [];
@@ -153,9 +65,10 @@ export function entriesToPrune(
if (!mapKey.startsWith(prefix)) continue;
const entry = normalizeEventMapEntry(raw);
if (!entry) continue;
if (shouldPruneEntry(mode, entry, mapKey, window, currentMapKeys)) {
entries.push([mapKey, entry.id]);
}
const stale = entry.date
? !isDateInRange(entry.date, window)
: !currentMapKeys.has(mapKey);
if (stale) entries.push([mapKey, entry.id]);
}
return entries;
@@ -178,6 +91,98 @@ export function emptyLessonsSyncResult(): GoogleCalendarSyncResult {
};
}
export function formatLessonSyncResultMessage(
result: GoogleCalendarSyncResult,
calendarLabel: string,
): 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 `${calendarLabel} is up to date.`;
return `${calendarLabel} updated (${parts.join(", ")}).`;
}
export function buildDeleteSyncResult(
deleted: number,
failed: number,
): GoogleCalendarDeleteResult {
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,
};
}
export async function deleteTrackedLessonEvents(
entries: Array<[string, string]>,
eventMap: EventMapRecord,
getAccessToken: () => Promise<string>,
deleteEvent: (
accessToken: string,
eventId: string,
refreshAccessToken: () => Promise<string>,
) => Promise<void>,
writeState: (patch: { eventMap: EventMapRecord }) => Promise<unknown>,
options: {
persistProgress?: boolean;
onProgress?: GoogleCalendarSyncOptions["onProgress"];
progressOffset?: number;
progressTotal?: number;
logLabel: string;
},
): Promise<{ deleted: number; failed: number }> {
if (entries.length === 0) return { deleted: 0, failed: 0 };
const {
persistProgress = false,
onProgress,
progressOffset = 0,
progressTotal = 0,
logLabel,
} = options;
let accessToken = await getAccessToken();
let deleted = 0;
let failed = 0;
for (const [mapKey, eventId] of entries) {
try {
await deleteEvent(accessToken, eventId, async () => {
accessToken = await getAccessToken();
return accessToken;
});
delete eventMap[mapKey];
deleted += 1;
} catch (err) {
verboseLog(`[BetterSEQTA+] ${logLabel} event delete failed:`, err);
failed += 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 writeState({ eventMap });
}
}
return { deleted, failed };
}
export function buildLessonSyncResult(
created: number,
updated: number,
@@ -202,24 +207,6 @@ export function buildLessonSyncResult(
};
}
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;
@@ -288,26 +275,20 @@ export async function upsertLessonEvents<TEvent extends MappedLessonEvent>(
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,
});
}
reportSyncProgress(onProgress, {
phase: "upserting",
current: progressCurrent,
total: totalSteps,
message: progressMessage,
});
}
return { created, updated, failed, accessToken };
@@ -0,0 +1,51 @@
import type { EventMapRecord } from "@/seqta/utils/calendarSync/eventMap";
import { createCalendarStateStorage } from "@/seqta/utils/calendarSync/eventMap";
export const BSPLUS_GOOGLE_CALENDAR_STORAGE_KEY = "bsplus_google_calendar";
export const BSPLUS_OUTLOOK_CALENDAR_STORAGE_KEY = "bsplus_outlook_calendar";
export interface GoogleCalendarStoredState {
accessToken?: string;
refreshToken?: string;
expiresAt?: number;
connectedAt?: number;
lastSyncAt?: number;
lastWeeklySyncAt?: number;
lastSyncOrigin?: string;
syncWeeksAhead?: number;
autoSyncWeekly?: boolean;
pendingWeeklySync?: boolean;
eventMap?: EventMapRecord;
}
export interface OutlookCalendarStatus {
configured: boolean;
connected: boolean;
lastSyncAt?: number;
lastSyncOrigin?: string;
}
export interface OutlookCalendarStoredState {
accessToken?: string;
refreshToken?: string;
expiresAt?: number;
connectedAt?: number;
lastSyncAt?: number;
lastSyncOrigin?: string;
eventMap?: EventMapRecord;
}
const googleStorage = createCalendarStateStorage<GoogleCalendarStoredState>(
BSPLUS_GOOGLE_CALENDAR_STORAGE_KEY,
);
const outlookStorage = createCalendarStateStorage<OutlookCalendarStoredState>(
BSPLUS_OUTLOOK_CALENDAR_STORAGE_KEY,
);
export const readGoogleCalendarState = googleStorage.read;
export const writeGoogleCalendarState = googleStorage.write;
export const clearGoogleCalendarState = googleStorage.clear;
export const readOutlookCalendarState = outlookStorage.read;
export const writeOutlookCalendarState = outlookStorage.write;
export const clearOutlookCalendarState = outlookStorage.clear;
@@ -0,0 +1,144 @@
import { GOOGLE_CALENDAR_API } from "@/config/googleCalendar";
import { OUTLOOK_GRAPH_API } from "@/config/outlookCalendar";
async function authorizedFetch(
accessToken: string,
url: string,
init: RequestInit,
refreshAccessToken?: () => Promise<string>,
): Promise<Response> {
const res = await fetch(url, {
...init,
headers: { Authorization: `Bearer ${accessToken}`, ...init.headers },
});
if (res.status === 401 && refreshAccessToken) {
return authorizedFetch(await refreshAccessToken(), url, init);
}
return res;
}
async function upsertRemoteEvent(
accessToken: string,
existingEventId: string | undefined,
body: Record<string, unknown>,
paths: { update: (id: string) => string; create: string },
label: string,
refreshAccessToken?: () => Promise<string>,
): Promise<string> {
const headers = { "Content-Type": "application/json" };
if (existingEventId) {
const res = await authorizedFetch(
accessToken,
paths.update(existingEventId),
{ method: "PATCH", headers, body: JSON.stringify(body) },
refreshAccessToken,
);
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 ?? `${label} update failed (${res.status})`);
}
}
const res = await authorizedFetch(
accessToken,
paths.create,
{ method: "POST", headers, body: JSON.stringify(body) },
refreshAccessToken,
);
const json = (await res.json().catch(() => ({}))) as { id?: string; error?: { message?: string } };
if (!res.ok || !json.id) {
throw new Error(json?.error?.message ?? `${label} create failed (${res.status})`);
}
return json.id;
}
async function deleteRemoteEvent(
accessToken: string,
eventUrl: string,
label: string,
refreshAccessToken?: () => Promise<string>,
): Promise<void> {
const res = await authorizedFetch(
accessToken,
eventUrl,
{ method: "DELETE" },
refreshAccessToken,
);
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 ?? `${label} delete failed (${res.status})`);
}
const GOOGLE_CALENDAR_ID = "primary";
export function upsertGoogleCalendarEvent(
accessToken: string,
calendarId: string,
existingEventId: string | undefined,
body: Record<string, unknown>,
refreshAccessToken?: () => Promise<string>,
): Promise<string> {
const encodedCalendar = encodeURIComponent(calendarId);
return upsertRemoteEvent(
accessToken,
existingEventId,
body,
{
update: (id) =>
`${GOOGLE_CALENDAR_API}/calendars/${encodedCalendar}/events/${encodeURIComponent(id)}`,
create: `${GOOGLE_CALENDAR_API}/calendars/${encodedCalendar}/events`,
},
"Google Calendar",
refreshAccessToken,
);
}
export function deleteGoogleCalendarEvent(
accessToken: string,
calendarId: string,
eventId: string,
refreshAccessToken?: () => Promise<string>,
): Promise<void> {
return deleteRemoteEvent(
accessToken,
`${GOOGLE_CALENDAR_API}/calendars/${encodeURIComponent(calendarId)}/events/${encodeURIComponent(eventId)}`,
"Google Calendar",
refreshAccessToken,
);
}
export function upsertOutlookCalendarEvent(
accessToken: string,
existingEventId: string | undefined,
body: Record<string, unknown>,
refreshAccessToken?: () => Promise<string>,
): Promise<string> {
return upsertRemoteEvent(
accessToken,
existingEventId,
body,
{
update: (id) => `${OUTLOOK_GRAPH_API}/me/events/${encodeURIComponent(id)}`,
create: `${OUTLOOK_GRAPH_API}/me/events`,
},
"Outlook Calendar",
refreshAccessToken,
);
}
export function deleteOutlookCalendarEvent(
accessToken: string,
eventId: string,
refreshAccessToken?: () => Promise<string>,
): Promise<void> {
return deleteRemoteEvent(
accessToken,
`${OUTLOOK_GRAPH_API}/me/events/${encodeURIComponent(eventId)}`,
"Outlook Calendar",
refreshAccessToken,
);
}
export { GOOGLE_CALENDAR_ID };
+44 -11
View File
@@ -1,20 +1,53 @@
import browser from "webextension-polyfill";
import {
GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT,
GOOGLE_CALENDAR_SYNC_WEEKS,
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";
import { readOutlookCalendarState } from "@/seqta/utils/outlookCalendar/storage";
export { CALENDAR_WEEKLY_ALARM, WEEKLY_SYNC_INTERVAL_MS } from "./sharedSettings";
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 clampSyncWeeks(weeks: number): number {
if (!Number.isFinite(weeks)) return GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT;
if (!Number.isFinite(weeks)) return GOOGLE_CALENDAR_SYNC_WEEKS;
return Math.min(
GOOGLE_CALENDAR_SYNC_WEEKS_MAX,
Math.max(GOOGLE_CALENDAR_SYNC_WEEKS_MIN, Math.round(weeks)),
@@ -23,7 +56,7 @@ export function clampSyncWeeks(weeks: number): number {
export async function getSyncWeeksAhead(): Promise<number> {
const settings = await readSharedCalendarSyncSettings();
return clampSyncWeeks(settings.syncWeeksAhead ?? GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT);
return clampSyncWeeks(settings.syncWeeksAhead ?? GOOGLE_CALENDAR_SYNC_WEEKS);
}
export async function getAutoSyncWeekly(): Promise<boolean> {
@@ -31,7 +64,7 @@ export async function getAutoSyncWeekly(): Promise<boolean> {
return settings.autoSyncWeekly !== false;
}
async function isAnyCalendarConnected(): Promise<boolean> {
export async function isAnyCalendarConnected(): Promise<boolean> {
const [google, outlook] = await Promise.all([
readGoogleCalendarState(),
readOutlookCalendarState(),
@@ -1,48 +0,0 @@
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;
}
+285
View File
@@ -0,0 +1,285 @@
import { isGoogleCalendarConfigured } from "@/config/googleCalendar";
import { isOutlookCalendarConfigured } from "@/config/outlookCalendar";
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
import { eventMapKey } from "@/seqta/utils/calendarSync/eventMap";
import type { EventMapRecord } from "@/seqta/utils/calendarSync/eventMap";
import {
buildDeleteSyncResult,
buildLessonSyncResult,
deleteTrackedLessonEvents,
emptyLessonsSyncResult,
entriesToPrune,
notConfiguredSyncResult,
notConnectedSyncResult,
originEventMapEntries,
reportSyncProgress,
upsertLessonEvents,
} from "@/seqta/utils/calendarSync/lessonSyncShared";
import { googleApiEventBody, mapLessonsToGoogleEvents, outlookGraphEventBody } from "@/seqta/utils/googleCalendar/eventMapper";
import {
readGoogleCalendarState,
writeGoogleCalendarState,
} from "@/seqta/utils/googleCalendar/storage";
import type {
GoogleCalendarDeleteResult,
GoogleCalendarEventInput,
GoogleCalendarSyncOptions,
GoogleCalendarSyncRequest,
GoogleCalendarSyncResult,
} from "@/seqta/utils/googleCalendar/types";
import {
deleteGoogleCalendarEvent,
deleteOutlookCalendarEvent,
GOOGLE_CALENDAR_ID,
upsertGoogleCalendarEvent,
upsertOutlookCalendarEvent,
} from "@/seqta/utils/calendarSync/remoteEvents";
import {
readOutlookCalendarState,
writeOutlookCalendarState,
} from "@/seqta/utils/outlookCalendar/storage";
type CalendarStoredState = {
refreshToken?: string;
accessToken?: string;
eventMap?: EventMapRecord;
};
export type CalendarLessonSyncProvider = {
label: string;
isConfigured: () => boolean;
notConfiguredError: string;
notConnectedError: string;
readState: () => Promise<CalendarStoredState>;
writeState: (patch: {
eventMap?: EventMapRecord;
lastSyncAt?: number;
lastSyncOrigin?: string;
}) => Promise<unknown>;
deleteEvent: (
accessToken: string,
eventId: string,
refreshAccessToken: () => Promise<string>,
) => Promise<void>;
upsertEvent: (
accessToken: string,
existingId: string | undefined,
body: Record<string, unknown>,
refreshAccessToken: () => Promise<string>,
) => Promise<string>;
toApiBody: (event: GoogleCalendarEventInput) => Record<string, unknown>;
};
export const googleLessonSyncProvider: CalendarLessonSyncProvider = {
label: "Google Calendar",
isConfigured: isGoogleCalendarConfigured,
notConfiguredError: "Google Calendar is not configured in this extension build.",
notConnectedError: "Connect Google Calendar first.",
readState: readGoogleCalendarState,
writeState: writeGoogleCalendarState,
deleteEvent: (accessToken, eventId, refreshAccessToken) =>
deleteGoogleCalendarEvent(accessToken, GOOGLE_CALENDAR_ID, eventId, refreshAccessToken),
upsertEvent: (accessToken, existingId, body, refreshAccessToken) =>
upsertGoogleCalendarEvent(
accessToken,
GOOGLE_CALENDAR_ID,
existingId,
body,
refreshAccessToken,
),
toApiBody: googleApiEventBody,
};
export const outlookLessonSyncProvider: CalendarLessonSyncProvider = {
label: "Outlook Calendar",
isConfigured: isOutlookCalendarConfigured,
notConfiguredError: "Outlook Calendar is not configured in this extension build.",
notConnectedError: "Connect Outlook Calendar first.",
readState: readOutlookCalendarState,
writeState: writeOutlookCalendarState,
deleteEvent: (accessToken, eventId, refreshAccessToken) =>
deleteOutlookCalendarEvent(accessToken, eventId, refreshAccessToken),
upsertEvent: (accessToken, existingId, body, refreshAccessToken) =>
upsertOutlookCalendarEvent(accessToken, existingId, body, refreshAccessToken),
toApiBody: outlookGraphEventBody,
};
/** Runs in the content script tab so long syncs are not killed by the MV3 service worker. */
export async function syncLessonsToCalendar(
provider: CalendarLessonSyncProvider,
request: GoogleCalendarSyncRequest,
getAccessToken: () => Promise<string>,
options: GoogleCalendarSyncOptions = {},
): Promise<GoogleCalendarSyncResult> {
if (!provider.isConfigured()) {
return notConfiguredSyncResult(provider.notConfiguredError);
}
const state = await provider.readState();
if (!state.refreshToken && !state.accessToken) {
return notConnectedSyncResult(provider.notConnectedError);
}
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 deleteTrackedLessonEvents(
staleEntries,
eventMap,
getAccessToken,
provider.deleteEvent,
provider.writeState,
{
onProgress: options.onProgress,
progressTotal: totalSteps,
logLabel: provider.label,
},
);
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) =>
provider.upsertEvent(
accessToken,
existingId,
provider.toApiBody(event),
refreshAccessToken,
),
writeState: provider.writeState,
onProgress: options.onProgress,
logLabel: provider.label,
});
if (staleResult.deleted > 0 || staleEntries.length > 0 || events.length > 0) {
await provider.writeState({
eventMap,
lastSyncAt,
lastSyncOrigin: request.origin,
});
}
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 the provider calendar. */
export async function deleteSyncedEventsFromCalendar(
provider: CalendarLessonSyncProvider,
origin: string,
getAccessToken: () => Promise<string>,
options: GoogleCalendarSyncOptions = {},
): Promise<GoogleCalendarDeleteResult> {
if (!provider.isConfigured()) {
return {
success: false,
configured: false,
error: provider.notConfiguredError,
};
}
const state = await provider.readState();
if (!state.refreshToken && !state.accessToken) {
return { success: false, configured: true, connected: false, error: provider.notConnectedError };
}
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 deleteTrackedLessonEvents(
entries,
eventMap,
getAccessToken,
provider.deleteEvent,
provider.writeState,
{
persistProgress: true,
onProgress: options.onProgress,
progressTotal: entries.length,
logLabel: provider.label,
},
);
await provider.writeState({ eventMap });
reportSyncProgress(options.onProgress, {
phase: "done",
current: entries.length,
total: entries.length,
message: "Removal complete",
});
return buildDeleteSyncResult(deleted, failed);
}
export const syncLessonsToGoogleCalendar = (
request: GoogleCalendarSyncRequest,
getAccessToken: () => Promise<string>,
options?: GoogleCalendarSyncOptions,
) => syncLessonsToCalendar(googleLessonSyncProvider, request, getAccessToken, options);
export const deleteSyncedEventsFromGoogleCalendar = (
origin: string,
getAccessToken: () => Promise<string>,
options?: GoogleCalendarSyncOptions,
) => deleteSyncedEventsFromCalendar(googleLessonSyncProvider, origin, getAccessToken, options);
export const syncLessonsToOutlookCalendar = (
request: GoogleCalendarSyncRequest,
getAccessToken: () => Promise<string>,
options?: GoogleCalendarSyncOptions,
) => syncLessonsToCalendar(outlookLessonSyncProvider, request, getAccessToken, options);
export const deleteSyncedEventsFromOutlookCalendar = (
origin: string,
getAccessToken: () => Promise<string>,
options?: GoogleCalendarSyncOptions,
) => deleteSyncedEventsFromCalendar(outlookLessonSyncProvider, origin, getAccessToken, options);
@@ -0,0 +1,86 @@
import browser from "webextension-polyfill";
import { fetchTimetableForSync, fetchTimetableLessons } from "@/seqta/utils/googleCalendar/fetchTimetable";
import { trailingWeekRange } from "@/seqta/utils/googleCalendar/syncDateRange";
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
import { reportSyncProgress } from "@/seqta/utils/calendarSync/lessonSyncShared";
import {
googleLessonSyncProvider,
outlookLessonSyncProvider,
syncLessonsToCalendar,
type CalendarLessonSyncProvider,
} from "@/seqta/utils/calendarSync/syncEngine";
import type {
GoogleCalendarSyncProgress,
GoogleCalendarSyncResult,
} from "@/seqta/utils/googleCalendar/types";
export interface RunCalendarSyncParams {
mode?: "full" | "incremental";
onProgress?: (progress: GoogleCalendarSyncProgress) => void;
}
type CalendarSyncRunnerConfig = {
accessTokenMessageType: string;
accessTokenError: string;
lessonSyncProvider: CalendarLessonSyncProvider;
};
const GOOGLE_SYNC_RUNNER: CalendarSyncRunnerConfig = {
accessTokenMessageType: "googleCalendarGetAccessToken",
accessTokenError: "Could not get Google Calendar access token.",
lessonSyncProvider: googleLessonSyncProvider,
};
const OUTLOOK_SYNC_RUNNER: CalendarSyncRunnerConfig = {
accessTokenMessageType: "outlookCalendarGetAccessToken",
accessTokenError: "Could not get Outlook Calendar access token.",
lessonSyncProvider: outlookLessonSyncProvider,
};
async function getAccessTokenFromBackground(
messageType: string,
errorMessage: string,
): Promise<string> {
const res = (await browser.runtime.sendMessage({ type: messageType })) as {
success?: boolean;
accessToken?: string;
error?: string;
};
if (!res?.success || !res.accessToken) {
throw new Error(res?.error ?? errorMessage);
}
return res.accessToken;
}
export async function runCalendarSync(
config: CalendarSyncRunnerConfig,
params: RunCalendarSyncParams = {},
): Promise<GoogleCalendarSyncResult> {
const mode = params.mode ?? "full";
const weeksAhead = await getSyncWeeksAhead();
reportSyncProgress(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);
return syncLessonsToCalendar(
config.lessonSyncProvider,
{ origin: location.origin, lessons, mode, weeksAhead },
() => getAccessTokenFromBackground(config.accessTokenMessageType, config.accessTokenError),
{ onProgress: params.onProgress },
);
}
export const runGoogleCalendarSync = (params?: RunCalendarSyncParams) =>
runCalendarSync(GOOGLE_SYNC_RUNNER, params);
export const runOutlookCalendarSync = (params?: RunCalendarSyncParams) =>
runCalendarSync(OUTLOOK_SYNC_RUNNER, params);
@@ -1,51 +0,0 @@
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;
}
@@ -1,76 +0,0 @@
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);
}
@@ -3,33 +3,38 @@ 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 { formatLessonSyncResultMessage } from "@/seqta/utils/calendarSync/lessonSyncShared";
import { runGoogleCalendarSync, runOutlookCalendarSync } from "@/seqta/utils/calendarSync/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[] = [];
const WEEKLY_PROVIDERS = [
{ label: "Google Calendar", read: readGoogleCalendarState, run: runGoogleCalendarSync },
{ label: "Outlook Calendar", read: readOutlookCalendarState, run: runOutlookCalendarSync },
] as const;
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 }));
function isConnected(state: { refreshToken?: string; accessToken?: string }): boolean {
return Boolean(state.refreshToken || state.accessToken);
}
function hadChanges(result: GoogleCalendarSyncResult): boolean {
return (result.created ?? 0) + (result.updated ?? 0) + (result.deleted ?? 0) > 0;
}
async function runWeeklySyncForConnectedProviders(): Promise<
Array<{ label: string; result: GoogleCalendarSyncResult }>
> {
const results: Array<{ label: string; result: GoogleCalendarSyncResult }> = [];
for (const provider of WEEKLY_PROVIDERS) {
if (!isConnected(await provider.read())) continue;
results.push({ label: provider.label, result: await provider.run({ mode: "incremental" }) });
}
if (results.some((r) => r.success)) {
if (results.some(({ result }) => result.success)) {
await markWeeklySyncComplete();
}
@@ -61,24 +66,20 @@ export async function maybeRunDueWeeklySync(
): 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);
const failed = results.find(({ result }) => !result.success);
if (failed) {
onComplete(failed.result.error ?? "Weekly calendar sync failed.", true);
return;
}
const messages = formatWeeklySyncMessages(google, outlook, results);
const messages = results
.filter(({ result }) => hadChanges(result))
.map(({ label, result }) => formatLessonSyncResultMessage(result, label));
if (messages.length > 0) {
onComplete(messages.join(" "));
}
}
/** @deprecated use registerCalendarContentHandlers */
export const registerGoogleCalendarContentHandlers = registerCalendarContentHandlers;
@@ -1,29 +0,0 @@
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;
}
@@ -1,4 +1,5 @@
import { BSPLUS_GOOGLE_CALENDAR_EVENT_PROP } from "@/config/googleCalendar";
import { BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY } from "@/config/outlookCalendar";
import type { GoogleCalendarEventInput, SeqtaTimetableLesson } from "./types";
const SKIP_TYPES = new Set(["note", "holiday", "assembly-note"]);
@@ -93,3 +94,20 @@ export function googleApiEventBody(event: GoogleCalendarEventInput): Record<stri
},
};
}
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;
}
@@ -76,5 +76,3 @@ export async function fetchTimetableLessons(
export async function fetchTimetableForSync(weeksAhead?: number): Promise<SeqtaTimetableLesson[]> {
return fetchTimetableLessons(syncWindowRange(weeksAhead));
}
export { syncWindowRange, trailingWeekRange, droppedWeekRange } from "./syncDateRange";
+8 -43
View File
@@ -1,44 +1,9 @@
import browser from "webextension-polyfill";
import type { GoogleCalendarEventMapEntry } from "./eventMapEntry";
export {
BSPLUS_GOOGLE_CALENDAR_STORAGE_KEY,
clearGoogleCalendarState,
readGoogleCalendarState,
writeGoogleCalendarState,
type GoogleCalendarStoredState,
} from "@/seqta/utils/calendarSync/providerStorage";
/** 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}`;
}
export type { EventMapRecord as GoogleCalendarEventMapRecord } from "@/seqta/utils/calendarSync/eventMap";
+14 -17
View File
@@ -1,6 +1,4 @@
import {
GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT,
} from "@/config/googleCalendar";
import { GOOGLE_CALENDAR_SYNC_WEEKS } from "@/config/googleCalendar";
import { toISODate, weekRangeContaining } from "@/seqta/utils/Loaders/engageParentTimetable";
export interface SyncDateRange {
@@ -12,8 +10,15 @@ function parseLocalDate(iso: string): Date {
return new Date(`${iso}T12:00:00`);
}
function weekEndingOn(until: string): SyncDateRange {
const end = parseLocalDate(until);
const start = new Date(end);
start.setDate(start.getDate() - 6);
return { from: toISODate(start), until };
}
/** Full rolling sync window from the start of the current week. */
export function syncWindowRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT): SyncDateRange {
export function syncWindowRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS): SyncDateRange {
const { from } = weekRangeContaining(new Date());
const end = parseLocalDate(from);
end.setDate(end.getDate() + weeksAhead * 7 - 1);
@@ -21,23 +26,15 @@ export function syncWindowRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT)
}
/** 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) };
export function trailingWeekRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS): SyncDateRange {
return weekEndingOn(syncWindowRange(weeksAhead).until);
}
/** 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);
export function droppedWeekRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS): SyncDateRange {
const end = parseLocalDate(syncWindowRange(weeksAhead).from);
end.setDate(end.getDate() - 1);
const start = new Date(end);
start.setDate(start.getDate() - 6);
return { from: toISODate(start), until: toISODate(end) };
return weekEndingOn(toISODate(end));
}
export function isDateInRange(date: string, range: SyncDateRange): boolean {
@@ -9,17 +9,22 @@ 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/googleCalendar/storage", () => {
const actual = jest.requireActual<typeof import("@/seqta/utils/googleCalendar/storage")>(
"@/seqta/utils/googleCalendar/storage",
);
return {
...actual,
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", () => ({
jest.mock("@/seqta/utils/calendarSync/remoteEvents", () => ({
upsertGoogleCalendarEvent: jest.fn(),
deleteGoogleCalendarEvent: jest.fn(),
}));
@@ -28,8 +33,8 @@ import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/storage";
import {
deleteGoogleCalendarEvent,
upsertGoogleCalendarEvent,
} from "@/seqta/utils/googleCalendar/upsertEvent";
import { deleteSyncedEventsFromGoogleCalendar, syncLessonsToGoogleCalendar } from "./syncEngine";
} from "@/seqta/utils/calendarSync/remoteEvents";
import { deleteSyncedEventsFromGoogleCalendar, syncLessonsToGoogleCalendar } from "@/seqta/utils/calendarSync/syncEngine";
const ORIGIN = "https://school.seqta.com.au";
const getAccessToken = async () => "test-token";
@@ -1,250 +0,0 @@
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,
};
}
@@ -1,77 +0,0 @@
import browser from "webextension-polyfill";
import {
fetchTimetableForSync,
fetchTimetableLessons,
trailingWeekRange,
} from "@/seqta/utils/googleCalendar/fetchTimetable";
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
import { reportSyncProgress } from "@/seqta/utils/calendarSync/lessonSyncShared";
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();
reportSyncProgress(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(", ")}).`;
}
@@ -1,10 +0,0 @@
export {
CALENDAR_WEEKLY_ALARM as GOOGLE_CALENDAR_WEEKLY_ALARM,
WEEKLY_SYNC_INTERVAL_MS,
clampSyncWeeks,
getAutoSyncWeekly,
getSyncWeeksAhead,
markWeeklySyncComplete,
markWeeklySyncPending,
shouldRunWeeklySync,
} from "@/seqta/utils/calendarSync/settings";
@@ -1,63 +0,0 @@
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})`);
}
@@ -1,36 +0,0 @@
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);
}
+8 -38
View File
@@ -1,38 +1,8 @@
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}`;
}
export {
BSPLUS_OUTLOOK_CALENDAR_STORAGE_KEY,
clearOutlookCalendarState,
readOutlookCalendarState,
writeOutlookCalendarState,
type OutlookCalendarStatus,
type OutlookCalendarStoredState,
} from "@/seqta/utils/calendarSync/providerStorage";
@@ -1,249 +0,0 @@
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,
};
}
@@ -1,77 +0,0 @@
import browser from "webextension-polyfill";
import {
fetchTimetableForSync,
fetchTimetableLessons,
trailingWeekRange,
} from "@/seqta/utils/googleCalendar/fetchTimetable";
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
import { reportSyncProgress } from "@/seqta/utils/calendarSync/lessonSyncShared";
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();
reportSyncProgress(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
@@ -1,6 +0,0 @@
export interface OutlookCalendarStatus {
configured: boolean;
connected: boolean;
lastSyncAt?: number;
lastSyncOrigin?: string;
}
@@ -1,48 +1,31 @@
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;
const mockFetch = jest.fn<typeof fetch>();
global.fetch = mockFetch as typeof fetch;
describe("upsertOutlookCalendarEvent", () => {
import {
deleteOutlookCalendarEvent,
upsertOutlookCalendarEvent,
} from "@/seqta/utils/calendarSync/remoteEvents";
describe("outlook calendar remote events", () => {
beforeEach(() => {
fetchMock.mockReset();
mockFetch.mockReset();
});
it("creates a new event when no existing id", async () => {
fetchMock.mockResolvedValue({
ok: true,
status: 200,
json: async () => ({ id: "evt-1" }),
});
it("creates a new event when none exists", async () => {
mockFetch.mockResolvedValueOnce(
new Response(JSON.stringify({ id: "evt-1" }), { status: 201 }),
);
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" }),
);
expect(mockFetch).toHaveBeenCalledTimes(1);
});
it("patches when an existing id is provided", async () => {
fetchMock.mockResolvedValue({ ok: true, status: 200, json: async () => ({}) });
it("deletes an event", async () => {
mockFetch.mockResolvedValueOnce(new Response(null, { status: 204 }));
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();
});
});
@@ -1,68 +0,0 @@
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})`);
}