mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-08-28 09:11:06 +00:00
Merge pull request #466 from BetterSEQTA/calendar-syncing
Calendar syncing
This commit is contained in:
@@ -0,0 +1,8 @@
|
|||||||
|
# Optional override for Google OAuth client ID at build/dev time.
|
||||||
|
# Client secret is NOT used in the extension — token exchange is on accounts.betterseqta.org.
|
||||||
|
# See docs/GOOGLE_CALENDAR_ACCOUNTS_CALLBACK.md
|
||||||
|
|
||||||
|
# GOOGLE_OAUTH_CLIENT_ID=your-id.apps.googleusercontent.com
|
||||||
|
|
||||||
|
# Outlook / Microsoft Graph (see docs/OUTLOOK_CALENDAR_ACCOUNTS_CALLBACK.md)
|
||||||
|
# OUTLOOK_OAUTH_CLIENT_ID=your-azure-application-client-id
|
||||||
@@ -11,6 +11,7 @@ export default {
|
|||||||
},
|
},
|
||||||
moduleNameMapper: {
|
moduleNameMapper: {
|
||||||
'^@/(.*)$': '<rootDir>/src/$1',
|
'^@/(.*)$': '<rootDir>/src/$1',
|
||||||
|
'^color$': '<rootDir>/src/test/mocks/color.ts',
|
||||||
'^webextension-polyfill$': '<rootDir>/src/test/mocks/webextension-polyfill.ts',
|
'^webextension-polyfill$': '<rootDir>/src/test/mocks/webextension-polyfill.ts',
|
||||||
},
|
},
|
||||||
moduleFileExtensions: ['ts', 'js', 'json'],
|
moduleFileExtensions: ['ts', 'js', 'json'],
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ import {
|
|||||||
withSuppressedCloudAutoUpload,
|
withSuppressedCloudAutoUpload,
|
||||||
} from "./background/cloudSettingsAutoSync";
|
} from "./background/cloudSettingsAutoSync";
|
||||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||||
|
import { registerGoogleCalendarMessageHandlers, initGoogleCalendarBackground } from "./background/googleCalendar";
|
||||||
|
import { registerOutlookCalendarMessageHandlers } from "./background/outlookCalendar";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Session-only dev-mode override of the content API base.
|
* Session-only dev-mode override of the content API base.
|
||||||
@@ -557,6 +559,10 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
registerGoogleCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
||||||
|
registerOutlookCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
||||||
|
initGoogleCalendarBackground();
|
||||||
|
|
||||||
browser.runtime.onMessage.addListener(
|
browser.runtime.onMessage.addListener(
|
||||||
// @ts-ignore - OnMessageListener expects literal true for async, we return boolean
|
// @ts-ignore - OnMessageListener expects literal true for async, we return boolean
|
||||||
(request: any, sender: browser.Runtime.MessageSender, sendResponse: MessageSender) => {
|
(request: any, sender: browser.Runtime.MessageSender, sendResponse: MessageSender) => {
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import { verboseLog } from "@/utils/verboseLog";
|
||||||
|
import {
|
||||||
|
CALENDAR_WEEKLY_ALARM,
|
||||||
|
getAutoSyncWeekly,
|
||||||
|
markWeeklySyncPending,
|
||||||
|
} from "@/seqta/utils/calendarSync/settings";
|
||||||
|
import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/storage";
|
||||||
|
import { readOutlookCalendarState } from "@/seqta/utils/outlookCalendar/storage";
|
||||||
|
|
||||||
|
const WEEKLY_PERIOD_MINUTES = 7 * 24 * 60;
|
||||||
|
|
||||||
|
function isSeqtaTab(tab: browser.Tabs.Tab): boolean {
|
||||||
|
const title = tab.title ?? "";
|
||||||
|
return title.includes("SEQTA Learn") || title.includes("SEQTA Engage");
|
||||||
|
}
|
||||||
|
|
||||||
|
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 ensureWeeklySyncAlarm(): Promise<void> {
|
||||||
|
const connected = await isAnyCalendarConnected();
|
||||||
|
const enabled = await getAutoSyncWeekly();
|
||||||
|
if (!connected || !enabled) {
|
||||||
|
await browser.alarms.clear(CALENDAR_WEEKLY_ALARM);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await browser.alarms.get(CALENDAR_WEEKLY_ALARM);
|
||||||
|
if (!existing) {
|
||||||
|
await browser.alarms.create(CALENDAR_WEEKLY_ALARM, {
|
||||||
|
periodInMinutes: WEEKLY_PERIOD_MINUTES,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function clearWeeklySyncAlarm(): Promise<void> {
|
||||||
|
await browser.alarms.clear(CALENDAR_WEEKLY_ALARM);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function triggerWeeklySyncOnSeqtaTabs(): Promise<boolean> {
|
||||||
|
const tabs = await browser.tabs.query({});
|
||||||
|
const seqtaTabs = tabs.filter((tab) => tab.id != null && isSeqtaTab(tab));
|
||||||
|
if (seqtaTabs.length === 0) return false;
|
||||||
|
|
||||||
|
let delivered = false;
|
||||||
|
for (const tab of seqtaTabs) {
|
||||||
|
if (tab.id == null) continue;
|
||||||
|
try {
|
||||||
|
await browser.tabs.sendMessage(tab.id, { type: "calendarRunWeeklySync" });
|
||||||
|
delivered = true;
|
||||||
|
} catch (err) {
|
||||||
|
verboseLog("[BetterSEQTA+] Weekly calendar sync message failed for tab:", tab.id, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return delivered;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handleWeeklySyncAlarm(): Promise<void> {
|
||||||
|
if (!(await isAnyCalendarConnected()) || !(await getAutoSyncWeekly())) return;
|
||||||
|
|
||||||
|
const delivered = await triggerWeeklySyncOnSeqtaTabs();
|
||||||
|
if (!delivered) {
|
||||||
|
await markWeeklySyncPending();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerWeeklySyncAlarmListener(): void {
|
||||||
|
browser.alarms.onAlarm.addListener((alarm) => {
|
||||||
|
if (alarm.name !== CALENDAR_WEEKLY_ALARM) return;
|
||||||
|
void handleWeeklySyncAlarm();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function initCalendarBackground(): void {
|
||||||
|
registerWeeklySyncAlarmListener();
|
||||||
|
void ensureWeeklySyncAlarm();
|
||||||
|
}
|
||||||
@@ -0,0 +1,363 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import {
|
||||||
|
GOOGLE_AUTH_URL,
|
||||||
|
GOOGLE_CALENDAR_OAUTH_CALLBACK,
|
||||||
|
GOOGLE_CALENDAR_SCOPE,
|
||||||
|
GOOGLE_OAUTH_CLIENT_ID,
|
||||||
|
googleOAuthRedirectUriHint,
|
||||||
|
isGoogleCalendarConfigured,
|
||||||
|
} from "@/config/googleCalendar";
|
||||||
|
import {
|
||||||
|
exchangeGoogleCodeViaAccounts,
|
||||||
|
refreshGoogleTokenViaAccounts,
|
||||||
|
} from "@/seqta/utils/googleCalendar/accountsToken";
|
||||||
|
import {
|
||||||
|
clearGoogleCalendarState,
|
||||||
|
readGoogleCalendarState,
|
||||||
|
writeGoogleCalendarState,
|
||||||
|
} from "@/seqta/utils/googleCalendar/storage";
|
||||||
|
import {
|
||||||
|
clampSyncWeeks,
|
||||||
|
getAutoSyncWeekly,
|
||||||
|
getSyncWeeksAhead,
|
||||||
|
} from "@/seqta/utils/calendarSync/settings";
|
||||||
|
import {
|
||||||
|
readSharedCalendarSyncSettings,
|
||||||
|
writeSharedCalendarSyncSettings,
|
||||||
|
} from "@/seqta/utils/calendarSync/sharedSettings";
|
||||||
|
import type {
|
||||||
|
GoogleCalendarStatus,
|
||||||
|
GoogleCalendarSyncResult,
|
||||||
|
} from "@/seqta/utils/googleCalendar/types";
|
||||||
|
import { ensureWeeklySyncAlarm, initCalendarBackground } from "./calendarWeekly";
|
||||||
|
|
||||||
|
function base64UrlEncode(buffer: ArrayBuffer): string {
|
||||||
|
const bytes = new Uint8Array(buffer);
|
||||||
|
let binary = "";
|
||||||
|
for (const b of bytes) binary += String.fromCharCode(b);
|
||||||
|
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sha256(input: string): Promise<ArrayBuffer> {
|
||||||
|
const data = new TextEncoder().encode(input);
|
||||||
|
return crypto.subtle.digest("SHA-256", data);
|
||||||
|
}
|
||||||
|
|
||||||
|
function randomVerifier(): string {
|
||||||
|
const bytes = new Uint8Array(32);
|
||||||
|
crypto.getRandomValues(bytes);
|
||||||
|
return base64UrlEncode(bytes.buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pkceChallenge(verifier: string): Promise<string> {
|
||||||
|
return base64UrlEncode(await sha256(verifier));
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseRedirectCode(responseUrl: string): string {
|
||||||
|
const url = new URL(responseUrl);
|
||||||
|
const err = url.searchParams.get("error");
|
||||||
|
if (err) throw new Error(url.searchParams.get("error_description") ?? err);
|
||||||
|
const code = url.searchParams.get("code");
|
||||||
|
if (!code) throw new Error("Google sign-in did not return an authorization code.");
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
const GOOGLE_OAUTH_CALLBACK_PREFIX = GOOGLE_CALENDAR_OAUTH_CALLBACK;
|
||||||
|
const GOOGLE_OAUTH_TIMEOUT_MS = 10 * 60 * 1000;
|
||||||
|
|
||||||
|
function isGoogleOAuthCallbackUrl(url: string): boolean {
|
||||||
|
if (!url.startsWith(GOOGLE_OAUTH_CALLBACK_PREFIX)) return false;
|
||||||
|
const parsed = new URL(url);
|
||||||
|
return parsed.searchParams.has("code") || parsed.searchParams.has("error");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tab-based OAuth (same pattern as cloud login) — launchWebAuthFlow does not reliably return external redirect URLs. */
|
||||||
|
function waitForGoogleOAuthCallback(authTabId: number): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const timeoutId = setTimeout(() => {
|
||||||
|
cleanup();
|
||||||
|
reject(new Error("Google sign-in timed out. Close the tab and try again."));
|
||||||
|
}, GOOGLE_OAUTH_TIMEOUT_MS);
|
||||||
|
|
||||||
|
const cleanup = () => {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
browser.tabs.onUpdated.removeListener(onUpdated);
|
||||||
|
browser.tabs.onRemoved.removeListener(onRemoved);
|
||||||
|
};
|
||||||
|
|
||||||
|
const finishFromUrl = (url: string, tabId: number) => {
|
||||||
|
if (!isGoogleOAuthCallbackUrl(url)) return false;
|
||||||
|
cleanup();
|
||||||
|
void browser.tabs.remove(tabId).catch(() => {});
|
||||||
|
resolve(url);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const onRemoved = (tabId: number) => {
|
||||||
|
if (tabId !== authTabId) return;
|
||||||
|
cleanup();
|
||||||
|
reject(new Error("Google sign-in was cancelled."));
|
||||||
|
};
|
||||||
|
|
||||||
|
const onUpdated = (
|
||||||
|
tabId: number,
|
||||||
|
changeInfo: browser.Tabs.OnUpdatedChangeInfoType,
|
||||||
|
tab: browser.Tabs.Tab,
|
||||||
|
) => {
|
||||||
|
if (tabId !== authTabId) return;
|
||||||
|
const url =
|
||||||
|
changeInfo.url ?? (changeInfo.status === "complete" ? tab.url : undefined);
|
||||||
|
if (url) finishFromUrl(url, tabId);
|
||||||
|
};
|
||||||
|
|
||||||
|
browser.tabs.onUpdated.addListener(onUpdated);
|
||||||
|
browser.tabs.onRemoved.addListener(onRemoved);
|
||||||
|
|
||||||
|
void browser.tabs
|
||||||
|
.get(authTabId)
|
||||||
|
.then((tab) => {
|
||||||
|
if (tab.url) finishFromUrl(tab.url, authTabId);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openGoogleOAuthTab(authUrl: string): Promise<string> {
|
||||||
|
const tab = await browser.tabs.create({ url: authUrl, active: true });
|
||||||
|
if (tab.id === undefined) {
|
||||||
|
throw new Error("Could not open Google sign-in tab.");
|
||||||
|
}
|
||||||
|
return waitForGoogleOAuthCallback(tab.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getValidAccessToken(): Promise<string> {
|
||||||
|
const state = await readGoogleCalendarState();
|
||||||
|
const now = Date.now();
|
||||||
|
if (state.accessToken && state.expiresAt && state.expiresAt > now + 60_000) {
|
||||||
|
return state.accessToken;
|
||||||
|
}
|
||||||
|
if (!state.refreshToken) {
|
||||||
|
throw new Error("Not connected to Google Calendar.");
|
||||||
|
}
|
||||||
|
const refreshed = await refreshGoogleTokenViaAccounts(state.refreshToken);
|
||||||
|
const expiresAt = refreshed.expires_in
|
||||||
|
? Date.now() + refreshed.expires_in * 1000
|
||||||
|
: Date.now() + 3_600_000;
|
||||||
|
await writeGoogleCalendarState({
|
||||||
|
accessToken: refreshed.access_token,
|
||||||
|
refreshToken: refreshed.refresh_token ?? state.refreshToken,
|
||||||
|
expiresAt,
|
||||||
|
});
|
||||||
|
return refreshed.access_token;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function connectGoogleCalendar(): Promise<GoogleCalendarSyncResult> {
|
||||||
|
if (!isGoogleCalendarConfigured()) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
configured: false,
|
||||||
|
error: "Google Calendar is not configured in this extension build.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const redirectUri = GOOGLE_CALENDAR_OAUTH_CALLBACK;
|
||||||
|
const verifier = randomVerifier();
|
||||||
|
const challenge = await pkceChallenge(verifier);
|
||||||
|
const authUrl = new URL(GOOGLE_AUTH_URL);
|
||||||
|
authUrl.searchParams.set("client_id", GOOGLE_OAUTH_CLIENT_ID);
|
||||||
|
authUrl.searchParams.set("response_type", "code");
|
||||||
|
authUrl.searchParams.set("redirect_uri", redirectUri);
|
||||||
|
authUrl.searchParams.set("scope", GOOGLE_CALENDAR_SCOPE);
|
||||||
|
authUrl.searchParams.set("access_type", "offline");
|
||||||
|
authUrl.searchParams.set("prompt", "consent");
|
||||||
|
authUrl.searchParams.set("code_challenge", challenge);
|
||||||
|
authUrl.searchParams.set("code_challenge_method", "S256");
|
||||||
|
|
||||||
|
let responseUrl: string;
|
||||||
|
try {
|
||||||
|
responseUrl = await openGoogleOAuthTab(authUrl.toString());
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : "Google sign-in failed";
|
||||||
|
const mismatch =
|
||||||
|
/redirect_uri_mismatch|invalid_request/i.test(message) ||
|
||||||
|
/redirect_uri_mismatch|invalid_request/i.test(String(err));
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
configured: true,
|
||||||
|
error: mismatch
|
||||||
|
? `Google redirect URI mismatch. ${googleOAuthRedirectUriHint()}`
|
||||||
|
: message.includes("cancel")
|
||||||
|
? "Google sign-in was cancelled."
|
||||||
|
: message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const code = parseRedirectCode(responseUrl);
|
||||||
|
const tokens = await exchangeGoogleCodeViaAccounts(code, redirectUri, verifier);
|
||||||
|
const expiresAt = tokens.expires_in
|
||||||
|
? Date.now() + tokens.expires_in * 1000
|
||||||
|
: Date.now() + 3_600_000;
|
||||||
|
|
||||||
|
const existing = await readGoogleCalendarState();
|
||||||
|
await writeGoogleCalendarState({
|
||||||
|
accessToken: tokens.access_token,
|
||||||
|
refreshToken: tokens.refresh_token ?? existing.refreshToken,
|
||||||
|
expiresAt,
|
||||||
|
connectedAt: Date.now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
await ensureWeeklySyncAlarm();
|
||||||
|
|
||||||
|
return { success: true, configured: true, connected: true };
|
||||||
|
} catch (err) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
configured: true,
|
||||||
|
error: err instanceof Error ? err.message : "Google sign-in failed",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getGoogleCalendarStatus(): Promise<GoogleCalendarStatus> {
|
||||||
|
const state = await readGoogleCalendarState();
|
||||||
|
const shared = await readSharedCalendarSyncSettings();
|
||||||
|
const syncWeeksAhead = await getSyncWeeksAhead();
|
||||||
|
const autoSyncWeekly = await getAutoSyncWeekly();
|
||||||
|
return {
|
||||||
|
configured: isGoogleCalendarConfigured(),
|
||||||
|
connected: !!(state.refreshToken || state.accessToken),
|
||||||
|
lastSyncAt: state.lastSyncAt,
|
||||||
|
lastWeeklySyncAt: shared.lastWeeklySyncAt,
|
||||||
|
lastSyncOrigin: state.lastSyncOrigin,
|
||||||
|
syncWeeksAhead,
|
||||||
|
autoSyncWeekly,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handleGoogleCalendarConnect(): Promise<GoogleCalendarSyncResult> {
|
||||||
|
return connectGoogleCalendar();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handleGoogleCalendarDisconnect(): Promise<{ success: boolean }> {
|
||||||
|
await clearGoogleCalendarState();
|
||||||
|
await ensureWeeklySyncAlarm();
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handleGoogleCalendarStatus(): Promise<GoogleCalendarStatus> {
|
||||||
|
return getGoogleCalendarStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerGoogleCalendarMessageHandlers(
|
||||||
|
handlers: Record<
|
||||||
|
string,
|
||||||
|
(
|
||||||
|
request: unknown,
|
||||||
|
sendResponse: (response?: unknown) => void,
|
||||||
|
sender?: browser.Runtime.MessageSender,
|
||||||
|
) => boolean | void
|
||||||
|
>,
|
||||||
|
isTrustedSender: (sender?: browser.Runtime.MessageSender) => boolean,
|
||||||
|
): void {
|
||||||
|
const rejectUntrusted = (
|
||||||
|
sendResponse: (response?: unknown) => void,
|
||||||
|
sender?: browser.Runtime.MessageSender,
|
||||||
|
): boolean => {
|
||||||
|
if (isTrustedSender(sender)) return false;
|
||||||
|
sendResponse({ success: false, error: "Unauthorized sender" });
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
handlers.googleCalendarConnect = (_req, sendResponse, sender) => {
|
||||||
|
if (rejectUntrusted(sendResponse, sender)) return false;
|
||||||
|
void handleGoogleCalendarConnect()
|
||||||
|
.then(sendResponse)
|
||||||
|
.catch((err) => {
|
||||||
|
sendResponse({
|
||||||
|
success: false,
|
||||||
|
error: err instanceof Error ? err.message : "Google sign-in failed",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
handlers.googleCalendarDisconnect = (_req, sendResponse, sender) => {
|
||||||
|
if (rejectUntrusted(sendResponse, sender)) return false;
|
||||||
|
void handleGoogleCalendarDisconnect()
|
||||||
|
.then(sendResponse)
|
||||||
|
.catch((err) => {
|
||||||
|
sendResponse({
|
||||||
|
success: false,
|
||||||
|
error: err instanceof Error ? err.message : "Disconnect failed",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
handlers.googleCalendarStatus = (_req, sendResponse, sender) => {
|
||||||
|
if (rejectUntrusted(sendResponse, sender)) return false;
|
||||||
|
void handleGoogleCalendarStatus()
|
||||||
|
.then(sendResponse)
|
||||||
|
.catch(() => {
|
||||||
|
sendResponse({ configured: isGoogleCalendarConfigured(), connected: false });
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
handlers.googleCalendarGetAccessToken = (_req, sendResponse, sender) => {
|
||||||
|
if (rejectUntrusted(sendResponse, sender)) return false;
|
||||||
|
void getValidAccessToken()
|
||||||
|
.then((accessToken) => sendResponse({ success: true, accessToken }))
|
||||||
|
.catch((err) => {
|
||||||
|
sendResponse({
|
||||||
|
success: false,
|
||||||
|
error: err instanceof Error ? err.message : "Token refresh failed",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
handlers.googleCalendarEnsureWeeklyAlarm = (_req, sendResponse, sender) => {
|
||||||
|
if (rejectUntrusted(sendResponse, sender)) return false;
|
||||||
|
void ensureWeeklySyncAlarm()
|
||||||
|
.then(() => sendResponse({ success: true }))
|
||||||
|
.catch((err) => {
|
||||||
|
sendResponse({
|
||||||
|
success: false,
|
||||||
|
error: err instanceof Error ? err.message : "Could not schedule weekly sync",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
handlers.googleCalendarUpdateSyncSettings = (request, sendResponse, sender) => {
|
||||||
|
if (rejectUntrusted(sendResponse, sender)) return false;
|
||||||
|
void (async () => {
|
||||||
|
const body = request as {
|
||||||
|
syncWeeksAhead?: number;
|
||||||
|
autoSyncWeekly?: boolean;
|
||||||
|
};
|
||||||
|
const patch: Record<string, unknown> = {};
|
||||||
|
if (body.syncWeeksAhead != null) {
|
||||||
|
patch.syncWeeksAhead = clampSyncWeeks(body.syncWeeksAhead);
|
||||||
|
}
|
||||||
|
if (body.autoSyncWeekly != null) {
|
||||||
|
patch.autoSyncWeekly = !!body.autoSyncWeekly;
|
||||||
|
}
|
||||||
|
if (Object.keys(patch).length > 0) {
|
||||||
|
await writeSharedCalendarSyncSettings(patch);
|
||||||
|
}
|
||||||
|
await ensureWeeklySyncAlarm();
|
||||||
|
sendResponse({ success: true, ...(await getGoogleCalendarStatus()) });
|
||||||
|
})().catch((err) => {
|
||||||
|
sendResponse({
|
||||||
|
success: false,
|
||||||
|
error: err instanceof Error ? err.message : "Could not update sync settings",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export { initCalendarBackground as initGoogleCalendarBackground } from "./calendarWeekly";
|
||||||
@@ -0,0 +1,302 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import {
|
||||||
|
OUTLOOK_AUTH_URL,
|
||||||
|
OUTLOOK_CALENDAR_OAUTH_CALLBACK,
|
||||||
|
OUTLOOK_CALENDAR_SCOPE,
|
||||||
|
OUTLOOK_OAUTH_CLIENT_ID,
|
||||||
|
isOutlookCalendarConfigured,
|
||||||
|
outlookOAuthRedirectUriHint,
|
||||||
|
} from "@/config/outlookCalendar";
|
||||||
|
import {
|
||||||
|
exchangeOutlookCodeViaAccounts,
|
||||||
|
refreshOutlookTokenViaAccounts,
|
||||||
|
} from "@/seqta/utils/outlookCalendar/accountsToken";
|
||||||
|
import {
|
||||||
|
clearOutlookCalendarState,
|
||||||
|
readOutlookCalendarState,
|
||||||
|
writeOutlookCalendarState,
|
||||||
|
} from "@/seqta/utils/outlookCalendar/storage";
|
||||||
|
import type { OutlookCalendarStatus } from "@/seqta/utils/outlookCalendar/types";
|
||||||
|
import type { GoogleCalendarSyncResult } from "@/seqta/utils/googleCalendar/types";
|
||||||
|
import { ensureWeeklySyncAlarm } from "./calendarWeekly";
|
||||||
|
|
||||||
|
function base64UrlEncode(buffer: ArrayBuffer): string {
|
||||||
|
const bytes = new Uint8Array(buffer);
|
||||||
|
let binary = "";
|
||||||
|
for (const b of bytes) binary += String.fromCharCode(b);
|
||||||
|
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sha256(input: string): Promise<ArrayBuffer> {
|
||||||
|
const data = new TextEncoder().encode(input);
|
||||||
|
return crypto.subtle.digest("SHA-256", data);
|
||||||
|
}
|
||||||
|
|
||||||
|
function randomVerifier(): string {
|
||||||
|
const bytes = new Uint8Array(32);
|
||||||
|
crypto.getRandomValues(bytes);
|
||||||
|
return base64UrlEncode(bytes.buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pkceChallenge(verifier: string): Promise<string> {
|
||||||
|
return base64UrlEncode(await sha256(verifier));
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseRedirectCode(responseUrl: string): string {
|
||||||
|
const url = new URL(responseUrl);
|
||||||
|
const err = url.searchParams.get("error");
|
||||||
|
if (err) throw new Error(url.searchParams.get("error_description") ?? err);
|
||||||
|
const code = url.searchParams.get("code");
|
||||||
|
if (!code) throw new Error("Microsoft sign-in did not return an authorization code.");
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
const OAUTH_CALLBACK_PREFIX = OUTLOOK_CALENDAR_OAUTH_CALLBACK;
|
||||||
|
const OAUTH_TIMEOUT_MS = 10 * 60 * 1000;
|
||||||
|
|
||||||
|
function isOAuthCallbackUrl(url: string): boolean {
|
||||||
|
if (!url.startsWith(OAUTH_CALLBACK_PREFIX)) return false;
|
||||||
|
const parsed = new URL(url);
|
||||||
|
return parsed.searchParams.has("code") || parsed.searchParams.has("error");
|
||||||
|
}
|
||||||
|
|
||||||
|
function waitForOAuthCallback(authTabId: number): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const timeoutId = setTimeout(() => {
|
||||||
|
cleanup();
|
||||||
|
reject(new Error("Microsoft sign-in timed out. Close the tab and try again."));
|
||||||
|
}, OAUTH_TIMEOUT_MS);
|
||||||
|
|
||||||
|
const cleanup = () => {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
browser.tabs.onUpdated.removeListener(onUpdated);
|
||||||
|
browser.tabs.onRemoved.removeListener(onRemoved);
|
||||||
|
};
|
||||||
|
|
||||||
|
const finishFromUrl = (url: string, tabId: number) => {
|
||||||
|
if (!isOAuthCallbackUrl(url)) return false;
|
||||||
|
cleanup();
|
||||||
|
void browser.tabs.remove(tabId).catch(() => {});
|
||||||
|
resolve(url);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const onRemoved = (tabId: number) => {
|
||||||
|
if (tabId !== authTabId) return;
|
||||||
|
cleanup();
|
||||||
|
reject(new Error("Microsoft sign-in was cancelled."));
|
||||||
|
};
|
||||||
|
|
||||||
|
const onUpdated = (
|
||||||
|
tabId: number,
|
||||||
|
changeInfo: browser.Tabs.OnUpdatedChangeInfoType,
|
||||||
|
tab: browser.Tabs.Tab,
|
||||||
|
) => {
|
||||||
|
if (tabId !== authTabId) return;
|
||||||
|
const url =
|
||||||
|
changeInfo.url ?? (changeInfo.status === "complete" ? tab.url : undefined);
|
||||||
|
if (url) finishFromUrl(url, tabId);
|
||||||
|
};
|
||||||
|
|
||||||
|
browser.tabs.onUpdated.addListener(onUpdated);
|
||||||
|
browser.tabs.onRemoved.addListener(onRemoved);
|
||||||
|
|
||||||
|
void browser.tabs
|
||||||
|
.get(authTabId)
|
||||||
|
.then((tab) => {
|
||||||
|
if (tab.url) finishFromUrl(tab.url, authTabId);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openOAuthTab(authUrl: string): Promise<string> {
|
||||||
|
const tab = await browser.tabs.create({ url: authUrl, active: true });
|
||||||
|
if (tab.id === undefined) {
|
||||||
|
throw new Error("Could not open Microsoft sign-in tab.");
|
||||||
|
}
|
||||||
|
return waitForOAuthCallback(tab.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getValidAccessToken(): Promise<string> {
|
||||||
|
const state = await readOutlookCalendarState();
|
||||||
|
const now = Date.now();
|
||||||
|
if (state.accessToken && state.expiresAt && state.expiresAt > now + 60_000) {
|
||||||
|
return state.accessToken;
|
||||||
|
}
|
||||||
|
if (!state.refreshToken) {
|
||||||
|
throw new Error("Not connected to Outlook Calendar.");
|
||||||
|
}
|
||||||
|
const refreshed = await refreshOutlookTokenViaAccounts(state.refreshToken);
|
||||||
|
const expiresAt = refreshed.expires_in
|
||||||
|
? Date.now() + refreshed.expires_in * 1000
|
||||||
|
: Date.now() + 3_600_000;
|
||||||
|
await writeOutlookCalendarState({
|
||||||
|
accessToken: refreshed.access_token,
|
||||||
|
refreshToken: refreshed.refresh_token ?? state.refreshToken,
|
||||||
|
expiresAt,
|
||||||
|
});
|
||||||
|
return refreshed.access_token;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function connectOutlookCalendar(): Promise<GoogleCalendarSyncResult> {
|
||||||
|
if (!isOutlookCalendarConfigured()) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
configured: false,
|
||||||
|
error: "Outlook Calendar is not configured in this extension build.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const redirectUri = OUTLOOK_CALENDAR_OAUTH_CALLBACK;
|
||||||
|
const verifier = randomVerifier();
|
||||||
|
const challenge = await pkceChallenge(verifier);
|
||||||
|
const authUrl = new URL(OUTLOOK_AUTH_URL);
|
||||||
|
authUrl.searchParams.set("client_id", OUTLOOK_OAUTH_CLIENT_ID);
|
||||||
|
authUrl.searchParams.set("response_type", "code");
|
||||||
|
authUrl.searchParams.set("redirect_uri", redirectUri);
|
||||||
|
authUrl.searchParams.set("scope", OUTLOOK_CALENDAR_SCOPE);
|
||||||
|
authUrl.searchParams.set("response_mode", "query");
|
||||||
|
authUrl.searchParams.set("prompt", "consent");
|
||||||
|
authUrl.searchParams.set("code_challenge", challenge);
|
||||||
|
authUrl.searchParams.set("code_challenge_method", "S256");
|
||||||
|
|
||||||
|
let responseUrl: string;
|
||||||
|
try {
|
||||||
|
responseUrl = await openOAuthTab(authUrl.toString());
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : "Microsoft sign-in failed";
|
||||||
|
const mismatch =
|
||||||
|
/redirect_uri|invalid_request|AADSTS50011/i.test(message) ||
|
||||||
|
/redirect_uri|invalid_request|AADSTS50011/i.test(String(err));
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
configured: true,
|
||||||
|
error: mismatch
|
||||||
|
? `Microsoft redirect URI mismatch. ${outlookOAuthRedirectUriHint()}`
|
||||||
|
: message.includes("cancel")
|
||||||
|
? "Microsoft sign-in was cancelled."
|
||||||
|
: message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const code = parseRedirectCode(responseUrl);
|
||||||
|
const tokens = await exchangeOutlookCodeViaAccounts(code, redirectUri, verifier);
|
||||||
|
const expiresAt = tokens.expires_in
|
||||||
|
? Date.now() + tokens.expires_in * 1000
|
||||||
|
: Date.now() + 3_600_000;
|
||||||
|
|
||||||
|
const existing = await readOutlookCalendarState();
|
||||||
|
await writeOutlookCalendarState({
|
||||||
|
accessToken: tokens.access_token,
|
||||||
|
refreshToken: tokens.refresh_token ?? existing.refreshToken,
|
||||||
|
expiresAt,
|
||||||
|
connectedAt: Date.now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
await ensureWeeklySyncAlarm();
|
||||||
|
|
||||||
|
return { success: true, configured: true, connected: true };
|
||||||
|
} catch (err) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
configured: true,
|
||||||
|
error: err instanceof Error ? err.message : "Microsoft sign-in failed",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getOutlookCalendarStatus(): Promise<OutlookCalendarStatus> {
|
||||||
|
const state = await readOutlookCalendarState();
|
||||||
|
return {
|
||||||
|
configured: isOutlookCalendarConfigured(),
|
||||||
|
connected: !!(state.refreshToken || state.accessToken),
|
||||||
|
lastSyncAt: state.lastSyncAt,
|
||||||
|
lastSyncOrigin: state.lastSyncOrigin,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handleOutlookCalendarConnect(): Promise<GoogleCalendarSyncResult> {
|
||||||
|
return connectOutlookCalendar();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handleOutlookCalendarDisconnect(): Promise<{ success: boolean }> {
|
||||||
|
await clearOutlookCalendarState();
|
||||||
|
await ensureWeeklySyncAlarm();
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handleOutlookCalendarStatus(): Promise<OutlookCalendarStatus> {
|
||||||
|
return getOutlookCalendarStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerOutlookCalendarMessageHandlers(
|
||||||
|
handlers: Record<
|
||||||
|
string,
|
||||||
|
(
|
||||||
|
request: unknown,
|
||||||
|
sendResponse: (response?: unknown) => void,
|
||||||
|
sender?: browser.Runtime.MessageSender,
|
||||||
|
) => boolean | void
|
||||||
|
>,
|
||||||
|
isTrustedSender: (sender?: browser.Runtime.MessageSender) => boolean,
|
||||||
|
): void {
|
||||||
|
const rejectUntrusted = (
|
||||||
|
sendResponse: (response?: unknown) => void,
|
||||||
|
sender?: browser.Runtime.MessageSender,
|
||||||
|
): boolean => {
|
||||||
|
if (isTrustedSender(sender)) return false;
|
||||||
|
sendResponse({ success: false, error: "Unauthorized sender" });
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
handlers.outlookCalendarConnect = (_req, sendResponse, sender) => {
|
||||||
|
if (rejectUntrusted(sendResponse, sender)) return false;
|
||||||
|
void handleOutlookCalendarConnect()
|
||||||
|
.then(sendResponse)
|
||||||
|
.catch((err) => {
|
||||||
|
sendResponse({
|
||||||
|
success: false,
|
||||||
|
error: err instanceof Error ? err.message : "Microsoft sign-in failed",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
handlers.outlookCalendarDisconnect = (_req, sendResponse, sender) => {
|
||||||
|
if (rejectUntrusted(sendResponse, sender)) return false;
|
||||||
|
void handleOutlookCalendarDisconnect()
|
||||||
|
.then(sendResponse)
|
||||||
|
.catch((err) => {
|
||||||
|
sendResponse({
|
||||||
|
success: false,
|
||||||
|
error: err instanceof Error ? err.message : "Disconnect failed",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
handlers.outlookCalendarStatus = (_req, sendResponse, sender) => {
|
||||||
|
if (rejectUntrusted(sendResponse, sender)) return false;
|
||||||
|
void handleOutlookCalendarStatus()
|
||||||
|
.then(sendResponse)
|
||||||
|
.catch(() => {
|
||||||
|
sendResponse({ configured: isOutlookCalendarConfigured(), connected: false });
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
handlers.outlookCalendarGetAccessToken = (_req, sendResponse, sender) => {
|
||||||
|
if (rejectUntrusted(sendResponse, sender)) return false;
|
||||||
|
void getValidAccessToken()
|
||||||
|
.then((accessToken) => sendResponse({ success: true, accessToken }))
|
||||||
|
.catch((err) => {
|
||||||
|
sendResponse({
|
||||||
|
success: false,
|
||||||
|
error: err instanceof Error ? err.message : "Token refresh failed",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
/**
|
||||||
|
* Google Calendar OAuth — public client config (extension).
|
||||||
|
* Client secret and token exchange live on accounts.betterseqta.org.
|
||||||
|
* See docs/GOOGLE_CALENDAR_ACCOUNTS_CALLBACK.md
|
||||||
|
*/
|
||||||
|
|
||||||
|
const HARDCODED_GOOGLE_OAUTH_CLIENT_ID =
|
||||||
|
"270834969641-f6t7jtpu6j0cemse8updj3rkos7nl0hf.apps.googleusercontent.com";
|
||||||
|
|
||||||
|
const envClientId =
|
||||||
|
typeof __GOOGLE_OAUTH_CLIENT_ID__ !== "undefined" ? __GOOGLE_OAUTH_CLIENT_ID__ : "";
|
||||||
|
|
||||||
|
export const GOOGLE_OAUTH_CLIENT_ID: string =
|
||||||
|
envClientId.trim() || HARDCODED_GOOGLE_OAUTH_CLIENT_ID.trim();
|
||||||
|
|
||||||
|
export const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||||
|
|
||||||
|
/** Must match Google Console + accounts callback route exactly. */
|
||||||
|
export const GOOGLE_CALENDAR_OAUTH_CALLBACK = `${ACCOUNTS_BASE}/auth/google/calendar/callback`;
|
||||||
|
|
||||||
|
export const GOOGLE_CALENDAR_TOKEN_URL = `${ACCOUNTS_BASE}/api/bsplus/google/calendar/token`;
|
||||||
|
export const GOOGLE_CALENDAR_REFRESH_URL = `${ACCOUNTS_BASE}/api/bsplus/google/calendar/refresh`;
|
||||||
|
|
||||||
|
export const GOOGLE_CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar.events";
|
||||||
|
|
||||||
|
export const GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
|
||||||
|
export const GOOGLE_CALENDAR_API = "https://www.googleapis.com/calendar/v3";
|
||||||
|
|
||||||
|
export const BSPLUS_GOOGLE_CALENDAR_EVENT_PROP = "bsplusSeqtaKey";
|
||||||
|
|
||||||
|
/** Default weeks of timetable to sync forward (from start of current week). */
|
||||||
|
export const GOOGLE_CALENDAR_SYNC_WEEKS = 12;
|
||||||
|
export const GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT = GOOGLE_CALENDAR_SYNC_WEEKS;
|
||||||
|
export const GOOGLE_CALENDAR_SYNC_WEEKS_MIN = 1;
|
||||||
|
export const GOOGLE_CALENDAR_SYNC_WEEKS_MAX = 52;
|
||||||
|
|
||||||
|
export function isGoogleCalendarConfigured(): boolean {
|
||||||
|
return GOOGLE_OAUTH_CLIENT_ID.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GOOGLE_CALENDAR_ACCOUNTS_NOT_READY_HINT =
|
||||||
|
"Google Calendar connect requires accounts.betterseqta.org — see docs/GOOGLE_CALENDAR_ACCOUNTS_CALLBACK.md";
|
||||||
|
|
||||||
|
export function googleOAuthRedirectUriHint(): string {
|
||||||
|
return `Authorized redirect URI in Google Cloud Console must be: ${GOOGLE_CALENDAR_OAUTH_CALLBACK}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/**
|
||||||
|
* Outlook Calendar OAuth — public client config (extension).
|
||||||
|
* Client secret and token exchange live on accounts.betterseqta.org.
|
||||||
|
* See docs/OUTLOOK_CALENDAR_ACCOUNTS_CALLBACK.md
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { ACCOUNTS_BASE } from "@/config/googleCalendar";
|
||||||
|
|
||||||
|
const HARDCODED_OUTLOOK_OAUTH_CLIENT_ID =
|
||||||
|
"0b55168c-916c-4323-8f67-b3dd30af3c9e";
|
||||||
|
|
||||||
|
const envClientId =
|
||||||
|
typeof __OUTLOOK_OAUTH_CLIENT_ID__ !== "undefined" ? __OUTLOOK_OAUTH_CLIENT_ID__ : "";
|
||||||
|
|
||||||
|
export const OUTLOOK_OAUTH_CLIENT_ID: string =
|
||||||
|
envClientId.trim() || HARDCODED_OUTLOOK_OAUTH_CLIENT_ID.trim();
|
||||||
|
|
||||||
|
/** Must match Azure app registration + accounts callback route exactly. */
|
||||||
|
export const OUTLOOK_CALENDAR_OAUTH_CALLBACK = `${ACCOUNTS_BASE}/auth/microsoft/calendar/callback`;
|
||||||
|
|
||||||
|
export const OUTLOOK_CALENDAR_TOKEN_URL = `${ACCOUNTS_BASE}/api/bsplus/microsoft/calendar/token`;
|
||||||
|
export const OUTLOOK_CALENDAR_REFRESH_URL = `${ACCOUNTS_BASE}/api/bsplus/microsoft/calendar/refresh`;
|
||||||
|
|
||||||
|
/** Delegated Graph scopes for create/update/delete calendar events. */
|
||||||
|
export const OUTLOOK_CALENDAR_SCOPE = "offline_access Calendars.ReadWrite User.Read";
|
||||||
|
|
||||||
|
export const OUTLOOK_AUTH_URL =
|
||||||
|
"https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
|
||||||
|
|
||||||
|
export const OUTLOOK_GRAPH_API = "https://graph.microsoft.com/v1.0";
|
||||||
|
|
||||||
|
export const BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY = "BetterSEQTA+";
|
||||||
|
|
||||||
|
export function isOutlookCalendarConfigured(): boolean {
|
||||||
|
return OUTLOOK_OAUTH_CLIENT_ID.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const OUTLOOK_CALENDAR_ACCOUNTS_NOT_READY_HINT =
|
||||||
|
"Outlook Calendar connect requires accounts.betterseqta.org — see docs/OUTLOOK_CALENDAR_ACCOUNTS_CALLBACK.md";
|
||||||
|
|
||||||
|
export function outlookOAuthRedirectUriHint(): string {
|
||||||
|
return `Authorized redirect URI in Azure must be: ${OUTLOOK_CALENDAR_OAUTH_CALLBACK}`;
|
||||||
|
}
|
||||||
Vendored
+2
@@ -2,3 +2,5 @@ declare const __ENABLE_GH_RELEASE_UPDATE_CHECK__: boolean;
|
|||||||
declare const __GH_RELEASE_REPO__: string;
|
declare const __GH_RELEASE_REPO__: string;
|
||||||
declare const __UPDATE_CHANNEL__: "stable" | "nightly";
|
declare const __UPDATE_CHANNEL__: "stable" | "nightly";
|
||||||
declare const __BUILD_LABEL__: string;
|
declare const __BUILD_LABEL__: string;
|
||||||
|
declare const __GOOGLE_OAUTH_CLIENT_ID__: string;
|
||||||
|
declare const __OUTLOOK_OAUTH_CLIENT_ID__: string;
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import "./index.css";
|
|||||||
import Settings from "./pages/settings.svelte";
|
import Settings from "./pages/settings.svelte";
|
||||||
import IconFamily from "@/resources/fonts/IconFamily.woff";
|
import IconFamily from "@/resources/fonts/IconFamily.woff";
|
||||||
import browser from "webextension-polyfill";
|
import browser from "webextension-polyfill";
|
||||||
|
import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
|
||||||
import renderSvelte from "./main";
|
import renderSvelte from "./main";
|
||||||
import { initializeSettingsState } from "@/seqta/utils/listeners/SettingsState";
|
import { initializeSettingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
|
|
||||||
@@ -13,7 +14,7 @@ function InjectCustomIcons() {
|
|||||||
style.innerHTML = `
|
style.innerHTML = `
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'IconFamily';
|
font-family: 'IconFamily';
|
||||||
src: url('${browser.runtime.getURL(IconFamily)}') format('woff');
|
src: url('${resolveExtensionAssetUrl(IconFamily)}') format('woff');
|
||||||
font-weight: normal;
|
font-weight: normal;
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
}`;
|
}`;
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { describe, expect, it } from "@jest/globals";
|
||||||
|
import { resolveExtensionAssetUrl } from "./extensionAssetUrl";
|
||||||
|
|
||||||
|
describe("resolveExtensionAssetUrl", () => {
|
||||||
|
it("returns already-resolved extension URLs unchanged", () => {
|
||||||
|
const url =
|
||||||
|
"chrome-extension://abc/assets/IconFamily-B8lopphU.woff";
|
||||||
|
expect(resolveExtensionAssetUrl(url)).toBe(url);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("repairs accidental double extension URL prefix", () => {
|
||||||
|
const doubled =
|
||||||
|
"chrome-extension://abc/chrome-extension://abc/assets/IconFamily-B8lopphU.woff";
|
||||||
|
expect(resolveExtensionAssetUrl(doubled)).toBe(
|
||||||
|
"chrome-extension://abc/assets/IconFamily-B8lopphU.woff",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
|
||||||
|
/** Vite asset imports are often already absolute extension URLs in production bundles. */
|
||||||
|
export function resolveExtensionAssetUrl(importedUrl: string): string {
|
||||||
|
if (!importedUrl) return importedUrl;
|
||||||
|
|
||||||
|
const doublePrefix = importedUrl.match(
|
||||||
|
/^((?:chrome|moz)-extension:\/\/[^/]+)\/\1\/(.+)$/,
|
||||||
|
);
|
||||||
|
if (doublePrefix) {
|
||||||
|
return `${doublePrefix[1]}/${doublePrefix[2]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (/^(chrome-extension|moz-extension|https?|data):/.test(importedUrl)) {
|
||||||
|
return importedUrl;
|
||||||
|
}
|
||||||
|
return browser.runtime.getURL(importedUrl.replace(/^\/+/, ""));
|
||||||
|
}
|
||||||
@@ -15,17 +15,27 @@
|
|||||||
"64": "resources/icons/icon-64.png"
|
"64": "resources/icons/icon-64.png"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"permissions": ["tabs", "notifications", "storage"],
|
"permissions": ["tabs", "notifications", "storage", "identity", "alarms"],
|
||||||
"host_permissions": ["https://newsapi.org/", "https://betterseqta.org/", "https://accounts.betterseqta.org/", "*://*/*"],
|
"host_permissions": [
|
||||||
|
"https://newsapi.org/",
|
||||||
|
"https://betterseqta.org/",
|
||||||
|
"https://accounts.betterseqta.org/",
|
||||||
|
"https://www.googleapis.com/",
|
||||||
|
"https://oauth2.googleapis.com/",
|
||||||
|
"https://graph.microsoft.com/",
|
||||||
|
"https://login.microsoftonline.com/",
|
||||||
|
"*://*/*"
|
||||||
|
],
|
||||||
"background": {
|
"background": {
|
||||||
"service_worker": "background.ts"
|
"service_worker": "background.ts"
|
||||||
},
|
},
|
||||||
"content_security_policy": {
|
"content_security_policy": {
|
||||||
"extension_pages": "script-src 'self'; object-src 'self'; connect-src 'self' http: https: https://betterseqta.org https://accounts.betterseqta.org https://raw.githubusercontent.com https://newsapi.org"
|
"extension_pages": "script-src 'self'; object-src 'self'; connect-src 'self' http: https: https://betterseqta.org https://accounts.betterseqta.org https://raw.githubusercontent.com https://newsapi.org https://www.googleapis.com https://oauth2.googleapis.com https://graph.microsoft.com https://login.microsoftonline.com"
|
||||||
},
|
},
|
||||||
"content_scripts": [
|
"content_scripts": [
|
||||||
{
|
{
|
||||||
"matches": ["*://*/*"],
|
"matches": ["*://*/*"],
|
||||||
|
"exclude_matches": ["*://accounts.betterseqta.org/*"],
|
||||||
"js": ["SEQTA.ts"],
|
"js": ["SEQTA.ts"],
|
||||||
"run_at": "document_start"
|
"run_at": "document_start"
|
||||||
}
|
}
|
||||||
@@ -36,7 +46,8 @@
|
|||||||
"resources/icons/*",
|
"resources/icons/*",
|
||||||
"resources/update-image.webp",
|
"resources/update-image.webp",
|
||||||
"resources/pdfjs/pdf.worker.min.mjs",
|
"resources/pdfjs/pdf.worker.min.mjs",
|
||||||
"resources/pdfjs/pdf.legacy.min.mjs"
|
"resources/pdfjs/pdf.legacy.min.mjs",
|
||||||
|
"assets/*"
|
||||||
],
|
],
|
||||||
"matches": ["*://*/*"]
|
"matches": ["*://*/*"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { fade } from "svelte/transition";
|
||||||
|
|
||||||
|
let {
|
||||||
|
open = false,
|
||||||
|
busy = false,
|
||||||
|
providerLabel = "Google",
|
||||||
|
onConfirm,
|
||||||
|
onCancel,
|
||||||
|
} = $props<{
|
||||||
|
open?: boolean;
|
||||||
|
busy?: boolean;
|
||||||
|
providerLabel?: string;
|
||||||
|
onConfirm: () => void | Promise<void>;
|
||||||
|
onCancel: () => void;
|
||||||
|
}>();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if open}
|
||||||
|
<div
|
||||||
|
class="bsplus-cal-modal-backdrop"
|
||||||
|
onclick={(e) => {
|
||||||
|
if (e.target === e.currentTarget && !busy) onCancel();
|
||||||
|
}}
|
||||||
|
onkeydown={(e) => {
|
||||||
|
if (e.key === "Escape" && !busy) onCancel();
|
||||||
|
}}
|
||||||
|
role="presentation"
|
||||||
|
transition:fade={{ duration: 150 }}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="bsplus-cal-modal"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby="bsplus-cal-delete-title"
|
||||||
|
transition:fade={{ duration: 180 }}
|
||||||
|
>
|
||||||
|
<h2 id="bsplus-cal-delete-title" class="bsplus-cal-modal-title">
|
||||||
|
Remove synced events?
|
||||||
|
</h2>
|
||||||
|
<p class="bsplus-cal-modal-body">
|
||||||
|
This removes all BetterSEQTA+ timetable events from your {providerLabel} Calendar for this school.
|
||||||
|
Your connection stays active — you can sync again later.
|
||||||
|
</p>
|
||||||
|
<div class="bsplus-cal-modal-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-btn bsplus-cal-btn--ghost"
|
||||||
|
disabled={busy}
|
||||||
|
onclick={onCancel}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-btn bsplus-cal-btn--danger"
|
||||||
|
disabled={busy}
|
||||||
|
onclick={() => void onConfirm()}
|
||||||
|
>
|
||||||
|
{busy ? "Removing…" : "Remove from calendar"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.bsplus-cal-modal-backdrop {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 2147483647;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 16px;
|
||||||
|
background: rgba(0, 0, 0, 0.5);
|
||||||
|
backdrop-filter: blur(4px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-modal {
|
||||||
|
width: min(100%, 400px);
|
||||||
|
padding: 20px;
|
||||||
|
border-radius: 16px;
|
||||||
|
background: var(--bsplus-cal-surface, #fff);
|
||||||
|
color: var(--bsplus-cal-text, #111);
|
||||||
|
box-shadow: 0 24px 48px rgba(0, 0, 0, 0.22);
|
||||||
|
border: 1px solid color-mix(in srgb, var(--bsplus-cal-text, #111) 12%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-modal-title {
|
||||||
|
margin: 0 0 8px;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-modal-body {
|
||||||
|
margin: 0 0 20px;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: color-mix(in srgb, var(--bsplus-cal-text, #111) 72%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-modal-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-btn {
|
||||||
|
padding: 8px 14px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 10px;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-btn:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-btn--ghost {
|
||||||
|
background: color-mix(in srgb, var(--bsplus-cal-text, #111) 8%, transparent);
|
||||||
|
color: var(--bsplus-cal-text, #111);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-btn--ghost:hover:not(:disabled) {
|
||||||
|
background: color-mix(in srgb, var(--bsplus-cal-text, #111) 14%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-btn--danger {
|
||||||
|
background: #dc2626;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-btn--danger:hover:not(:disabled) {
|
||||||
|
background: #b91c1c;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { fade } from "svelte/transition";
|
||||||
|
|
||||||
|
let {
|
||||||
|
open = false,
|
||||||
|
busy = false,
|
||||||
|
providerLabel = "Google",
|
||||||
|
onConfirm,
|
||||||
|
onCancel,
|
||||||
|
} = $props<{
|
||||||
|
open?: boolean;
|
||||||
|
busy?: boolean;
|
||||||
|
providerLabel?: string;
|
||||||
|
onConfirm: () => void | Promise<void>;
|
||||||
|
onCancel: () => void;
|
||||||
|
}>();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if open}
|
||||||
|
<div
|
||||||
|
class="bsplus-cal-modal-backdrop"
|
||||||
|
onclick={(e) => {
|
||||||
|
if (e.target === e.currentTarget && !busy) onCancel();
|
||||||
|
}}
|
||||||
|
onkeydown={(e) => {
|
||||||
|
if (e.key === "Escape" && !busy) onCancel();
|
||||||
|
}}
|
||||||
|
role="presentation"
|
||||||
|
transition:fade={{ duration: 150 }}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="bsplus-cal-modal"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby="bsplus-cal-disconnect-title"
|
||||||
|
transition:fade={{ duration: 180 }}
|
||||||
|
>
|
||||||
|
<h2 id="bsplus-cal-disconnect-title" class="bsplus-cal-modal-title">
|
||||||
|
Disconnect {providerLabel} Calendar?
|
||||||
|
</h2>
|
||||||
|
<p class="bsplus-cal-modal-body">
|
||||||
|
Your synced timetable events will stay in {providerLabel} Calendar, but BetterSEQTA+ will stop
|
||||||
|
updating them until you connect again.
|
||||||
|
</p>
|
||||||
|
<div class="bsplus-cal-modal-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-btn bsplus-cal-btn--ghost"
|
||||||
|
disabled={busy}
|
||||||
|
onclick={onCancel}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-btn bsplus-cal-btn--danger"
|
||||||
|
disabled={busy}
|
||||||
|
onclick={() => void onConfirm()}
|
||||||
|
>
|
||||||
|
{busy ? "Disconnecting…" : "Disconnect"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.bsplus-cal-modal-backdrop {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 2147483647;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 16px;
|
||||||
|
background: rgba(0, 0, 0, 0.5);
|
||||||
|
backdrop-filter: blur(4px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-modal {
|
||||||
|
width: min(100%, 400px);
|
||||||
|
padding: 20px;
|
||||||
|
border-radius: 16px;
|
||||||
|
background: var(--bsplus-cal-surface, #fff);
|
||||||
|
color: var(--bsplus-cal-text, #111);
|
||||||
|
box-shadow: 0 24px 48px rgba(0, 0, 0, 0.22);
|
||||||
|
border: 1px solid color-mix(in srgb, var(--bsplus-cal-text, #111) 12%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-modal-title {
|
||||||
|
margin: 0 0 8px;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-modal-body {
|
||||||
|
margin: 0 0 20px;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: color-mix(in srgb, var(--bsplus-cal-text, #111) 72%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-modal-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-btn {
|
||||||
|
padding: 8px 14px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 10px;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-btn:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-btn--ghost {
|
||||||
|
background: color-mix(in srgb, var(--bsplus-cal-text, #111) 8%, transparent);
|
||||||
|
color: var(--bsplus-cal-text, #111);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-btn--ghost:hover:not(:disabled) {
|
||||||
|
background: color-mix(in srgb, var(--bsplus-cal-text, #111) 14%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-btn--danger {
|
||||||
|
background: #dc2626;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-btn--danger:hover:not(:disabled) {
|
||||||
|
background: #b91c1c;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,946 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from "svelte";
|
||||||
|
import { fade, fly } from "svelte/transition";
|
||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import {
|
||||||
|
GOOGLE_CALENDAR_SYNC_WEEKS_MAX,
|
||||||
|
GOOGLE_CALENDAR_SYNC_WEEKS_MIN,
|
||||||
|
} from "@/config/googleCalendar";
|
||||||
|
import { maybeRunDueWeeklySync } from "@/seqta/utils/googleCalendar/calendarSyncListener";
|
||||||
|
import { deleteSyncedEventsFromGoogleCalendar } from "@/seqta/utils/googleCalendar/syncEngine";
|
||||||
|
import {
|
||||||
|
formatOutlookSyncResultMessage,
|
||||||
|
runOutlookCalendarSync,
|
||||||
|
} from "@/seqta/utils/outlookCalendar/syncRunner";
|
||||||
|
import {
|
||||||
|
formatSyncResultMessage,
|
||||||
|
runGoogleCalendarSync,
|
||||||
|
} from "@/seqta/utils/googleCalendar/syncRunner";
|
||||||
|
import type {
|
||||||
|
GoogleCalendarStatus,
|
||||||
|
GoogleCalendarSyncProgress,
|
||||||
|
GoogleCalendarSyncResult,
|
||||||
|
} from "@/seqta/utils/googleCalendar/types";
|
||||||
|
import type { OutlookCalendarStatus } from "@/seqta/utils/outlookCalendar/types";
|
||||||
|
import { deleteSyncedEventsFromOutlookCalendar } from "@/seqta/utils/outlookCalendar/syncEngine";
|
||||||
|
import CalendarDeleteEventsModal from "./CalendarDeleteEventsModal.svelte";
|
||||||
|
import CalendarDisconnectModal from "./CalendarDisconnectModal.svelte";
|
||||||
|
import CalendarSyncProgress from "./CalendarSyncProgress.svelte";
|
||||||
|
import OutlookCalendarIcon from "./OutlookCalendarIcon.svelte";
|
||||||
|
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
|
import { syncCalendarSyncTheme } from "./calendarSyncTheme";
|
||||||
|
|
||||||
|
type CalendarProvider = "google" | "outlook";
|
||||||
|
type BusyPhase = "connect" | "sync" | "delete" | "disconnect" | null;
|
||||||
|
type BusyState = { provider: CalendarProvider; phase: BusyPhase } | null;
|
||||||
|
|
||||||
|
let googleStatus = $state<GoogleCalendarStatus>({ configured: true, connected: false });
|
||||||
|
let outlookStatus = $state<OutlookCalendarStatus>({ configured: true, connected: false });
|
||||||
|
let busy = $state<BusyState>(null);
|
||||||
|
let menuOpen = $state(false);
|
||||||
|
let modalProvider = $state<CalendarProvider | null>(null);
|
||||||
|
let showDisconnect = $state(false);
|
||||||
|
let showDeleteEvents = $state(false);
|
||||||
|
let toast = $state<{ message: string; error: boolean } | null>(null);
|
||||||
|
let syncProgress = $state<GoogleCalendarSyncProgress | null>(null);
|
||||||
|
let syncWeeksAhead = $state(12);
|
||||||
|
let autoSyncWeekly = $state(true);
|
||||||
|
|
||||||
|
let rootEl = $state<HTMLDivElement | null>(null);
|
||||||
|
let triggerEl = $state<HTMLButtonElement | null>(null);
|
||||||
|
let menuEl = $state<HTMLDivElement | null>(null);
|
||||||
|
let menuStyle = $state("");
|
||||||
|
let toastTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
|
const isBusy = $derived(busy !== null);
|
||||||
|
const anyConnected = $derived(googleStatus.connected || outlookStatus.connected);
|
||||||
|
const accent = "var(--bsplus-cal-accent, var(--better-main, #3b82f6))";
|
||||||
|
|
||||||
|
function isProviderBusy(provider: CalendarProvider): boolean {
|
||||||
|
return busy?.provider === provider;
|
||||||
|
}
|
||||||
|
|
||||||
|
function providerPhase(provider: CalendarProvider): BusyPhase {
|
||||||
|
return busy?.provider === provider ? busy.phase : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function showToastMessage(message: string, isError = false) {
|
||||||
|
toast = { message, error: isError };
|
||||||
|
if (toastTimer) clearTimeout(toastTimer);
|
||||||
|
toastTimer = setTimeout(() => {
|
||||||
|
toast = null;
|
||||||
|
}, 4500);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshStatus() {
|
||||||
|
const [google, outlook] = await Promise.all([
|
||||||
|
browser.runtime.sendMessage({ type: "googleCalendarStatus" }) as Promise<GoogleCalendarStatus>,
|
||||||
|
browser.runtime.sendMessage({ type: "outlookCalendarStatus" }) as Promise<OutlookCalendarStatus>,
|
||||||
|
]);
|
||||||
|
googleStatus = google;
|
||||||
|
outlookStatus = outlook;
|
||||||
|
syncWeeksAhead = google.syncWeeksAhead ?? 12;
|
||||||
|
autoSyncWeekly = google.autoSyncWeekly !== false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getAccessToken(provider: CalendarProvider): Promise<string> {
|
||||||
|
const messageType =
|
||||||
|
provider === "google" ? "googleCalendarGetAccessToken" : "outlookCalendarGetAccessToken";
|
||||||
|
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 ?? "Could not get calendar access token.");
|
||||||
|
}
|
||||||
|
return res.accessToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSyncProgress(progress: GoogleCalendarSyncProgress) {
|
||||||
|
syncProgress = progress;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveSyncSettings(patch: {
|
||||||
|
syncWeeksAhead?: number;
|
||||||
|
autoSyncWeekly?: boolean;
|
||||||
|
}) {
|
||||||
|
const result = (await browser.runtime.sendMessage({
|
||||||
|
type: "googleCalendarUpdateSyncSettings",
|
||||||
|
...patch,
|
||||||
|
})) as GoogleCalendarStatus & { success?: boolean };
|
||||||
|
if (result.syncWeeksAhead != null) syncWeeksAhead = result.syncWeeksAhead;
|
||||||
|
if (result.autoSyncWeekly != null) autoSyncWeekly = result.autoSyncWeekly;
|
||||||
|
googleStatus = { ...googleStatus, ...result };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function performSync(
|
||||||
|
provider: CalendarProvider,
|
||||||
|
mode: "full" | "incremental" = "full",
|
||||||
|
): Promise<boolean> {
|
||||||
|
const run = provider === "google" ? runGoogleCalendarSync : runOutlookCalendarSync;
|
||||||
|
const format = provider === "google" ? formatSyncResultMessage : formatOutlookSyncResultMessage;
|
||||||
|
|
||||||
|
const result = await run({ mode, onProgress: handleSyncProgress });
|
||||||
|
syncProgress = null;
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
showToastMessage(result.error ?? "Calendar sync failed.", true);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (provider === "google") {
|
||||||
|
googleStatus = {
|
||||||
|
...googleStatus,
|
||||||
|
connected: true,
|
||||||
|
lastSyncAt: result.lastSyncAt ?? googleStatus.lastSyncAt,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
outlookStatus = {
|
||||||
|
...outlookStatus,
|
||||||
|
connected: true,
|
||||||
|
lastSyncAt: result.lastSyncAt ?? outlookStatus.lastSyncAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
showToastMessage(format(result));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function connectProvider(provider: CalendarProvider) {
|
||||||
|
const status = provider === "google" ? googleStatus : outlookStatus;
|
||||||
|
if (!status.configured || isBusy) return;
|
||||||
|
menuOpen = true;
|
||||||
|
busy = { provider, phase: "connect" };
|
||||||
|
const connectType =
|
||||||
|
provider === "google" ? "googleCalendarConnect" : "outlookCalendarConnect";
|
||||||
|
try {
|
||||||
|
const result = (await browser.runtime.sendMessage({
|
||||||
|
type: connectType,
|
||||||
|
})) as GoogleCalendarSyncResult;
|
||||||
|
if (!result.success) {
|
||||||
|
const label = provider === "google" ? "Google" : "Outlook";
|
||||||
|
showToastMessage(result.error ?? `Could not connect to ${label} Calendar.`, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (provider === "google") {
|
||||||
|
googleStatus = { ...googleStatus, connected: true };
|
||||||
|
} else {
|
||||||
|
outlookStatus = { ...outlookStatus, connected: true };
|
||||||
|
}
|
||||||
|
busy = { provider, phase: "sync" };
|
||||||
|
await performSync(provider);
|
||||||
|
} catch (err) {
|
||||||
|
showToastMessage(err instanceof Error ? err.message : "Could not connect.", true);
|
||||||
|
} finally {
|
||||||
|
syncProgress = null;
|
||||||
|
busy = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function syncProvider(provider: CalendarProvider) {
|
||||||
|
const status = provider === "google" ? googleStatus : outlookStatus;
|
||||||
|
if (!status.configured || isBusy) return;
|
||||||
|
if (!status.connected) {
|
||||||
|
await connectProvider(provider);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
busy = { provider, phase: "sync" };
|
||||||
|
try {
|
||||||
|
await performSync(provider);
|
||||||
|
} catch (err) {
|
||||||
|
showToastMessage(err instanceof Error ? err.message : "Calendar sync failed.", true);
|
||||||
|
} finally {
|
||||||
|
syncProgress = null;
|
||||||
|
busy = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmDeleteEvents() {
|
||||||
|
if (isBusy || !modalProvider) return;
|
||||||
|
const provider = modalProvider;
|
||||||
|
busy = { provider, phase: "delete" };
|
||||||
|
syncProgress = {
|
||||||
|
phase: "preparing",
|
||||||
|
current: 0,
|
||||||
|
total: 1,
|
||||||
|
message: "Preparing removal…",
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const deleteFn =
|
||||||
|
provider === "google"
|
||||||
|
? deleteSyncedEventsFromGoogleCalendar
|
||||||
|
: deleteSyncedEventsFromOutlookCalendar;
|
||||||
|
const result = await deleteFn(location.origin, () => getAccessToken(provider), {
|
||||||
|
onProgress: handleSyncProgress,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
showToastMessage(result.error ?? "Could not remove calendar events.", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const removed = result.deleted ?? 0;
|
||||||
|
showDeleteEvents = false;
|
||||||
|
menuOpen = false;
|
||||||
|
modalProvider = null;
|
||||||
|
if (removed === 0) {
|
||||||
|
showToastMessage("No synced events to remove.");
|
||||||
|
} else {
|
||||||
|
showToastMessage(`Removed ${removed} event${removed === 1 ? "" : "s"} from Google Calendar.`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
showToastMessage(err instanceof Error ? err.message : "Remove failed.", true);
|
||||||
|
} finally {
|
||||||
|
syncProgress = null;
|
||||||
|
busy = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onWeeksAheadChange(event: Event) {
|
||||||
|
const value = Number((event.currentTarget as HTMLInputElement).value);
|
||||||
|
if (!Number.isFinite(value)) return;
|
||||||
|
await saveSyncSettings({ syncWeeksAhead: value });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onAutoSyncToggle(event: Event) {
|
||||||
|
const checked = (event.currentTarget as HTMLInputElement).checked;
|
||||||
|
autoSyncWeekly = checked;
|
||||||
|
await saveSyncSettings({ autoSyncWeekly: checked });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmDisconnect() {
|
||||||
|
if (isBusy || !modalProvider) return;
|
||||||
|
const provider = modalProvider;
|
||||||
|
busy = { provider, phase: "disconnect" };
|
||||||
|
const disconnectType =
|
||||||
|
provider === "google" ? "googleCalendarDisconnect" : "outlookCalendarDisconnect";
|
||||||
|
const label = provider === "google" ? "Google" : "Outlook";
|
||||||
|
try {
|
||||||
|
const result = (await browser.runtime.sendMessage({
|
||||||
|
type: disconnectType,
|
||||||
|
})) as { success?: boolean };
|
||||||
|
if (!result?.success) {
|
||||||
|
showToastMessage(`Could not disconnect ${label} Calendar.`, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (provider === "google") {
|
||||||
|
googleStatus = { ...googleStatus, connected: false, lastSyncAt: undefined };
|
||||||
|
} else {
|
||||||
|
outlookStatus = { ...outlookStatus, connected: false, lastSyncAt: undefined };
|
||||||
|
}
|
||||||
|
showDisconnect = false;
|
||||||
|
menuOpen = false;
|
||||||
|
modalProvider = null;
|
||||||
|
showToastMessage(`Disconnected from ${label} Calendar.`);
|
||||||
|
} catch (err) {
|
||||||
|
showToastMessage(err instanceof Error ? err.message : "Disconnect failed.", true);
|
||||||
|
} finally {
|
||||||
|
busy = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleMenu() {
|
||||||
|
if (isBusy) return;
|
||||||
|
menuOpen = !menuOpen;
|
||||||
|
if (menuOpen) {
|
||||||
|
queueMicrotask(() => syncMenuTheme());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatLastSync(ts?: number): string | null {
|
||||||
|
if (!ts) return null;
|
||||||
|
const diff = Date.now() - ts;
|
||||||
|
if (diff < 60_000) return "Synced just now";
|
||||||
|
if (diff < 3_600_000) return `Synced ${Math.floor(diff / 60_000)}m ago`;
|
||||||
|
if (diff < 86_400_000) return `Synced ${Math.floor(diff / 3_600_000)}h ago`;
|
||||||
|
return `Synced ${new Date(ts).toLocaleDateString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateMenuPosition() {
|
||||||
|
if (!triggerEl) return;
|
||||||
|
const rect = triggerEl.getBoundingClientRect();
|
||||||
|
menuStyle = `top:${rect.bottom + 8}px;right:${window.innerWidth - rect.right}px;`;
|
||||||
|
syncMenuTheme();
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncMenuTheme() {
|
||||||
|
if (!menuEl) return;
|
||||||
|
syncCalendarSyncTheme(menuEl);
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncMountedTheme() {
|
||||||
|
const themeHost = rootEl?.closest(".bsplus-calendar-sync-mount") as HTMLElement | null;
|
||||||
|
if (themeHost) syncCalendarSyncTheme(themeHost);
|
||||||
|
if (menuOpen) syncMenuTheme();
|
||||||
|
}
|
||||||
|
|
||||||
|
function portalMenu(node: HTMLElement) {
|
||||||
|
document.body.appendChild(node);
|
||||||
|
return {
|
||||||
|
destroy() {
|
||||||
|
node.remove();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
const host = rootEl?.closest(".timetable-calendar-controls");
|
||||||
|
host?.classList.toggle("bsplus-cal-menu-open", menuOpen);
|
||||||
|
return () => host?.classList.remove("bsplus-cal-menu-open");
|
||||||
|
});
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (!menuOpen || !menuEl) return;
|
||||||
|
syncMenuTheme();
|
||||||
|
updateMenuPosition();
|
||||||
|
const onLayout = () => updateMenuPosition();
|
||||||
|
window.addEventListener("resize", onLayout);
|
||||||
|
window.addEventListener("scroll", onLayout, true);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("resize", onLayout);
|
||||||
|
window.removeEventListener("scroll", onLayout, true);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
void refreshStatus().then(() => {
|
||||||
|
void maybeRunDueWeeklySync((message, isError) => {
|
||||||
|
showToastMessage(message, isError);
|
||||||
|
void refreshStatus();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const themeKeys = [
|
||||||
|
"selectedColor",
|
||||||
|
"selectedFont",
|
||||||
|
"DarkMode",
|
||||||
|
"adaptiveThemeColour",
|
||||||
|
"adaptiveThemeGradient",
|
||||||
|
"selectedTheme",
|
||||||
|
] as const;
|
||||||
|
const onThemeChange = () => syncMountedTheme();
|
||||||
|
for (const key of themeKeys) {
|
||||||
|
settingsState.register(key, onThemeChange);
|
||||||
|
}
|
||||||
|
|
||||||
|
const themeObserver = new MutationObserver(onThemeChange);
|
||||||
|
themeObserver.observe(document.documentElement, {
|
||||||
|
attributes: true,
|
||||||
|
attributeFilter: ["style", "class"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const onDocPointer = (event: PointerEvent) => {
|
||||||
|
if (!menuOpen) return;
|
||||||
|
const target = event.target as Node;
|
||||||
|
if (rootEl?.contains(target)) return;
|
||||||
|
if (menuEl?.contains(target)) return;
|
||||||
|
menuOpen = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener("pointerdown", onDocPointer);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("pointerdown", onDocPointer);
|
||||||
|
for (const key of themeKeys) {
|
||||||
|
settingsState.unregister(key, onThemeChange);
|
||||||
|
}
|
||||||
|
themeObserver.disconnect();
|
||||||
|
if (toastTimer) clearTimeout(toastTimer);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="bsplus-cal-sync" bind:this={rootEl}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="uiButton bsplus-cal-trigger"
|
||||||
|
bind:this={triggerEl}
|
||||||
|
class:bsplus-cal-trigger--open={menuOpen}
|
||||||
|
class:bsplus-cal-trigger--connected={anyConnected}
|
||||||
|
class:bsplus-cal-trigger--busy={isBusy}
|
||||||
|
aria-haspopup="menu"
|
||||||
|
aria-expanded={menuOpen}
|
||||||
|
aria-busy={isBusy}
|
||||||
|
aria-label={anyConnected ? "Calendar sync options" : "Sync with Calendar"}
|
||||||
|
onclick={() => {
|
||||||
|
if (!isBusy) toggleMenu();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span class="bsplus-cal-trigger-icon iconFamily" aria-hidden="true"></span>
|
||||||
|
<span class="bsplus-cal-trigger-text">Sync with Calendar</span>
|
||||||
|
{#if anyConnected}
|
||||||
|
<span class="bsplus-cal-status-dot" aria-hidden="true"></span>
|
||||||
|
{/if}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{#if menuOpen}
|
||||||
|
<div
|
||||||
|
class="bsplus-cal-menu"
|
||||||
|
role="menu"
|
||||||
|
bind:this={menuEl}
|
||||||
|
style={menuStyle}
|
||||||
|
use:portalMenu
|
||||||
|
transition:fly={{ y: -6, duration: 160 }}
|
||||||
|
>
|
||||||
|
<div class="bsplus-cal-menu-header">
|
||||||
|
<span class="bsplus-cal-menu-title">Calendar sync</span>
|
||||||
|
<span class="bsplus-cal-menu-sub">Connect providers to sync your timetable</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="bsplus-cal-provider" role="none">
|
||||||
|
<div class="bsplus-cal-provider-row">
|
||||||
|
<span class="bsplus-cal-provider-icon" aria-hidden="true">
|
||||||
|
<svg viewBox="0 0 24 24">
|
||||||
|
<path
|
||||||
|
fill="#4285F4"
|
||||||
|
d="M22 12c0-.96-.08-1.88-.24-2.76H12v5.22h5.68c-.24 1.28-.96 2.44-2.04 3.18v2.64h3.3c1.92-1.76 3.06-4.36 3.06-7.28z"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
fill="#34A853"
|
||||||
|
d="M12 22c2.76 0 5.08-.92 6.78-2.5l-3.3-2.64c-.92.62-2.1.98-3.48.98-2.68 0-4.96-1.8-5.78-4.22H2.18v2.72A10 10 0 0 0 12 22z"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
fill="#FBBC05"
|
||||||
|
d="M6.22 13.62A5.98 5.98 0 0 1 5.82 12c0-.56.1-1.1.28-1.62V7.66H2.18A10 10 0 0 0 2 12c0 1.62.38 3.16 1.06 4.52l3.16-2.9z"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
fill="#EA4335"
|
||||||
|
d="M12 5.38c1.5 0 2.84.52 3.9 1.54l2.92-2.92C17.08 2.34 14.76 1.2 12 1.2 7.54 1.2 3.72 3.94 2.18 7.66l4.04 3.14c.82-2.42 3.1-4.22 5.78-4.22z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
<div class="bsplus-cal-provider-copy">
|
||||||
|
<span class="bsplus-cal-provider-name">
|
||||||
|
<span class="bsplus-google-word bsplus-google-word--sm">
|
||||||
|
<span class="bsplus-google-g">G</span><span class="bsplus-google-o1">o</span><span class="bsplus-google-o2">o</span><span class="bsplus-google-g2">g</span><span class="bsplus-google-l">l</span><span class="bsplus-google-e">e</span>
|
||||||
|
</span>
|
||||||
|
<span> Calendar</span>
|
||||||
|
</span>
|
||||||
|
<span class="bsplus-cal-provider-status">
|
||||||
|
{#if !googleStatus.configured}
|
||||||
|
Not available in this build
|
||||||
|
{:else if googleStatus.connected}
|
||||||
|
Connected{formatLastSync(googleStatus.lastSyncAt) ? ` · ${formatLastSync(googleStatus.lastSyncAt)}` : ""}
|
||||||
|
{:else}
|
||||||
|
Not connected
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="bsplus-cal-provider-actions">
|
||||||
|
{#if !googleStatus.connected}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-action bsplus-cal-action--primary"
|
||||||
|
style:--bsplus-cal-accent={accent}
|
||||||
|
role="menuitem"
|
||||||
|
disabled={!googleStatus.configured || isBusy}
|
||||||
|
onclick={() => void connectProvider("google")}
|
||||||
|
>
|
||||||
|
{providerPhase("google") === "connect" ? "Connecting…" : "Connect"}
|
||||||
|
</button>
|
||||||
|
{:else}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-action bsplus-cal-action--primary"
|
||||||
|
style:--bsplus-cal-accent={accent}
|
||||||
|
role="menuitem"
|
||||||
|
disabled={isBusy}
|
||||||
|
onclick={() => void syncProvider("google")}
|
||||||
|
>
|
||||||
|
{providerPhase("google") === "sync" ? "Syncing…" : "Sync now"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-action bsplus-cal-action--ghost"
|
||||||
|
role="menuitem"
|
||||||
|
disabled={isBusy}
|
||||||
|
onclick={() => {
|
||||||
|
modalProvider = "google";
|
||||||
|
showDeleteEvents = true;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{providerPhase("google") === "delete" ? "Removing…" : "Remove from calendar"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-action bsplus-cal-action--ghost"
|
||||||
|
role="menuitem"
|
||||||
|
disabled={isBusy}
|
||||||
|
onclick={() => {
|
||||||
|
modalProvider = "google";
|
||||||
|
showDisconnect = true;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Disconnect
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="bsplus-cal-provider" role="none">
|
||||||
|
<div class="bsplus-cal-provider-row">
|
||||||
|
<span class="bsplus-cal-provider-icon" aria-hidden="true">
|
||||||
|
<OutlookCalendarIcon />
|
||||||
|
</span>
|
||||||
|
<div class="bsplus-cal-provider-copy">
|
||||||
|
<span class="bsplus-cal-provider-name">Outlook Calendar</span>
|
||||||
|
<span class="bsplus-cal-provider-status">
|
||||||
|
{#if !outlookStatus.configured}
|
||||||
|
Set OUTLOOK_OAUTH_CLIENT_ID to enable
|
||||||
|
{:else if outlookStatus.connected}
|
||||||
|
Connected{formatLastSync(outlookStatus.lastSyncAt) ? ` · ${formatLastSync(outlookStatus.lastSyncAt)}` : ""}
|
||||||
|
{:else}
|
||||||
|
Not connected
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="bsplus-cal-provider-actions">
|
||||||
|
{#if !outlookStatus.connected}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-action bsplus-cal-action--primary"
|
||||||
|
style:--bsplus-cal-accent={accent}
|
||||||
|
role="menuitem"
|
||||||
|
disabled={!outlookStatus.configured || isBusy}
|
||||||
|
onclick={() => void connectProvider("outlook")}
|
||||||
|
>
|
||||||
|
{providerPhase("outlook") === "connect" ? "Connecting…" : "Connect"}
|
||||||
|
</button>
|
||||||
|
{:else}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-action bsplus-cal-action--primary"
|
||||||
|
style:--bsplus-cal-accent={accent}
|
||||||
|
role="menuitem"
|
||||||
|
disabled={isBusy}
|
||||||
|
onclick={() => void syncProvider("outlook")}
|
||||||
|
>
|
||||||
|
{providerPhase("outlook") === "sync" ? "Syncing…" : "Sync now"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-action bsplus-cal-action--ghost"
|
||||||
|
role="menuitem"
|
||||||
|
disabled={isBusy}
|
||||||
|
onclick={() => {
|
||||||
|
modalProvider = "outlook";
|
||||||
|
showDeleteEvents = true;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{providerPhase("outlook") === "delete" ? "Removing…" : "Remove from calendar"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-action bsplus-cal-action--ghost"
|
||||||
|
role="menuitem"
|
||||||
|
disabled={isBusy}
|
||||||
|
onclick={() => {
|
||||||
|
modalProvider = "outlook";
|
||||||
|
showDisconnect = true;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Disconnect
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if anyConnected}
|
||||||
|
<div class="bsplus-cal-settings" role="group" aria-label="Sync settings">
|
||||||
|
<label class="bsplus-cal-setting">
|
||||||
|
<span class="bsplus-cal-setting-label">Weeks ahead</span>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
class="bsplus-cal-setting-input"
|
||||||
|
min={GOOGLE_CALENDAR_SYNC_WEEKS_MIN}
|
||||||
|
max={GOOGLE_CALENDAR_SYNC_WEEKS_MAX}
|
||||||
|
value={syncWeeksAhead}
|
||||||
|
disabled={isBusy}
|
||||||
|
onchange={(e) => void onWeeksAheadChange(e)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label class="bsplus-cal-setting bsplus-cal-setting--toggle">
|
||||||
|
<span class="bsplus-cal-setting-label">Auto-sync weekly</span>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
class="bsplus-cal-setting-checkbox"
|
||||||
|
checked={autoSyncWeekly}
|
||||||
|
disabled={isBusy}
|
||||||
|
onchange={(e) => void onAutoSyncToggle(e)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<p class="bsplus-cal-setting-hint">
|
||||||
|
Syncs {syncWeeksAhead} weeks ahead on connect and manual sync. Weekly auto-sync adds each new week forward.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<CalendarSyncProgress progress={syncProgress} />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<CalendarDeleteEventsModal
|
||||||
|
open={showDeleteEvents}
|
||||||
|
busy={busy?.phase === "delete"}
|
||||||
|
providerLabel={modalProvider === "outlook" ? "Outlook" : "Google"}
|
||||||
|
onCancel={() => {
|
||||||
|
if (busy?.phase !== "delete") showDeleteEvents = false;
|
||||||
|
}}
|
||||||
|
onConfirm={confirmDeleteEvents}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<CalendarDisconnectModal
|
||||||
|
open={showDisconnect}
|
||||||
|
busy={busy?.phase === "disconnect"}
|
||||||
|
providerLabel={modalProvider === "outlook" ? "Outlook" : "Google"}
|
||||||
|
onCancel={() => {
|
||||||
|
if (busy?.phase !== "disconnect") showDisconnect = false;
|
||||||
|
}}
|
||||||
|
onConfirm={confirmDisconnect}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{#if toast}
|
||||||
|
<div
|
||||||
|
class="bsplus-cal-toast"
|
||||||
|
class:bsplus-cal-toast--error={toast.error}
|
||||||
|
role="status"
|
||||||
|
transition:fade={{ duration: 150 }}
|
||||||
|
>
|
||||||
|
{toast.message}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.bsplus-cal-sync {
|
||||||
|
position: relative;
|
||||||
|
display: inline-flex;
|
||||||
|
font-family: var(--bsplus-cal-font-family, var(--betterseqta-font-family, Rubik), sans-serif);
|
||||||
|
color: var(--bsplus-cal-text, var(--text-primary, #111));
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-trigger {
|
||||||
|
position: relative;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: auto;
|
||||||
|
height: auto;
|
||||||
|
padding: 0 10px;
|
||||||
|
margin-left: 4px;
|
||||||
|
border-radius: 16px !important;
|
||||||
|
font-family: inherit;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-trigger-icon {
|
||||||
|
font-family: "IconFamily" !important;
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 1;
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-trigger-text {
|
||||||
|
font-family: inherit;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-google-word {
|
||||||
|
display: inline-flex;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: -0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-google-word--sm {
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-google-g,
|
||||||
|
.bsplus-google-g2 {
|
||||||
|
color: #4285f4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-google-o1,
|
||||||
|
.bsplus-google-e {
|
||||||
|
color: #ea4335;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-google-o2 {
|
||||||
|
color: #fbbc05;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-google-l {
|
||||||
|
color: #34a853;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-trigger:hover:not(.bsplus-cal-trigger--busy) {
|
||||||
|
transform: scale(1.03);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-trigger:active:not(.bsplus-cal-trigger--busy) {
|
||||||
|
transform: scale(0.97);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-trigger--open {
|
||||||
|
background: color-mix(in srgb, var(--bsplus-cal-accent, var(--better-main, #3b82f6)) 14%, transparent) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-trigger--connected .bsplus-cal-status-dot {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-trigger--busy {
|
||||||
|
opacity: 0.85;
|
||||||
|
cursor: wait;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-status-dot {
|
||||||
|
position: absolute;
|
||||||
|
top: 4px;
|
||||||
|
right: 4px;
|
||||||
|
width: 7px;
|
||||||
|
height: 7px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: #22c55e;
|
||||||
|
box-shadow: 0 0 0 2px var(--bsplus-cal-surface, #fff);
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-settings {
|
||||||
|
margin: 8px 0 10px;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 10px;
|
||||||
|
border: 1px solid var(--bsplus-cal-border, color-mix(in srgb, var(--bsplus-cal-text) 12%, transparent));
|
||||||
|
background: color-mix(in srgb, var(--bsplus-cal-surface, #fff) 92%, transparent);
|
||||||
|
display: grid;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-setting {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-setting-label {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--bsplus-cal-text, var(--text-primary, #111));
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-setting-input {
|
||||||
|
width: 64px;
|
||||||
|
padding: 6px 8px;
|
||||||
|
border-radius: 10px;
|
||||||
|
border: 1px solid var(--bsplus-cal-border, color-mix(in srgb, var(--bsplus-cal-text) 18%, transparent));
|
||||||
|
background: var(--bsplus-cal-surface, #fff);
|
||||||
|
color: var(--bsplus-cal-text, var(--text-primary, #111));
|
||||||
|
font-size: 12px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-setting-checkbox {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
accent-color: var(--bsplus-cal-accent, var(--better-main, #3b82f6));
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-setting-hint {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 10px;
|
||||||
|
line-height: 1.4;
|
||||||
|
color: color-mix(in srgb, var(--bsplus-cal-text, #111) 58%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-menu {
|
||||||
|
position: fixed;
|
||||||
|
z-index: 2147483647;
|
||||||
|
width: min(320px, calc(100vw - 24px));
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 14px;
|
||||||
|
background: var(--bsplus-cal-surface, #fff);
|
||||||
|
color: var(--bsplus-cal-text, #18181b);
|
||||||
|
border: 1px solid var(--bsplus-cal-border, color-mix(in srgb, var(--bsplus-cal-text) 12%, transparent));
|
||||||
|
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.22);
|
||||||
|
font-family: var(--bsplus-cal-font-family, var(--betterseqta-font-family, Rubik), sans-serif);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-menu.dark {
|
||||||
|
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.45);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-menu-header {
|
||||||
|
padding: 6px 8px 10px;
|
||||||
|
border-bottom: 1px solid var(--bsplus-cal-border, color-mix(in srgb, var(--bsplus-cal-text) 10%, transparent));
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-menu-title {
|
||||||
|
display: block;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-menu-sub {
|
||||||
|
display: block;
|
||||||
|
margin-top: 2px;
|
||||||
|
font-size: 11px;
|
||||||
|
color: color-mix(in srgb, var(--bsplus-cal-text, #111) 62%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-provider {
|
||||||
|
padding: 8px;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--bsplus-cal-surface-muted, color-mix(in srgb, var(--bsplus-cal-text) 4%, transparent));
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-provider-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-provider-icon {
|
||||||
|
display: flex;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-provider-icon svg {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-provider-copy {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-provider-name {
|
||||||
|
display: block;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-provider-status {
|
||||||
|
display: block;
|
||||||
|
margin-top: 1px;
|
||||||
|
font-size: 11px;
|
||||||
|
color: color-mix(in srgb, var(--bsplus-cal-text, #111) 62%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-provider-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-action {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-width: 0;
|
||||||
|
padding: 7px 10px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-action:disabled {
|
||||||
|
opacity: 0.55;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-action--primary {
|
||||||
|
background: var(--bsplus-cal-accent, var(--better-main, #3b82f6));
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-action--primary:hover:not(:disabled) {
|
||||||
|
filter: brightness(1.06);
|
||||||
|
transform: scale(1.02);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-action--ghost {
|
||||||
|
background: var(--bsplus-cal-surface-muted, color-mix(in srgb, var(--bsplus-cal-text) 8%, transparent));
|
||||||
|
color: var(--bsplus-cal-text, #18181b);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-action--ghost:hover:not(:disabled) {
|
||||||
|
background: color-mix(in srgb, var(--bsplus-cal-text) 14%, var(--bsplus-cal-surface));
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-toast {
|
||||||
|
position: fixed;
|
||||||
|
right: 16px;
|
||||||
|
bottom: 16px;
|
||||||
|
z-index: 100000;
|
||||||
|
max-width: min(360px, calc(100vw - 32px));
|
||||||
|
padding: 12px 14px;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: rgba(20, 20, 20, 0.92);
|
||||||
|
color: #fff;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.4;
|
||||||
|
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.25);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-toast--error {
|
||||||
|
background: rgba(120, 24, 24, 0.95);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { GoogleCalendarSyncProgress } from "@/seqta/utils/googleCalendar/types";
|
||||||
|
|
||||||
|
let {
|
||||||
|
progress = null,
|
||||||
|
} = $props<{
|
||||||
|
progress?: GoogleCalendarSyncProgress | null;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const percent = $derived(
|
||||||
|
progress && progress.total > 0
|
||||||
|
? Math.min(100, Math.round((progress.current / progress.total) * 100))
|
||||||
|
: progress?.phase === "preparing"
|
||||||
|
? 8
|
||||||
|
: 0,
|
||||||
|
);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if progress && progress.phase !== "done"}
|
||||||
|
<div class="bsplus-cal-progress" role="status" aria-live="polite" aria-busy="true">
|
||||||
|
<div class="bsplus-cal-progress-label">{progress.message}</div>
|
||||||
|
<div class="bsplus-cal-progress-track" aria-hidden="true">
|
||||||
|
<div class="bsplus-cal-progress-bar" style:width={`${percent}%`}></div>
|
||||||
|
</div>
|
||||||
|
{#if progress.total > 0}
|
||||||
|
<div class="bsplus-cal-progress-meta">{progress.current} / {progress.total}</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.bsplus-cal-progress {
|
||||||
|
margin-top: 8px;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: color-mix(in srgb, var(--bsplus-cal-accent, var(--better-main, #3b82f6)) 10%, transparent);
|
||||||
|
border: 1px solid color-mix(in srgb, var(--bsplus-cal-accent, var(--better-main, #3b82f6)) 22%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-progress-label {
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--bsplus-cal-text, var(--text-primary, #111));
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-progress-track {
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
overflow: hidden;
|
||||||
|
background: color-mix(in srgb, var(--bsplus-cal-text, #111) 10%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-progress-bar {
|
||||||
|
height: 100%;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--bsplus-cal-accent, var(--better-main, #3b82f6));
|
||||||
|
transition: width 0.25s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-cal-progress-meta {
|
||||||
|
margin-top: 6px;
|
||||||
|
font-size: 10px;
|
||||||
|
color: color-mix(in srgb, var(--bsplus-cal-text, #111) 62%, transparent);
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="60 90.4 570.02 539.67" aria-hidden="true">
|
||||||
|
<defs>
|
||||||
|
<linearGradient
|
||||||
|
id="bsplus-outlook-linear0"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
x1="9.98908"
|
||||||
|
y1="22.364901"
|
||||||
|
x2="30.932199"
|
||||||
|
y2="9.37495"
|
||||||
|
gradientTransform="matrix(15,0,0,15,0,0)"
|
||||||
|
>
|
||||||
|
<stop offset="0" style="stop-color:rgb(12.54902%,65.490196%,98.039216%);stop-opacity:1;" />
|
||||||
|
<stop offset="0.4" style="stop-color:rgb(23.137255%,83.529412%,100%);stop-opacity:1;" />
|
||||||
|
<stop offset="1" style="stop-color:rgb(76.862745%,69.019608%,100%);stop-opacity:1;" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient
|
||||||
|
id="bsplus-outlook-linear1"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
x1="17.197201"
|
||||||
|
y1="26.7945"
|
||||||
|
x2="28.856199"
|
||||||
|
y2="8.12575"
|
||||||
|
gradientTransform="matrix(15,0,0,15,0,0)"
|
||||||
|
>
|
||||||
|
<stop offset="0" style="stop-color:rgb(8.627451%,35.294118%,85.098039%);stop-opacity:1;" />
|
||||||
|
<stop offset="0.5008" style="stop-color:rgb(9.411765%,50.196078%,89.803922%);stop-opacity:1;" />
|
||||||
|
<stop offset="1" style="stop-color:rgb(52.156863%,52.941176%,100%);stop-opacity:1;" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient
|
||||||
|
id="bsplus-outlook-linear2"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
x1="25.7005"
|
||||||
|
y1="27.048401"
|
||||||
|
x2="12.7563"
|
||||||
|
y2="16.501301"
|
||||||
|
gradientTransform="matrix(15,0,0,15,0,0)"
|
||||||
|
>
|
||||||
|
<stop offset="0.236946" style="stop-color:rgb(26.666667%,54.117647%,100%);stop-opacity:0;" />
|
||||||
|
<stop offset="0.792113" style="stop-color:rgb(0%,19.607843%,69.411765%);stop-opacity:0.2;" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient
|
||||||
|
id="bsplus-outlook-linear3"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
x1="24.0534"
|
||||||
|
y1="31.1099"
|
||||||
|
x2="44.509998"
|
||||||
|
y2="18.0177"
|
||||||
|
gradientTransform="matrix(15,0,0,15,0,0)"
|
||||||
|
>
|
||||||
|
<stop offset="0" style="stop-color:rgb(10.196078%,26.27451%,65.098039%);stop-opacity:1;" />
|
||||||
|
<stop offset="0.492267" style="stop-color:rgb(12.54902%,32.156863%,79.607843%);stop-opacity:1;" />
|
||||||
|
<stop offset="1" style="stop-color:rgb(37.254902%,12.54902%,79.607843%);stop-opacity:1;" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient
|
||||||
|
id="bsplus-outlook-linear4"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
x1="29.8281"
|
||||||
|
y1="30.327299"
|
||||||
|
x2="17.397499"
|
||||||
|
y2="19.570801"
|
||||||
|
gradientTransform="matrix(15,0,0,15,0,0)"
|
||||||
|
>
|
||||||
|
<stop offset="0" style="stop-color:rgb(0%,27.058824%,72.54902%);stop-opacity:0;" />
|
||||||
|
<stop offset="0.669859" style="stop-color:rgb(5.098039%,12.156863%,41.176471%);stop-opacity:0.2;" />
|
||||||
|
</linearGradient>
|
||||||
|
<radialGradient
|
||||||
|
id="bsplus-outlook-radial0"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
cx="0"
|
||||||
|
cy="0"
|
||||||
|
fx="0"
|
||||||
|
fy="0"
|
||||||
|
r="1"
|
||||||
|
gradientTransform="matrix(0.000000000000024802,-405.040512,438.393002,0.000000000000026844,360.027008,102.268202)"
|
||||||
|
>
|
||||||
|
<stop offset="0.568182" style="stop-color:rgb(15.294118%,37.254902%,94.117647%);stop-opacity:0;" />
|
||||||
|
<stop offset="0.992424" style="stop-color:rgb(0%,12.941176%,46.666667%);stop-opacity:1;" />
|
||||||
|
</radialGradient>
|
||||||
|
<linearGradient
|
||||||
|
id="bsplus-outlook-linear5"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
x1="41.998001"
|
||||||
|
y1="29.9431"
|
||||||
|
x2="23.8517"
|
||||||
|
y2="29.9431"
|
||||||
|
gradientTransform="matrix(15,0,0,15,0,0)"
|
||||||
|
>
|
||||||
|
<stop offset="0" style="stop-color:rgb(30.196078%,76.862745%,100%);stop-opacity:1;" />
|
||||||
|
<stop offset="0.196145" style="stop-color:rgb(5.882353%,68.627451%,100%);stop-opacity:1;" />
|
||||||
|
</linearGradient>
|
||||||
|
<radialGradient
|
||||||
|
id="bsplus-outlook-radial1"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
cx="0"
|
||||||
|
cy="0"
|
||||||
|
fx="0"
|
||||||
|
fy="0"
|
||||||
|
r="1"
|
||||||
|
gradientTransform="matrix(122.73959,-122.73959,122.73959,122.73959,421.392002,568.675518)"
|
||||||
|
>
|
||||||
|
<stop offset="0.259477" style="stop-color:rgb(0%,37.647059%,81.960784%);stop-opacity:0.4;" />
|
||||||
|
<stop offset="0.908166" style="stop-color:rgb(1.176471%,51.372549%,94.509804%);stop-opacity:0;" />
|
||||||
|
</radialGradient>
|
||||||
|
<radialGradient
|
||||||
|
id="bsplus-outlook-radial2"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
cx="0"
|
||||||
|
cy="0"
|
||||||
|
fx="0"
|
||||||
|
fy="0"
|
||||||
|
r="1"
|
||||||
|
gradientTransform="matrix(357.407022,-468.445926,423.594568,323.187085,159.471002,697.080002)"
|
||||||
|
>
|
||||||
|
<stop offset="0.732317" style="stop-color:rgb(95.686275%,65.490196%,96.862745%);stop-opacity:0;" />
|
||||||
|
<stop offset="1" style="stop-color:rgb(95.686275%,65.490196%,96.862745%);stop-opacity:0.501961;" />
|
||||||
|
</radialGradient>
|
||||||
|
<radialGradient
|
||||||
|
id="bsplus-outlook-radial3"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
cx="0"
|
||||||
|
cy="0"
|
||||||
|
fx="0"
|
||||||
|
fy="0"
|
||||||
|
r="1"
|
||||||
|
gradientTransform="matrix(-170.860868,259.725406,-674.018133,-443.404152,278.562012,412.978506)"
|
||||||
|
>
|
||||||
|
<stop offset="0" style="stop-color:rgb(28.627451%,87.058824%,100%);stop-opacity:1;" />
|
||||||
|
<stop offset="0.724349" style="stop-color:rgb(16.078431%,76.470588%,100%);stop-opacity:1;" />
|
||||||
|
</radialGradient>
|
||||||
|
<linearGradient
|
||||||
|
id="bsplus-outlook-linear6"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
x1="3.45756"
|
||||||
|
y1="37.872299"
|
||||||
|
x2="20.9291"
|
||||||
|
y2="37.859699"
|
||||||
|
gradientTransform="matrix(15,0,0,15,0,0)"
|
||||||
|
>
|
||||||
|
<stop offset="0.205882" style="stop-color:rgb(42.352941%,87.843137%,100%);stop-opacity:1;" />
|
||||||
|
<stop offset="0.535" style="stop-color:rgb(31.372549%,83.529412%,100%);stop-opacity:0;" />
|
||||||
|
</linearGradient>
|
||||||
|
<radialGradient
|
||||||
|
id="bsplus-outlook-radial4"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
cx="0"
|
||||||
|
cy="0"
|
||||||
|
fx="0"
|
||||||
|
fy="0"
|
||||||
|
r="1"
|
||||||
|
gradientTransform="matrix(215.76719,230.769125,-230.769125,215.76719,59.143649,354.231005)"
|
||||||
|
>
|
||||||
|
<stop offset="0.038877" style="stop-color:rgb(0%,56.862745%,100%);stop-opacity:1;" />
|
||||||
|
<stop offset="0.919119" style="stop-color:rgb(9.411765%,23.921569%,67.843137%);stop-opacity:1;" />
|
||||||
|
</radialGradient>
|
||||||
|
<radialGradient
|
||||||
|
id="bsplus-outlook-radial5"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
cx="0"
|
||||||
|
cy="0"
|
||||||
|
fx="0"
|
||||||
|
fy="0"
|
||||||
|
r="1"
|
||||||
|
gradientTransform="matrix(0.000000000000010287,167.999997,-193.782005,0.000000000000011866,180,491.158504)"
|
||||||
|
>
|
||||||
|
<stop offset="0.557796" style="stop-color:rgb(5.882353%,64.705882%,96.862745%);stop-opacity:0;" />
|
||||||
|
<stop offset="1" style="stop-color:rgb(45.490196%,77.647059%,100%);stop-opacity:0.501961;" />
|
||||||
|
</radialGradient>
|
||||||
|
</defs>
|
||||||
|
<g>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:url(#bsplus-outlook-linear0);"
|
||||||
|
d="M 463.984375 140.144531 L 119.636719 358.414062 L 90.023438 311.695312 L 90.023438 271.4375 C 90.023438 256.78125 97.445312 243.121094 109.742188 235.144531 L 309.910156 105.257812 C 340.40625 85.46875 379.6875 85.464844 410.1875 105.25 Z M 463.984375 140.144531 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:url(#bsplus-outlook-linear1);"
|
||||||
|
d="M 407.101562 103.339844 C 408.136719 103.953125 409.164062 104.59375 410.183594 105.253906 L 566.398438 206.585938 L 179.0625 452.105469 L 119.625 358.335938 L 403.894531 177.800781 C 430.820312 160.699219 432 122.230469 407.101562 103.339844 Z M 407.101562 103.339844 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:url(#bsplus-outlook-linear2);"
|
||||||
|
d="M 407.101562 103.339844 C 408.136719 103.953125 409.164062 104.59375 410.183594 105.253906 L 566.398438 206.585938 L 179.0625 452.105469 L 119.625 358.335938 L 403.894531 177.800781 C 430.820312 160.699219 432 122.230469 407.101562 103.339844 Z M 407.101562 103.339844 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:url(#bsplus-outlook-linear3);"
|
||||||
|
d="M 333.601562 498.988281 L 179.066406 452.109375 L 507.628906 243.835938 C 535.300781 226.296875 535.230469 185.898438 507.496094 168.457031 L 506.015625 167.527344 L 510.277344 170.175781 L 610.273438 235.042969 C 622.574219 243.019531 629.996094 256.683594 629.996094 271.34375 L 629.996094 310.304688 Z M 333.601562 498.988281 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:url(#bsplus-outlook-linear4);"
|
||||||
|
d="M 333.601562 498.988281 L 179.066406 452.109375 L 507.628906 243.835938 C 535.300781 226.296875 535.230469 185.898438 507.496094 168.457031 L 506.015625 167.527344 L 510.277344 170.175781 L 610.273438 235.042969 C 622.574219 243.019531 629.996094 256.683594 629.996094 271.34375 L 629.996094 310.304688 Z M 333.601562 498.988281 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:url(#bsplus-outlook-radial0);"
|
||||||
|
d="M 410.1875 105.25 C 379.6875 85.464844 340.40625 85.46875 309.90625 105.257812 L 109.742188 235.144531 C 97.445312 243.121094 90.023438 256.78125 90.023438 271.4375 L 90.023438 273.40625 C 90.507812 288.121094 98.25 301.679688 110.757812 309.566406 L 359.644531 466.476562 L 609.160156 309.804688 C 622.121094 301.667969 629.984375 287.441406 629.984375 272.140625 L 629.984375 310.308594 L 629.992188 271.34375 C 629.992188 256.683594 622.566406 243.023438 610.269531 235.042969 Z M 410.1875 105.25 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:url(#bsplus-outlook-linear5);"
|
||||||
|
d="M 315.769531 630.050781 L 536.21875 630.050781 C 587.996094 630.050781 629.96875 588.078125 629.96875 536.300781 L 629.96875 272.140625 C 629.96875 287.441406 622.105469 301.667969 609.148438 309.804688 L 281.242188 515.695312 C 263.554688 526.804688 252.820312 546.222656 252.820312 567.109375 C 252.824219 601.871094 281.003906 630.050781 315.769531 630.050781 Z M 315.769531 630.050781 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:url(#bsplus-outlook-radial1);"
|
||||||
|
d="M 315.769531 630.050781 L 536.21875 630.050781 C 587.996094 630.050781 629.96875 588.078125 629.96875 536.300781 L 629.96875 272.140625 C 629.96875 287.441406 622.105469 301.667969 609.148438 309.804688 L 281.242188 515.695312 C 263.554688 526.804688 252.820312 546.222656 252.820312 567.109375 C 252.824219 601.871094 281.003906 630.050781 315.769531 630.050781 Z M 315.769531 630.050781 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:url(#bsplus-outlook-radial2);"
|
||||||
|
d="M 315.769531 630.050781 L 536.21875 630.050781 C 587.996094 630.050781 629.96875 588.078125 629.96875 536.300781 L 629.96875 272.140625 C 629.96875 287.441406 622.105469 301.667969 609.148438 309.804688 L 281.242188 515.695312 C 263.554688 526.804688 252.820312 546.222656 252.820312 567.109375 C 252.824219 601.871094 281.003906 630.050781 315.769531 630.050781 Z M 315.769531 630.050781 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:url(#bsplus-outlook-radial3);"
|
||||||
|
d="M 405.402344 630.035156 L 183.738281 630.035156 C 131.960938 630.035156 89.988281 588.0625 89.988281 536.285156 L 89.988281 271.945312 C 89.988281 287.21875 97.824219 301.421875 110.742188 309.566406 L 438.324219 516.085938 C 456.257812 527.390625 467.132812 547.113281 467.132812 568.3125 C 467.128906 602.402344 439.492188 630.035156 405.402344 630.035156 Z M 405.402344 630.035156 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:url(#bsplus-outlook-linear6);"
|
||||||
|
d="M 405.402344 630.035156 L 183.738281 630.035156 C 131.960938 630.035156 89.988281 588.0625 89.988281 536.285156 L 89.988281 271.945312 C 89.988281 287.21875 97.824219 301.421875 110.742188 309.566406 L 438.324219 516.085938 C 456.257812 527.390625 467.132812 547.113281 467.132812 568.3125 C 467.128906 602.402344 439.492188 630.035156 405.402344 630.035156 Z M 405.402344 630.035156 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:url(#bsplus-outlook-radial4);"
|
||||||
|
d="M 108.75 345 L 251.25 345 C 278.175781 345 300 366.824219 300 393.75 L 300 536.25 C 300 563.175781 278.175781 585 251.25 585 L 108.75 585 C 81.824219 585 60 563.175781 60 536.25 L 60 393.75 C 60 366.824219 81.824219 345 108.75 345 Z M 108.75 345 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:url(#bsplus-outlook-radial5);"
|
||||||
|
d="M 108.75 345 L 251.25 345 C 278.175781 345 300 366.824219 300 393.75 L 300 536.25 C 300 563.175781 278.175781 585 251.25 585 L 108.75 585 C 81.824219 585 60 563.175781 60 536.25 L 60 393.75 C 60 366.824219 81.824219 345 108.75 345 Z M 108.75 345 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;"
|
||||||
|
d="M 179.386719 534 C 159.539062 534 143.25 527.789062 130.511719 515.375 C 117.773438 502.960938 111.402344 486.757812 111.402344 466.769531 C 111.402344 445.660156 117.867188 428.589844 130.796875 415.550781 C 143.730469 402.515625 160.660156 396 181.59375 396 C 201.375 396 217.472656 402.238281 229.890625 414.714844 C 242.375 427.191406 248.617188 443.644531 248.617188 464.066406 C 248.617188 485.050781 242.148438 501.964844 229.21875 514.816406 C 216.351562 527.605469 199.742188 534 179.386719 534 Z M 179.960938 507.648438 C 190.777344 507.648438 199.484375 503.953125 206.078125 496.566406 C 212.671875 489.179688 215.96875 478.902344 215.96875 465.742188 C 215.96875 452.023438 212.765625 441.347656 206.367188 433.710938 C 199.964844 426.074219 191.417969 422.257812 180.730469 422.257812 C 169.71875 422.257812 160.851562 426.199219 154.132812 434.082031 C 147.410156 441.90625 144.050781 452.273438 144.050781 465.183594 C 144.050781 478.285156 147.410156 488.652344 154.132812 496.285156 C 160.851562 503.859375 169.460938 507.648438 179.960938 507.648438 Z M 179.960938 507.648438 "
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
style="stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;"
|
||||||
|
d="M 179.332031 535.847656 C 159.5625 535.847656 143.332031 529.472656 130.640625 516.71875 C 117.953125 503.964844 111.605469 487.320312 111.605469 466.789062 C 111.605469 445.105469 118.046875 427.570312 130.929688 414.179688 C 143.8125 400.785156 160.679688 394.089844 181.53125 394.089844 C 201.234375 394.089844 217.273438 400.5 229.644531 413.316406 C 242.082031 426.136719 248.296875 443.035156 248.296875 464.015625 C 248.296875 485.566406 241.855469 502.945312 228.976562 516.144531 C 216.15625 529.28125 199.609375 535.847656 179.332031 535.847656 Z M 179.902344 508.78125 C 190.679688 508.78125 199.355469 504.984375 205.921875 497.398438 C 212.492188 489.808594 215.773438 479.253906 215.773438 465.734375 C 215.773438 451.640625 212.585938 440.675781 206.210938 432.832031 C 199.832031 424.988281 191.320312 421.066406 180.671875 421.066406 C 169.699219 421.066406 160.867188 425.113281 154.171875 433.214844 C 147.476562 441.246094 144.128906 451.898438 144.128906 465.160156 C 144.128906 478.617188 147.476562 489.265625 154.171875 497.109375 C 160.867188 504.890625 169.445312 508.78125 179.902344 508.78125 Z M 179.902344 508.78125 "
|
||||||
|
/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,24 @@
|
|||||||
|
.timetablepage #toolbar {
|
||||||
|
position: relative;
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timetable-calendar-controls {
|
||||||
|
position: relative;
|
||||||
|
z-index: 100001;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timetable-calendar-controls.bsplus-cal-menu-open {
|
||||||
|
z-index: 2147483646;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timetablepage #toolbar:has(.bsplus-cal-menu-open) {
|
||||||
|
z-index: 2147483646 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bsplus-calendar-sync-mount {
|
||||||
|
display: inline-flex;
|
||||||
|
font-family: var(--bsplus-cal-font-family, var(--betterseqta-font-family, Rubik), sans-serif);
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
|
import { extractSolidColor } from "@/seqta/ui/colors/parseCssColor";
|
||||||
|
import { ensureFontLoaded } from "@/seqta/ui/fonts/Manager";
|
||||||
|
import { getFontPreset } from "@/seqta/ui/fonts/presets";
|
||||||
|
|
||||||
|
export const CALENDAR_THEME_CSS_VARS = [
|
||||||
|
"--better-main",
|
||||||
|
"--better-pale",
|
||||||
|
"--better-light",
|
||||||
|
"--text-color",
|
||||||
|
"--background-primary",
|
||||||
|
"--background-secondary",
|
||||||
|
"--text-primary",
|
||||||
|
"--theme-offset-bg",
|
||||||
|
"--better-sub",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const ACCENT_CSS_VARS = [
|
||||||
|
"--better-main",
|
||||||
|
"--accent-color-value",
|
||||||
|
"--accentColor",
|
||||||
|
"--colour-betterseqta-blue",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export function isCalendarDarkMode(): boolean {
|
||||||
|
return !!settingsState.DarkMode || document.documentElement.classList.contains("dark");
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolvePageAccentColor(): string {
|
||||||
|
const computed = getComputedStyle(document.documentElement);
|
||||||
|
for (const name of ACCENT_CSS_VARS) {
|
||||||
|
const solid = extractSolidColor(computed.getPropertyValue(name));
|
||||||
|
if (solid) return solid;
|
||||||
|
}
|
||||||
|
const fromSettings = settingsState.selectedColor?.trim();
|
||||||
|
if (fromSettings) {
|
||||||
|
const solid = extractSolidColor(fromSettings);
|
||||||
|
if (solid) return solid;
|
||||||
|
}
|
||||||
|
return "#3b82f6";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sync extension theme (including dark mode) onto a calendar UI host or portaled menu. */
|
||||||
|
export function syncCalendarSyncTheme(target: HTMLElement): void {
|
||||||
|
const computed = getComputedStyle(document.documentElement);
|
||||||
|
const dark = isCalendarDarkMode();
|
||||||
|
const fontPreset = getFontPreset(settingsState.selectedFont);
|
||||||
|
|
||||||
|
ensureFontLoaded(fontPreset);
|
||||||
|
target.style.setProperty("--bsplus-cal-font-family", fontPreset.stack);
|
||||||
|
|
||||||
|
for (const name of CALENDAR_THEME_CSS_VARS) {
|
||||||
|
const value =
|
||||||
|
document.documentElement.style.getPropertyValue(name).trim() ||
|
||||||
|
computed.getPropertyValue(name).trim();
|
||||||
|
if (value) target.style.setProperty(name, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
const accent = resolvePageAccentColor();
|
||||||
|
target.style.setProperty("--bsplus-cal-accent", accent);
|
||||||
|
target.style.setProperty("--better-main", accent);
|
||||||
|
target.classList.toggle("dark", dark);
|
||||||
|
|
||||||
|
const textPrimary =
|
||||||
|
computed.getPropertyValue("--text-primary").trim() ||
|
||||||
|
computed.getPropertyValue("--text-color").trim();
|
||||||
|
const bgPrimary =
|
||||||
|
computed.getPropertyValue("--background-primary").trim() ||
|
||||||
|
computed.getPropertyValue("--background-secondary").trim() ||
|
||||||
|
computed.getPropertyValue("--theme-offset-bg").trim();
|
||||||
|
|
||||||
|
target.style.setProperty(
|
||||||
|
"--bsplus-cal-text",
|
||||||
|
textPrimary || (dark ? "#f4f4f5" : "#18181b"),
|
||||||
|
);
|
||||||
|
target.style.setProperty(
|
||||||
|
"--bsplus-cal-surface",
|
||||||
|
bgPrimary || (dark ? "#27272a" : "#ffffff"),
|
||||||
|
);
|
||||||
|
target.style.setProperty(
|
||||||
|
"--bsplus-cal-surface-muted",
|
||||||
|
dark ? "#3f3f46" : "color-mix(in srgb, var(--bsplus-cal-text) 5%, var(--bsplus-cal-surface))",
|
||||||
|
);
|
||||||
|
target.style.setProperty(
|
||||||
|
"--bsplus-cal-border",
|
||||||
|
dark ? "color-mix(in srgb, #ffffff 14%, transparent)" : "color-mix(in srgb, var(--bsplus-cal-text) 12%, transparent)",
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { mount, unmount } from "svelte";
|
||||||
|
import CalendarSyncControl from "./CalendarSyncControl.svelte";
|
||||||
|
import { syncCalendarSyncTheme } from "./calendarSyncTheme";
|
||||||
|
import { registerCalendarContentHandlers } from "@/seqta/utils/googleCalendar/calendarSyncListener";
|
||||||
|
import hostStyles from "./calendarSyncHost.css?inline";
|
||||||
|
|
||||||
|
const CONTROLS_CLASS = "timetable-calendar-controls";
|
||||||
|
const HOST_STYLE_ID = "bsplus-calendar-sync-host-styles";
|
||||||
|
|
||||||
|
let currentApp: ReturnType<typeof mount> | null = null;
|
||||||
|
let mountRoot: HTMLElement | null = null;
|
||||||
|
|
||||||
|
function ensureHostStyles() {
|
||||||
|
if (document.getElementById(HOST_STYLE_ID)) return;
|
||||||
|
const style = document.createElement("style");
|
||||||
|
style.id = HOST_STYLE_ID;
|
||||||
|
style.textContent = hostStyles;
|
||||||
|
document.head.appendChild(style);
|
||||||
|
}
|
||||||
|
|
||||||
|
function teardown() {
|
||||||
|
if (currentApp) {
|
||||||
|
unmount(currentApp);
|
||||||
|
currentApp = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
mountRoot = null;
|
||||||
|
document.querySelector(`.${CONTROLS_CLASS}`)?.remove();
|
||||||
|
document.getElementById(HOST_STYLE_ID)?.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function mountGoogleCalendarButton(): Promise<void> {
|
||||||
|
if (document.querySelector(`.${CONTROLS_CLASS}`)) return;
|
||||||
|
|
||||||
|
const toolbar = document.getElementById("toolbar");
|
||||||
|
if (!toolbar) return;
|
||||||
|
|
||||||
|
ensureHostStyles();
|
||||||
|
registerCalendarContentHandlers();
|
||||||
|
|
||||||
|
const controls = document.createElement("div");
|
||||||
|
controls.className = `${CONTROLS_CLASS} bsplus-timetable-control`;
|
||||||
|
toolbar.appendChild(controls);
|
||||||
|
|
||||||
|
mountRoot = document.createElement("div");
|
||||||
|
mountRoot.className = "bsplus-calendar-sync-mount";
|
||||||
|
syncCalendarSyncTheme(mountRoot);
|
||||||
|
controls.appendChild(mountRoot);
|
||||||
|
|
||||||
|
currentApp = mount(CalendarSyncControl, { target: mountRoot });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unmountGoogleCalendarButton(): void {
|
||||||
|
teardown();
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
|||||||
import type { Plugin } from "../../core/types";
|
import type { Plugin } from "../../core/types";
|
||||||
import { convertTo12HourFormat } from "@/seqta/utils/convertTo12HourFormat";
|
import { convertTo12HourFormat } from "@/seqta/utils/convertTo12HourFormat";
|
||||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||||
|
import { mountGoogleCalendarButton, unmountGoogleCalendarButton } from "./calendarSyncUi";
|
||||||
|
|
||||||
const timetablePlugin: Plugin<{}, {}> = {
|
const timetablePlugin: Plugin<{}, {}> = {
|
||||||
id: "timetable",
|
id: "timetable",
|
||||||
@@ -26,6 +27,7 @@ const timetablePlugin: Plugin<{}, {}> = {
|
|||||||
const hideControls = document.querySelector(".timetable-hide-controls");
|
const hideControls = document.querySelector(".timetable-hide-controls");
|
||||||
if (hideControls) hideControls.remove();
|
if (hideControls) hideControls.remove();
|
||||||
|
|
||||||
|
unmountGoogleCalendarButton();
|
||||||
resetTimetableStyles();
|
resetTimetableStyles();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -81,6 +83,7 @@ async function handleTimetable(): Promise<void> {
|
|||||||
|
|
||||||
handleTimetableZoom();
|
handleTimetableZoom();
|
||||||
handleTimetableAssessmentHide();
|
handleTimetableAssessmentHide();
|
||||||
|
void mountGoogleCalendarButton();
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleTimetableZoom(): void {
|
function handleTimetableZoom(): void {
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ import { observeMenuItemPosition } from "@/seqta/utils/sidebarMenuIcons";
|
|||||||
|
|
||||||
// Icons and fonts
|
// Icons and fonts
|
||||||
import IconFamily from "@/resources/fonts/IconFamily.woff";
|
import IconFamily from "@/resources/fonts/IconFamily.woff";
|
||||||
|
import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
|
||||||
|
|
||||||
// Stylesheets
|
// Stylesheets
|
||||||
import iframeCSS from "@/css/iframe.scss?raw";
|
import iframeCSS from "@/css/iframe.scss?raw";
|
||||||
@@ -106,7 +107,7 @@ export async function finishLoad() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function GetCSSElement(file: string) {
|
export function GetCSSElement(file: string) {
|
||||||
const cssFile = browser.runtime.getURL(file);
|
const cssFile = resolveExtensionAssetUrl(file);
|
||||||
const fileref = document.createElement("link");
|
const fileref = document.createElement("link");
|
||||||
fileref.setAttribute("rel", "stylesheet");
|
fileref.setAttribute("rel", "stylesheet");
|
||||||
fileref.setAttribute("type", "text/css");
|
fileref.setAttribute("type", "text/css");
|
||||||
@@ -814,7 +815,7 @@ function InjectCustomIcons() {
|
|||||||
style.innerHTML = `
|
style.innerHTML = `
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'IconFamily';
|
font-family: 'IconFamily';
|
||||||
src: url('${browser.runtime.getURL(IconFamily)}') format('woff');
|
src: url('${resolveExtensionAssetUrl(IconFamily)}') format('woff');
|
||||||
font-weight: normal;
|
font-weight: normal;
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
}`;
|
}`;
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import {
|
||||||
|
extractSolidColor,
|
||||||
|
normalizeCssColorString,
|
||||||
|
parseCssColor,
|
||||||
|
} from "./parseCssColor";
|
||||||
|
|
||||||
|
describe("normalizeCssColorString", () => {
|
||||||
|
it("lowercases uppercase RGBA/RGB function names", () => {
|
||||||
|
expect(normalizeCssColorString("RGBA(3, 29, 11, 0.58)")).toBe(
|
||||||
|
"rgba(3, 29, 11, 0.58)",
|
||||||
|
);
|
||||||
|
expect(normalizeCssColorString("RGB(10, 20, 30)")).toBe("rgb(10, 20, 30)");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("extractSolidColor", () => {
|
||||||
|
it("extracts solid uppercase RGBA values", () => {
|
||||||
|
expect(extractSolidColor("RGBA(3, 29, 11, 0.58)")).toBe(
|
||||||
|
"rgba(3, 29, 11, 0.58)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("extracts the first rgba stop from gradients with mixed casing", () => {
|
||||||
|
expect(
|
||||||
|
extractSolidColor(
|
||||||
|
"linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)",
|
||||||
|
),
|
||||||
|
).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",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
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.
|
||||||
|
*/
|
||||||
|
export function normalizeCssColorString(value: string): string {
|
||||||
|
return value
|
||||||
|
.trim()
|
||||||
|
.replace(/\bRGBA?\(/gi, (match) => match.toLowerCase())
|
||||||
|
.replace(/\bHSLA?\(/gi, (match) => match.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pick a single solid colour from a CSS value (hex, rgb(a), hsl(a), or gradient). */
|
||||||
|
export function extractSolidColor(value: string): string | null {
|
||||||
|
const trimmed = normalizeCssColorString(value);
|
||||||
|
if (!trimmed || trimmed === "initial") return null;
|
||||||
|
if (
|
||||||
|
trimmed.startsWith("#") ||
|
||||||
|
/^rgba?\(/i.test(trimmed) ||
|
||||||
|
/^hsla?\(/i.test(trimmed)
|
||||||
|
) {
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
if (trimmed.includes("gradient")) {
|
||||||
|
const match = trimmed.match(
|
||||||
|
/#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgba?\([^)]+\)/gi,
|
||||||
|
);
|
||||||
|
return match?.[0] ? normalizeCssColorString(match[0]) : 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);
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { animate } from "motion";
|
import { animate } from "motion";
|
||||||
import browser from "webextension-polyfill";
|
import browser from "webextension-polyfill";
|
||||||
import LogoLight from "@/resources/icons/betterseqta-light-icon.png";
|
import LogoLight from "@/resources/icons/betterseqta-light-icon.png";
|
||||||
|
import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
|
||||||
import { GetThresholdOfColor } from "@/seqta/ui/colors/getThresholdColour";
|
import { GetThresholdOfColor } from "@/seqta/ui/colors/getThresholdColour";
|
||||||
import { convertTo12HourFormat } from "@/seqta/utils/convertTo12HourFormat";
|
import { convertTo12HourFormat } from "@/seqta/utils/convertTo12HourFormat";
|
||||||
import debounce from "@/seqta/utils/debounce";
|
import debounce from "@/seqta/utils/debounce";
|
||||||
@@ -129,7 +130,7 @@ function renderEngageDayLessons(): void {
|
|||||||
if (lessons.length === 0) {
|
if (lessons.length === 0) {
|
||||||
dayContainer.innerHTML = `
|
dayContainer.innerHTML = `
|
||||||
<div class="day-empty">
|
<div class="day-empty">
|
||||||
<img src="${browser.runtime.getURL(LogoLight)}" alt="" />
|
<img src="${resolveExtensionAssetUrl(LogoLight)}" alt="" />
|
||||||
<p>No lessons for this day.</p>
|
<p>No lessons for this day.</p>
|
||||||
</div>`;
|
</div>`;
|
||||||
} else {
|
} else {
|
||||||
@@ -714,7 +715,7 @@ function showEngageTimetableError(message: string): void {
|
|||||||
dayContainer.classList.remove("loading");
|
dayContainer.classList.remove("loading");
|
||||||
dayContainer.innerHTML = `
|
dayContainer.innerHTML = `
|
||||||
<div class="day-empty">
|
<div class="day-empty">
|
||||||
<img src="${browser.runtime.getURL(LogoLight)}" alt="" />
|
<img src="${resolveExtensionAssetUrl(LogoLight)}" alt="" />
|
||||||
<p>${message}</p>
|
<p>${message}</p>
|
||||||
</div>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
@@ -725,7 +726,7 @@ function showEngageNoticesSectionError(message: string): void {
|
|||||||
noticeContainer.classList.remove("loading");
|
noticeContainer.classList.remove("loading");
|
||||||
noticeContainer.innerHTML = `
|
noticeContainer.innerHTML = `
|
||||||
<div class="day-empty">
|
<div class="day-empty">
|
||||||
<img src="${browser.runtime.getURL(LogoLight)}" alt="" />
|
<img src="${resolveExtensionAssetUrl(LogoLight)}" alt="" />
|
||||||
<p>${message}</p>
|
<p>${message}</p>
|
||||||
</div>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { animate, stagger } from "motion";
|
import { animate, stagger } from "motion";
|
||||||
import browser from "webextension-polyfill";
|
import browser from "webextension-polyfill";
|
||||||
import LogoLight from "@/resources/icons/betterseqta-light-icon.png";
|
import LogoLight from "@/resources/icons/betterseqta-light-icon.png";
|
||||||
|
import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
|
||||||
import assessmentsicon from "@/seqta/icons/assessmentsIcon";
|
import assessmentsicon from "@/seqta/icons/assessmentsIcon";
|
||||||
import coursesicon from "@/seqta/icons/coursesIcon";
|
import coursesicon from "@/seqta/icons/coursesIcon";
|
||||||
import { GetThresholdOfColor } from "@/seqta/ui/colors/getThresholdColour";
|
import { GetThresholdOfColor } from "@/seqta/ui/colors/getThresholdColour";
|
||||||
@@ -726,7 +727,7 @@ function callHomeTimetable(date: string, change?: any) {
|
|||||||
const dummyDay = document.createElement("div");
|
const dummyDay = document.createElement("div");
|
||||||
dummyDay.classList.add("day-empty");
|
dummyDay.classList.add("day-empty");
|
||||||
const img = document.createElement("img");
|
const img = document.createElement("img");
|
||||||
img.src = browser.runtime.getURL(LogoLight);
|
img.src = resolveExtensionAssetUrl(LogoLight);
|
||||||
const text = document.createElement("p");
|
const text = document.createElement("p");
|
||||||
text.innerText = "No lessons available.";
|
text.innerText = "No lessons available.";
|
||||||
dummyDay.append(img, text);
|
dummyDay.append(img, text);
|
||||||
@@ -978,7 +979,7 @@ async function CreateUpcomingSection(assessments: any, activeSubjects: any) {
|
|||||||
if (assessments.length === 0) {
|
if (assessments.length === 0) {
|
||||||
upcomingitemcontainer!.innerHTML = `
|
upcomingitemcontainer!.innerHTML = `
|
||||||
<div class="day-empty">
|
<div class="day-empty">
|
||||||
<img src="${browser.runtime.getURL(LogoLight)}" />
|
<img src="${resolveExtensionAssetUrl(LogoLight)}" />
|
||||||
<p>No assessments available.</p>
|
<p>No assessments available.</p>
|
||||||
</div>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { delay } from "./delay";
|
|||||||
import { settingsState } from "./listeners/SettingsState";
|
import { settingsState } from "./listeners/SettingsState";
|
||||||
import browser from "webextension-polyfill";
|
import browser from "webextension-polyfill";
|
||||||
import LogoLightOutline from "@/resources/icons/betterseqta-light-outline.png";
|
import LogoLightOutline from "@/resources/icons/betterseqta-light-outline.png";
|
||||||
|
import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
|
||||||
import { animate, stagger } from "motion";
|
import { animate, stagger } from "motion";
|
||||||
|
|
||||||
export async function SendNewsPage() {
|
export async function SendNewsPage() {
|
||||||
@@ -58,7 +59,7 @@ export async function SendNewsPage() {
|
|||||||
const emptyState = document.createElement("div");
|
const emptyState = document.createElement("div");
|
||||||
emptyState.classList.add("day-empty");
|
emptyState.classList.add("day-empty");
|
||||||
const img = document.createElement("img");
|
const img = document.createElement("img");
|
||||||
img.src = browser.runtime.getURL(LogoLightOutline);
|
img.src = resolveExtensionAssetUrl(LogoLightOutline);
|
||||||
const text = document.createElement("p");
|
const text = document.createElement("p");
|
||||||
text.innerText = "No news articles available right now.";
|
text.innerText = "No news articles available right now.";
|
||||||
emptyState.append(img, text);
|
emptyState.append(img, text);
|
||||||
@@ -79,7 +80,7 @@ export async function SendNewsPage() {
|
|||||||
|
|
||||||
if (article.urlToImage == "null" || article.urlToImage == null) {
|
if (article.urlToImage == "null" || article.urlToImage == null) {
|
||||||
articleimage.style.cssText = `
|
articleimage.style.cssText = `
|
||||||
background-image: url(${browser.runtime.getURL(LogoLightOutline)});
|
background-image: url(${resolveExtensionAssetUrl(LogoLightOutline)});
|
||||||
width: 20%;
|
width: 20%;
|
||||||
margin: 0 7.5%;
|
margin: 0 7.5%;
|
||||||
`;
|
`;
|
||||||
|
|||||||
@@ -0,0 +1,236 @@
|
|||||||
|
import { verboseLog } from "@/utils/verboseLog";
|
||||||
|
import {
|
||||||
|
getStoredEventId,
|
||||||
|
lessonDateFromSeqtaKey,
|
||||||
|
normalizeEventMapEntry,
|
||||||
|
} from "@/seqta/utils/googleCalendar/eventMapEntry";
|
||||||
|
import {
|
||||||
|
isDateInRange,
|
||||||
|
syncWindowRange,
|
||||||
|
} from "@/seqta/utils/googleCalendar/syncDateRange";
|
||||||
|
import type {
|
||||||
|
GoogleCalendarSyncOptions,
|
||||||
|
GoogleCalendarSyncProgress,
|
||||||
|
GoogleCalendarSyncResult,
|
||||||
|
} from "@/seqta/utils/googleCalendar/types";
|
||||||
|
|
||||||
|
export const EVENT_MAP_PERSIST_EVERY = 10;
|
||||||
|
|
||||||
|
export type EventMapRecord = Record<string, string | { id: string; date: string }>;
|
||||||
|
|
||||||
|
export type MappedLessonEvent = {
|
||||||
|
seqtaKey: string;
|
||||||
|
startDateTime: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function reportSyncProgress(
|
||||||
|
onProgress: GoogleCalendarSyncOptions["onProgress"],
|
||||||
|
progress: GoogleCalendarSyncProgress,
|
||||||
|
) {
|
||||||
|
onProgress?.(progress);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function lessonDateForEvent(startDateTime: string, seqtaKey: string): string {
|
||||||
|
return startDateTime.slice(0, 10) || lessonDateFromSeqtaKey(seqtaKey) || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function originEventMapEntries(
|
||||||
|
eventMap: EventMapRecord,
|
||||||
|
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 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,
|
||||||
|
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;
|
||||||
|
if (shouldPruneEntry(mode, entry, mapKey, window, currentMapKeys)) {
|
||||||
|
entries.push([mapKey, entry.id]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function notConfiguredSyncResult(error: string): GoogleCalendarSyncResult {
|
||||||
|
return { success: false, configured: false, error };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function notConnectedSyncResult(error: string): GoogleCalendarSyncResult {
|
||||||
|
return { success: false, configured: true, connected: false, error };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function emptyLessonsSyncResult(): GoogleCalendarSyncResult {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
configured: true,
|
||||||
|
connected: true,
|
||||||
|
error: "No timetable classes found to sync for the selected range.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildLessonSyncResult(
|
||||||
|
created: number,
|
||||||
|
updated: number,
|
||||||
|
deleted: number,
|
||||||
|
failed: number,
|
||||||
|
lastSyncAt: number,
|
||||||
|
): GoogleCalendarSyncResult {
|
||||||
|
return {
|
||||||
|
success: failed === 0,
|
||||||
|
configured: true,
|
||||||
|
connected: true,
|
||||||
|
created,
|
||||||
|
updated,
|
||||||
|
deleted,
|
||||||
|
skipped: 0,
|
||||||
|
failed,
|
||||||
|
lastSyncAt,
|
||||||
|
error:
|
||||||
|
failed > 0
|
||||||
|
? `Synced with ${failed} error${failed === 1 ? "" : "s"}. Check the console for details.`
|
||||||
|
: undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
origin: string;
|
||||||
|
staleEntryCount: number;
|
||||||
|
totalSteps: number;
|
||||||
|
lastSyncAt: number;
|
||||||
|
initialFailed: number;
|
||||||
|
getAccessToken: () => Promise<string>;
|
||||||
|
mapKey: (origin: string, seqtaKey: string) => string;
|
||||||
|
upsert: (
|
||||||
|
accessToken: string,
|
||||||
|
existingId: string | undefined,
|
||||||
|
event: TEvent,
|
||||||
|
refreshAccessToken: () => Promise<string>,
|
||||||
|
) => Promise<string>;
|
||||||
|
writeState: (patch: {
|
||||||
|
eventMap: EventMapRecord;
|
||||||
|
lastSyncAt: number;
|
||||||
|
lastSyncOrigin: string;
|
||||||
|
}) => Promise<unknown>;
|
||||||
|
onProgress?: GoogleCalendarSyncOptions["onProgress"];
|
||||||
|
logLabel: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function upsertLessonEvents<TEvent extends MappedLessonEvent>(
|
||||||
|
params: UpsertLessonEventsParams<TEvent>,
|
||||||
|
): Promise<{ created: number; updated: number; failed: number; accessToken: string }> {
|
||||||
|
const {
|
||||||
|
events,
|
||||||
|
eventMap,
|
||||||
|
origin,
|
||||||
|
staleEntryCount,
|
||||||
|
totalSteps,
|
||||||
|
lastSyncAt,
|
||||||
|
initialFailed,
|
||||||
|
getAccessToken,
|
||||||
|
mapKey,
|
||||||
|
upsert,
|
||||||
|
writeState,
|
||||||
|
onProgress,
|
||||||
|
logLabel,
|
||||||
|
} = params;
|
||||||
|
|
||||||
|
let accessToken = await getAccessToken();
|
||||||
|
let created = 0;
|
||||||
|
let updated = 0;
|
||||||
|
let failed = initialFailed;
|
||||||
|
|
||||||
|
for (let i = 0; i < events.length; i++) {
|
||||||
|
const event = events[i];
|
||||||
|
const key = mapKey(origin, event.seqtaKey);
|
||||||
|
const existingId = getStoredEventId(eventMap[key]);
|
||||||
|
const progressCurrent = staleEntryCount + i + 1;
|
||||||
|
const progressMessage = `Syncing events (${i + 1}/${events.length})…`;
|
||||||
|
|
||||||
|
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 });
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
verboseLog(`[BetterSEQTA+] ${logLabel} event sync failed:`, err);
|
||||||
|
failed += 1;
|
||||||
|
reportSyncProgress(onProgress, {
|
||||||
|
phase: "upserting",
|
||||||
|
current: progressCurrent,
|
||||||
|
total: totalSteps,
|
||||||
|
message: progressMessage,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { created, updated, failed, accessToken };
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
@@ -37,6 +37,7 @@ export const KEYS_OMITTED_FROM_CLOUD_UPLOAD = [
|
|||||||
"bsplus_user",
|
"bsplus_user",
|
||||||
"cloudAccessToken",
|
"cloudAccessToken",
|
||||||
"cloudUsername",
|
"cloudUsername",
|
||||||
|
"bsplus_google_calendar",
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -67,6 +68,7 @@ const AUTH_KEYS_TO_PRESERVE = [
|
|||||||
"bsplus_refresh_token",
|
"bsplus_refresh_token",
|
||||||
"bsplus_client_id",
|
"bsplus_client_id",
|
||||||
"bsplus_user",
|
"bsplus_user",
|
||||||
|
"bsplus_google_calendar",
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
const OMIT_FROM_UPLOAD_EXACT = new Set<string>([
|
const OMIT_FROM_UPLOAD_EXACT = new Set<string>([
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
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,84 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
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 { 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[] = [];
|
||||||
|
|
||||||
|
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 === "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 false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function maybeRunDueWeeklySync(
|
||||||
|
onComplete?: (message: string, isError?: boolean) => void,
|
||||||
|
): 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);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const messages = formatWeeklySyncMessages(google, outlook, results);
|
||||||
|
if (messages.length > 0) {
|
||||||
|
onComplete(messages.join(" "));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @deprecated use registerCalendarContentHandlers */
|
||||||
|
export const registerGoogleCalendarContentHandlers = registerCalendarContentHandlers;
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
export interface GoogleCalendarEventMapEntry {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeEventMapEntry(
|
||||||
|
value: string | GoogleCalendarEventMapEntry | undefined,
|
||||||
|
): GoogleCalendarEventMapEntry | undefined {
|
||||||
|
if (value == null) return undefined;
|
||||||
|
if (typeof value === "string") return { id: value, date: "" };
|
||||||
|
if (typeof value.id === "string" && value.id.length > 0) {
|
||||||
|
return { id: value.id, date: value.date ?? "" };
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getStoredEventId(
|
||||||
|
value: string | GoogleCalendarEventMapEntry | undefined,
|
||||||
|
): string | undefined {
|
||||||
|
return normalizeEventMapEntry(value)?.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function lessonDateFromSeqtaKey(seqtaKey: string): string | undefined {
|
||||||
|
const parts = seqtaKey.split(":");
|
||||||
|
for (const part of parts) {
|
||||||
|
if (/^\d{4}-\d{2}-\d{2}$/.test(part)) return part;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { describe, expect, it } from "@jest/globals";
|
||||||
|
import {
|
||||||
|
lessonToGoogleEvent,
|
||||||
|
mapLessonsToGoogleEvents,
|
||||||
|
seqtaLessonKey,
|
||||||
|
shouldSyncLesson,
|
||||||
|
} from "./eventMapper";
|
||||||
|
import type { SeqtaTimetableLesson } from "./types";
|
||||||
|
|
||||||
|
const ORIGIN = "https://school.seqta.com.au";
|
||||||
|
|
||||||
|
const baseLesson: SeqtaTimetableLesson = {
|
||||||
|
date: "2026-06-27",
|
||||||
|
from: "09:00:00",
|
||||||
|
until: "10:00:00",
|
||||||
|
description: "10 Mathematics",
|
||||||
|
staff: "Mr Smith",
|
||||||
|
room: "MA1",
|
||||||
|
code: "10MAT",
|
||||||
|
type: "class",
|
||||||
|
calendarid: 12345,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("shouldSyncLesson", () => {
|
||||||
|
it("accepts normal class rows", () => {
|
||||||
|
expect(shouldSyncLesson(baseLesson)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects holidays and rows without times", () => {
|
||||||
|
expect(shouldSyncLesson({ ...baseLesson, type: "holiday" })).toBe(false);
|
||||||
|
expect(shouldSyncLesson({ ...baseLesson, from: "" })).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("seqtaLessonKey", () => {
|
||||||
|
it("prefers calendarid when present", () => {
|
||||||
|
expect(seqtaLessonKey(ORIGIN, baseLesson)).toBe(`${ORIGIN}:cal:12345`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("lessonToGoogleEvent", () => {
|
||||||
|
it("maps SEQTA lesson fields to Google event input", () => {
|
||||||
|
const event = lessonToGoogleEvent(ORIGIN, baseLesson, "Australia/Perth");
|
||||||
|
expect(event).toMatchObject({
|
||||||
|
summary: "10 Mathematics",
|
||||||
|
location: "MA1",
|
||||||
|
startDateTime: "2026-06-27T09:00:00",
|
||||||
|
endDateTime: "2026-06-27T10:00:00",
|
||||||
|
timeZone: "Australia/Perth",
|
||||||
|
});
|
||||||
|
expect(event?.description).toContain("Mr Smith");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("mapLessonsToGoogleEvents", () => {
|
||||||
|
it("deduplicates by seqta key", () => {
|
||||||
|
const events = mapLessonsToGoogleEvents(
|
||||||
|
ORIGIN,
|
||||||
|
[baseLesson, { ...baseLesson }],
|
||||||
|
"Australia/Perth",
|
||||||
|
);
|
||||||
|
expect(events).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { BSPLUS_GOOGLE_CALENDAR_EVENT_PROP } from "@/config/googleCalendar";
|
||||||
|
import type { GoogleCalendarEventInput, SeqtaTimetableLesson } from "./types";
|
||||||
|
|
||||||
|
const SKIP_TYPES = new Set(["note", "holiday", "assembly-note"]);
|
||||||
|
|
||||||
|
function normalizeTime(value: string): string {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (/^\d{1,2}:\d{2}:\d{2}$/.test(trimmed)) return trimmed.slice(0, 5);
|
||||||
|
if (/^\d{1,2}:\d{2}$/.test(trimmed)) return trimmed;
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function seqtaLessonKey(origin: string, lesson: SeqtaTimetableLesson): string {
|
||||||
|
if (lesson.calendarid != null && String(lesson.calendarid).length > 0) {
|
||||||
|
return `${origin}:cal:${lesson.calendarid}`;
|
||||||
|
}
|
||||||
|
if (lesson.ci != null) {
|
||||||
|
return `${origin}:ci:${lesson.ci}:${lesson.date}:${normalizeTime(lesson.from)}`;
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
origin,
|
||||||
|
lesson.date,
|
||||||
|
normalizeTime(lesson.from),
|
||||||
|
lesson.code ?? "",
|
||||||
|
lesson.description ?? "",
|
||||||
|
].join(":");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shouldSyncLesson(lesson: SeqtaTimetableLesson): boolean {
|
||||||
|
if (!lesson.date || !lesson.from || !lesson.until) return false;
|
||||||
|
if (lesson.type && SKIP_TYPES.has(lesson.type.toLowerCase())) return false;
|
||||||
|
const title = (lesson.description ?? lesson.code ?? "").trim();
|
||||||
|
if (!title) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function lessonToGoogleEvent(
|
||||||
|
origin: string,
|
||||||
|
lesson: SeqtaTimetableLesson,
|
||||||
|
timeZone: string,
|
||||||
|
): GoogleCalendarEventInput | null {
|
||||||
|
if (!shouldSyncLesson(lesson)) return null;
|
||||||
|
|
||||||
|
const from = normalizeTime(lesson.from);
|
||||||
|
const until = normalizeTime(lesson.until);
|
||||||
|
const summary = (lesson.description ?? lesson.code ?? "Class").trim();
|
||||||
|
const staff = lesson.staff?.trim();
|
||||||
|
const room = lesson.room?.trim();
|
||||||
|
|
||||||
|
const descriptionLines = ["Synced by BetterSEQTA+"];
|
||||||
|
if (staff) descriptionLines.push(`Teacher: ${staff}`);
|
||||||
|
if (lesson.code) descriptionLines.push(`Code: ${lesson.code}`);
|
||||||
|
if (lesson.period) descriptionLines.push(`Period: ${lesson.period}`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
seqtaKey: seqtaLessonKey(origin, lesson),
|
||||||
|
summary,
|
||||||
|
location: room || undefined,
|
||||||
|
description: descriptionLines.join("\n"),
|
||||||
|
startDateTime: `${lesson.date}T${from}:00`,
|
||||||
|
endDateTime: `${lesson.date}T${until}:00`,
|
||||||
|
timeZone,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapLessonsToGoogleEvents(
|
||||||
|
origin: string,
|
||||||
|
lessons: SeqtaTimetableLesson[],
|
||||||
|
timeZone: string,
|
||||||
|
): GoogleCalendarEventInput[] {
|
||||||
|
const out: GoogleCalendarEventInput[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
for (const lesson of lessons) {
|
||||||
|
const mapped = lessonToGoogleEvent(origin, lesson, timeZone);
|
||||||
|
if (!mapped || seen.has(mapped.seqtaKey)) continue;
|
||||||
|
seen.add(mapped.seqtaKey);
|
||||||
|
out.push(mapped);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function googleApiEventBody(event: GoogleCalendarEventInput): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
summary: event.summary,
|
||||||
|
location: event.location,
|
||||||
|
description: event.description,
|
||||||
|
start: { dateTime: event.startDateTime, timeZone: event.timeZone },
|
||||||
|
end: { dateTime: event.endDateTime, timeZone: event.timeZone },
|
||||||
|
extendedProperties: {
|
||||||
|
private: {
|
||||||
|
[BSPLUS_GOOGLE_CALENDAR_EVENT_PROP]: event.seqtaKey,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import type { SyncDateRange } from "./syncDateRange";
|
||||||
|
import { syncWindowRange } from "./syncDateRange";
|
||||||
|
import type { SeqtaTimetableLesson } from "./types";
|
||||||
|
|
||||||
|
async function postSeqtaJson<T>(path: string, body: Record<string, unknown>): Promise<T> {
|
||||||
|
const res = await fetch(`${location.origin}${path}`, {
|
||||||
|
method: "POST",
|
||||||
|
credentials: "include",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json; charset=utf-8",
|
||||||
|
"X-Requested-With": "XMLHttpRequest",
|
||||||
|
Accept: "text/javascript, text/html, application/xml, text/xml, */*",
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`SEQTA request failed (${res.status})`);
|
||||||
|
}
|
||||||
|
return (await res.json()) as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resolveStudentId(): Promise<number | undefined> {
|
||||||
|
try {
|
||||||
|
const json = await postSeqtaJson<{ payload?: { id?: number; student?: number } }>(
|
||||||
|
"/seqta/student/login",
|
||||||
|
{ mode: "normal", query: null, redirect_url: location.origin },
|
||||||
|
);
|
||||||
|
const id = json?.payload?.id ?? json?.payload?.student;
|
||||||
|
return typeof id === "number" && Number.isFinite(id) ? id : undefined;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isEngageParentContext(): boolean {
|
||||||
|
return (
|
||||||
|
location.pathname.includes("/parent/") ||
|
||||||
|
location.hash.includes("/parent/") ||
|
||||||
|
document.body.classList.contains("parent")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchTimetableLessons(
|
||||||
|
range: SyncDateRange,
|
||||||
|
): Promise<SeqtaTimetableLesson[]> {
|
||||||
|
const { from, until } = range;
|
||||||
|
|
||||||
|
if (isEngageParentContext()) {
|
||||||
|
const listJson = await postSeqtaJson<{ payload?: { id?: string | number }[] }>(
|
||||||
|
"/seqta/parent/load/timetable",
|
||||||
|
{ list: true },
|
||||||
|
);
|
||||||
|
const firstChild = Array.isArray(listJson?.payload) ? listJson.payload[0] : undefined;
|
||||||
|
const studentId = firstChild?.id;
|
||||||
|
if (studentId == null) {
|
||||||
|
throw new Error("No student found on this parent account.");
|
||||||
|
}
|
||||||
|
const data = await postSeqtaJson<{ payload?: { items?: SeqtaTimetableLesson[] } }>(
|
||||||
|
"/seqta/parent/load/timetable",
|
||||||
|
{ from, until, student: studentId },
|
||||||
|
);
|
||||||
|
return Array.isArray(data?.payload?.items) ? data.payload.items : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const studentId = await resolveStudentId();
|
||||||
|
const body: Record<string, unknown> = { from, until };
|
||||||
|
if (studentId != null) body.student = studentId;
|
||||||
|
|
||||||
|
const data = await postSeqtaJson<{ payload?: { items?: SeqtaTimetableLesson[] } }>(
|
||||||
|
"/seqta/student/load/timetable?",
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
return Array.isArray(data?.payload?.items) ? data.payload.items : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchTimetableForSync(weeksAhead?: number): Promise<SeqtaTimetableLesson[]> {
|
||||||
|
return fetchTimetableLessons(syncWindowRange(weeksAhead));
|
||||||
|
}
|
||||||
|
|
||||||
|
export { syncWindowRange, trailingWeekRange, droppedWeekRange } from "./syncDateRange";
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import type { GoogleCalendarEventMapEntry } from "./eventMapEntry";
|
||||||
|
|
||||||
|
/** Never uploaded to BetterSEQTA Cloud (OAuth tokens + per-device event map). */
|
||||||
|
export const BSPLUS_GOOGLE_CALENDAR_STORAGE_KEY = "bsplus_google_calendar";
|
||||||
|
|
||||||
|
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}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { describe, expect, it } from "@jest/globals";
|
||||||
|
import {
|
||||||
|
droppedWeekRange,
|
||||||
|
syncWindowRange,
|
||||||
|
trailingWeekRange,
|
||||||
|
} from "./syncDateRange";
|
||||||
|
|
||||||
|
describe("syncDateRange", () => {
|
||||||
|
it("builds a 12-week rolling window from the current week", () => {
|
||||||
|
const range = syncWindowRange(12);
|
||||||
|
expect(range.from <= range.until).toBe(true);
|
||||||
|
|
||||||
|
const start = new Date(`${range.from}T12:00:00`);
|
||||||
|
const end = new Date(`${range.until}T12:00:00`);
|
||||||
|
const days = Math.round((end.getTime() - start.getTime()) / 86_400_000) + 1;
|
||||||
|
expect(days).toBe(12 * 7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("places the trailing week at the end of the window", () => {
|
||||||
|
const window = syncWindowRange(12);
|
||||||
|
const trailing = trailingWeekRange(12);
|
||||||
|
expect(trailing.from >= window.from).toBe(true);
|
||||||
|
expect(trailing.until <= window.until).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("places the dropped week before the window start", () => {
|
||||||
|
const window = syncWindowRange(12);
|
||||||
|
const dropped = droppedWeekRange(12);
|
||||||
|
expect(dropped.until < window.from).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import {
|
||||||
|
GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT,
|
||||||
|
} from "@/config/googleCalendar";
|
||||||
|
import { toISODate, weekRangeContaining } from "@/seqta/utils/Loaders/engageParentTimetable";
|
||||||
|
|
||||||
|
export interface SyncDateRange {
|
||||||
|
from: string;
|
||||||
|
until: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseLocalDate(iso: string): Date {
|
||||||
|
return new Date(`${iso}T12:00:00`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Full rolling sync window from the start of the current week. */
|
||||||
|
export function syncWindowRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT): SyncDateRange {
|
||||||
|
const { from } = weekRangeContaining(new Date());
|
||||||
|
const end = parseLocalDate(from);
|
||||||
|
end.setDate(end.getDate() + weeksAhead * 7 - 1);
|
||||||
|
return { from, until: toISODate(end) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The trailing week at the end of the sync window (added each weekly roll). */
|
||||||
|
export function trailingWeekRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT): SyncDateRange {
|
||||||
|
const { from: windowStart } = syncWindowRange(weeksAhead);
|
||||||
|
const start = parseLocalDate(windowStart);
|
||||||
|
start.setDate(start.getDate() + (weeksAhead - 1) * 7);
|
||||||
|
const end = new Date(start);
|
||||||
|
end.setDate(end.getDate() + 6);
|
||||||
|
return { from: toISODate(start), until: toISODate(end) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The week that rolled off when the window advances (removed each weekly roll). */
|
||||||
|
export function droppedWeekRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT): SyncDateRange {
|
||||||
|
const { from: windowStart } = syncWindowRange(weeksAhead);
|
||||||
|
const end = parseLocalDate(windowStart);
|
||||||
|
end.setDate(end.getDate() - 1);
|
||||||
|
const start = new Date(end);
|
||||||
|
start.setDate(start.getDate() - 6);
|
||||||
|
return { from: toISODate(start), until: toISODate(end) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDateInRange(date: string, range: SyncDateRange): boolean {
|
||||||
|
return date >= range.from && date <= range.until;
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||||
|
import type { SeqtaTimetableLesson } from "./types";
|
||||||
|
|
||||||
|
jest.mock("@/config/googleCalendar", () => ({
|
||||||
|
isGoogleCalendarConfigured: jest.fn(() => true),
|
||||||
|
}));
|
||||||
|
|
||||||
|
jest.mock("@/utils/verboseLog", () => ({
|
||||||
|
verboseLog: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
jest.mock("@/seqta/utils/googleCalendar/storage", () => ({
|
||||||
|
eventMapKey: (origin: string, seqtaKey: string) => `${origin}::${seqtaKey}`,
|
||||||
|
readGoogleCalendarState: jest.fn(),
|
||||||
|
writeGoogleCalendarState: jest.fn(async (patch: unknown) => patch),
|
||||||
|
}));
|
||||||
|
|
||||||
|
jest.mock("@/seqta/utils/calendarSync/settings", () => ({
|
||||||
|
getSyncWeeksAhead: jest.fn(async () => 12),
|
||||||
|
}));
|
||||||
|
|
||||||
|
jest.mock("@/seqta/utils/googleCalendar/upsertEvent", () => ({
|
||||||
|
upsertGoogleCalendarEvent: jest.fn(),
|
||||||
|
deleteGoogleCalendarEvent: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/storage";
|
||||||
|
import {
|
||||||
|
deleteGoogleCalendarEvent,
|
||||||
|
upsertGoogleCalendarEvent,
|
||||||
|
} from "@/seqta/utils/googleCalendar/upsertEvent";
|
||||||
|
import { deleteSyncedEventsFromGoogleCalendar, syncLessonsToGoogleCalendar } from "./syncEngine";
|
||||||
|
|
||||||
|
const ORIGIN = "https://school.seqta.com.au";
|
||||||
|
const getAccessToken = async () => "test-token";
|
||||||
|
|
||||||
|
const baseLesson: SeqtaTimetableLesson = {
|
||||||
|
date: "2026-06-27",
|
||||||
|
from: "09:00:00",
|
||||||
|
until: "10:00:00",
|
||||||
|
description: "10 Mathematics",
|
||||||
|
staff: "Mr Smith",
|
||||||
|
room: "MA1",
|
||||||
|
code: "10MAT",
|
||||||
|
type: "class",
|
||||||
|
calendarid: 12345,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("syncLessonsToGoogleCalendar", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||||
|
refreshToken: "refresh",
|
||||||
|
eventMap: {
|
||||||
|
[`${ORIGIN}::${ORIGIN}:cal:12345`]: { id: "google-existing", date: "2026-06-27" },
|
||||||
|
[`${ORIGIN}::${ORIGIN}:cal:99999`]: { id: "google-stale", date: "2020-01-06" },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-existing");
|
||||||
|
jest.mocked(deleteGoogleCalendarEvent).mockResolvedValue(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("updates existing events and removes stale tracked events on full sync", async () => {
|
||||||
|
const result = await syncLessonsToGoogleCalendar(
|
||||||
|
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
|
||||||
|
getAccessToken,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(deleteGoogleCalendarEvent).toHaveBeenCalled();
|
||||||
|
expect(upsertGoogleCalendarEvent).toHaveBeenCalledTimes(1);
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
success: true,
|
||||||
|
created: 0,
|
||||||
|
updated: 1,
|
||||||
|
failed: 0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("creates events that are not yet tracked", async () => {
|
||||||
|
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||||
|
refreshToken: "refresh",
|
||||||
|
eventMap: {},
|
||||||
|
});
|
||||||
|
jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-new");
|
||||||
|
|
||||||
|
const result = await syncLessonsToGoogleCalendar(
|
||||||
|
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
|
||||||
|
getAccessToken,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(deleteGoogleCalendarEvent).not.toHaveBeenCalled();
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
success: true,
|
||||||
|
created: 1,
|
||||||
|
updated: 0,
|
||||||
|
deleted: 0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not delete events during incremental sync", async () => {
|
||||||
|
const result = await syncLessonsToGoogleCalendar(
|
||||||
|
{ origin: ORIGIN, lessons: [baseLesson], mode: "incremental" },
|
||||||
|
getAccessToken,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(deleteGoogleCalendarEvent).not.toHaveBeenCalled();
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
success: true,
|
||||||
|
deleted: 0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports progress while syncing", async () => {
|
||||||
|
const progress: Array<{ phase: string; current: number; total: number }> = [];
|
||||||
|
await syncLessonsToGoogleCalendar(
|
||||||
|
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
|
||||||
|
getAccessToken,
|
||||||
|
{
|
||||||
|
onProgress: (entry) => progress.push(entry),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(progress.some((entry) => entry.phase === "upserting")).toBe(true);
|
||||||
|
expect(progress.at(-1)?.phase).toBe("done");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("deleteSyncedEventsFromGoogleCalendar", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||||
|
refreshToken: "refresh",
|
||||||
|
eventMap: {
|
||||||
|
[`${ORIGIN}::${ORIGIN}:cal:12345`]: { id: "google-1", date: "2026-06-27" },
|
||||||
|
[`${ORIGIN}::${ORIGIN}:cal:99999`]: { id: "google-2", date: "2026-06-28" },
|
||||||
|
"https://other.seqta.com.au::other:key": { id: "google-other", date: "2026-06-28" },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
jest.mocked(deleteGoogleCalendarEvent).mockResolvedValue(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("deletes only events for the requested origin", async () => {
|
||||||
|
const result = await deleteSyncedEventsFromGoogleCalendar(ORIGIN, getAccessToken);
|
||||||
|
|
||||||
|
expect(deleteGoogleCalendarEvent).toHaveBeenCalledTimes(2);
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
success: true,
|
||||||
|
deleted: 2,
|
||||||
|
failed: 0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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 { 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(", ")}).`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
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,75 @@
|
|||||||
|
export interface SeqtaTimetableLesson {
|
||||||
|
date: string;
|
||||||
|
from: string;
|
||||||
|
until: string;
|
||||||
|
description: string;
|
||||||
|
staff?: string;
|
||||||
|
room?: string;
|
||||||
|
code?: string;
|
||||||
|
type?: string;
|
||||||
|
period?: string;
|
||||||
|
calendarid?: string | number;
|
||||||
|
ci?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GoogleCalendarEventInput {
|
||||||
|
seqtaKey: string;
|
||||||
|
summary: string;
|
||||||
|
location?: string;
|
||||||
|
description?: string;
|
||||||
|
startDateTime: string;
|
||||||
|
endDateTime: string;
|
||||||
|
timeZone: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GoogleCalendarSyncRequest {
|
||||||
|
origin: string;
|
||||||
|
lessons: SeqtaTimetableLesson[];
|
||||||
|
mode?: "full" | "incremental";
|
||||||
|
weeksAhead?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type GoogleCalendarSyncPhase = "preparing" | "deleting" | "upserting" | "done";
|
||||||
|
|
||||||
|
export interface GoogleCalendarSyncProgress {
|
||||||
|
phase: GoogleCalendarSyncPhase;
|
||||||
|
current: number;
|
||||||
|
total: number;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GoogleCalendarSyncOptions {
|
||||||
|
onProgress?: (progress: GoogleCalendarSyncProgress) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GoogleCalendarSyncResult {
|
||||||
|
success: boolean;
|
||||||
|
connected?: boolean;
|
||||||
|
configured?: boolean;
|
||||||
|
created?: number;
|
||||||
|
updated?: number;
|
||||||
|
deleted?: number;
|
||||||
|
skipped?: number;
|
||||||
|
failed?: number;
|
||||||
|
lastSyncAt?: number;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GoogleCalendarStatus {
|
||||||
|
configured: boolean;
|
||||||
|
connected: boolean;
|
||||||
|
lastSyncAt?: number;
|
||||||
|
lastWeeklySyncAt?: number;
|
||||||
|
lastSyncOrigin?: string;
|
||||||
|
syncWeeksAhead?: number;
|
||||||
|
autoSyncWeekly?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GoogleCalendarDeleteResult {
|
||||||
|
success: boolean;
|
||||||
|
configured?: boolean;
|
||||||
|
connected?: boolean;
|
||||||
|
deleted?: number;
|
||||||
|
failed?: number;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
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})`);
|
||||||
|
}
|
||||||
@@ -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,249 @@
|
|||||||
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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})`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
type ColorChannels = {
|
||||||
|
r: number;
|
||||||
|
g: number;
|
||||||
|
b: number;
|
||||||
|
a: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function clampByte(value: number): number {
|
||||||
|
return Math.max(0, Math.min(255, Math.round(value)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function clampAlpha(value: number): number {
|
||||||
|
return Math.max(0, Math.min(1, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function toHexByte(value: number): string {
|
||||||
|
return clampByte(value).toString(16).padStart(2, "0");
|
||||||
|
}
|
||||||
|
|
||||||
|
function createColor(channels: ColorChannels) {
|
||||||
|
const color = {
|
||||||
|
red: () => clampByte(channels.r),
|
||||||
|
green: () => clampByte(channels.g),
|
||||||
|
blue: () => clampByte(channels.b),
|
||||||
|
alpha: () => clampAlpha(channels.a),
|
||||||
|
hex: () =>
|
||||||
|
`#${toHexByte(channels.r)}${toHexByte(channels.g)}${toHexByte(channels.b)}`,
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
...color,
|
||||||
|
alpha: (value?: number) => {
|
||||||
|
if (value === undefined) return clampAlpha(channels.a);
|
||||||
|
return createColor({ ...channels, a: value });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseHex(input: string): ColorChannels | null {
|
||||||
|
const short = input.match(/^#([0-9a-f]{3})$/i);
|
||||||
|
if (short) {
|
||||||
|
const [r, g, b] = short[1].split("");
|
||||||
|
return {
|
||||||
|
r: parseInt(`${r}${r}`, 16),
|
||||||
|
g: parseInt(`${g}${g}`, 16),
|
||||||
|
b: parseInt(`${b}${b}`, 16),
|
||||||
|
a: 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const long = input.match(/^#([0-9a-f]{6})$/i);
|
||||||
|
if (!long) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
r: parseInt(long[1].slice(0, 2), 16),
|
||||||
|
g: parseInt(long[1].slice(2, 4), 16),
|
||||||
|
b: parseInt(long[1].slice(4, 6), 16),
|
||||||
|
a: 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseRgb(input: string): ColorChannels | null {
|
||||||
|
const match = input.match(
|
||||||
|
/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)/i,
|
||||||
|
);
|
||||||
|
if (!match) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
r: Number(match[1]),
|
||||||
|
g: Number(match[2]),
|
||||||
|
b: Number(match[3]),
|
||||||
|
a: match[4] !== undefined ? Number(match[4]) : 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function Color(input: string) {
|
||||||
|
const channels = parseHex(input) ?? parseRgb(input);
|
||||||
|
if (!channels) {
|
||||||
|
throw new Error(`Unable to parse color: ${input}`);
|
||||||
|
}
|
||||||
|
return createColor(channels);
|
||||||
|
}
|
||||||
|
|
||||||
|
Color.rgb = (r: number, g: number, b: number) => createColor({ r, g, b, a: 1 });
|
||||||
|
|
||||||
|
export default Color;
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
|
|
||||||
|
const VERBOSE_LOG_ATTR = "data-bsplus-verbose-log";
|
||||||
|
|
||||||
|
export function isVerboseLoggingEnabled(): boolean {
|
||||||
|
return Boolean(settingsState.devMode && settingsState.verboseLogging);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function syncVerboseLogDomFlag(): void {
|
||||||
|
if (typeof document === "undefined") return;
|
||||||
|
document.documentElement.toggleAttribute(
|
||||||
|
VERBOSE_LOG_ATTR,
|
||||||
|
isVerboseLoggingEnabled(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let initialized = false;
|
||||||
|
|
||||||
|
/** Register DOM flag sync when dev / verbose toggles change. Call after settings load. */
|
||||||
|
export function initVerboseLogging(): void {
|
||||||
|
if (initialized) return;
|
||||||
|
initialized = true;
|
||||||
|
syncVerboseLogDomFlag();
|
||||||
|
settingsState.register("devMode", () => syncVerboseLogDomFlag());
|
||||||
|
settingsState.register("verboseLogging", () => syncVerboseLogDomFlag());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function verboseDebug(...args: unknown[]): void {
|
||||||
|
if (isVerboseLoggingEnabled()) console.debug(...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function verboseInfo(...args: unknown[]): void {
|
||||||
|
if (isVerboseLoggingEnabled()) console.info(...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function verboseLog(...args: unknown[]): void {
|
||||||
|
if (isVerboseLoggingEnabled()) console.log(...args);
|
||||||
|
}
|
||||||
+13
-3
@@ -1,4 +1,4 @@
|
|||||||
import { defineConfig } from "vite";
|
import { defineConfig, loadEnv } from "vite";
|
||||||
import { join, resolve } from "path";
|
import { join, resolve } from "path";
|
||||||
|
|
||||||
import touchGlobalCSSPlugin from "./lib/touchGlobalCSS";
|
import touchGlobalCSSPlugin from "./lib/touchGlobalCSS";
|
||||||
@@ -59,7 +59,13 @@ const mode = process.env.MODE || "chrome"; // Check the environment variable to
|
|||||||
/** Million's compiler can emit `new Function()`, which Firefox extension pages block (strict CSP, no unsafe-eval). */
|
/** Million's compiler can emit `new Function()`, which Firefox extension pages block (strict CSP, no unsafe-eval). */
|
||||||
const useMillion = mode.toLowerCase() !== "firefox";
|
const useMillion = mode.toLowerCase() !== "firefox";
|
||||||
|
|
||||||
export default defineConfig(({ command }) => ({
|
const repoRoot = __dirname;
|
||||||
|
|
||||||
|
export default defineConfig(({ command, mode: viteMode }) => {
|
||||||
|
// `.env` lives at repo root (not `src/`). Required for `npm run dev` and builds.
|
||||||
|
const env = loadEnv(viteMode, repoRoot, "");
|
||||||
|
|
||||||
|
return {
|
||||||
// Content scripts run on the host page; absolute `/assets/...` URLs would
|
// Content scripts run on the host page; absolute `/assets/...` URLs would
|
||||||
// resolve against SEQTA instead of chrome-extension://. Relative base makes
|
// resolve against SEQTA instead of chrome-extension://. Relative base makes
|
||||||
// Vite emit import.meta.url-relative chunk/CSS URLs at runtime.
|
// Vite emit import.meta.url-relative chunk/CSS URLs at runtime.
|
||||||
@@ -73,7 +79,10 @@ export default defineConfig(({ command }) => ({
|
|||||||
),
|
),
|
||||||
__UPDATE_CHANNEL__: JSON.stringify(process.env.UPDATE_CHANNEL ?? "stable"),
|
__UPDATE_CHANNEL__: JSON.stringify(process.env.UPDATE_CHANNEL ?? "stable"),
|
||||||
__BUILD_LABEL__: JSON.stringify(process.env.BUILD_LABEL ?? ""),
|
__BUILD_LABEL__: JSON.stringify(process.env.BUILD_LABEL ?? ""),
|
||||||
|
__GOOGLE_OAUTH_CLIENT_ID__: JSON.stringify(env.GOOGLE_OAUTH_CLIENT_ID ?? ""),
|
||||||
|
__OUTLOOK_OAUTH_CLIENT_ID__: JSON.stringify(env.OUTLOOK_OAUTH_CLIENT_ID ?? ""),
|
||||||
},
|
},
|
||||||
|
envDir: repoRoot,
|
||||||
plugins: [
|
plugins: [
|
||||||
base64Loader,
|
base64Loader,
|
||||||
InlineWorkerPlugin(),
|
InlineWorkerPlugin(),
|
||||||
@@ -145,4 +154,5 @@ export default defineConfig(({ command }) => ({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}));
|
};
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user