mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-08-28 17:21:05 +00:00
feat: support outlook for calendar plus minor fixes
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import {
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT,
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_MAX,
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_MIN,
|
||||
} from "@/config/googleCalendar";
|
||||
import { readOutlookCalendarState } from "@/seqta/utils/outlookCalendar/storage";
|
||||
import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/storage";
|
||||
import {
|
||||
readSharedCalendarSyncSettings,
|
||||
WEEKLY_SYNC_INTERVAL_MS,
|
||||
writeSharedCalendarSyncSettings,
|
||||
} from "./sharedSettings";
|
||||
|
||||
export { CALENDAR_WEEKLY_ALARM, WEEKLY_SYNC_INTERVAL_MS } from "./sharedSettings";
|
||||
|
||||
export function clampSyncWeeks(weeks: number): number {
|
||||
if (!Number.isFinite(weeks)) return GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT;
|
||||
return Math.min(
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_MAX,
|
||||
Math.max(GOOGLE_CALENDAR_SYNC_WEEKS_MIN, Math.round(weeks)),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getSyncWeeksAhead(): Promise<number> {
|
||||
const settings = await readSharedCalendarSyncSettings();
|
||||
return clampSyncWeeks(settings.syncWeeksAhead ?? GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT);
|
||||
}
|
||||
|
||||
export async function getAutoSyncWeekly(): Promise<boolean> {
|
||||
const settings = await readSharedCalendarSyncSettings();
|
||||
return settings.autoSyncWeekly !== false;
|
||||
}
|
||||
|
||||
async function isAnyCalendarConnected(): Promise<boolean> {
|
||||
const [google, outlook] = await Promise.all([
|
||||
readGoogleCalendarState(),
|
||||
readOutlookCalendarState(),
|
||||
]);
|
||||
return !!(
|
||||
google.refreshToken ||
|
||||
google.accessToken ||
|
||||
outlook.refreshToken ||
|
||||
outlook.accessToken
|
||||
);
|
||||
}
|
||||
|
||||
export async function shouldRunWeeklySync(): Promise<boolean> {
|
||||
const settings = await readSharedCalendarSyncSettings();
|
||||
if (settings.autoSyncWeekly === false) return false;
|
||||
if (!(await isAnyCalendarConnected())) return false;
|
||||
if (settings.pendingWeeklySync) return true;
|
||||
const last = settings.lastWeeklySyncAt ?? 0;
|
||||
return Date.now() - last >= WEEKLY_SYNC_INTERVAL_MS;
|
||||
}
|
||||
|
||||
export async function markWeeklySyncComplete(): Promise<void> {
|
||||
await writeSharedCalendarSyncSettings({
|
||||
lastWeeklySyncAt: Date.now(),
|
||||
pendingWeeklySync: false,
|
||||
});
|
||||
}
|
||||
|
||||
export async function markWeeklySyncPending(): Promise<void> {
|
||||
await writeSharedCalendarSyncSettings({ pendingWeeklySync: true });
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import {
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT,
|
||||
} from "@/config/googleCalendar";
|
||||
import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/storage";
|
||||
|
||||
export const BSPLUS_CALENDAR_SYNC_SETTINGS_KEY = "bsplus_calendar_sync_settings";
|
||||
export const CALENDAR_WEEKLY_ALARM = "bsplus_calendar_weekly";
|
||||
export const WEEKLY_SYNC_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export interface SharedCalendarSyncSettings {
|
||||
syncWeeksAhead?: number;
|
||||
autoSyncWeekly?: boolean;
|
||||
lastWeeklySyncAt?: number;
|
||||
pendingWeeklySync?: boolean;
|
||||
}
|
||||
|
||||
export async function readSharedCalendarSyncSettings(): Promise<SharedCalendarSyncSettings> {
|
||||
const got = await browser.storage.local.get(BSPLUS_CALENDAR_SYNC_SETTINGS_KEY);
|
||||
const raw = got[BSPLUS_CALENDAR_SYNC_SETTINGS_KEY];
|
||||
const shared =
|
||||
raw && typeof raw === "object" && !Array.isArray(raw)
|
||||
? (raw as SharedCalendarSyncSettings)
|
||||
: {};
|
||||
|
||||
if (Object.keys(shared).length > 0) return shared;
|
||||
|
||||
const legacy = await readGoogleCalendarState();
|
||||
return {
|
||||
syncWeeksAhead: legacy.syncWeeksAhead,
|
||||
autoSyncWeekly: legacy.autoSyncWeekly,
|
||||
lastWeeklySyncAt: legacy.lastWeeklySyncAt,
|
||||
pendingWeeklySync: legacy.pendingWeeklySync,
|
||||
};
|
||||
}
|
||||
|
||||
export async function writeSharedCalendarSyncSettings(
|
||||
patch: Partial<SharedCalendarSyncSettings>,
|
||||
): Promise<SharedCalendarSyncSettings> {
|
||||
const current = await readSharedCalendarSyncSettings();
|
||||
const next = { ...current, ...patch };
|
||||
await browser.storage.local.set({ [BSPLUS_CALENDAR_SYNC_SETTINGS_KEY]: next });
|
||||
return next;
|
||||
}
|
||||
|
||||
export function defaultSyncWeeksAhead(): number {
|
||||
return GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT;
|
||||
}
|
||||
@@ -1,28 +1,60 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import { shouldRunWeeklySync } from "@/seqta/utils/googleCalendar/syncSettings";
|
||||
import {
|
||||
markWeeklySyncComplete,
|
||||
shouldRunWeeklySync,
|
||||
} from "@/seqta/utils/calendarSync/settings";
|
||||
import {
|
||||
formatSyncResultMessage,
|
||||
runGoogleCalendarSync,
|
||||
} from "@/seqta/utils/googleCalendar/syncRunner";
|
||||
import {
|
||||
formatOutlookSyncResultMessage,
|
||||
runOutlookCalendarSync,
|
||||
} from "@/seqta/utils/outlookCalendar/syncRunner";
|
||||
import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/storage";
|
||||
import { readOutlookCalendarState } from "@/seqta/utils/outlookCalendar/storage";
|
||||
import type { GoogleCalendarSyncResult } from "@/seqta/utils/googleCalendar/types";
|
||||
|
||||
let listenerRegistered = false;
|
||||
|
||||
export function registerGoogleCalendarContentHandlers(): void {
|
||||
async function runWeeklySyncForConnectedProviders(): Promise<GoogleCalendarSyncResult[]> {
|
||||
const [google, outlook] = await Promise.all([
|
||||
readGoogleCalendarState(),
|
||||
readOutlookCalendarState(),
|
||||
]);
|
||||
const results: GoogleCalendarSyncResult[] = [];
|
||||
|
||||
if (google.refreshToken || google.accessToken) {
|
||||
results.push(await runGoogleCalendarSync({ mode: "incremental", silent: true }));
|
||||
}
|
||||
if (outlook.refreshToken || outlook.accessToken) {
|
||||
results.push(await runOutlookCalendarSync({ mode: "incremental", silent: true }));
|
||||
}
|
||||
|
||||
if (results.some((r) => r.success)) {
|
||||
await markWeeklySyncComplete();
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
export function registerCalendarContentHandlers(): void {
|
||||
if (listenerRegistered) return;
|
||||
listenerRegistered = true;
|
||||
|
||||
browser.runtime.onMessage.addListener((request, _sender, sendResponse) => {
|
||||
if (request?.type !== "googleCalendarRunWeeklySync") return false;
|
||||
void runGoogleCalendarSync({ mode: "incremental", silent: true })
|
||||
.then((result: GoogleCalendarSyncResult) => sendResponse(result))
|
||||
.catch((err: unknown) => {
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Weekly sync failed",
|
||||
if (request?.type === "calendarRunWeeklySync" || request?.type === "googleCalendarRunWeeklySync") {
|
||||
void runWeeklySyncForConnectedProviders()
|
||||
.then((results) => sendResponse({ success: true, results }))
|
||||
.catch((err: unknown) => {
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Weekly sync failed",
|
||||
});
|
||||
});
|
||||
});
|
||||
return true;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -31,17 +63,38 @@ export async function maybeRunDueWeeklySync(
|
||||
): Promise<void> {
|
||||
if (!(await shouldRunWeeklySync())) return;
|
||||
|
||||
const result = await runGoogleCalendarSync({ mode: "incremental", silent: true });
|
||||
const [google, outlook] = await Promise.all([
|
||||
readGoogleCalendarState(),
|
||||
readOutlookCalendarState(),
|
||||
]);
|
||||
const results = await runWeeklySyncForConnectedProviders();
|
||||
if (!onComplete) return;
|
||||
|
||||
if (!result.success) {
|
||||
onComplete(result.error ?? "Weekly calendar sync failed.", true);
|
||||
const errors = results.filter((r) => !r.success);
|
||||
if (errors.length > 0) {
|
||||
onComplete(errors[0]?.error ?? "Weekly calendar sync failed.", true);
|
||||
return;
|
||||
}
|
||||
|
||||
const changed =
|
||||
(result.created ?? 0) + (result.updated ?? 0) + (result.deleted ?? 0) > 0;
|
||||
if (changed) {
|
||||
onComplete(formatSyncResultMessage(result));
|
||||
const messages: string[] = [];
|
||||
let index = 0;
|
||||
if (google.refreshToken || google.accessToken) {
|
||||
const result = results[index++];
|
||||
const changed =
|
||||
(result.created ?? 0) + (result.updated ?? 0) + (result.deleted ?? 0) > 0;
|
||||
if (changed) messages.push(formatSyncResultMessage(result));
|
||||
}
|
||||
if (outlook.refreshToken || outlook.accessToken) {
|
||||
const result = results[index++];
|
||||
const changed =
|
||||
(result.created ?? 0) + (result.updated ?? 0) + (result.deleted ?? 0) > 0;
|
||||
if (changed) messages.push(formatOutlookSyncResultMessage(result));
|
||||
}
|
||||
|
||||
if (messages.length > 0) {
|
||||
onComplete(messages.join(" "));
|
||||
}
|
||||
}
|
||||
|
||||
/** @deprecated use registerCalendarContentHandlers */
|
||||
export const registerGoogleCalendarContentHandlers = registerCalendarContentHandlers;
|
||||
|
||||
@@ -15,7 +15,7 @@ jest.mock("@/seqta/utils/googleCalendar/storage", () => ({
|
||||
writeGoogleCalendarState: jest.fn(async (patch: unknown) => patch),
|
||||
}));
|
||||
|
||||
jest.mock("@/seqta/utils/googleCalendar/syncSettings", () => ({
|
||||
jest.mock("@/seqta/utils/calendarSync/settings", () => ({
|
||||
getSyncWeeksAhead: jest.fn(async () => 12),
|
||||
}));
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
isDateInRange,
|
||||
syncWindowRange,
|
||||
} from "@/seqta/utils/googleCalendar/syncDateRange";
|
||||
import { getSyncWeeksAhead } from "@/seqta/utils/googleCalendar/syncSettings";
|
||||
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
|
||||
import {
|
||||
eventMapKey,
|
||||
readGoogleCalendarState,
|
||||
|
||||
@@ -4,10 +4,7 @@ import {
|
||||
fetchTimetableLessons,
|
||||
trailingWeekRange,
|
||||
} from "@/seqta/utils/googleCalendar/fetchTimetable";
|
||||
import {
|
||||
getSyncWeeksAhead,
|
||||
markWeeklySyncComplete,
|
||||
} from "@/seqta/utils/googleCalendar/syncSettings";
|
||||
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
|
||||
import { syncLessonsToGoogleCalendar } from "@/seqta/utils/googleCalendar/syncEngine";
|
||||
import type {
|
||||
GoogleCalendarSyncOptions,
|
||||
@@ -63,10 +60,6 @@ export async function runGoogleCalendarSync(
|
||||
options,
|
||||
);
|
||||
|
||||
if (result.success && mode === "incremental") {
|
||||
await markWeeklySyncComplete();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,57 +1,10 @@
|
||||
import {
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT,
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_MAX,
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_MIN,
|
||||
} from "@/config/googleCalendar";
|
||||
import { readGoogleCalendarState, writeGoogleCalendarState } from "./storage";
|
||||
|
||||
export const GOOGLE_CALENDAR_WEEKLY_ALARM = "bsplus_google_calendar_weekly";
|
||||
export const WEEKLY_SYNC_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export function clampSyncWeeks(weeks: number): number {
|
||||
if (!Number.isFinite(weeks)) return GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT;
|
||||
return Math.min(
|
||||
GOOGLE_CALENDAR_SYNC_WEEKS_MAX,
|
||||
Math.max(GOOGLE_CALENDAR_SYNC_WEEKS_MIN, Math.round(weeks)),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getSyncWeeksAhead(): Promise<number> {
|
||||
const state = await readGoogleCalendarState();
|
||||
return clampSyncWeeks(state.syncWeeksAhead ?? GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT);
|
||||
}
|
||||
|
||||
export async function setSyncWeeksAhead(weeks: number): Promise<number> {
|
||||
const syncWeeksAhead = clampSyncWeeks(weeks);
|
||||
await writeGoogleCalendarState({ syncWeeksAhead });
|
||||
return syncWeeksAhead;
|
||||
}
|
||||
|
||||
export async function getAutoSyncWeekly(): Promise<boolean> {
|
||||
const state = await readGoogleCalendarState();
|
||||
return state.autoSyncWeekly !== false;
|
||||
}
|
||||
|
||||
export async function setAutoSyncWeekly(enabled: boolean): Promise<void> {
|
||||
await writeGoogleCalendarState({ autoSyncWeekly: enabled });
|
||||
}
|
||||
|
||||
export async function shouldRunWeeklySync(): Promise<boolean> {
|
||||
const state = await readGoogleCalendarState();
|
||||
if (!state.refreshToken && !state.accessToken) return false;
|
||||
if (state.autoSyncWeekly === false) return false;
|
||||
if (state.pendingWeeklySync) return true;
|
||||
const last = state.lastWeeklySyncAt ?? state.lastSyncAt ?? 0;
|
||||
return Date.now() - last >= WEEKLY_SYNC_INTERVAL_MS;
|
||||
}
|
||||
|
||||
export async function markWeeklySyncComplete(): Promise<void> {
|
||||
await writeGoogleCalendarState({
|
||||
lastWeeklySyncAt: Date.now(),
|
||||
pendingWeeklySync: false,
|
||||
});
|
||||
}
|
||||
|
||||
export async function markWeeklySyncPending(): Promise<void> {
|
||||
await writeGoogleCalendarState({ pendingWeeklySync: true });
|
||||
}
|
||||
export {
|
||||
CALENDAR_WEEKLY_ALARM as GOOGLE_CALENDAR_WEEKLY_ALARM,
|
||||
WEEKLY_SYNC_INTERVAL_MS,
|
||||
clampSyncWeeks,
|
||||
getAutoSyncWeekly,
|
||||
getSyncWeeksAhead,
|
||||
markWeeklySyncComplete,
|
||||
markWeeklySyncPending,
|
||||
shouldRunWeeklySync,
|
||||
} from "@/seqta/utils/calendarSync/settings";
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import {
|
||||
OUTLOOK_CALENDAR_ACCOUNTS_NOT_READY_HINT,
|
||||
OUTLOOK_CALENDAR_REFRESH_URL,
|
||||
OUTLOOK_CALENDAR_TOKEN_URL,
|
||||
} from "@/config/outlookCalendar";
|
||||
|
||||
type OutlookTokenPayload = {
|
||||
access_token: string;
|
||||
refresh_token?: string;
|
||||
expires_in?: number;
|
||||
};
|
||||
|
||||
async function parseAccountsJson(res: Response): Promise<Record<string, unknown>> {
|
||||
const text = await res.text();
|
||||
try {
|
||||
return text ? (JSON.parse(text) as Record<string, unknown>) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function extractTokens(json: Record<string, unknown>): OutlookTokenPayload {
|
||||
const access_token = json.access_token;
|
||||
if (typeof access_token !== "string" || !access_token) {
|
||||
throw new Error("Token response missing access_token");
|
||||
}
|
||||
return {
|
||||
access_token,
|
||||
refresh_token: typeof json.refresh_token === "string" ? json.refresh_token : undefined,
|
||||
expires_in: typeof json.expires_in === "number" ? json.expires_in : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function formatAccountsTokenError(res: Response, json: Record<string, unknown>): string {
|
||||
if (res.status === 404 || res.status === 501) {
|
||||
return OUTLOOK_CALENDAR_ACCOUNTS_NOT_READY_HINT;
|
||||
}
|
||||
const err = typeof json.error === "string" ? json.error : "";
|
||||
const desc = typeof json.error_description === "string" ? json.error_description : "";
|
||||
return desc || err || `Accounts token API failed (${res.status})`;
|
||||
}
|
||||
|
||||
export async function exchangeOutlookCodeViaAccounts(
|
||||
code: string,
|
||||
redirectUri: string,
|
||||
codeVerifier: string,
|
||||
): Promise<OutlookTokenPayload> {
|
||||
const res = await fetch(OUTLOOK_CALENDAR_TOKEN_URL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
code,
|
||||
redirect_uri: redirectUri,
|
||||
code_verifier: codeVerifier,
|
||||
}),
|
||||
});
|
||||
const json = await parseAccountsJson(res);
|
||||
if (!res.ok) {
|
||||
throw new Error(formatAccountsTokenError(res, json));
|
||||
}
|
||||
return extractTokens(json);
|
||||
}
|
||||
|
||||
export async function refreshOutlookTokenViaAccounts(
|
||||
refreshToken: string,
|
||||
): Promise<OutlookTokenPayload> {
|
||||
const res = await fetch(OUTLOOK_CALENDAR_REFRESH_URL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ refresh_token: refreshToken }),
|
||||
});
|
||||
const json = await parseAccountsJson(res);
|
||||
if (!res.ok) {
|
||||
throw new Error(formatAccountsTokenError(res, json));
|
||||
}
|
||||
return extractTokens(json);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY } from "@/config/outlookCalendar";
|
||||
import type {
|
||||
GoogleCalendarEventInput,
|
||||
SeqtaTimetableLesson,
|
||||
} from "@/seqta/utils/googleCalendar/types";
|
||||
import {
|
||||
lessonToGoogleEvent,
|
||||
mapLessonsToGoogleEvents,
|
||||
} from "@/seqta/utils/googleCalendar/eventMapper";
|
||||
|
||||
export { mapLessonsToGoogleEvents, lessonToGoogleEvent, seqtaLessonKey } from "@/seqta/utils/googleCalendar/eventMapper";
|
||||
|
||||
export function outlookGraphEventBody(event: GoogleCalendarEventInput): Record<string, unknown> {
|
||||
const body: Record<string, unknown> = {
|
||||
subject: event.summary,
|
||||
body: {
|
||||
contentType: "text",
|
||||
content: event.description ?? "Synced by BetterSEQTA+",
|
||||
},
|
||||
start: { dateTime: event.startDateTime, timeZone: event.timeZone },
|
||||
end: { dateTime: event.endDateTime, timeZone: event.timeZone },
|
||||
categories: [BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY],
|
||||
};
|
||||
if (event.location) {
|
||||
body.location = { displayName: event.location };
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export function mapLessonsToOutlookEvents(
|
||||
origin: string,
|
||||
lessons: SeqtaTimetableLesson[],
|
||||
timeZone: string,
|
||||
): GoogleCalendarEventInput[] {
|
||||
return mapLessonsToGoogleEvents(origin, lessons, timeZone);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import type { GoogleCalendarEventMapEntry } from "@/seqta/utils/googleCalendar/eventMapEntry";
|
||||
|
||||
export const BSPLUS_OUTLOOK_CALENDAR_STORAGE_KEY = "bsplus_outlook_calendar";
|
||||
|
||||
export interface OutlookCalendarStoredState {
|
||||
accessToken?: string;
|
||||
refreshToken?: string;
|
||||
expiresAt?: number;
|
||||
connectedAt?: number;
|
||||
lastSyncAt?: number;
|
||||
lastSyncOrigin?: string;
|
||||
eventMap?: Record<string, string | GoogleCalendarEventMapEntry>;
|
||||
}
|
||||
|
||||
export async function readOutlookCalendarState(): Promise<OutlookCalendarStoredState> {
|
||||
const got = await browser.storage.local.get(BSPLUS_OUTLOOK_CALENDAR_STORAGE_KEY);
|
||||
const raw = got[BSPLUS_OUTLOOK_CALENDAR_STORAGE_KEY];
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
||||
return raw as OutlookCalendarStoredState;
|
||||
}
|
||||
|
||||
export async function writeOutlookCalendarState(
|
||||
patch: Partial<OutlookCalendarStoredState>,
|
||||
): Promise<OutlookCalendarStoredState> {
|
||||
const current = await readOutlookCalendarState();
|
||||
const next: OutlookCalendarStoredState = { ...current, ...patch };
|
||||
await browser.storage.local.set({ [BSPLUS_OUTLOOK_CALENDAR_STORAGE_KEY]: next });
|
||||
return next;
|
||||
}
|
||||
|
||||
export async function clearOutlookCalendarState(): Promise<void> {
|
||||
await browser.storage.local.remove(BSPLUS_OUTLOOK_CALENDAR_STORAGE_KEY);
|
||||
}
|
||||
|
||||
export function outlookEventMapKey(origin: string, seqtaKey: string): string {
|
||||
return `${origin}::${seqtaKey}`;
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
import { verboseLog } from "@/utils/verboseLog";
|
||||
import { isOutlookCalendarConfigured } from "@/config/outlookCalendar";
|
||||
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
|
||||
import {
|
||||
getStoredEventId,
|
||||
lessonDateFromSeqtaKey,
|
||||
normalizeEventMapEntry,
|
||||
} from "@/seqta/utils/googleCalendar/eventMapEntry";
|
||||
import {
|
||||
isDateInRange,
|
||||
syncWindowRange,
|
||||
} from "@/seqta/utils/googleCalendar/syncDateRange";
|
||||
import type {
|
||||
GoogleCalendarDeleteResult,
|
||||
GoogleCalendarSyncOptions,
|
||||
GoogleCalendarSyncProgress,
|
||||
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";
|
||||
|
||||
const EVENT_MAP_PERSIST_EVERY = 10;
|
||||
|
||||
type DeleteTrackedEventsResult = {
|
||||
deleted: number;
|
||||
failed: number;
|
||||
};
|
||||
|
||||
function reportProgress(
|
||||
onProgress: GoogleCalendarSyncOptions["onProgress"],
|
||||
progress: GoogleCalendarSyncProgress,
|
||||
) {
|
||||
onProgress?.(progress);
|
||||
}
|
||||
|
||||
function lessonDateForEvent(startDateTime: string, seqtaKey: string): string {
|
||||
return startDateTime.slice(0, 10) || lessonDateFromSeqtaKey(seqtaKey) || "";
|
||||
}
|
||||
|
||||
async function 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;
|
||||
|
||||
reportProgress(onProgress, {
|
||||
phase: "deleting",
|
||||
current: progressOffset + deleted + failed,
|
||||
total: progressTotal,
|
||||
message: `Removing old events (${deleted + failed}/${entries.length})…`,
|
||||
});
|
||||
|
||||
if (persistProgress && (deleted + failed) % EVENT_MAP_PERSIST_EVERY === 0) {
|
||||
await writeOutlookCalendarState({ eventMap });
|
||||
}
|
||||
} catch (err) {
|
||||
verboseLog("[BetterSEQTA+] Outlook Calendar event delete failed:", err);
|
||||
failed += 1;
|
||||
reportProgress(onProgress, {
|
||||
phase: "deleting",
|
||||
current: progressOffset + deleted + failed,
|
||||
total: progressTotal,
|
||||
message: `Removing old events (${deleted + failed}/${entries.length})…`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { deleted, failed };
|
||||
}
|
||||
|
||||
function originEventMapEntries(
|
||||
eventMap: Record<string, string | { id: string; date: string }>,
|
||||
origin: string,
|
||||
): Array<[string, string]> {
|
||||
const prefix = `${origin}::`;
|
||||
const entries: Array<[string, string]> = [];
|
||||
for (const [key, value] of Object.entries(eventMap)) {
|
||||
if (!key.startsWith(prefix)) continue;
|
||||
const id = getStoredEventId(value);
|
||||
if (id) entries.push([key, id]);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function entriesToPrune(
|
||||
eventMap: Record<string, string | { id: string; date: string }>,
|
||||
origin: string,
|
||||
mode: "full" | "incremental",
|
||||
weeksAhead: number,
|
||||
currentMapKeys: Set<string>,
|
||||
): Array<[string, string]> {
|
||||
const window = syncWindowRange(weeksAhead);
|
||||
const prefix = `${origin}::`;
|
||||
const entries: Array<[string, string]> = [];
|
||||
|
||||
for (const [mapKey, raw] of Object.entries(eventMap)) {
|
||||
if (!mapKey.startsWith(prefix)) continue;
|
||||
const entry = normalizeEventMapEntry(raw);
|
||||
if (!entry) continue;
|
||||
|
||||
let shouldDelete = false;
|
||||
if (mode === "incremental") {
|
||||
shouldDelete = false;
|
||||
} else if (entry.date) {
|
||||
shouldDelete = !isDateInRange(entry.date, window);
|
||||
} else {
|
||||
shouldDelete = !currentMapKeys.has(mapKey);
|
||||
}
|
||||
|
||||
if (shouldDelete) entries.push([mapKey, entry.id]);
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
export async function syncLessonsToOutlookCalendar(
|
||||
request: GoogleCalendarSyncRequest,
|
||||
getAccessToken: () => Promise<string>,
|
||||
options: GoogleCalendarSyncOptions = {},
|
||||
): Promise<GoogleCalendarSyncResult> {
|
||||
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 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 {
|
||||
success: false,
|
||||
configured: true,
|
||||
connected: true,
|
||||
error: "No timetable classes found to sync for the selected range.",
|
||||
};
|
||||
}
|
||||
|
||||
reportProgress(options.onProgress, {
|
||||
phase: "preparing",
|
||||
current: 0,
|
||||
total: Math.max(events.length, 1),
|
||||
message: mode === "incremental" ? "Preparing weekly sync…" : "Preparing sync…",
|
||||
});
|
||||
|
||||
let accessToken = await getAccessToken();
|
||||
const 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 staleResult = await deleteTrackedEventsFromOutlook(
|
||||
staleEntries,
|
||||
eventMap,
|
||||
getAccessToken,
|
||||
false,
|
||||
options.onProgress,
|
||||
0,
|
||||
totalSteps,
|
||||
);
|
||||
|
||||
let created = 0;
|
||||
let updated = 0;
|
||||
let failed = staleResult.failed;
|
||||
const lastSyncAt = Date.now();
|
||||
|
||||
for (let i = 0; i < events.length; i++) {
|
||||
const event = events[i];
|
||||
const mapKey = outlookEventMapKey(request.origin, event.seqtaKey);
|
||||
const existingId = getStoredEventId(eventMap[mapKey]);
|
||||
try {
|
||||
const outlookId = await upsertOutlookCalendarEvent(
|
||||
accessToken,
|
||||
existingId,
|
||||
outlookGraphEventBody(event),
|
||||
async () => {
|
||||
accessToken = await getAccessToken();
|
||||
return accessToken;
|
||||
},
|
||||
);
|
||||
if (existingId) updated += 1;
|
||||
else created += 1;
|
||||
eventMap[mapKey] = {
|
||||
id: outlookId,
|
||||
date: lessonDateForEvent(event.startDateTime, event.seqtaKey),
|
||||
};
|
||||
|
||||
reportProgress(options.onProgress, {
|
||||
phase: "upserting",
|
||||
current: staleEntries.length + i + 1,
|
||||
total: totalSteps,
|
||||
message: `Syncing events (${i + 1}/${events.length})…`,
|
||||
});
|
||||
|
||||
if ((i + 1) % EVENT_MAP_PERSIST_EVERY === 0 || i === events.length - 1) {
|
||||
await writeOutlookCalendarState({
|
||||
eventMap,
|
||||
lastSyncAt,
|
||||
lastSyncOrigin: request.origin,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
verboseLog("[BetterSEQTA+] Outlook Calendar event sync failed:", err);
|
||||
failed += 1;
|
||||
reportProgress(options.onProgress, {
|
||||
phase: "upserting",
|
||||
current: staleEntries.length + i + 1,
|
||||
total: totalSteps,
|
||||
message: `Syncing events (${i + 1}/${events.length})…`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (staleResult.deleted > 0 || staleEntries.length > 0 || events.length > 0) {
|
||||
await writeOutlookCalendarState({
|
||||
eventMap,
|
||||
lastSyncAt,
|
||||
lastSyncOrigin: request.origin,
|
||||
});
|
||||
}
|
||||
|
||||
reportProgress(options.onProgress, {
|
||||
phase: "done",
|
||||
current: totalSteps,
|
||||
total: totalSteps,
|
||||
message: "Sync complete",
|
||||
});
|
||||
|
||||
return {
|
||||
success: failed === 0,
|
||||
configured: true,
|
||||
connected: true,
|
||||
created,
|
||||
updated,
|
||||
deleted: staleResult.deleted,
|
||||
skipped: 0,
|
||||
failed,
|
||||
lastSyncAt,
|
||||
error:
|
||||
failed > 0
|
||||
? `Synced with ${failed} error${failed === 1 ? "" : "s"}. Check the console for details.`
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
reportProgress(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 });
|
||||
|
||||
reportProgress(options.onProgress, {
|
||||
phase: "done",
|
||||
current: entries.length,
|
||||
total: entries.length,
|
||||
message: "Removal complete",
|
||||
});
|
||||
|
||||
return {
|
||||
success: failed === 0,
|
||||
configured: true,
|
||||
connected: true,
|
||||
deleted,
|
||||
failed,
|
||||
error:
|
||||
failed > 0
|
||||
? `Removed ${deleted} event${deleted === 1 ? "" : "s"} with ${failed} error${failed === 1 ? "" : "s"}.`
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import {
|
||||
fetchTimetableForSync,
|
||||
fetchTimetableLessons,
|
||||
trailingWeekRange,
|
||||
} from "@/seqta/utils/googleCalendar/fetchTimetable";
|
||||
import { getSyncWeeksAhead } from "@/seqta/utils/calendarSync/settings";
|
||||
import { syncLessonsToOutlookCalendar } from "@/seqta/utils/outlookCalendar/syncEngine";
|
||||
import type {
|
||||
GoogleCalendarSyncOptions,
|
||||
GoogleCalendarSyncProgress,
|
||||
GoogleCalendarSyncResult,
|
||||
} from "@/seqta/utils/googleCalendar/types";
|
||||
|
||||
export type OutlookCalendarRunMode = "full" | "incremental";
|
||||
|
||||
export interface RunOutlookCalendarSyncParams {
|
||||
mode?: OutlookCalendarRunMode;
|
||||
silent?: boolean;
|
||||
onProgress?: (progress: GoogleCalendarSyncProgress) => void;
|
||||
}
|
||||
|
||||
async function getAccessTokenFromBackground(): Promise<string> {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "outlookCalendarGetAccessToken",
|
||||
})) as { success?: boolean; accessToken?: string; error?: string };
|
||||
if (!res?.success || !res.accessToken) {
|
||||
throw new Error(res?.error ?? "Could not get Outlook Calendar access token.");
|
||||
}
|
||||
return res.accessToken;
|
||||
}
|
||||
|
||||
export async function runOutlookCalendarSync(
|
||||
params: RunOutlookCalendarSyncParams = {},
|
||||
): Promise<GoogleCalendarSyncResult> {
|
||||
const mode = params.mode ?? "full";
|
||||
const weeksAhead = await getSyncWeeksAhead();
|
||||
|
||||
params.onProgress?.({
|
||||
phase: "preparing",
|
||||
current: 0,
|
||||
total: 1,
|
||||
message: mode === "incremental" ? "Fetching new week…" : "Fetching timetable…",
|
||||
});
|
||||
|
||||
const lessons =
|
||||
mode === "incremental"
|
||||
? await fetchTimetableLessons(trailingWeekRange(weeksAhead))
|
||||
: await fetchTimetableForSync(weeksAhead);
|
||||
|
||||
const options: GoogleCalendarSyncOptions = { onProgress: params.onProgress };
|
||||
const result = await syncLessonsToOutlookCalendar(
|
||||
{
|
||||
origin: location.origin,
|
||||
lessons,
|
||||
mode,
|
||||
weeksAhead,
|
||||
},
|
||||
getAccessTokenFromBackground,
|
||||
options,
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function formatOutlookSyncResultMessage(result: GoogleCalendarSyncResult): string {
|
||||
const created = result.created ?? 0;
|
||||
const updated = result.updated ?? 0;
|
||||
const deleted = result.deleted ?? 0;
|
||||
const parts: string[] = [];
|
||||
if (created > 0) parts.push(`${created} new`);
|
||||
if (updated > 0) parts.push(`${updated} updated`);
|
||||
if (deleted > 0) parts.push(`${deleted} removed`);
|
||||
if (parts.length === 0) return "Outlook Calendar is up to date.";
|
||||
return `Outlook Calendar updated (${parts.join(", ")}).`;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export interface OutlookCalendarStatus {
|
||||
configured: boolean;
|
||||
connected: boolean;
|
||||
lastSyncAt?: number;
|
||||
lastSyncOrigin?: string;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import { upsertOutlookCalendarEvent, deleteOutlookCalendarEvent } from "./upsertEvent";
|
||||
|
||||
const fetchMock = jest.fn();
|
||||
global.fetch = fetchMock as unknown as typeof fetch;
|
||||
|
||||
describe("upsertOutlookCalendarEvent", () => {
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset();
|
||||
});
|
||||
|
||||
it("creates a new event when no existing id", async () => {
|
||||
fetchMock.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ id: "evt-1" }),
|
||||
});
|
||||
|
||||
const id = await upsertOutlookCalendarEvent("token", undefined, { subject: "Math" });
|
||||
expect(id).toBe("evt-1");
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://graph.microsoft.com/v1.0/me/events",
|
||||
expect.objectContaining({ method: "POST" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("patches when an existing id is provided", async () => {
|
||||
fetchMock.mockResolvedValue({ ok: true, status: 200, json: async () => ({}) });
|
||||
|
||||
const id = await upsertOutlookCalendarEvent("token", "evt-1", { subject: "Math" });
|
||||
expect(id).toBe("evt-1");
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://graph.microsoft.com/v1.0/me/events/evt-1",
|
||||
expect.objectContaining({ method: "PATCH" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteOutlookCalendarEvent", () => {
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset();
|
||||
});
|
||||
|
||||
it("treats 404 as success", async () => {
|
||||
fetchMock.mockResolvedValue({ ok: false, status: 404, json: async () => ({}) });
|
||||
await expect(deleteOutlookCalendarEvent("token", "evt-1")).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { OUTLOOK_GRAPH_API } from "@/config/outlookCalendar";
|
||||
|
||||
export async function upsertOutlookCalendarEvent(
|
||||
accessToken: string,
|
||||
existingEventId: string | undefined,
|
||||
body: Record<string, unknown>,
|
||||
refreshAccessToken?: () => Promise<string>,
|
||||
): Promise<string> {
|
||||
const headers = {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
if (existingEventId) {
|
||||
const res = await fetch(`${OUTLOOK_GRAPH_API}/me/events/${encodeURIComponent(existingEventId)}`, {
|
||||
method: "PATCH",
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (res.status === 401 && refreshAccessToken) {
|
||||
const nextToken = await refreshAccessToken();
|
||||
return upsertOutlookCalendarEvent(nextToken, existingEventId, body);
|
||||
}
|
||||
if (res.ok) return existingEventId;
|
||||
if (res.status !== 404) {
|
||||
const err = (await res.json().catch(() => ({}))) as {
|
||||
error?: { message?: string };
|
||||
};
|
||||
throw new Error(err?.error?.message ?? `Outlook Calendar update failed (${res.status})`);
|
||||
}
|
||||
}
|
||||
|
||||
const res = await fetch(`${OUTLOOK_GRAPH_API}/me/events`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (res.status === 401 && refreshAccessToken) {
|
||||
const nextToken = await refreshAccessToken();
|
||||
return upsertOutlookCalendarEvent(nextToken, undefined, body);
|
||||
}
|
||||
const json = (await res.json().catch(() => ({}))) as {
|
||||
id?: string;
|
||||
error?: { message?: string };
|
||||
};
|
||||
if (!res.ok || !json.id) {
|
||||
throw new Error(json?.error?.message ?? `Outlook Calendar create failed (${res.status})`);
|
||||
}
|
||||
return json.id;
|
||||
}
|
||||
|
||||
export async function deleteOutlookCalendarEvent(
|
||||
accessToken: string,
|
||||
eventId: string,
|
||||
refreshAccessToken?: () => Promise<string>,
|
||||
): Promise<void> {
|
||||
const res = await fetch(`${OUTLOOK_GRAPH_API}/me/events/${encodeURIComponent(eventId)}`, {
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
if (res.status === 401 && refreshAccessToken) {
|
||||
const nextToken = await refreshAccessToken();
|
||||
return deleteOutlookCalendarEvent(nextToken, eventId);
|
||||
}
|
||||
if (res.ok || res.status === 404 || res.status === 410) return;
|
||||
const err = (await res.json().catch(() => ({}))) as { error?: { message?: string } };
|
||||
throw new Error(err?.error?.message ?? `Outlook Calendar delete failed (${res.status})`);
|
||||
}
|
||||
Reference in New Issue
Block a user