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
@@ -0,0 +1,83 @@
export type AccountsTokenPayload = {
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>): AccountsTokenPayload {
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>,
notReadyHint: string,
includeErrorDescription: boolean,
): string {
if (res.status === 404 || res.status === 501) return notReadyHint;
const err = typeof json.error === "string" ? json.error : "";
const desc =
includeErrorDescription && typeof json.error_description === "string"
? json.error_description
: "";
return desc || err || `Accounts token API failed (${res.status})`;
}
export async function exchangeAccountsCode(
tokenUrl: string,
code: string,
redirectUri: string,
codeVerifier: string,
notReadyHint: string,
includeErrorDescription = false,
): Promise<AccountsTokenPayload> {
const res = await fetch(tokenUrl, {
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, notReadyHint, includeErrorDescription));
}
return extractTokens(json);
}
export async function refreshAccountsToken(
refreshUrl: string,
refreshToken: string,
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, 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;
}