mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-08-28 17:21:05 +00:00
feat: tweak calendar and clean it up
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import { shouldRunWeeklySync } from "@/seqta/utils/googleCalendar/syncSettings";
|
||||
import {
|
||||
formatSyncResultMessage,
|
||||
runGoogleCalendarSync,
|
||||
} from "@/seqta/utils/googleCalendar/syncRunner";
|
||||
import type { GoogleCalendarSyncResult } from "@/seqta/utils/googleCalendar/types";
|
||||
|
||||
let listenerRegistered = false;
|
||||
|
||||
export function registerGoogleCalendarContentHandlers(): void {
|
||||
if (listenerRegistered) return;
|
||||
listenerRegistered = true;
|
||||
|
||||
browser.runtime.onMessage.addListener((request, _sender, sendResponse) => {
|
||||
if (request?.type !== "googleCalendarRunWeeklySync") return false;
|
||||
void runGoogleCalendarSync({ mode: "incremental", silent: true })
|
||||
.then((result: GoogleCalendarSyncResult) => sendResponse(result))
|
||||
.catch((err: unknown) => {
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Weekly sync failed",
|
||||
});
|
||||
});
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
export async function maybeRunDueWeeklySync(
|
||||
onComplete?: (message: string, isError?: boolean) => void,
|
||||
): Promise<void> {
|
||||
if (!(await shouldRunWeeklySync())) return;
|
||||
|
||||
const result = await runGoogleCalendarSync({ mode: "incremental", silent: true });
|
||||
if (!onComplete) return;
|
||||
|
||||
if (!result.success) {
|
||||
onComplete(result.error ?? "Weekly calendar sync failed.", true);
|
||||
return;
|
||||
}
|
||||
|
||||
const changed =
|
||||
(result.created ?? 0) + (result.updated ?? 0) + (result.deleted ?? 0) > 0;
|
||||
if (changed) {
|
||||
onComplete(formatSyncResultMessage(result));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
export interface GoogleCalendarEventMapEntry {
|
||||
id: string;
|
||||
date: string;
|
||||
}
|
||||
|
||||
export function normalizeEventMapEntry(
|
||||
value: string | GoogleCalendarEventMapEntry | undefined,
|
||||
): GoogleCalendarEventMapEntry | undefined {
|
||||
if (value == null) return undefined;
|
||||
if (typeof value === "string") return { id: value, date: "" };
|
||||
if (typeof value.id === "string" && value.id.length > 0) {
|
||||
return { id: value.id, date: value.date ?? "" };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function getStoredEventId(
|
||||
value: string | GoogleCalendarEventMapEntry | undefined,
|
||||
): string | undefined {
|
||||
return normalizeEventMapEntry(value)?.id;
|
||||
}
|
||||
|
||||
export function lessonDateFromSeqtaKey(seqtaKey: string): string | undefined {
|
||||
const parts = seqtaKey.split(":");
|
||||
for (const part of parts) {
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(part)) return part;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -1,17 +1,7 @@
|
||||
import { GOOGLE_CALENDAR_SYNC_WEEKS } from "@/config/googleCalendar";
|
||||
import { toISODate, weekRangeContaining } from "@/seqta/utils/Loaders/engageParentTimetable";
|
||||
import type { SyncDateRange } from "./syncDateRange";
|
||||
import { syncWindowRange } from "./syncDateRange";
|
||||
import type { SeqtaTimetableLesson } from "./types";
|
||||
|
||||
export function syncDateRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS): {
|
||||
from: string;
|
||||
until: string;
|
||||
} {
|
||||
const { from } = weekRangeContaining(new Date());
|
||||
const end = new Date(from + "T12:00:00");
|
||||
end.setDate(end.getDate() + weeksAhead * 7 - 1);
|
||||
return { from, until: toISODate(end) };
|
||||
}
|
||||
|
||||
async function postSeqtaJson<T>(path: string, body: Record<string, unknown>): Promise<T> {
|
||||
const res = await fetch(`${location.origin}${path}`, {
|
||||
method: "POST",
|
||||
@@ -50,8 +40,10 @@ function isEngageParentContext(): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
export async function fetchTimetableForSync(): Promise<SeqtaTimetableLesson[]> {
|
||||
const { from, until } = syncDateRange();
|
||||
export async function fetchTimetableLessons(
|
||||
range: SyncDateRange,
|
||||
): Promise<SeqtaTimetableLesson[]> {
|
||||
const { from, until } = range;
|
||||
|
||||
if (isEngageParentContext()) {
|
||||
const listJson = await postSeqtaJson<{ payload?: { id?: string | number }[] }>(
|
||||
@@ -80,3 +72,9 @@ export async function fetchTimetableForSync(): Promise<SeqtaTimetableLesson[]> {
|
||||
);
|
||||
return Array.isArray(data?.payload?.items) ? data.payload.items : [];
|
||||
}
|
||||
|
||||
export async function fetchTimetableForSync(weeksAhead?: number): Promise<SeqtaTimetableLesson[]> {
|
||||
return fetchTimetableLessons(syncWindowRange(weeksAhead));
|
||||
}
|
||||
|
||||
export { syncWindowRange, trailingWeekRange, droppedWeekRange } from "./syncDateRange";
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import type { GoogleCalendarEventMapEntry } from "./eventMapEntry";
|
||||
|
||||
/** Never uploaded to BetterSEQTA Cloud (OAuth tokens + per-device event map). */
|
||||
export const BSPLUS_GOOGLE_CALENDAR_STORAGE_KEY = "bsplus_google_calendar";
|
||||
@@ -9,9 +10,13 @@ export interface GoogleCalendarStoredState {
|
||||
expiresAt?: number;
|
||||
connectedAt?: number;
|
||||
lastSyncAt?: number;
|
||||
lastWeeklySyncAt?: number;
|
||||
lastSyncOrigin?: string;
|
||||
/** `${origin}::${seqtaKey}` → Google Calendar event id */
|
||||
eventMap?: Record<string, 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> {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from "@jest/globals";
|
||||
import {
|
||||
droppedWeekRange,
|
||||
syncWindowRange,
|
||||
trailingWeekRange,
|
||||
} from "./syncDateRange";
|
||||
|
||||
describe("syncDateRange", () => {
|
||||
it("builds a 12-week rolling window from the current week", () => {
|
||||
const range = syncWindowRange(12);
|
||||
expect(range.from <= range.until).toBe(true);
|
||||
|
||||
const start = new Date(`${range.from}T12:00:00`);
|
||||
const end = new Date(`${range.until}T12:00:00`);
|
||||
const days = Math.round((end.getTime() - start.getTime()) / 86_400_000) + 1;
|
||||
expect(days).toBe(12 * 7);
|
||||
});
|
||||
|
||||
it("places the trailing week at the end of the window", () => {
|
||||
const window = syncWindowRange(12);
|
||||
const trailing = trailingWeekRange(12);
|
||||
expect(trailing.from >= window.from).toBe(true);
|
||||
expect(trailing.until <= window.until).toBe(true);
|
||||
});
|
||||
|
||||
it("places the dropped week before the window start", () => {
|
||||
const window = syncWindowRange(12);
|
||||
const dropped = droppedWeekRange(12);
|
||||
expect(dropped.until < window.from).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import {
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT,
|
||||
} from "@/config/googleCalendar";
|
||||
import { toISODate, weekRangeContaining } from "@/seqta/utils/Loaders/engageParentTimetable";
|
||||
|
||||
export interface SyncDateRange {
|
||||
from: string;
|
||||
until: string;
|
||||
}
|
||||
|
||||
function parseLocalDate(iso: string): Date {
|
||||
return new Date(`${iso}T12:00:00`);
|
||||
}
|
||||
|
||||
/** Full rolling sync window from the start of the current week. */
|
||||
export function syncWindowRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT): SyncDateRange {
|
||||
const { from } = weekRangeContaining(new Date());
|
||||
const end = parseLocalDate(from);
|
||||
end.setDate(end.getDate() + weeksAhead * 7 - 1);
|
||||
return { from, until: toISODate(end) };
|
||||
}
|
||||
|
||||
/** The trailing week at the end of the sync window (added each weekly roll). */
|
||||
export function trailingWeekRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT): SyncDateRange {
|
||||
const { from: windowStart } = syncWindowRange(weeksAhead);
|
||||
const start = parseLocalDate(windowStart);
|
||||
start.setDate(start.getDate() + (weeksAhead - 1) * 7);
|
||||
const end = new Date(start);
|
||||
end.setDate(end.getDate() + 6);
|
||||
return { from: toISODate(start), until: toISODate(end) };
|
||||
}
|
||||
|
||||
/** The week that rolled off when the window advances (removed each weekly roll). */
|
||||
export function droppedWeekRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT): SyncDateRange {
|
||||
const { from: windowStart } = syncWindowRange(weeksAhead);
|
||||
const end = parseLocalDate(windowStart);
|
||||
end.setDate(end.getDate() - 1);
|
||||
const start = new Date(end);
|
||||
start.setDate(start.getDate() - 6);
|
||||
return { from: toISODate(start), until: toISODate(end) };
|
||||
}
|
||||
|
||||
export function isDateInRange(date: string, range: SyncDateRange): boolean {
|
||||
return date >= range.from && date <= range.until;
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import type { SeqtaTimetableLesson } from "./types";
|
||||
|
||||
jest.mock("@/config/googleCalendar", () => ({
|
||||
isGoogleCalendarConfigured: jest.fn(() => true),
|
||||
}));
|
||||
|
||||
jest.mock("@/utils/verboseLog", () => ({
|
||||
verboseLog: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("@/seqta/utils/googleCalendar/storage", () => ({
|
||||
eventMapKey: (origin: string, seqtaKey: string) => `${origin}::${seqtaKey}`,
|
||||
readGoogleCalendarState: jest.fn(),
|
||||
writeGoogleCalendarState: jest.fn(async (patch: unknown) => patch),
|
||||
}));
|
||||
|
||||
jest.mock("@/seqta/utils/googleCalendar/syncSettings", () => ({
|
||||
getSyncWeeksAhead: jest.fn(async () => 12),
|
||||
}));
|
||||
|
||||
jest.mock("@/seqta/utils/googleCalendar/upsertEvent", () => ({
|
||||
upsertGoogleCalendarEvent: jest.fn(),
|
||||
deleteGoogleCalendarEvent: jest.fn(),
|
||||
}));
|
||||
|
||||
import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/storage";
|
||||
import {
|
||||
deleteGoogleCalendarEvent,
|
||||
upsertGoogleCalendarEvent,
|
||||
} from "@/seqta/utils/googleCalendar/upsertEvent";
|
||||
import { deleteSyncedEventsFromGoogleCalendar, syncLessonsToGoogleCalendar } from "./syncEngine";
|
||||
|
||||
const ORIGIN = "https://school.seqta.com.au";
|
||||
const getAccessToken = async () => "test-token";
|
||||
|
||||
const baseLesson: SeqtaTimetableLesson = {
|
||||
date: "2026-06-27",
|
||||
from: "09:00:00",
|
||||
until: "10:00:00",
|
||||
description: "10 Mathematics",
|
||||
staff: "Mr Smith",
|
||||
room: "MA1",
|
||||
code: "10MAT",
|
||||
type: "class",
|
||||
calendarid: 12345,
|
||||
};
|
||||
|
||||
describe("syncLessonsToGoogleCalendar", () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||
refreshToken: "refresh",
|
||||
eventMap: {
|
||||
[`${ORIGIN}::${ORIGIN}:cal:12345`]: { id: "google-existing", date: "2026-06-27" },
|
||||
[`${ORIGIN}::${ORIGIN}:cal:99999`]: { id: "google-stale", date: "2020-01-06" },
|
||||
},
|
||||
});
|
||||
jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-existing");
|
||||
jest.mocked(deleteGoogleCalendarEvent).mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("updates existing events and removes stale tracked events on full sync", async () => {
|
||||
const result = await syncLessonsToGoogleCalendar(
|
||||
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
|
||||
getAccessToken,
|
||||
);
|
||||
|
||||
expect(deleteGoogleCalendarEvent).toHaveBeenCalled();
|
||||
expect(upsertGoogleCalendarEvent).toHaveBeenCalledTimes(1);
|
||||
expect(result).toMatchObject({
|
||||
success: true,
|
||||
created: 0,
|
||||
updated: 1,
|
||||
failed: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("creates events that are not yet tracked", async () => {
|
||||
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||
refreshToken: "refresh",
|
||||
eventMap: {},
|
||||
});
|
||||
jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-new");
|
||||
|
||||
const result = await syncLessonsToGoogleCalendar(
|
||||
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
|
||||
getAccessToken,
|
||||
);
|
||||
|
||||
expect(deleteGoogleCalendarEvent).not.toHaveBeenCalled();
|
||||
expect(result).toMatchObject({
|
||||
success: true,
|
||||
created: 1,
|
||||
updated: 0,
|
||||
deleted: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports progress while syncing", async () => {
|
||||
const progress: Array<{ phase: string; current: number; total: number }> = [];
|
||||
await syncLessonsToGoogleCalendar(
|
||||
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
|
||||
getAccessToken,
|
||||
{
|
||||
onProgress: (entry) => progress.push(entry),
|
||||
},
|
||||
);
|
||||
|
||||
expect(progress.some((entry) => entry.phase === "upserting")).toBe(true);
|
||||
expect(progress.at(-1)?.phase).toBe("done");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteSyncedEventsFromGoogleCalendar", () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||
refreshToken: "refresh",
|
||||
eventMap: {
|
||||
[`${ORIGIN}::${ORIGIN}:cal:12345`]: { id: "google-1", date: "2026-06-27" },
|
||||
[`${ORIGIN}::${ORIGIN}:cal:99999`]: { id: "google-2", date: "2026-06-28" },
|
||||
"https://other.seqta.com.au::other:key": { id: "google-other", date: "2026-06-28" },
|
||||
},
|
||||
});
|
||||
jest.mocked(deleteGoogleCalendarEvent).mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("deletes only events for the requested origin", async () => {
|
||||
const result = await deleteSyncedEventsFromGoogleCalendar(ORIGIN, getAccessToken);
|
||||
|
||||
expect(deleteGoogleCalendarEvent).toHaveBeenCalledTimes(2);
|
||||
expect(result).toMatchObject({
|
||||
success: true,
|
||||
deleted: 2,
|
||||
failed: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,154 @@
|
||||
import { verboseLog } from "@/utils/verboseLog";
|
||||
import { isGoogleCalendarConfigured } from "@/config/googleCalendar";
|
||||
import { googleApiEventBody, mapLessonsToGoogleEvents } from "@/seqta/utils/googleCalendar/eventMapper";
|
||||
import {
|
||||
getStoredEventId,
|
||||
lessonDateFromSeqtaKey,
|
||||
normalizeEventMapEntry,
|
||||
} from "@/seqta/utils/googleCalendar/eventMapEntry";
|
||||
import {
|
||||
droppedWeekRange,
|
||||
isDateInRange,
|
||||
syncWindowRange,
|
||||
} from "@/seqta/utils/googleCalendar/syncDateRange";
|
||||
import { getSyncWeeksAhead } from "@/seqta/utils/googleCalendar/syncSettings";
|
||||
import {
|
||||
eventMapKey,
|
||||
readGoogleCalendarState,
|
||||
writeGoogleCalendarState,
|
||||
} from "@/seqta/utils/googleCalendar/storage";
|
||||
import type { GoogleCalendarSyncRequest, GoogleCalendarSyncResult } from "@/seqta/utils/googleCalendar/types";
|
||||
import { upsertGoogleCalendarEvent } from "@/seqta/utils/googleCalendar/upsertEvent";
|
||||
import type {
|
||||
GoogleCalendarDeleteResult,
|
||||
GoogleCalendarSyncOptions,
|
||||
GoogleCalendarSyncProgress,
|
||||
GoogleCalendarSyncRequest,
|
||||
GoogleCalendarSyncResult,
|
||||
} from "@/seqta/utils/googleCalendar/types";
|
||||
import {
|
||||
deleteGoogleCalendarEvent,
|
||||
upsertGoogleCalendarEvent,
|
||||
} from "@/seqta/utils/googleCalendar/upsertEvent";
|
||||
|
||||
const EVENT_MAP_PERSIST_EVERY = 10;
|
||||
const CALENDAR_ID = "primary";
|
||||
|
||||
type DeleteTrackedEventsResult = {
|
||||
deleted: number;
|
||||
failed: number;
|
||||
};
|
||||
|
||||
function reportProgress(
|
||||
onProgress: GoogleCalendarSyncOptions["onProgress"],
|
||||
progress: GoogleCalendarSyncProgress,
|
||||
) {
|
||||
onProgress?.(progress);
|
||||
}
|
||||
|
||||
function lessonDateForEvent(startDateTime: string, seqtaKey: string): string {
|
||||
return startDateTime.slice(0, 10) || lessonDateFromSeqtaKey(seqtaKey) || "";
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
reportProgress(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;
|
||||
reportProgress(onProgress, {
|
||||
phase: "deleting",
|
||||
current: progressOffset + deleted + failed,
|
||||
total: progressTotal,
|
||||
message: `Removing old events (${deleted + failed}/${entries.length})…`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { deleted, failed };
|
||||
}
|
||||
|
||||
function originEventMapEntries(
|
||||
eventMap: Record<string, string | { id: string; date: string }>,
|
||||
origin: string,
|
||||
): Array<[string, string]> {
|
||||
const prefix = `${origin}::`;
|
||||
const entries: Array<[string, string]> = [];
|
||||
for (const [key, value] of Object.entries(eventMap)) {
|
||||
if (!key.startsWith(prefix)) continue;
|
||||
const id = getStoredEventId(value);
|
||||
if (id) entries.push([key, id]);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function entriesToPrune(
|
||||
eventMap: Record<string, string | { id: string; date: string }>,
|
||||
origin: string,
|
||||
mode: "full" | "incremental",
|
||||
weeksAhead: number,
|
||||
currentMapKeys: Set<string>,
|
||||
): Array<[string, string]> {
|
||||
const window = syncWindowRange(weeksAhead);
|
||||
const dropped = droppedWeekRange(weeksAhead);
|
||||
const prefix = `${origin}::`;
|
||||
const entries: Array<[string, string]> = [];
|
||||
|
||||
for (const [mapKey, raw] of Object.entries(eventMap)) {
|
||||
if (!mapKey.startsWith(prefix)) continue;
|
||||
const entry = normalizeEventMapEntry(raw);
|
||||
if (!entry) continue;
|
||||
|
||||
let shouldDelete = false;
|
||||
if (mode === "incremental") {
|
||||
shouldDelete = !!entry.date && isDateInRange(entry.date, dropped);
|
||||
} else if (entry.date) {
|
||||
shouldDelete = !isDateInRange(entry.date, window);
|
||||
} else {
|
||||
shouldDelete = !currentMapKeys.has(mapKey);
|
||||
}
|
||||
|
||||
if (shouldDelete) entries.push([mapKey, entry.id]);
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
@@ -29,9 +163,12 @@ export async function syncLessonsToGoogleCalendar(
|
||||
return { success: false, configured: true, connected: false, error: "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) {
|
||||
|
||||
if (events.length === 0 && mode === "full") {
|
||||
return {
|
||||
success: false,
|
||||
configured: true,
|
||||
@@ -40,23 +177,42 @@ export async function syncLessonsToGoogleCalendar(
|
||||
};
|
||||
}
|
||||
|
||||
reportProgress(options.onProgress, {
|
||||
phase: "preparing",
|
||||
current: 0,
|
||||
total: Math.max(events.length, 1),
|
||||
message: mode === "incremental" ? "Preparing weekly sync…" : "Preparing sync…",
|
||||
});
|
||||
|
||||
let accessToken = await getAccessToken();
|
||||
const calendarId = "primary";
|
||||
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 staleResult = await deleteTrackedEventsFromGoogle(
|
||||
staleEntries,
|
||||
eventMap,
|
||||
getAccessToken,
|
||||
false,
|
||||
options.onProgress,
|
||||
0,
|
||||
totalSteps,
|
||||
);
|
||||
|
||||
let created = 0;
|
||||
let updated = 0;
|
||||
let failed = 0;
|
||||
let failed = staleResult.failed;
|
||||
const lastSyncAt = Date.now();
|
||||
|
||||
for (let i = 0; i < events.length; i++) {
|
||||
const event = events[i];
|
||||
const mapKey = eventMapKey(request.origin, event.seqtaKey);
|
||||
const existingId = eventMap[mapKey];
|
||||
const existingId = getStoredEventId(eventMap[mapKey]);
|
||||
try {
|
||||
const googleId = await upsertGoogleCalendarEvent(
|
||||
accessToken,
|
||||
calendarId,
|
||||
CALENDAR_ID,
|
||||
existingId,
|
||||
googleApiEventBody(event),
|
||||
async () => {
|
||||
@@ -66,7 +222,17 @@ export async function syncLessonsToGoogleCalendar(
|
||||
);
|
||||
if (existingId) updated += 1;
|
||||
else created += 1;
|
||||
eventMap[mapKey] = googleId;
|
||||
eventMap[mapKey] = {
|
||||
id: googleId,
|
||||
date: lessonDateForEvent(event.startDateTime, event.seqtaKey),
|
||||
};
|
||||
|
||||
reportProgress(options.onProgress, {
|
||||
phase: "upserting",
|
||||
current: staleEntries.length + i + 1,
|
||||
total: totalSteps,
|
||||
message: `Syncing events (${i + 1}/${events.length})…`,
|
||||
});
|
||||
|
||||
if ((i + 1) % EVENT_MAP_PERSIST_EVERY === 0 || i === events.length - 1) {
|
||||
await writeGoogleCalendarState({
|
||||
@@ -78,15 +244,37 @@ export async function syncLessonsToGoogleCalendar(
|
||||
} catch (err) {
|
||||
verboseLog("[BetterSEQTA+] Google Calendar event sync failed:", err);
|
||||
failed += 1;
|
||||
reportProgress(options.onProgress, {
|
||||
phase: "upserting",
|
||||
current: staleEntries.length + i + 1,
|
||||
total: totalSteps,
|
||||
message: `Syncing events (${i + 1}/${events.length})…`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const syncResult: GoogleCalendarSyncResult = {
|
||||
if (staleResult.deleted > 0 || staleEntries.length > 0 || events.length > 0) {
|
||||
await writeGoogleCalendarState({
|
||||
eventMap,
|
||||
lastSyncAt,
|
||||
lastSyncOrigin: request.origin,
|
||||
});
|
||||
}
|
||||
|
||||
reportProgress(options.onProgress, {
|
||||
phase: "done",
|
||||
current: totalSteps,
|
||||
total: totalSteps,
|
||||
message: "Sync complete",
|
||||
});
|
||||
|
||||
return {
|
||||
success: failed === 0,
|
||||
configured: true,
|
||||
connected: true,
|
||||
created,
|
||||
updated,
|
||||
deleted: staleResult.deleted,
|
||||
skipped: 0,
|
||||
failed,
|
||||
lastSyncAt,
|
||||
@@ -95,6 +283,68 @@ export async function syncLessonsToGoogleCalendar(
|
||||
? `Synced with ${failed} error${failed === 1 ? "" : "s"}. Check the console for details.`
|
||||
: undefined,
|
||||
};
|
||||
|
||||
return syncResult;
|
||||
}
|
||||
|
||||
/** 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 };
|
||||
}
|
||||
|
||||
reportProgress(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 });
|
||||
|
||||
reportProgress(options.onProgress, {
|
||||
phase: "done",
|
||||
current: entries.length,
|
||||
total: entries.length,
|
||||
message: "Removal complete",
|
||||
});
|
||||
|
||||
return {
|
||||
success: failed === 0,
|
||||
configured: true,
|
||||
connected: true,
|
||||
deleted,
|
||||
failed,
|
||||
error:
|
||||
failed > 0
|
||||
? `Removed ${deleted} event${deleted === 1 ? "" : "s"} with ${failed} error${failed === 1 ? "" : "s"}.`
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import {
|
||||
fetchTimetableForSync,
|
||||
fetchTimetableLessons,
|
||||
trailingWeekRange,
|
||||
} from "@/seqta/utils/googleCalendar/fetchTimetable";
|
||||
import {
|
||||
getSyncWeeksAhead,
|
||||
markWeeklySyncComplete,
|
||||
} from "@/seqta/utils/googleCalendar/syncSettings";
|
||||
import { syncLessonsToGoogleCalendar } from "@/seqta/utils/googleCalendar/syncEngine";
|
||||
import type {
|
||||
GoogleCalendarSyncOptions,
|
||||
GoogleCalendarSyncProgress,
|
||||
GoogleCalendarSyncResult,
|
||||
} from "@/seqta/utils/googleCalendar/types";
|
||||
|
||||
export type GoogleCalendarRunMode = "full" | "incremental";
|
||||
|
||||
export interface RunGoogleCalendarSyncParams {
|
||||
mode?: GoogleCalendarRunMode;
|
||||
silent?: boolean;
|
||||
onProgress?: (progress: GoogleCalendarSyncProgress) => void;
|
||||
}
|
||||
|
||||
async function getAccessTokenFromBackground(): Promise<string> {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "googleCalendarGetAccessToken",
|
||||
})) as { success?: boolean; accessToken?: string; error?: string };
|
||||
if (!res?.success || !res.accessToken) {
|
||||
throw new Error(res?.error ?? "Could not get Google Calendar access token.");
|
||||
}
|
||||
return res.accessToken;
|
||||
}
|
||||
|
||||
export async function runGoogleCalendarSync(
|
||||
params: RunGoogleCalendarSyncParams = {},
|
||||
): Promise<GoogleCalendarSyncResult> {
|
||||
const mode = params.mode ?? "full";
|
||||
const weeksAhead = await getSyncWeeksAhead();
|
||||
|
||||
params.onProgress?.({
|
||||
phase: "preparing",
|
||||
current: 0,
|
||||
total: 1,
|
||||
message: mode === "incremental" ? "Fetching new week…" : "Fetching timetable…",
|
||||
});
|
||||
|
||||
const lessons =
|
||||
mode === "incremental"
|
||||
? await fetchTimetableLessons(trailingWeekRange(weeksAhead))
|
||||
: await fetchTimetableForSync(weeksAhead);
|
||||
|
||||
const options: GoogleCalendarSyncOptions = { onProgress: params.onProgress };
|
||||
const result = await syncLessonsToGoogleCalendar(
|
||||
{
|
||||
origin: location.origin,
|
||||
lessons,
|
||||
mode,
|
||||
weeksAhead,
|
||||
},
|
||||
getAccessTokenFromBackground,
|
||||
options,
|
||||
);
|
||||
|
||||
if (result.success && mode === "incremental") {
|
||||
await markWeeklySyncComplete();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function formatSyncResultMessage(result: GoogleCalendarSyncResult): string {
|
||||
const created = result.created ?? 0;
|
||||
const updated = result.updated ?? 0;
|
||||
const deleted = result.deleted ?? 0;
|
||||
const parts: string[] = [];
|
||||
if (created > 0) parts.push(`${created} new`);
|
||||
if (updated > 0) parts.push(`${updated} updated`);
|
||||
if (deleted > 0) parts.push(`${deleted} removed`);
|
||||
if (parts.length === 0) return "Google Calendar is up to date.";
|
||||
return `Google Calendar updated (${parts.join(", ")}).`;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import {
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT,
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_MAX,
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_MIN,
|
||||
} from "@/config/googleCalendar";
|
||||
import { readGoogleCalendarState, writeGoogleCalendarState } from "./storage";
|
||||
|
||||
export const GOOGLE_CALENDAR_WEEKLY_ALARM = "bsplus_google_calendar_weekly";
|
||||
export const WEEKLY_SYNC_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export function clampSyncWeeks(weeks: number): number {
|
||||
if (!Number.isFinite(weeks)) return GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT;
|
||||
return Math.min(
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_MAX,
|
||||
Math.max(GOOGLE_CALENDAR_SYNC_WEEKS_MIN, Math.round(weeks)),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getSyncWeeksAhead(): Promise<number> {
|
||||
const state = await readGoogleCalendarState();
|
||||
return clampSyncWeeks(state.syncWeeksAhead ?? GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT);
|
||||
}
|
||||
|
||||
export async function setSyncWeeksAhead(weeks: number): Promise<number> {
|
||||
const syncWeeksAhead = clampSyncWeeks(weeks);
|
||||
await writeGoogleCalendarState({ syncWeeksAhead });
|
||||
return syncWeeksAhead;
|
||||
}
|
||||
|
||||
export async function getAutoSyncWeekly(): Promise<boolean> {
|
||||
const state = await readGoogleCalendarState();
|
||||
return state.autoSyncWeekly !== false;
|
||||
}
|
||||
|
||||
export async function setAutoSyncWeekly(enabled: boolean): Promise<void> {
|
||||
await writeGoogleCalendarState({ autoSyncWeekly: enabled });
|
||||
}
|
||||
|
||||
export async function shouldRunWeeklySync(): Promise<boolean> {
|
||||
const state = await readGoogleCalendarState();
|
||||
if (!state.refreshToken && !state.accessToken) return false;
|
||||
if (state.autoSyncWeekly === false) return false;
|
||||
if (state.pendingWeeklySync) return true;
|
||||
const last = state.lastWeeklySyncAt ?? state.lastSyncAt ?? 0;
|
||||
return Date.now() - last >= WEEKLY_SYNC_INTERVAL_MS;
|
||||
}
|
||||
|
||||
export async function markWeeklySyncComplete(): Promise<void> {
|
||||
await writeGoogleCalendarState({
|
||||
lastWeeklySyncAt: Date.now(),
|
||||
pendingWeeklySync: false,
|
||||
});
|
||||
}
|
||||
|
||||
export async function markWeeklySyncPending(): Promise<void> {
|
||||
await writeGoogleCalendarState({ pendingWeeklySync: true });
|
||||
}
|
||||
@@ -25,6 +25,21 @@ export interface GoogleCalendarEventInput {
|
||||
export interface GoogleCalendarSyncRequest {
|
||||
origin: string;
|
||||
lessons: SeqtaTimetableLesson[];
|
||||
mode?: "full" | "incremental";
|
||||
weeksAhead?: number;
|
||||
}
|
||||
|
||||
export type GoogleCalendarSyncPhase = "preparing" | "deleting" | "upserting" | "done";
|
||||
|
||||
export interface GoogleCalendarSyncProgress {
|
||||
phase: GoogleCalendarSyncPhase;
|
||||
current: number;
|
||||
total: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface GoogleCalendarSyncOptions {
|
||||
onProgress?: (progress: GoogleCalendarSyncProgress) => void;
|
||||
}
|
||||
|
||||
export interface GoogleCalendarSyncResult {
|
||||
@@ -33,6 +48,7 @@ export interface GoogleCalendarSyncResult {
|
||||
configured?: boolean;
|
||||
created?: number;
|
||||
updated?: number;
|
||||
deleted?: number;
|
||||
skipped?: number;
|
||||
failed?: number;
|
||||
lastSyncAt?: number;
|
||||
@@ -43,5 +59,17 @@ export interface GoogleCalendarStatus {
|
||||
configured: boolean;
|
||||
connected: boolean;
|
||||
lastSyncAt?: number;
|
||||
lastWeeklySyncAt?: number;
|
||||
lastSyncOrigin?: string;
|
||||
syncWeeksAhead?: number;
|
||||
autoSyncWeekly?: boolean;
|
||||
}
|
||||
|
||||
export interface GoogleCalendarDeleteResult {
|
||||
success: boolean;
|
||||
configured?: boolean;
|
||||
connected?: boolean;
|
||||
deleted?: number;
|
||||
failed?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
@@ -42,3 +42,22 @@ export async function upsertGoogleCalendarEvent(
|
||||
}
|
||||
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})`);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user