mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-08-28 17:21:05 +00:00
Merge remote-tracking branch 'origin/main' into various-bugfixes
This commit is contained in:
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
extractSolidColor,
|
||||
normalizeCssColorString,
|
||||
parseCssColor,
|
||||
} from "./parseCssColor";
|
||||
import { extractSolidColor, normalizeCssColorString } from "./parseCssColor";
|
||||
|
||||
describe("normalizeCssColorString", () => {
|
||||
it("lowercases uppercase RGBA/RGB function names", () => {
|
||||
@@ -28,19 +24,3 @@ describe("extractSolidColor", () => {
|
||||
).toBe("rgba(201,61,0,1)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseCssColor", () => {
|
||||
it("parses uppercase RGBA without throwing", () => {
|
||||
const parsed = parseCssColor("RGBA(3, 29, 11, 0.58)");
|
||||
expect(parsed.alpha()).toBeCloseTo(0.58, 2);
|
||||
expect(parsed.red()).toBe(3);
|
||||
expect(parsed.green()).toBe(29);
|
||||
expect(parsed.blue()).toBe(11);
|
||||
});
|
||||
|
||||
it("falls back when the value is not a colour", () => {
|
||||
expect(parseCssColor("not-a-color", "#007bff").hex().toLowerCase()).toBe(
|
||||
"#007bff",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import Color from "color";
|
||||
|
||||
type ColorInstance = ReturnType<typeof Color>;
|
||||
|
||||
/**
|
||||
* SEQTA themes and user gradients often use uppercase `RGBA()` / `RGB()`.
|
||||
* The `color` package only accepts lowercase function names.
|
||||
@@ -32,34 +28,3 @@ export function extractSolidColor(value: string): string | null {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Parse a CSS colour for the `color` library; never throws. */
|
||||
export function parseCssColor(value: string, fallback = "#007bff"): ColorInstance {
|
||||
const candidates = [
|
||||
extractSolidColor(value),
|
||||
normalizeCssColorString(value),
|
||||
].filter((candidate): candidate is string => Boolean(candidate));
|
||||
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
return Color(candidate);
|
||||
} catch {
|
||||
// try next strategy
|
||||
}
|
||||
|
||||
const rgbaMatch = candidate.match(
|
||||
/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)/i,
|
||||
);
|
||||
if (rgbaMatch) {
|
||||
try {
|
||||
const [, r, g, b, a] = rgbaMatch;
|
||||
const rgb = Color.rgb(Number(r), Number(g), Number(b));
|
||||
return a !== undefined ? rgb.alpha(Number(a)) : rgb;
|
||||
} catch {
|
||||
// fall through
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Color(fallback);
|
||||
}
|
||||
|
||||
+27
-21
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/** Stable content fingerprint for skip-unchanged calendar sync. */
|
||||
|
||||
export type FingerprintableEvent = {
|
||||
summary: string;
|
||||
location?: string;
|
||||
description?: string;
|
||||
startDateTime: string;
|
||||
endDateTime: string;
|
||||
timeZone: string;
|
||||
};
|
||||
|
||||
export function eventFingerprint(event: FingerprintableEvent): string {
|
||||
return [
|
||||
event.summary.trim(),
|
||||
(event.location ?? "").trim(),
|
||||
(event.description ?? "").trim(),
|
||||
event.startDateTime.trim(),
|
||||
event.endDateTime.trim(),
|
||||
event.timeZone.trim(),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/** Parse `Key: {seqtaKey}` from Outlook event body text. */
|
||||
export function parseOutlookSeqtaKey(bodyContent: string | undefined | null): string | undefined {
|
||||
if (!bodyContent) return undefined;
|
||||
const match = bodyContent.match(/^Key:\s*(.+)$/m);
|
||||
const key = match?.[1]?.trim();
|
||||
return key && key.length > 0 ? key : undefined;
|
||||
}
|
||||
|
||||
export function outlookDescriptionWithKey(
|
||||
description: string | undefined,
|
||||
seqtaKey: string,
|
||||
): string {
|
||||
const base = (description ?? "Synced by BetterSEQTA+").trim();
|
||||
const withoutKey = base
|
||||
.split("\n")
|
||||
.filter((line) => !/^Key:\s*/.test(line))
|
||||
.join("\n")
|
||||
.trim();
|
||||
return `${withoutKey}\nKey: ${seqtaKey}`;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
export interface EventMapEntry {
|
||||
id: string;
|
||||
date: string;
|
||||
/** Last-synced content fingerprint; used to skip unchanged events. */
|
||||
fingerprint?: 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 ?? "",
|
||||
fingerprint: value.fingerprint,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function getStoredFingerprint(
|
||||
value: string | EventMapEntry | undefined,
|
||||
): string | undefined {
|
||||
return normalizeEventMapEntry(value)?.fingerprint;
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
import { describe, expect, it, jest } from "@jest/globals";
|
||||
|
||||
jest.mock("@/utils/verboseLog", () => ({
|
||||
verboseLog: jest.fn(),
|
||||
}));
|
||||
|
||||
import {
|
||||
eventFingerprint,
|
||||
outlookDescriptionWithKey,
|
||||
parseOutlookSeqtaKey,
|
||||
} from "./eventFingerprint";
|
||||
import {
|
||||
buildLessonSyncResult,
|
||||
collectOriginDeleteEntries,
|
||||
entriesToPrune,
|
||||
formatLessonSyncResultMessage,
|
||||
mapPool,
|
||||
mergeRemoteEventsIntoMap,
|
||||
reportSyncProgress,
|
||||
upsertLessonEvents,
|
||||
} from "./lessonSyncShared";
|
||||
import type { GoogleCalendarSyncProgress } from "@/seqta/utils/googleCalendar/types";
|
||||
import { syncWindowRange } from "@/seqta/utils/googleCalendar/syncDateRange";
|
||||
|
||||
describe("reportSyncProgress", () => {
|
||||
it("calls onProgress when provided", () => {
|
||||
const onProgress = jest.fn();
|
||||
const progress: GoogleCalendarSyncProgress = {
|
||||
phase: "upserting",
|
||||
current: 1,
|
||||
total: 5,
|
||||
message: "Syncing events (1/5)…",
|
||||
};
|
||||
|
||||
reportSyncProgress(onProgress, progress);
|
||||
reportSyncProgress(undefined, progress);
|
||||
|
||||
expect(onProgress).toHaveBeenCalledTimes(1);
|
||||
expect(onProgress).toHaveBeenCalledWith(progress);
|
||||
});
|
||||
});
|
||||
|
||||
describe("eventFingerprint", () => {
|
||||
it("is stable for equivalent event content", () => {
|
||||
const base = {
|
||||
summary: "Math",
|
||||
location: "MA1",
|
||||
description: "Synced by BetterSEQTA+",
|
||||
startDateTime: "2026-07-13T09:00:00",
|
||||
endDateTime: "2026-07-13T10:00:00",
|
||||
timeZone: "Australia/Adelaide",
|
||||
};
|
||||
expect(eventFingerprint(base)).toBe(eventFingerprint({ ...base }));
|
||||
expect(eventFingerprint(base)).not.toBe(
|
||||
eventFingerprint({ ...base, summary: "English" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("outlook Key helpers", () => {
|
||||
it("embeds and parses Key lines", () => {
|
||||
const withKey = outlookDescriptionWithKey("Synced by BetterSEQTA+\nTeacher: A", "origin:cal:1");
|
||||
expect(withKey).toContain("Key: origin:cal:1");
|
||||
expect(parseOutlookSeqtaKey(withKey)).toBe("origin:cal:1");
|
||||
expect(outlookDescriptionWithKey(withKey, "origin:cal:2")).toContain("Key: origin:cal:2");
|
||||
expect(outlookDescriptionWithKey(withKey, "origin:cal:2").match(/^Key:/gm)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("entriesToPrune", () => {
|
||||
const origin = "https://school.seqta.com.au";
|
||||
const weeksAhead = 12;
|
||||
const syncDate = syncWindowRange(weeksAhead).from;
|
||||
const mapKey = `${origin}::${origin}:cal:1`;
|
||||
const cancelledKey = `${origin}::${origin}:cal:cancelled`;
|
||||
|
||||
it("returns nothing for incremental mode", () => {
|
||||
expect(
|
||||
entriesToPrune(
|
||||
{ [mapKey]: { id: "evt-1", date: syncDate } },
|
||||
origin,
|
||||
"incremental",
|
||||
weeksAhead,
|
||||
new Set([mapKey]),
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("prunes cancelled lessons still inside the sync window", () => {
|
||||
const pruned = entriesToPrune(
|
||||
{
|
||||
[mapKey]: { id: "evt-1", date: syncDate },
|
||||
[cancelledKey]: { id: "evt-cancelled", date: syncDate },
|
||||
},
|
||||
origin,
|
||||
"full",
|
||||
weeksAhead,
|
||||
new Set([mapKey]),
|
||||
);
|
||||
expect(pruned).toEqual([[cancelledKey, "evt-cancelled"]]);
|
||||
});
|
||||
|
||||
it("prunes events whose date is outside the sync window", () => {
|
||||
const staleKey = `${origin}::${origin}:cal:old`;
|
||||
const pruned = entriesToPrune(
|
||||
{ [staleKey]: { id: "evt-old", date: "2020-01-06" } },
|
||||
origin,
|
||||
"full",
|
||||
weeksAhead,
|
||||
new Set(),
|
||||
);
|
||||
expect(pruned).toEqual([[staleKey, "evt-old"]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergeRemoteEventsIntoMap", () => {
|
||||
const origin = "https://school.seqta.com.au";
|
||||
const mapKey = (o: string, seqtaKey: string) => `${o}::${seqtaKey}`;
|
||||
|
||||
it("recovers remote IDs for the current origin only", () => {
|
||||
const eventMap: Record<string, { id: string; date: string; fingerprint?: string }> = {};
|
||||
mergeRemoteEventsIntoMap(
|
||||
eventMap,
|
||||
origin,
|
||||
[
|
||||
{
|
||||
seqtaKey: `${origin}:cal:1`,
|
||||
id: "remote-1",
|
||||
date: "2026-07-13",
|
||||
fingerprint: "fp-1",
|
||||
},
|
||||
{
|
||||
seqtaKey: "https://other.seqta.com.au:cal:2",
|
||||
id: "remote-other",
|
||||
date: "2026-07-13",
|
||||
fingerprint: "fp-other",
|
||||
},
|
||||
],
|
||||
mapKey,
|
||||
);
|
||||
|
||||
expect(eventMap[`${origin}::${origin}:cal:1`]).toMatchObject({
|
||||
id: "remote-1",
|
||||
fingerprint: "fp-1",
|
||||
});
|
||||
expect(eventMap[`${origin}::https://other.seqta.com.au:cal:2`]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps an existing local fingerprint when reconciling", () => {
|
||||
const key = `${origin}::${origin}:cal:1`;
|
||||
const eventMap = {
|
||||
[key]: { id: "old-id", date: "2026-07-13", fingerprint: "local-fp" },
|
||||
};
|
||||
mergeRemoteEventsIntoMap(
|
||||
eventMap,
|
||||
origin,
|
||||
[
|
||||
{
|
||||
seqtaKey: `${origin}:cal:1`,
|
||||
id: "remote-1",
|
||||
date: "2026-07-13",
|
||||
fingerprint: "remote-fp",
|
||||
},
|
||||
],
|
||||
mapKey,
|
||||
);
|
||||
expect(eventMap[key]).toMatchObject({ id: "remote-1", fingerprint: "local-fp" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("collectOriginDeleteEntries", () => {
|
||||
const origin = "https://school.seqta.com.au";
|
||||
const mapKey = (o: string, seqtaKey: string) => `${o}::${seqtaKey}`;
|
||||
|
||||
it("includes local map entries and matching remote events", () => {
|
||||
const eventMap = {
|
||||
[`${origin}::${origin}:cal:1`]: { id: "local-1", date: "2026-07-13" },
|
||||
};
|
||||
const entries = collectOriginDeleteEntries(
|
||||
eventMap,
|
||||
origin,
|
||||
[
|
||||
{
|
||||
seqtaKey: `${origin}:cal:2`,
|
||||
id: "remote-2",
|
||||
date: "2026-07-14",
|
||||
fingerprint: "fp",
|
||||
},
|
||||
{
|
||||
seqtaKey: "",
|
||||
id: "orphan-3",
|
||||
date: "2026-07-15",
|
||||
fingerprint: "fp",
|
||||
},
|
||||
{
|
||||
seqtaKey: "https://other.seqta.com.au:cal:9",
|
||||
id: "other",
|
||||
date: "2026-07-15",
|
||||
fingerprint: "fp",
|
||||
},
|
||||
],
|
||||
mapKey,
|
||||
);
|
||||
|
||||
const ids = entries.map(([, id]) => id).sort();
|
||||
expect(ids).toEqual(["local-1", "orphan-3", "remote-2"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatLessonSyncResultMessage", () => {
|
||||
it("includes unchanged counts", () => {
|
||||
expect(
|
||||
formatLessonSyncResultMessage(
|
||||
{ success: true, created: 1, updated: 2, deleted: 0, skipped: 3 },
|
||||
"Google Calendar",
|
||||
),
|
||||
).toBe("Google Calendar updated (1 new, 2 updated, 3 unchanged).");
|
||||
});
|
||||
|
||||
it("reports up to date when nothing changed", () => {
|
||||
expect(
|
||||
formatLessonSyncResultMessage(
|
||||
buildLessonSyncResult(0, 0, 0, 0, 0, Date.now()),
|
||||
"Outlook Calendar",
|
||||
),
|
||||
).toBe("Outlook Calendar is up to date.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("upsertLessonEvents skip unchanged", () => {
|
||||
it("skips API writes when fingerprint matches", async () => {
|
||||
const origin = "https://school.seqta.com.au";
|
||||
const event = {
|
||||
seqtaKey: `${origin}:cal:1`,
|
||||
summary: "Math",
|
||||
description: "Synced by BetterSEQTA+",
|
||||
startDateTime: "2026-07-13T09:00:00",
|
||||
endDateTime: "2026-07-13T10:00:00",
|
||||
timeZone: "UTC",
|
||||
};
|
||||
const fp = eventFingerprint(event);
|
||||
const key = `${origin}::${event.seqtaKey}`;
|
||||
const eventMap = {
|
||||
[key]: { id: "existing", date: "2026-07-13", fingerprint: fp },
|
||||
};
|
||||
const upsert = jest.fn(async () => "existing");
|
||||
|
||||
const result = await upsertLessonEvents({
|
||||
events: [event],
|
||||
eventMap,
|
||||
origin,
|
||||
staleEntryCount: 0,
|
||||
totalSteps: 1,
|
||||
lastSyncAt: Date.now(),
|
||||
initialFailed: 0,
|
||||
getAccessToken: async () => "token",
|
||||
mapKey: (o, k) => `${o}::${k}`,
|
||||
upsert,
|
||||
writeState: async () => undefined,
|
||||
logLabel: "Test",
|
||||
});
|
||||
|
||||
expect(upsert).not.toHaveBeenCalled();
|
||||
expect(result).toMatchObject({ created: 0, updated: 0, skipped: 1, failed: 0 });
|
||||
});
|
||||
|
||||
it("runs upserts concurrently", async () => {
|
||||
const origin = "https://school.seqta.com.au";
|
||||
let inFlight = 0;
|
||||
let maxInFlight = 0;
|
||||
const events = Array.from({ length: 6 }, (_, i) => ({
|
||||
seqtaKey: `${origin}:cal:${i}`,
|
||||
summary: `Class ${i}`,
|
||||
description: "Synced by BetterSEQTA+",
|
||||
startDateTime: "2026-07-13T09:00:00",
|
||||
endDateTime: "2026-07-13T10:00:00",
|
||||
timeZone: "UTC",
|
||||
}));
|
||||
|
||||
const upsert = jest.fn(async () => {
|
||||
inFlight += 1;
|
||||
maxInFlight = Math.max(maxInFlight, inFlight);
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
inFlight -= 1;
|
||||
return `id-${Math.random()}`;
|
||||
});
|
||||
|
||||
const result = await upsertLessonEvents({
|
||||
events,
|
||||
eventMap: {},
|
||||
origin,
|
||||
staleEntryCount: 0,
|
||||
totalSteps: events.length,
|
||||
lastSyncAt: Date.now(),
|
||||
initialFailed: 0,
|
||||
getAccessToken: async () => "token",
|
||||
mapKey: (o, k) => `${o}::${k}`,
|
||||
upsert,
|
||||
writeState: async () => undefined,
|
||||
logLabel: "Test",
|
||||
concurrency: 2,
|
||||
});
|
||||
|
||||
expect(result.created).toBe(6);
|
||||
expect(upsert).toHaveBeenCalledTimes(6);
|
||||
expect(maxInFlight).toBeGreaterThan(1);
|
||||
expect(maxInFlight).toBeLessThanOrEqual(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mapPool", () => {
|
||||
it("limits concurrency", async () => {
|
||||
let inFlight = 0;
|
||||
let maxInFlight = 0;
|
||||
await mapPool([1, 2, 3, 4, 5], 2, async () => {
|
||||
inFlight += 1;
|
||||
maxInFlight = Math.max(maxInFlight, inFlight);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
inFlight -= 1;
|
||||
});
|
||||
expect(maxInFlight).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,20 @@
|
||||
import { verboseLog } from "@/utils/verboseLog";
|
||||
import {
|
||||
getStoredEventId,
|
||||
getStoredFingerprint,
|
||||
lessonDateFromSeqtaKey,
|
||||
normalizeEventMapEntry,
|
||||
} from "@/seqta/utils/googleCalendar/eventMapEntry";
|
||||
type EventMapRecord,
|
||||
} from "@/seqta/utils/calendarSync/eventMap";
|
||||
import { eventFingerprint } from "@/seqta/utils/calendarSync/eventFingerprint";
|
||||
import type { RemoteSyncedEvent } from "@/seqta/utils/calendarSync/remoteEvents";
|
||||
import {
|
||||
isDateInRange,
|
||||
syncWindowRange,
|
||||
type SyncDateRange,
|
||||
} from "@/seqta/utils/googleCalendar/syncDateRange";
|
||||
import type {
|
||||
GoogleCalendarDeleteResult,
|
||||
GoogleCalendarSyncOptions,
|
||||
GoogleCalendarSyncProgress,
|
||||
GoogleCalendarSyncResult,
|
||||
@@ -16,11 +22,42 @@ import type {
|
||||
|
||||
export const EVENT_MAP_PERSIST_EVERY = 10;
|
||||
|
||||
export type EventMapRecord = Record<string, string | { id: string; date: string }>;
|
||||
/** Max concurrent Google/Outlook create/update/delete requests during sync. */
|
||||
export const SYNC_CONCURRENCY = 2;
|
||||
|
||||
/** Same cap for deletes to avoid provider rate limits. */
|
||||
export const SYNC_DELETE_CONCURRENCY = 2;
|
||||
|
||||
/** Run async work over items with a fixed concurrency pool. */
|
||||
export async function mapPool<T>(
|
||||
items: readonly T[],
|
||||
concurrency: number,
|
||||
worker: (item: T, index: number) => Promise<void>,
|
||||
): Promise<void> {
|
||||
if (items.length === 0) return;
|
||||
const limit = Math.max(1, Math.min(concurrency, items.length));
|
||||
let nextIndex = 0;
|
||||
|
||||
async function runWorker(): Promise<void> {
|
||||
while (true) {
|
||||
const index = nextIndex;
|
||||
nextIndex += 1;
|
||||
if (index >= items.length) return;
|
||||
await worker(items[index], index);
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(Array.from({ length: limit }, () => runWorker()));
|
||||
}
|
||||
|
||||
export type MappedLessonEvent = {
|
||||
seqtaKey: string;
|
||||
summary: string;
|
||||
location?: string;
|
||||
description?: string;
|
||||
startDateTime: string;
|
||||
endDateTime: string;
|
||||
timeZone: string;
|
||||
};
|
||||
|
||||
export function reportSyncProgress(
|
||||
@@ -48,18 +85,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,
|
||||
@@ -67,6 +92,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]> = [];
|
||||
@@ -75,7 +102,9 @@ export function entriesToPrune(
|
||||
if (!mapKey.startsWith(prefix)) continue;
|
||||
const entry = normalizeEventMapEntry(raw);
|
||||
if (!entry) continue;
|
||||
if (shouldPruneEntry(mode, entry, mapKey, window, currentMapKeys)) {
|
||||
const missingFromTimetable = !currentMapKeys.has(mapKey);
|
||||
const outsideWindow = entry.date ? !isDateInRange(entry.date, window) : false;
|
||||
if (missingFromTimetable || outsideWindow) {
|
||||
entries.push([mapKey, entry.id]);
|
||||
}
|
||||
}
|
||||
@@ -83,6 +112,74 @@ export function entriesToPrune(
|
||||
return entries;
|
||||
}
|
||||
|
||||
/** Merge remote BS+ events into the local eventMap (origin-scoped keys). */
|
||||
export function mergeRemoteEventsIntoMap(
|
||||
eventMap: EventMapRecord,
|
||||
origin: string,
|
||||
remoteEvents: RemoteSyncedEvent[],
|
||||
mapKey: (origin: string, seqtaKey: string) => string,
|
||||
): void {
|
||||
for (const remote of remoteEvents) {
|
||||
if (!remote.seqtaKey.startsWith(origin)) continue;
|
||||
const key = mapKey(origin, remote.seqtaKey);
|
||||
const existing = normalizeEventMapEntry(eventMap[key]);
|
||||
eventMap[key] = {
|
||||
id: remote.id,
|
||||
date: remote.date || existing?.date || lessonDateFromSeqtaKey(remote.seqtaKey) || "",
|
||||
// Prefer last-written local fingerprint so skip stays stable across API format quirks.
|
||||
fingerprint: existing?.fingerprint ?? remote.fingerprint,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a deduped delete list from local map + remote events for an origin.
|
||||
* Unkeyed remote events (empty seqtaKey) are included as orphan removals.
|
||||
*/
|
||||
export function collectOriginDeleteEntries(
|
||||
eventMap: EventMapRecord,
|
||||
origin: string,
|
||||
remoteEvents: RemoteSyncedEvent[],
|
||||
mapKey: (origin: string, seqtaKey: string) => string,
|
||||
): Array<[string, string]> {
|
||||
const byId = new Map<string, string>();
|
||||
|
||||
for (const [key, id] of originEventMapEntries(eventMap, origin)) {
|
||||
byId.set(id, key);
|
||||
}
|
||||
|
||||
for (const remote of remoteEvents) {
|
||||
if (remote.seqtaKey && !remote.seqtaKey.startsWith(origin)) continue;
|
||||
if (byId.has(remote.id)) continue;
|
||||
const key = remote.seqtaKey
|
||||
? mapKey(origin, remote.seqtaKey)
|
||||
: `${origin}::__orphan__:${remote.id}`;
|
||||
byId.set(remote.id, key);
|
||||
}
|
||||
|
||||
return Array.from(byId.entries()).map(([id, key]) => [key, id]);
|
||||
}
|
||||
|
||||
export function clearOriginEventMapEntries(eventMap: EventMapRecord, origin: string): void {
|
||||
const prefix = `${origin}::`;
|
||||
for (const key of Object.keys(eventMap)) {
|
||||
if (key.startsWith(prefix)) delete eventMap[key];
|
||||
}
|
||||
}
|
||||
|
||||
export function reconcileRangeForMode(
|
||||
mode: "full" | "incremental",
|
||||
weeksAhead: number,
|
||||
ranges: {
|
||||
syncWindowRange: (weeks: number) => SyncDateRange;
|
||||
trailingWeekRange: (weeks: number) => SyncDateRange;
|
||||
},
|
||||
): SyncDateRange {
|
||||
return mode === "incremental"
|
||||
? ranges.trailingWeekRange(weeksAhead)
|
||||
: ranges.syncWindowRange(weeksAhead);
|
||||
}
|
||||
|
||||
export function notConfiguredSyncResult(error: string): GoogleCalendarSyncResult {
|
||||
return { success: false, configured: false, error };
|
||||
}
|
||||
@@ -100,10 +197,116 @@ 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 skipped = result.skipped ?? 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 (skipped > 0) parts.push(`${skipped} unchanged`);
|
||||
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;
|
||||
concurrency?: number;
|
||||
},
|
||||
): Promise<{ deleted: number; failed: number }> {
|
||||
if (entries.length === 0) return { deleted: 0, failed: 0 };
|
||||
|
||||
const {
|
||||
persistProgress = false,
|
||||
onProgress,
|
||||
progressOffset = 0,
|
||||
progressTotal = 0,
|
||||
logLabel,
|
||||
concurrency = SYNC_DELETE_CONCURRENCY,
|
||||
} = options;
|
||||
|
||||
let accessToken = await getAccessToken();
|
||||
const refreshAccessToken = async () => {
|
||||
accessToken = await getAccessToken();
|
||||
return accessToken;
|
||||
};
|
||||
let deleted = 0;
|
||||
let failed = 0;
|
||||
let completed = 0;
|
||||
let persistChain: Promise<unknown> = Promise.resolve();
|
||||
|
||||
await mapPool(entries, concurrency, async ([mapKey, eventId]) => {
|
||||
try {
|
||||
await deleteEvent(accessToken, eventId, refreshAccessToken);
|
||||
delete eventMap[mapKey];
|
||||
deleted += 1;
|
||||
} catch (err) {
|
||||
verboseLog(`[BetterSEQTA+] ${logLabel} event delete failed:`, err);
|
||||
failed += 1;
|
||||
}
|
||||
|
||||
completed += 1;
|
||||
reportSyncProgress(onProgress, {
|
||||
phase: "deleting",
|
||||
current: progressOffset + completed,
|
||||
total: progressTotal,
|
||||
message: `Removing old events (${completed}/${entries.length})…`,
|
||||
});
|
||||
|
||||
if (persistProgress && completed % EVENT_MAP_PERSIST_EVERY === 0) {
|
||||
persistChain = persistChain.then(() => writeState({ eventMap }));
|
||||
await persistChain;
|
||||
}
|
||||
});
|
||||
|
||||
if (persistProgress) {
|
||||
await persistChain;
|
||||
}
|
||||
|
||||
return { deleted, failed };
|
||||
}
|
||||
|
||||
export function buildLessonSyncResult(
|
||||
created: number,
|
||||
updated: number,
|
||||
deleted: number,
|
||||
skipped: number,
|
||||
failed: number,
|
||||
lastSyncAt: number,
|
||||
): GoogleCalendarSyncResult {
|
||||
@@ -114,7 +317,7 @@ export function buildLessonSyncResult(
|
||||
created,
|
||||
updated,
|
||||
deleted,
|
||||
skipped: 0,
|
||||
skipped,
|
||||
failed,
|
||||
lastSyncAt,
|
||||
error:
|
||||
@@ -124,24 +327,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;
|
||||
@@ -165,11 +350,18 @@ type UpsertLessonEventsParams<TEvent extends MappedLessonEvent> = {
|
||||
}) => Promise<unknown>;
|
||||
onProgress?: GoogleCalendarSyncOptions["onProgress"];
|
||||
logLabel: string;
|
||||
concurrency?: number;
|
||||
};
|
||||
|
||||
export async function upsertLessonEvents<TEvent extends MappedLessonEvent>(
|
||||
params: UpsertLessonEventsParams<TEvent>,
|
||||
): Promise<{ created: number; updated: number; failed: number; accessToken: string }> {
|
||||
): Promise<{
|
||||
created: number;
|
||||
updated: number;
|
||||
skipped: number;
|
||||
failed: number;
|
||||
accessToken: string;
|
||||
}> {
|
||||
const {
|
||||
events,
|
||||
eventMap,
|
||||
@@ -184,53 +376,67 @@ export async function upsertLessonEvents<TEvent extends MappedLessonEvent>(
|
||||
writeState,
|
||||
onProgress,
|
||||
logLabel,
|
||||
concurrency = SYNC_CONCURRENCY,
|
||||
} = params;
|
||||
|
||||
let accessToken = await getAccessToken();
|
||||
const refreshAccessToken = async () => {
|
||||
accessToken = await getAccessToken();
|
||||
return accessToken;
|
||||
};
|
||||
let created = 0;
|
||||
let updated = 0;
|
||||
let skipped = 0;
|
||||
let failed = initialFailed;
|
||||
let completed = 0;
|
||||
let persistChain: Promise<unknown> = Promise.resolve();
|
||||
|
||||
for (let i = 0; i < events.length; i++) {
|
||||
const event = events[i];
|
||||
const persistState = () => {
|
||||
persistChain = persistChain.then(() =>
|
||||
writeState({ eventMap, lastSyncAt, lastSyncOrigin: origin }),
|
||||
);
|
||||
return persistChain;
|
||||
};
|
||||
|
||||
await mapPool(events, concurrency, async (event) => {
|
||||
const key = mapKey(origin, event.seqtaKey);
|
||||
const existingId = getStoredEventId(eventMap[key]);
|
||||
const progressCurrent = staleEntryCount + i + 1;
|
||||
const progressMessage = `Syncing events (${i + 1}/${events.length})…`;
|
||||
const desiredFingerprint = eventFingerprint(event);
|
||||
|
||||
try {
|
||||
const remoteId = await upsert(accessToken, existingId, event, async () => {
|
||||
accessToken = await getAccessToken();
|
||||
return accessToken;
|
||||
});
|
||||
if (existingId) updated += 1;
|
||||
else created += 1;
|
||||
eventMap[key] = {
|
||||
id: remoteId,
|
||||
date: lessonDateForEvent(event.startDateTime, event.seqtaKey),
|
||||
};
|
||||
|
||||
reportSyncProgress(onProgress, {
|
||||
phase: "upserting",
|
||||
current: progressCurrent,
|
||||
total: totalSteps,
|
||||
message: progressMessage,
|
||||
});
|
||||
|
||||
if ((i + 1) % EVENT_MAP_PERSIST_EVERY === 0 || i === events.length - 1) {
|
||||
await writeState({ eventMap, lastSyncAt, lastSyncOrigin: origin });
|
||||
if (existingId && getStoredFingerprint(eventMap[key]) === desiredFingerprint) {
|
||||
skipped += 1;
|
||||
} else {
|
||||
const remoteId = await upsert(accessToken, existingId, event, refreshAccessToken);
|
||||
if (existingId) updated += 1;
|
||||
else created += 1;
|
||||
eventMap[key] = {
|
||||
id: remoteId,
|
||||
date: lessonDateForEvent(event.startDateTime, event.seqtaKey),
|
||||
fingerprint: desiredFingerprint,
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
verboseLog(`[BetterSEQTA+] ${logLabel} event sync failed:`, err);
|
||||
failed += 1;
|
||||
reportSyncProgress(onProgress, {
|
||||
phase: "upserting",
|
||||
current: progressCurrent,
|
||||
total: totalSteps,
|
||||
message: progressMessage,
|
||||
});
|
||||
}
|
||||
|
||||
completed += 1;
|
||||
reportSyncProgress(onProgress, {
|
||||
phase: "upserting",
|
||||
current: staleEntryCount + completed,
|
||||
total: totalSteps,
|
||||
message: `Syncing events (${completed}/${events.length})…`,
|
||||
});
|
||||
|
||||
if (completed % EVENT_MAP_PERSIST_EVERY === 0) {
|
||||
await persistState();
|
||||
}
|
||||
});
|
||||
|
||||
if (events.length > 0) {
|
||||
await persistState();
|
||||
}
|
||||
|
||||
return { created, updated, failed, accessToken };
|
||||
return { created, updated, skipped, failed, accessToken };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
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;
|
||||
/** Google calendar id for the app-owned "BetterSEQTA+ Timetable" secondary calendar. */
|
||||
calendarId?: string;
|
||||
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,380 @@
|
||||
import { BSPLUS_GOOGLE_CALENDAR_EVENT_PROP, GOOGLE_CALENDAR_API } from "@/config/googleCalendar";
|
||||
import {
|
||||
BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY,
|
||||
OUTLOOK_GRAPH_API,
|
||||
} from "@/config/outlookCalendar";
|
||||
import {
|
||||
eventFingerprint,
|
||||
parseOutlookSeqtaKey,
|
||||
} from "@/seqta/utils/calendarSync/eventFingerprint";
|
||||
import type { SyncDateRange } from "@/seqta/utils/googleCalendar/syncDateRange";
|
||||
|
||||
export type RemoteSyncedEvent = {
|
||||
seqtaKey: string;
|
||||
id: string;
|
||||
fingerprint: string;
|
||||
date: string;
|
||||
};
|
||||
|
||||
export type ListSyncedEventsOptions = {
|
||||
/** Include category/calendar events that are missing a seqta key (legacy orphans). */
|
||||
includeUnkeyed?: boolean;
|
||||
};
|
||||
|
||||
const MAX_RETRIES = 4;
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
function isRetryableStatus(status: number): boolean {
|
||||
return status === 429 || status === 500 || status === 502 || status === 503 || status === 403;
|
||||
}
|
||||
|
||||
async function authorizedFetch(
|
||||
accessToken: string,
|
||||
url: string,
|
||||
init: RequestInit,
|
||||
refreshAccessToken?: () => Promise<string>,
|
||||
): Promise<Response> {
|
||||
let token = accessToken;
|
||||
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
|
||||
const res = await fetch(url, {
|
||||
...init,
|
||||
headers: { Authorization: `Bearer ${token}`, ...init.headers },
|
||||
});
|
||||
if (res.status === 401 && refreshAccessToken) {
|
||||
token = await refreshAccessToken();
|
||||
continue;
|
||||
}
|
||||
if (isRetryableStatus(res.status) && attempt < MAX_RETRIES - 1) {
|
||||
await sleep(250 * 2 ** attempt + Math.floor(Math.random() * 100));
|
||||
continue;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
return fetch(url, {
|
||||
...init,
|
||||
headers: { Authorization: `Bearer ${token}`, ...init.headers },
|
||||
});
|
||||
}
|
||||
|
||||
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})`);
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
function toRfc3339Start(date: string): string {
|
||||
return `${date}T00:00:00Z`;
|
||||
}
|
||||
|
||||
function toRfc3339EndExclusive(date: string): string {
|
||||
const d = new Date(`${date}T12:00:00Z`);
|
||||
d.setUTCDate(d.getUTCDate() + 1);
|
||||
const y = d.getUTCFullYear();
|
||||
const m = String(d.getUTCMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getUTCDate()).padStart(2, "0");
|
||||
return `${y}-${m}-${day}T00:00:00Z`;
|
||||
}
|
||||
|
||||
function dateFromDateTime(value: string | undefined): string {
|
||||
if (!value) return "";
|
||||
return value.slice(0, 10);
|
||||
}
|
||||
|
||||
type GoogleListItem = {
|
||||
id?: string;
|
||||
summary?: string;
|
||||
location?: string;
|
||||
description?: string;
|
||||
start?: { dateTime?: string; date?: string; timeZone?: string };
|
||||
end?: { dateTime?: string; date?: string; timeZone?: string };
|
||||
extendedProperties?: { private?: Record<string, string> };
|
||||
};
|
||||
|
||||
function googleItemToRemote(
|
||||
item: GoogleListItem,
|
||||
includeUnkeyed: boolean,
|
||||
): RemoteSyncedEvent | null {
|
||||
if (!item.id) return null;
|
||||
const seqtaKey = item.extendedProperties?.private?.[BSPLUS_GOOGLE_CALENDAR_EVENT_PROP] ?? "";
|
||||
if (!seqtaKey && !includeUnkeyed) return null;
|
||||
const startDateTime = item.start?.dateTime ?? (item.start?.date ? `${item.start.date}T00:00:00` : "");
|
||||
const endDateTime = item.end?.dateTime ?? (item.end?.date ? `${item.end.date}T00:00:00` : "");
|
||||
const timeZone = item.start?.timeZone ?? item.end?.timeZone ?? "UTC";
|
||||
return {
|
||||
seqtaKey,
|
||||
id: item.id,
|
||||
date: dateFromDateTime(startDateTime) || item.start?.date || "",
|
||||
fingerprint: eventFingerprint({
|
||||
summary: item.summary ?? "",
|
||||
location: item.location,
|
||||
description: item.description,
|
||||
startDateTime,
|
||||
endDateTime,
|
||||
timeZone,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function listGoogleSyncedEvents(
|
||||
accessToken: string,
|
||||
calendarId: string,
|
||||
range: SyncDateRange,
|
||||
refreshAccessToken?: () => Promise<string>,
|
||||
options: ListSyncedEventsOptions = {},
|
||||
): Promise<RemoteSyncedEvent[]> {
|
||||
const includeUnkeyed = options.includeUnkeyed === true;
|
||||
const encodedCalendar = encodeURIComponent(calendarId);
|
||||
const out: RemoteSyncedEvent[] = [];
|
||||
let pageToken: string | undefined;
|
||||
|
||||
do {
|
||||
const params = new URLSearchParams({
|
||||
singleEvents: "true",
|
||||
orderBy: "startTime",
|
||||
maxResults: "2500",
|
||||
timeMin: toRfc3339Start(range.from),
|
||||
timeMax: toRfc3339EndExclusive(range.until),
|
||||
fields:
|
||||
"nextPageToken,items(id,summary,location,description,start,end,extendedProperties)",
|
||||
});
|
||||
if (pageToken) params.set("pageToken", pageToken);
|
||||
|
||||
const res = await authorizedFetch(
|
||||
accessToken,
|
||||
`${GOOGLE_CALENDAR_API}/calendars/${encodedCalendar}/events?${params}`,
|
||||
{ method: "GET" },
|
||||
refreshAccessToken,
|
||||
);
|
||||
const json = (await res.json().catch(() => ({}))) as {
|
||||
items?: GoogleListItem[];
|
||||
nextPageToken?: string;
|
||||
error?: { message?: string };
|
||||
};
|
||||
if (!res.ok) {
|
||||
throw new Error(json?.error?.message ?? `Google Calendar list failed (${res.status})`);
|
||||
}
|
||||
|
||||
for (const item of json.items ?? []) {
|
||||
const mapped = googleItemToRemote(item, includeUnkeyed);
|
||||
if (mapped) out.push(mapped);
|
||||
}
|
||||
pageToken = json.nextPageToken;
|
||||
} while (pageToken);
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
type OutlookListItem = {
|
||||
id?: string;
|
||||
subject?: string;
|
||||
body?: { content?: string; contentType?: string };
|
||||
location?: { displayName?: string };
|
||||
start?: { dateTime?: string; timeZone?: string };
|
||||
end?: { dateTime?: string; timeZone?: string };
|
||||
categories?: string[];
|
||||
};
|
||||
|
||||
function outlookItemToRemote(
|
||||
item: OutlookListItem,
|
||||
includeUnkeyed: boolean,
|
||||
): RemoteSyncedEvent | null {
|
||||
if (!item.id) return null;
|
||||
const categories = item.categories ?? [];
|
||||
if (!categories.includes(BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY)) return null;
|
||||
const bodyContent = item.body?.content ?? "";
|
||||
const seqtaKey = parseOutlookSeqtaKey(bodyContent) ?? "";
|
||||
if (!seqtaKey && !includeUnkeyed) return null;
|
||||
|
||||
const startDateTime = (item.start?.dateTime ?? "").replace(/\.\d+$/, "");
|
||||
const endDateTime = (item.end?.dateTime ?? "").replace(/\.\d+$/, "");
|
||||
const timeZone = item.start?.timeZone ?? item.end?.timeZone ?? "UTC";
|
||||
|
||||
return {
|
||||
seqtaKey,
|
||||
id: item.id,
|
||||
date: dateFromDateTime(startDateTime),
|
||||
fingerprint: eventFingerprint({
|
||||
summary: item.subject ?? "",
|
||||
location: item.location?.displayName,
|
||||
description: outlookDescriptionForFingerprint(bodyContent),
|
||||
startDateTime,
|
||||
endDateTime,
|
||||
timeZone,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Strip Outlook Key line so fingerprint matches local mapped event description. */
|
||||
function outlookDescriptionForFingerprint(bodyContent: string): string {
|
||||
return bodyContent
|
||||
.split("\n")
|
||||
.filter((line) => !/^Key:\s*/.test(line))
|
||||
.join("\n")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export async function listOutlookSyncedEvents(
|
||||
accessToken: string,
|
||||
range: SyncDateRange,
|
||||
refreshAccessToken?: () => Promise<string>,
|
||||
options: ListSyncedEventsOptions = {},
|
||||
): Promise<RemoteSyncedEvent[]> {
|
||||
const includeUnkeyed = options.includeUnkeyed === true;
|
||||
const out: RemoteSyncedEvent[] = [];
|
||||
const params = new URLSearchParams({
|
||||
startDateTime: toRfc3339Start(range.from),
|
||||
endDateTime: toRfc3339EndExclusive(range.until),
|
||||
$top: "100",
|
||||
$select: "id,subject,body,location,start,end,categories",
|
||||
});
|
||||
|
||||
let nextUrl: string | undefined =
|
||||
`${OUTLOOK_GRAPH_API}/me/calendarView?${params.toString()}`;
|
||||
|
||||
while (nextUrl) {
|
||||
const res = await authorizedFetch(
|
||||
accessToken,
|
||||
nextUrl,
|
||||
{
|
||||
method: "GET",
|
||||
headers: { Prefer: 'outlook.body-content-type="text"' },
|
||||
},
|
||||
refreshAccessToken,
|
||||
);
|
||||
const json = (await res.json().catch(() => ({}))) as {
|
||||
value?: OutlookListItem[];
|
||||
"@odata.nextLink"?: string;
|
||||
error?: { message?: string };
|
||||
};
|
||||
if (!res.ok) {
|
||||
throw new Error(json?.error?.message ?? `Outlook Calendar list failed (${res.status})`);
|
||||
}
|
||||
|
||||
for (const item of json.value ?? []) {
|
||||
const mapped = outlookItemToRemote(item, includeUnkeyed);
|
||||
if (mapped) out.push(mapped);
|
||||
}
|
||||
nextUrl = json["@odata.nextLink"];
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
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,
|
||||
clearOriginEventMapEntries,
|
||||
collectOriginDeleteEntries,
|
||||
deleteTrackedLessonEvents,
|
||||
emptyLessonsSyncResult,
|
||||
entriesToPrune,
|
||||
mergeRemoteEventsIntoMap,
|
||||
notConfiguredSyncResult,
|
||||
notConnectedSyncResult,
|
||||
reconcileRangeForMode,
|
||||
reportSyncProgress,
|
||||
upsertLessonEvents,
|
||||
} from "@/seqta/utils/calendarSync/lessonSyncShared";
|
||||
import {
|
||||
deleteGoogleCalendarEvent,
|
||||
deleteOutlookCalendarEvent,
|
||||
listGoogleSyncedEvents,
|
||||
listOutlookSyncedEvents,
|
||||
upsertGoogleCalendarEvent,
|
||||
upsertOutlookCalendarEvent,
|
||||
type ListSyncedEventsOptions,
|
||||
type RemoteSyncedEvent,
|
||||
} from "@/seqta/utils/calendarSync/remoteEvents";
|
||||
import {
|
||||
googleApiEventBody,
|
||||
mapLessonsToGoogleEvents,
|
||||
outlookGraphEventBody,
|
||||
} from "@/seqta/utils/googleCalendar/eventMapper";
|
||||
import { ensureGoogleAppCalendar } from "@/seqta/utils/googleCalendar/calendarProvisioning";
|
||||
import {
|
||||
readGoogleCalendarState,
|
||||
writeGoogleCalendarState,
|
||||
} from "@/seqta/utils/googleCalendar/storage";
|
||||
import {
|
||||
syncWindowRange,
|
||||
trailingWeekRange,
|
||||
wideCleanupRange,
|
||||
type SyncDateRange,
|
||||
} from "@/seqta/utils/googleCalendar/syncDateRange";
|
||||
import type {
|
||||
GoogleCalendarDeleteResult,
|
||||
GoogleCalendarEventInput,
|
||||
GoogleCalendarSyncOptions,
|
||||
GoogleCalendarSyncRequest,
|
||||
GoogleCalendarSyncResult,
|
||||
} from "@/seqta/utils/googleCalendar/types";
|
||||
import {
|
||||
readOutlookCalendarState,
|
||||
writeOutlookCalendarState,
|
||||
} from "@/seqta/utils/outlookCalendar/storage";
|
||||
import { verboseLog } from "@/utils/verboseLog";
|
||||
|
||||
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>;
|
||||
listSyncedEvents: (
|
||||
accessToken: string,
|
||||
range: SyncDateRange,
|
||||
refreshAccessToken: () => Promise<string>,
|
||||
options?: ListSyncedEventsOptions,
|
||||
) => Promise<RemoteSyncedEvent[]>;
|
||||
toApiBody: (event: GoogleCalendarEventInput) => Record<string, unknown>;
|
||||
};
|
||||
|
||||
async function getOrProvisionGoogleCalendarId(accessToken: string): Promise<string> {
|
||||
const state = await readGoogleCalendarState();
|
||||
if (state.calendarId) return state.calendarId;
|
||||
|
||||
const calendarId = await ensureGoogleAppCalendar(accessToken);
|
||||
await writeGoogleCalendarState({ calendarId });
|
||||
return calendarId;
|
||||
}
|
||||
|
||||
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: async (accessToken, eventId, refreshAccessToken) =>
|
||||
deleteGoogleCalendarEvent(
|
||||
accessToken,
|
||||
await getOrProvisionGoogleCalendarId(accessToken),
|
||||
eventId,
|
||||
refreshAccessToken,
|
||||
),
|
||||
upsertEvent: async (accessToken, existingId, body, refreshAccessToken) =>
|
||||
upsertGoogleCalendarEvent(
|
||||
accessToken,
|
||||
await getOrProvisionGoogleCalendarId(accessToken),
|
||||
existingId,
|
||||
body,
|
||||
refreshAccessToken,
|
||||
),
|
||||
listSyncedEvents: async (accessToken, range, refreshAccessToken, options) =>
|
||||
listGoogleSyncedEvents(
|
||||
accessToken,
|
||||
await getOrProvisionGoogleCalendarId(accessToken),
|
||||
range,
|
||||
refreshAccessToken,
|
||||
options,
|
||||
),
|
||||
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),
|
||||
listSyncedEvents: (accessToken, range, refreshAccessToken, options) =>
|
||||
listOutlookSyncedEvents(accessToken, range, refreshAccessToken, options),
|
||||
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);
|
||||
|
||||
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 ?? {}) };
|
||||
let accessToken = await getAccessToken();
|
||||
const refreshAccessToken = async () => {
|
||||
accessToken = await getAccessToken();
|
||||
return accessToken;
|
||||
};
|
||||
|
||||
const reconcileRange = reconcileRangeForMode(mode, weeksAhead, {
|
||||
syncWindowRange,
|
||||
trailingWeekRange,
|
||||
});
|
||||
|
||||
try {
|
||||
const remoteEvents = await provider.listSyncedEvents(
|
||||
accessToken,
|
||||
reconcileRange,
|
||||
refreshAccessToken,
|
||||
);
|
||||
mergeRemoteEventsIntoMap(eventMap, request.origin, remoteEvents, eventMapKey);
|
||||
} catch (err) {
|
||||
verboseLog(`[BetterSEQTA+] ${provider.label} remote event list failed:`, err);
|
||||
}
|
||||
|
||||
const currentMapKeys = new Set(events.map((event) => eventMapKey(request.origin, event.seqtaKey)));
|
||||
const staleEntries = entriesToPrune(eventMap, request.origin, mode, weeksAhead, currentMapKeys);
|
||||
const totalSteps = Math.max(staleEntries.length + events.length, 1);
|
||||
const lastSyncAt = Date.now();
|
||||
|
||||
const staleResult = await deleteTrackedLessonEvents(
|
||||
staleEntries,
|
||||
eventMap,
|
||||
getAccessToken,
|
||||
provider.deleteEvent,
|
||||
provider.writeState,
|
||||
{
|
||||
onProgress: options.onProgress,
|
||||
progressTotal: totalSteps,
|
||||
logLabel: provider.label,
|
||||
},
|
||||
);
|
||||
|
||||
if (events.length === 0 && mode === "full") {
|
||||
await provider.writeState({
|
||||
eventMap,
|
||||
lastSyncAt,
|
||||
lastSyncOrigin: request.origin,
|
||||
});
|
||||
reportSyncProgress(options.onProgress, {
|
||||
phase: "done",
|
||||
current: totalSteps,
|
||||
total: totalSteps,
|
||||
message: "Sync complete",
|
||||
});
|
||||
if (staleResult.deleted > 0) {
|
||||
return buildLessonSyncResult(0, 0, staleResult.deleted, 0, staleResult.failed, lastSyncAt);
|
||||
}
|
||||
return emptyLessonsSyncResult();
|
||||
}
|
||||
|
||||
const upsertResult = await upsertLessonEvents({
|
||||
events,
|
||||
eventMap,
|
||||
origin: request.origin,
|
||||
staleEntryCount: staleEntries.length,
|
||||
totalSteps,
|
||||
lastSyncAt,
|
||||
initialFailed: staleResult.failed,
|
||||
getAccessToken,
|
||||
mapKey: eventMapKey,
|
||||
upsert: (token, existingId, event, refresh) =>
|
||||
provider.upsertEvent(token, existingId, provider.toApiBody(event), refresh),
|
||||
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.skipped,
|
||||
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 };
|
||||
}
|
||||
|
||||
reportSyncProgress(options.onProgress, {
|
||||
phase: "preparing",
|
||||
current: 0,
|
||||
total: 1,
|
||||
message: "Preparing removal…",
|
||||
});
|
||||
|
||||
const eventMap = { ...(state.eventMap ?? {}) };
|
||||
let accessToken = await getAccessToken();
|
||||
const refreshAccessToken = async () => {
|
||||
accessToken = await getAccessToken();
|
||||
return accessToken;
|
||||
};
|
||||
|
||||
let remoteEvents: RemoteSyncedEvent[] = [];
|
||||
try {
|
||||
remoteEvents = await provider.listSyncedEvents(
|
||||
accessToken,
|
||||
wideCleanupRange(),
|
||||
refreshAccessToken,
|
||||
{ includeUnkeyed: true },
|
||||
);
|
||||
mergeRemoteEventsIntoMap(eventMap, origin, remoteEvents, eventMapKey);
|
||||
} catch (err) {
|
||||
verboseLog(`[BetterSEQTA+] ${provider.label} cleanup list failed:`, err);
|
||||
}
|
||||
|
||||
const entries = collectOriginDeleteEntries(eventMap, origin, remoteEvents, eventMapKey);
|
||||
if (entries.length === 0) {
|
||||
clearOriginEventMapEntries(eventMap, origin);
|
||||
await provider.writeState({ eventMap });
|
||||
return { success: true, configured: true, connected: true, deleted: 0, failed: 0 };
|
||||
}
|
||||
|
||||
const { deleted, failed } = await deleteTrackedLessonEvents(
|
||||
entries,
|
||||
eventMap,
|
||||
getAccessToken,
|
||||
provider.deleteEvent,
|
||||
provider.writeState,
|
||||
{
|
||||
persistProgress: true,
|
||||
onProgress: options.onProgress,
|
||||
progressTotal: entries.length,
|
||||
logLabel: provider.label,
|
||||
},
|
||||
);
|
||||
|
||||
// Only wipe remaining origin keys when every delete succeeded — keep failed IDs for retry.
|
||||
if (failed === 0) {
|
||||
clearOriginEventMapEntries(eventMap, origin);
|
||||
}
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
|
||||
jest.mock("@/config/googleCalendar", () => ({
|
||||
BSPLUS_GOOGLE_CALENDAR_DESCRIPTION: "desc",
|
||||
BSPLUS_GOOGLE_CALENDAR_NAME: "BetterSEQTA+ Timetable",
|
||||
GOOGLE_CALENDAR_API: "https://www.googleapis.com/calendar/v3",
|
||||
}));
|
||||
|
||||
import { ensureGoogleAppCalendar } from "./calendarProvisioning";
|
||||
|
||||
const fetchMock = jest.fn<typeof fetch>();
|
||||
global.fetch = fetchMock as typeof fetch;
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
json: async () => body,
|
||||
} as Response;
|
||||
}
|
||||
|
||||
describe("ensureGoogleAppCalendar", () => {
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset();
|
||||
});
|
||||
|
||||
it("reuses a stored calendar id when it still exists", async () => {
|
||||
fetchMock.mockResolvedValueOnce(jsonResponse({ id: "stored-id", summary: "BetterSEQTA+ Timetable" }));
|
||||
|
||||
await expect(ensureGoogleAppCalendar("token", "stored-id")).resolves.toBe("stored-id");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("finds an existing app calendar by name when stored id is missing", async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
jsonResponse({
|
||||
items: [{ id: "found-id", summary: "BetterSEQTA+ Timetable" }],
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureGoogleAppCalendar("token")).resolves.toBe("found-id");
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://www.googleapis.com/calendar/v3/users/me/calendarList",
|
||||
expect.objectContaining({ headers: expect.objectContaining({ Authorization: "Bearer token" }) }),
|
||||
);
|
||||
});
|
||||
|
||||
it("creates a calendar when none exists", async () => {
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(jsonResponse({ items: [] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ id: "new-id" }));
|
||||
|
||||
await expect(ensureGoogleAppCalendar("token")).resolves.toBe("new-id");
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://www.googleapis.com/calendar/v3/calendars",
|
||||
expect.objectContaining({ method: "POST" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import {
|
||||
BSPLUS_GOOGLE_CALENDAR_DESCRIPTION,
|
||||
BSPLUS_GOOGLE_CALENDAR_NAME,
|
||||
GOOGLE_CALENDAR_API,
|
||||
} from "@/config/googleCalendar";
|
||||
|
||||
type GoogleCalendarResource = { id?: string; summary?: string };
|
||||
type GoogleCalendarListResponse = { items?: GoogleCalendarResource[] };
|
||||
type GoogleApiError = { error?: { message?: string } };
|
||||
|
||||
async function googleCalendarFetch<T>(
|
||||
accessToken: string,
|
||||
path: string,
|
||||
init?: RequestInit,
|
||||
): Promise<{ ok: boolean; status: number; data: T }> {
|
||||
const res = await fetch(`${GOOGLE_CALENDAR_API}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
...(init?.body ? { "Content-Type": "application/json" } : {}),
|
||||
...init?.headers,
|
||||
},
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as T & GoogleApiError;
|
||||
return { ok: res.ok, status: res.status, data };
|
||||
}
|
||||
|
||||
async function calendarExists(accessToken: string, calendarId: string): Promise<boolean> {
|
||||
const { ok, status } = await googleCalendarFetch<GoogleCalendarResource>(
|
||||
accessToken,
|
||||
`/calendars/${encodeURIComponent(calendarId)}`,
|
||||
);
|
||||
return ok || status === 404 ? ok : false;
|
||||
}
|
||||
|
||||
async function findExistingAppCalendar(accessToken: string): Promise<string | undefined> {
|
||||
const { ok, data } = await googleCalendarFetch<GoogleCalendarListResponse>(
|
||||
accessToken,
|
||||
"/users/me/calendarList",
|
||||
);
|
||||
if (!ok) return undefined;
|
||||
|
||||
const match = (data.items ?? []).find((item) => item.summary === BSPLUS_GOOGLE_CALENDAR_NAME);
|
||||
return match?.id;
|
||||
}
|
||||
|
||||
async function createAppCalendar(accessToken: string): Promise<string> {
|
||||
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
||||
const { ok, status, data } = await googleCalendarFetch<GoogleCalendarResource>(
|
||||
accessToken,
|
||||
"/calendars",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
summary: BSPLUS_GOOGLE_CALENDAR_NAME,
|
||||
description: BSPLUS_GOOGLE_CALENDAR_DESCRIPTION,
|
||||
timeZone,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!ok || !data.id) {
|
||||
throw new Error(
|
||||
data.error?.message ?? `Could not create BetterSEQTA+ calendar (${status}).`,
|
||||
);
|
||||
}
|
||||
return data.id;
|
||||
}
|
||||
|
||||
/** Resolves the app-owned calendar id, reusing stored or existing calendars when possible. */
|
||||
export async function ensureGoogleAppCalendar(
|
||||
accessToken: string,
|
||||
storedCalendarId?: string,
|
||||
): Promise<string> {
|
||||
if (storedCalendarId && (await calendarExists(accessToken, storedCalendarId))) {
|
||||
return storedCalendarId;
|
||||
}
|
||||
|
||||
const existing = await findExistingAppCalendar(accessToken);
|
||||
if (existing) return existing;
|
||||
|
||||
return createAppCalendar(accessToken);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "@jest/globals";
|
||||
import {
|
||||
lessonToGoogleEvent,
|
||||
mapLessonsToGoogleEvents,
|
||||
outlookGraphEventBody,
|
||||
seqtaLessonKey,
|
||||
shouldSyncLesson,
|
||||
} from "./eventMapper";
|
||||
@@ -62,3 +63,14 @@ describe("mapLessonsToGoogleEvents", () => {
|
||||
expect(events).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("outlookGraphEventBody", () => {
|
||||
it("embeds Key: seqtaKey in the body for remote reconcile", () => {
|
||||
const event = lessonToGoogleEvent(ORIGIN, baseLesson, "Australia/Perth");
|
||||
expect(event).not.toBeNull();
|
||||
const body = outlookGraphEventBody(event!);
|
||||
const content = (body.body as { content: string }).content;
|
||||
expect(content).toContain(`Key: ${ORIGIN}:cal:12345`);
|
||||
expect(content).toContain("Synced by BetterSEQTA+");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { BSPLUS_GOOGLE_CALENDAR_EVENT_PROP } from "@/config/googleCalendar";
|
||||
import { BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY } from "@/config/outlookCalendar";
|
||||
import { outlookDescriptionWithKey } from "@/seqta/utils/calendarSync/eventFingerprint";
|
||||
import type { GoogleCalendarEventInput, SeqtaTimetableLesson } from "./types";
|
||||
|
||||
const SKIP_TYPES = new Set(["note", "holiday", "assembly-note"]);
|
||||
@@ -93,3 +95,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: outlookDescriptionWithKey(event.description, event.seqtaKey),
|
||||
},
|
||||
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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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,25 +26,27 @@ 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 {
|
||||
return date >= range.from && date <= range.until;
|
||||
}
|
||||
|
||||
/** Wide range used when removing all synced events (covers past + future terms). */
|
||||
export function wideCleanupRange(years = 3): SyncDateRange {
|
||||
const now = new Date();
|
||||
const from = new Date(now);
|
||||
from.setFullYear(from.getFullYear() - years);
|
||||
const until = new Date(now);
|
||||
until.setFullYear(until.getFullYear() + years);
|
||||
return { from: toISODate(from), until: toISODate(until) };
|
||||
}
|
||||
|
||||
@@ -3,39 +3,56 @@ import type { SeqtaTimetableLesson } from "./types";
|
||||
|
||||
jest.mock("@/config/googleCalendar", () => ({
|
||||
isGoogleCalendarConfigured: jest.fn(() => true),
|
||||
BSPLUS_GOOGLE_CALENDAR_EVENT_PROP: "bsplusSeqtaKey",
|
||||
GOOGLE_CALENDAR_API: "https://www.googleapis.com/calendar/v3",
|
||||
}));
|
||||
|
||||
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(),
|
||||
listGoogleSyncedEvents: jest.fn(async () => []),
|
||||
}));
|
||||
|
||||
import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/storage";
|
||||
import {
|
||||
deleteGoogleCalendarEvent,
|
||||
listGoogleSyncedEvents,
|
||||
upsertGoogleCalendarEvent,
|
||||
} from "@/seqta/utils/googleCalendar/upsertEvent";
|
||||
import { deleteSyncedEventsFromGoogleCalendar, syncLessonsToGoogleCalendar } from "./syncEngine";
|
||||
} from "@/seqta/utils/calendarSync/remoteEvents";
|
||||
import {
|
||||
deleteSyncedEventsFromGoogleCalendar,
|
||||
syncLessonsToGoogleCalendar,
|
||||
} from "@/seqta/utils/calendarSync/syncEngine";
|
||||
import { eventFingerprint } from "@/seqta/utils/calendarSync/eventFingerprint";
|
||||
import { lessonToGoogleEvent } from "@/seqta/utils/googleCalendar/eventMapper";
|
||||
|
||||
import { syncWindowRange } from "@/seqta/utils/googleCalendar/syncDateRange";
|
||||
|
||||
const ORIGIN = "https://school.seqta.com.au";
|
||||
const getAccessToken = async () => "test-token";
|
||||
const syncDate = syncWindowRange(12).from;
|
||||
|
||||
const baseLesson: SeqtaTimetableLesson = {
|
||||
date: "2026-06-27",
|
||||
date: syncDate,
|
||||
from: "09:00:00",
|
||||
until: "10:00:00",
|
||||
description: "10 Mathematics",
|
||||
@@ -51,13 +68,15 @@ describe("syncLessonsToGoogleCalendar", () => {
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||
refreshToken: "refresh",
|
||||
calendarId: "app-calendar-id",
|
||||
eventMap: {
|
||||
[`${ORIGIN}::${ORIGIN}:cal:12345`]: { id: "google-existing", date: "2026-06-27" },
|
||||
[`${ORIGIN}::${ORIGIN}:cal:12345`]: { id: "google-existing", date: syncDate },
|
||||
[`${ORIGIN}::${ORIGIN}:cal:99999`]: { id: "google-stale", date: "2020-01-06" },
|
||||
},
|
||||
});
|
||||
jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-existing");
|
||||
jest.mocked(deleteGoogleCalendarEvent).mockResolvedValue(undefined);
|
||||
jest.mocked(listGoogleSyncedEvents).mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("updates existing events and removes stale tracked events on full sync", async () => {
|
||||
@@ -66,6 +85,7 @@ describe("syncLessonsToGoogleCalendar", () => {
|
||||
getAccessToken,
|
||||
);
|
||||
|
||||
expect(listGoogleSyncedEvents).toHaveBeenCalled();
|
||||
expect(deleteGoogleCalendarEvent).toHaveBeenCalled();
|
||||
expect(upsertGoogleCalendarEvent).toHaveBeenCalledTimes(1);
|
||||
expect(result).toMatchObject({
|
||||
@@ -79,6 +99,7 @@ describe("syncLessonsToGoogleCalendar", () => {
|
||||
it("creates events that are not yet tracked", async () => {
|
||||
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||
refreshToken: "refresh",
|
||||
calendarId: "app-calendar-id",
|
||||
eventMap: {},
|
||||
});
|
||||
jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-new");
|
||||
@@ -97,6 +118,64 @@ describe("syncLessonsToGoogleCalendar", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("recovers remote IDs when the local map is empty and skips unchanged", async () => {
|
||||
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
||||
const mapped = lessonToGoogleEvent(ORIGIN, baseLesson, timeZone);
|
||||
expect(mapped).not.toBeNull();
|
||||
const fp = eventFingerprint(mapped!);
|
||||
|
||||
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||
refreshToken: "refresh",
|
||||
calendarId: "app-calendar-id",
|
||||
eventMap: {},
|
||||
});
|
||||
jest.mocked(listGoogleSyncedEvents).mockResolvedValue([
|
||||
{
|
||||
seqtaKey: `${ORIGIN}:cal:12345`,
|
||||
id: "recovered-id",
|
||||
date: syncDate,
|
||||
fingerprint: fp,
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await syncLessonsToGoogleCalendar(
|
||||
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
|
||||
getAccessToken,
|
||||
);
|
||||
|
||||
expect(upsertGoogleCalendarEvent).not.toHaveBeenCalled();
|
||||
expect(result).toMatchObject({
|
||||
success: true,
|
||||
created: 0,
|
||||
updated: 0,
|
||||
skipped: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("deletes cancelled lessons that remain inside the sync window", async () => {
|
||||
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||
refreshToken: "refresh",
|
||||
calendarId: "app-calendar-id",
|
||||
eventMap: {
|
||||
[`${ORIGIN}::${ORIGIN}:cal:12345`]: { id: "keep", date: syncDate },
|
||||
[`${ORIGIN}::${ORIGIN}:cal:cancelled`]: { id: "gone", date: syncDate },
|
||||
},
|
||||
});
|
||||
|
||||
const result = await syncLessonsToGoogleCalendar(
|
||||
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
|
||||
getAccessToken,
|
||||
);
|
||||
|
||||
expect(deleteGoogleCalendarEvent).toHaveBeenCalledWith(
|
||||
"test-token",
|
||||
"app-calendar-id",
|
||||
"gone",
|
||||
expect.any(Function),
|
||||
);
|
||||
expect(result.deleted).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("does not delete events during incremental sync", async () => {
|
||||
const result = await syncLessonsToGoogleCalendar(
|
||||
{ origin: ORIGIN, lessons: [baseLesson], mode: "incremental" },
|
||||
@@ -130,6 +209,7 @@ describe("deleteSyncedEventsFromGoogleCalendar", () => {
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||
refreshToken: "refresh",
|
||||
calendarId: "app-calendar-id",
|
||||
eventMap: {
|
||||
[`${ORIGIN}::${ORIGIN}:cal:12345`]: { id: "google-1", date: "2026-06-27" },
|
||||
[`${ORIGIN}::${ORIGIN}:cal:99999`]: { id: "google-2", date: "2026-06-28" },
|
||||
@@ -142,6 +222,7 @@ describe("deleteSyncedEventsFromGoogleCalendar", () => {
|
||||
it("deletes only events for the requested origin", async () => {
|
||||
const result = await deleteSyncedEventsFromGoogleCalendar(ORIGIN, getAccessToken);
|
||||
|
||||
expect(listGoogleSyncedEvents).toHaveBeenCalled();
|
||||
expect(deleteGoogleCalendarEvent).toHaveBeenCalledTimes(2);
|
||||
expect(result).toMatchObject({
|
||||
success: true,
|
||||
@@ -149,4 +230,31 @@ describe("deleteSyncedEventsFromGoogleCalendar", () => {
|
||||
failed: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("also deletes remote orphans found by list", async () => {
|
||||
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||
refreshToken: "refresh",
|
||||
calendarId: "app-calendar-id",
|
||||
eventMap: {},
|
||||
});
|
||||
jest.mocked(listGoogleSyncedEvents).mockResolvedValue([
|
||||
{
|
||||
seqtaKey: `${ORIGIN}:cal:1`,
|
||||
id: "remote-a",
|
||||
date: "2026-06-27",
|
||||
fingerprint: "fp",
|
||||
},
|
||||
{
|
||||
seqtaKey: "",
|
||||
id: "orphan-b",
|
||||
date: "2026-06-28",
|
||||
fingerprint: "fp",
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await deleteSyncedEventsFromGoogleCalendar(ORIGIN, getAccessToken);
|
||||
|
||||
expect(deleteGoogleCalendarEvent).toHaveBeenCalledTimes(2);
|
||||
expect(result).toMatchObject({ success: true, deleted: 2, failed: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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,76 +0,0 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import {
|
||||
fetchTimetableForSync,
|
||||
fetchTimetableLessons,
|
||||
trailingWeekRange,
|
||||
} from "@/seqta/utils/googleCalendar/fetchTimetable";
|
||||
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
|
||||
import { syncLessonsToGoogleCalendar } from "@/seqta/utils/googleCalendar/syncEngine";
|
||||
import type {
|
||||
GoogleCalendarSyncOptions,
|
||||
GoogleCalendarSyncProgress,
|
||||
GoogleCalendarSyncResult,
|
||||
} from "@/seqta/utils/googleCalendar/types";
|
||||
|
||||
export type GoogleCalendarRunMode = "full" | "incremental";
|
||||
|
||||
export interface RunGoogleCalendarSyncParams {
|
||||
mode?: GoogleCalendarRunMode;
|
||||
silent?: boolean;
|
||||
onProgress?: (progress: GoogleCalendarSyncProgress) => void;
|
||||
}
|
||||
|
||||
async function getAccessTokenFromBackground(): Promise<string> {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "googleCalendarGetAccessToken",
|
||||
})) as { success?: boolean; accessToken?: string; error?: string };
|
||||
if (!res?.success || !res.accessToken) {
|
||||
throw new Error(res?.error ?? "Could not get Google Calendar access token.");
|
||||
}
|
||||
return res.accessToken;
|
||||
}
|
||||
|
||||
export async function runGoogleCalendarSync(
|
||||
params: RunGoogleCalendarSyncParams = {},
|
||||
): Promise<GoogleCalendarSyncResult> {
|
||||
const mode = params.mode ?? "full";
|
||||
const weeksAhead = await getSyncWeeksAhead();
|
||||
|
||||
params.onProgress?.({
|
||||
phase: "preparing",
|
||||
current: 0,
|
||||
total: 1,
|
||||
message: mode === "incremental" ? "Fetching new week…" : "Fetching timetable…",
|
||||
});
|
||||
|
||||
const lessons =
|
||||
mode === "incremental"
|
||||
? await fetchTimetableLessons(trailingWeekRange(weeksAhead))
|
||||
: await fetchTimetableForSync(weeksAhead);
|
||||
|
||||
const options: GoogleCalendarSyncOptions = { onProgress: params.onProgress };
|
||||
const result = await syncLessonsToGoogleCalendar(
|
||||
{
|
||||
origin: location.origin,
|
||||
lessons,
|
||||
mode,
|
||||
weeksAhead,
|
||||
},
|
||||
getAccessTokenFromBackground,
|
||||
options,
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function formatSyncResultMessage(result: GoogleCalendarSyncResult): string {
|
||||
const created = result.created ?? 0;
|
||||
const updated = result.updated ?? 0;
|
||||
const deleted = result.deleted ?? 0;
|
||||
const parts: string[] = [];
|
||||
if (created > 0) parts.push(`${created} new`);
|
||||
if (updated > 0) parts.push(`${updated} updated`);
|
||||
if (deleted > 0) parts.push(`${deleted} removed`);
|
||||
if (parts.length === 0) return "Google Calendar is up to date.";
|
||||
return `Google Calendar updated (${parts.join(", ")}).`;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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,76 +0,0 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import {
|
||||
fetchTimetableForSync,
|
||||
fetchTimetableLessons,
|
||||
trailingWeekRange,
|
||||
} from "@/seqta/utils/googleCalendar/fetchTimetable";
|
||||
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
|
||||
import { syncLessonsToOutlookCalendar } from "@/seqta/utils/outlookCalendar/syncEngine";
|
||||
import type {
|
||||
GoogleCalendarSyncOptions,
|
||||
GoogleCalendarSyncProgress,
|
||||
GoogleCalendarSyncResult,
|
||||
} from "@/seqta/utils/googleCalendar/types";
|
||||
|
||||
export type OutlookCalendarRunMode = "full" | "incremental";
|
||||
|
||||
export interface RunOutlookCalendarSyncParams {
|
||||
mode?: OutlookCalendarRunMode;
|
||||
silent?: boolean;
|
||||
onProgress?: (progress: GoogleCalendarSyncProgress) => void;
|
||||
}
|
||||
|
||||
async function getAccessTokenFromBackground(): Promise<string> {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "outlookCalendarGetAccessToken",
|
||||
})) as { success?: boolean; accessToken?: string; error?: string };
|
||||
if (!res?.success || !res.accessToken) {
|
||||
throw new Error(res?.error ?? "Could not get Outlook Calendar access token.");
|
||||
}
|
||||
return res.accessToken;
|
||||
}
|
||||
|
||||
export async function runOutlookCalendarSync(
|
||||
params: RunOutlookCalendarSyncParams = {},
|
||||
): Promise<GoogleCalendarSyncResult> {
|
||||
const mode = params.mode ?? "full";
|
||||
const weeksAhead = await getSyncWeeksAhead();
|
||||
|
||||
params.onProgress?.({
|
||||
phase: "preparing",
|
||||
current: 0,
|
||||
total: 1,
|
||||
message: mode === "incremental" ? "Fetching new week…" : "Fetching timetable…",
|
||||
});
|
||||
|
||||
const lessons =
|
||||
mode === "incremental"
|
||||
? await fetchTimetableLessons(trailingWeekRange(weeksAhead))
|
||||
: await fetchTimetableForSync(weeksAhead);
|
||||
|
||||
const options: GoogleCalendarSyncOptions = { onProgress: params.onProgress };
|
||||
const result = await syncLessonsToOutlookCalendar(
|
||||
{
|
||||
origin: location.origin,
|
||||
lessons,
|
||||
mode,
|
||||
weeksAhead,
|
||||
},
|
||||
getAccessTokenFromBackground,
|
||||
options,
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function formatOutlookSyncResultMessage(result: GoogleCalendarSyncResult): string {
|
||||
const created = result.created ?? 0;
|
||||
const updated = result.updated ?? 0;
|
||||
const deleted = result.deleted ?? 0;
|
||||
const parts: string[] = [];
|
||||
if (created > 0) parts.push(`${created} new`);
|
||||
if (updated > 0) parts.push(`${updated} updated`);
|
||||
if (deleted > 0) parts.push(`${deleted} removed`);
|
||||
if (parts.length === 0) return "Outlook Calendar is up to date.";
|
||||
return `Outlook Calendar updated (${parts.join(", ")}).`;
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
export interface OutlookCalendarStatus {
|
||||
configured: boolean;
|
||||
connected: boolean;
|
||||
lastSyncAt?: number;
|
||||
lastSyncOrigin?: string;
|
||||
}
|
||||
@@ -1,48 +1,132 @@
|
||||
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,
|
||||
listGoogleSyncedEvents,
|
||||
listOutlookSyncedEvents,
|
||||
upsertOutlookCalendarEvent,
|
||||
} from "@/seqta/utils/calendarSync/remoteEvents";
|
||||
import { BSPLUS_GOOGLE_CALENDAR_EVENT_PROP } from "@/config/googleCalendar";
|
||||
import { BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY } from "@/config/outlookCalendar";
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
it("lists Outlook synced events and paginates", async () => {
|
||||
mockFetch
|
||||
.mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
value: [
|
||||
{
|
||||
id: "o1",
|
||||
subject: "Math",
|
||||
body: { content: "Synced by BetterSEQTA+\nKey: https://school.seqta.com.au:cal:1" },
|
||||
start: { dateTime: "2026-07-13T09:00:00", timeZone: "UTC" },
|
||||
end: { dateTime: "2026-07-13T10:00:00", timeZone: "UTC" },
|
||||
categories: [BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY],
|
||||
},
|
||||
],
|
||||
"@odata.nextLink": "https://graph.microsoft.com/v1.0/me/calendarView?$skiptoken=2",
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
value: [
|
||||
{
|
||||
id: "o2",
|
||||
subject: "English",
|
||||
body: { content: "Synced by BetterSEQTA+\nKey: https://school.seqta.com.au:cal:2" },
|
||||
start: { dateTime: "2026-07-14T09:00:00", timeZone: "UTC" },
|
||||
end: { dateTime: "2026-07-14T10:00:00", timeZone: "UTC" },
|
||||
categories: [BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY],
|
||||
},
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
|
||||
const events = await listOutlookSyncedEvents("token", {
|
||||
from: "2026-07-13",
|
||||
until: "2026-07-20",
|
||||
});
|
||||
|
||||
expect(events).toHaveLength(2);
|
||||
expect(events[0]).toMatchObject({
|
||||
id: "o1",
|
||||
seqtaKey: "https://school.seqta.com.au:cal:1",
|
||||
});
|
||||
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("google calendar remote list", () => {
|
||||
beforeEach(() => {
|
||||
mockFetch.mockReset();
|
||||
});
|
||||
|
||||
it("lists Google synced events using private extended properties", async () => {
|
||||
mockFetch.mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
items: [
|
||||
{
|
||||
id: "g1",
|
||||
summary: "Math",
|
||||
description: "Synced by BetterSEQTA+",
|
||||
start: { dateTime: "2026-07-13T09:00:00", timeZone: "UTC" },
|
||||
end: { dateTime: "2026-07-13T10:00:00", timeZone: "UTC" },
|
||||
extendedProperties: {
|
||||
private: { [BSPLUS_GOOGLE_CALENDAR_EVENT_PROP]: "https://school.seqta.com.au:cal:1" },
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "g-skip",
|
||||
summary: "Unrelated",
|
||||
start: { dateTime: "2026-07-13T11:00:00", timeZone: "UTC" },
|
||||
end: { dateTime: "2026-07-13T12:00:00", timeZone: "UTC" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
|
||||
const events = await listGoogleSyncedEvents("token", "cal-id", {
|
||||
from: "2026-07-13",
|
||||
until: "2026-07-20",
|
||||
});
|
||||
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]).toMatchObject({
|
||||
id: "g1",
|
||||
seqtaKey: "https://school.seqta.com.au:cal:1",
|
||||
date: "2026-07-13",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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})`);
|
||||
}
|
||||
Reference in New Issue
Block a user