mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-08-28 17:21:05 +00:00
feat: tweak calendar and clean it up
This commit is contained in:
+2
-1
@@ -13,7 +13,7 @@ import {
|
|||||||
withSuppressedCloudAutoUpload,
|
withSuppressedCloudAutoUpload,
|
||||||
} from "./background/cloudSettingsAutoSync";
|
} from "./background/cloudSettingsAutoSync";
|
||||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||||
import { registerGoogleCalendarMessageHandlers } from "./background/googleCalendar";
|
import { registerGoogleCalendarMessageHandlers, initGoogleCalendarBackground } from "./background/googleCalendar";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Session-only dev-mode override of the content API base.
|
* Session-only dev-mode override of the content API base.
|
||||||
@@ -559,6 +559,7 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
registerGoogleCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
registerGoogleCalendarMessageHandlers(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
|
||||||
|
|||||||
@@ -16,10 +16,20 @@ import {
|
|||||||
readGoogleCalendarState,
|
readGoogleCalendarState,
|
||||||
writeGoogleCalendarState,
|
writeGoogleCalendarState,
|
||||||
} from "@/seqta/utils/googleCalendar/storage";
|
} from "@/seqta/utils/googleCalendar/storage";
|
||||||
|
import {
|
||||||
|
clampSyncWeeks,
|
||||||
|
getAutoSyncWeekly,
|
||||||
|
getSyncWeeksAhead,
|
||||||
|
} from "@/seqta/utils/googleCalendar/syncSettings";
|
||||||
import type {
|
import type {
|
||||||
GoogleCalendarStatus,
|
GoogleCalendarStatus,
|
||||||
GoogleCalendarSyncResult,
|
GoogleCalendarSyncResult,
|
||||||
} from "@/seqta/utils/googleCalendar/types";
|
} from "@/seqta/utils/googleCalendar/types";
|
||||||
|
import {
|
||||||
|
clearWeeklySyncAlarm,
|
||||||
|
ensureWeeklySyncAlarm,
|
||||||
|
registerWeeklySyncAlarmListener,
|
||||||
|
} from "./googleCalendarWeekly";
|
||||||
|
|
||||||
function base64UrlEncode(buffer: ArrayBuffer): string {
|
function base64UrlEncode(buffer: ArrayBuffer): string {
|
||||||
const bytes = new Uint8Array(buffer);
|
const bytes = new Uint8Array(buffer);
|
||||||
@@ -197,6 +207,8 @@ async function connectGoogleCalendar(): Promise<GoogleCalendarSyncResult> {
|
|||||||
connectedAt: Date.now(),
|
connectedAt: Date.now(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
await ensureWeeklySyncAlarm();
|
||||||
|
|
||||||
return { success: true, configured: true, connected: true };
|
return { success: true, configured: true, connected: true };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return {
|
return {
|
||||||
@@ -209,11 +221,16 @@ async function connectGoogleCalendar(): Promise<GoogleCalendarSyncResult> {
|
|||||||
|
|
||||||
async function getGoogleCalendarStatus(): Promise<GoogleCalendarStatus> {
|
async function getGoogleCalendarStatus(): Promise<GoogleCalendarStatus> {
|
||||||
const state = await readGoogleCalendarState();
|
const state = await readGoogleCalendarState();
|
||||||
|
const syncWeeksAhead = await getSyncWeeksAhead();
|
||||||
|
const autoSyncWeekly = await getAutoSyncWeekly();
|
||||||
return {
|
return {
|
||||||
configured: isGoogleCalendarConfigured(),
|
configured: isGoogleCalendarConfigured(),
|
||||||
connected: !!(state.refreshToken || state.accessToken),
|
connected: !!(state.refreshToken || state.accessToken),
|
||||||
lastSyncAt: state.lastSyncAt,
|
lastSyncAt: state.lastSyncAt,
|
||||||
|
lastWeeklySyncAt: state.lastWeeklySyncAt,
|
||||||
lastSyncOrigin: state.lastSyncOrigin,
|
lastSyncOrigin: state.lastSyncOrigin,
|
||||||
|
syncWeeksAhead,
|
||||||
|
autoSyncWeekly,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,6 +239,7 @@ export async function handleGoogleCalendarConnect(): Promise<GoogleCalendarSyncR
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function handleGoogleCalendarDisconnect(): Promise<{ success: boolean }> {
|
export async function handleGoogleCalendarDisconnect(): Promise<{ success: boolean }> {
|
||||||
|
await clearWeeklySyncAlarm();
|
||||||
await clearGoogleCalendarState();
|
await clearGoogleCalendarState();
|
||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
@@ -298,4 +316,50 @@ export function registerGoogleCalendarMessageHandlers(
|
|||||||
});
|
});
|
||||||
return true;
|
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 writeGoogleCalendarState(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 function initGoogleCalendarBackground(): void {
|
||||||
|
registerWeeklySyncAlarmListener();
|
||||||
|
void ensureWeeklySyncAlarm();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import { verboseLog } from "@/utils/verboseLog";
|
||||||
|
import {
|
||||||
|
getAutoSyncWeekly,
|
||||||
|
GOOGLE_CALENDAR_WEEKLY_ALARM,
|
||||||
|
markWeeklySyncPending,
|
||||||
|
} from "@/seqta/utils/googleCalendar/syncSettings";
|
||||||
|
import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/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 isCalendarConnected(): Promise<boolean> {
|
||||||
|
const state = await readGoogleCalendarState();
|
||||||
|
return !!(state.refreshToken || state.accessToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function ensureWeeklySyncAlarm(): Promise<void> {
|
||||||
|
const connected = await isCalendarConnected();
|
||||||
|
const enabled = await getAutoSyncWeekly();
|
||||||
|
if (!connected || !enabled) {
|
||||||
|
await browser.alarms.clear(GOOGLE_CALENDAR_WEEKLY_ALARM);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await browser.alarms.get(GOOGLE_CALENDAR_WEEKLY_ALARM);
|
||||||
|
if (!existing) {
|
||||||
|
await browser.alarms.create(GOOGLE_CALENDAR_WEEKLY_ALARM, {
|
||||||
|
periodInMinutes: WEEKLY_PERIOD_MINUTES,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function clearWeeklySyncAlarm(): Promise<void> {
|
||||||
|
await browser.alarms.clear(GOOGLE_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: "googleCalendarRunWeeklySync" });
|
||||||
|
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 isCalendarConnected()) || !(await getAutoSyncWeekly())) return;
|
||||||
|
|
||||||
|
const delivered = await triggerWeeklySyncOnSeqtaTabs();
|
||||||
|
if (!delivered) {
|
||||||
|
await markWeeklySyncPending();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerWeeklySyncAlarmListener(): void {
|
||||||
|
browser.alarms.onAlarm.addListener((alarm) => {
|
||||||
|
if (alarm.name !== GOOGLE_CALENDAR_WEEKLY_ALARM) return;
|
||||||
|
void handleWeeklySyncAlarm();
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -28,8 +28,11 @@ export const GOOGLE_CALENDAR_API = "https://www.googleapis.com/calendar/v3";
|
|||||||
|
|
||||||
export const BSPLUS_GOOGLE_CALENDAR_EVENT_PROP = "bsplusSeqtaKey";
|
export const BSPLUS_GOOGLE_CALENDAR_EVENT_PROP = "bsplusSeqtaKey";
|
||||||
|
|
||||||
/** Weeks of timetable to sync (from start of current week). */
|
/** 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 = 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 {
|
export function isGoogleCalendarConfigured(): boolean {
|
||||||
return GOOGLE_OAUTH_CLIENT_ID.length > 0;
|
return GOOGLE_OAUTH_CLIENT_ID.length > 0;
|
||||||
|
|||||||
@@ -15,7 +15,7 @@
|
|||||||
"64": "resources/icons/icon-64.png"
|
"64": "resources/icons/icon-64.png"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"permissions": ["tabs", "notifications", "storage", "identity"],
|
"permissions": ["tabs", "notifications", "storage", "identity", "alarms"],
|
||||||
"host_permissions": [
|
"host_permissions": [
|
||||||
"https://newsapi.org/",
|
"https://newsapi.org/",
|
||||||
"https://betterseqta.org/",
|
"https://betterseqta.org/",
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { fade } from "svelte/transition";
|
||||||
|
|
||||||
|
let {
|
||||||
|
open = false,
|
||||||
|
busy = false,
|
||||||
|
onConfirm,
|
||||||
|
onCancel,
|
||||||
|
} = $props<{
|
||||||
|
open?: boolean;
|
||||||
|
busy?: boolean;
|
||||||
|
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 Google 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>
|
||||||
@@ -2,20 +2,38 @@
|
|||||||
import { onMount } from "svelte";
|
import { onMount } from "svelte";
|
||||||
import { fade, fly } from "svelte/transition";
|
import { fade, fly } from "svelte/transition";
|
||||||
import browser from "webextension-polyfill";
|
import browser from "webextension-polyfill";
|
||||||
import { fetchTimetableForSync } from "@/seqta/utils/googleCalendar/fetchTimetable";
|
import {
|
||||||
import { syncLessonsToGoogleCalendar } from "@/seqta/utils/googleCalendar/syncEngine";
|
GOOGLE_CALENDAR_SYNC_WEEKS_MAX,
|
||||||
import type { GoogleCalendarStatus, GoogleCalendarSyncResult } from "@/seqta/utils/googleCalendar/types";
|
GOOGLE_CALENDAR_SYNC_WEEKS_MIN,
|
||||||
|
} from "@/config/googleCalendar";
|
||||||
|
import { maybeRunDueWeeklySync } from "@/seqta/utils/googleCalendar/calendarSyncListener";
|
||||||
|
import { deleteSyncedEventsFromGoogleCalendar } from "@/seqta/utils/googleCalendar/syncEngine";
|
||||||
|
import {
|
||||||
|
formatSyncResultMessage,
|
||||||
|
runGoogleCalendarSync,
|
||||||
|
} from "@/seqta/utils/googleCalendar/syncRunner";
|
||||||
|
import type {
|
||||||
|
GoogleCalendarStatus,
|
||||||
|
GoogleCalendarSyncProgress,
|
||||||
|
GoogleCalendarSyncResult,
|
||||||
|
} from "@/seqta/utils/googleCalendar/types";
|
||||||
|
import CalendarDeleteEventsModal from "./CalendarDeleteEventsModal.svelte";
|
||||||
import CalendarDisconnectModal from "./CalendarDisconnectModal.svelte";
|
import CalendarDisconnectModal from "./CalendarDisconnectModal.svelte";
|
||||||
|
import CalendarSyncProgress from "./CalendarSyncProgress.svelte";
|
||||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
import { syncCalendarSyncTheme } from "./calendarSyncTheme";
|
import { syncCalendarSyncTheme } from "./calendarSyncTheme";
|
||||||
|
|
||||||
type BusyPhase = "connect" | "sync" | "disconnect" | null;
|
type BusyPhase = "connect" | "sync" | "delete" | "disconnect" | null;
|
||||||
|
|
||||||
let status = $state<GoogleCalendarStatus>({ configured: true, connected: false });
|
let status = $state<GoogleCalendarStatus>({ configured: true, connected: false });
|
||||||
let busy = $state<BusyPhase>(null);
|
let busy = $state<BusyPhase>(null);
|
||||||
let menuOpen = $state(false);
|
let menuOpen = $state(false);
|
||||||
let showDisconnect = $state(false);
|
let showDisconnect = $state(false);
|
||||||
|
let showDeleteEvents = $state(false);
|
||||||
let toast = $state<{ message: string; error: boolean } | null>(null);
|
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 rootEl = $state<HTMLDivElement | null>(null);
|
||||||
let triggerEl = $state<HTMLButtonElement | null>(null);
|
let triggerEl = $state<HTMLButtonElement | null>(null);
|
||||||
@@ -38,6 +56,8 @@
|
|||||||
status = (await browser.runtime.sendMessage({
|
status = (await browser.runtime.sendMessage({
|
||||||
type: "googleCalendarStatus",
|
type: "googleCalendarStatus",
|
||||||
})) as GoogleCalendarStatus;
|
})) as GoogleCalendarStatus;
|
||||||
|
syncWeeksAhead = status.syncWeeksAhead ?? 12;
|
||||||
|
autoSyncWeekly = status.autoSyncWeekly !== false;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getAccessTokenFromBackground(): Promise<string> {
|
async function getAccessTokenFromBackground(): Promise<string> {
|
||||||
@@ -50,26 +70,42 @@
|
|||||||
return res.accessToken;
|
return res.accessToken;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function performSync(): Promise<boolean> {
|
function handleSyncProgress(progress: GoogleCalendarSyncProgress) {
|
||||||
const lessons = await fetchTimetableForSync();
|
syncProgress = progress;
|
||||||
const result = await syncLessonsToGoogleCalendar(
|
}
|
||||||
{ origin: location.origin, lessons },
|
|
||||||
getAccessTokenFromBackground,
|
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;
|
||||||
|
status = { ...status, ...result };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function performSync(mode: "full" | "incremental" = "full"): Promise<boolean> {
|
||||||
|
const result = await runGoogleCalendarSync({
|
||||||
|
mode,
|
||||||
|
onProgress: handleSyncProgress,
|
||||||
|
});
|
||||||
|
|
||||||
|
syncProgress = null;
|
||||||
|
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
showToastMessage(result.error ?? "Calendar sync failed.", true);
|
showToastMessage(result.error ?? "Calendar sync failed.", true);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const created = result.created ?? 0;
|
|
||||||
const updated = result.updated ?? 0;
|
|
||||||
status = {
|
status = {
|
||||||
...status,
|
...status,
|
||||||
connected: true,
|
connected: true,
|
||||||
lastSyncAt: result.lastSyncAt ?? status.lastSyncAt,
|
lastSyncAt: result.lastSyncAt ?? status.lastSyncAt,
|
||||||
};
|
};
|
||||||
showToastMessage(`Google Calendar updated (${created} new, ${updated} updated).`);
|
showToastMessage(formatSyncResultMessage(result));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,6 +127,7 @@
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
showToastMessage(err instanceof Error ? err.message : "Could not connect.", true);
|
showToastMessage(err instanceof Error ? err.message : "Could not connect.", true);
|
||||||
} finally {
|
} finally {
|
||||||
|
syncProgress = null;
|
||||||
busy = null;
|
busy = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -108,10 +145,60 @@
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
showToastMessage(err instanceof Error ? err.message : "Calendar sync failed.", true);
|
showToastMessage(err instanceof Error ? err.message : "Calendar sync failed.", true);
|
||||||
} finally {
|
} finally {
|
||||||
|
syncProgress = null;
|
||||||
busy = null;
|
busy = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function confirmDeleteEvents() {
|
||||||
|
if (isBusy) return;
|
||||||
|
busy = "delete";
|
||||||
|
syncProgress = {
|
||||||
|
phase: "preparing",
|
||||||
|
current: 0,
|
||||||
|
total: 1,
|
||||||
|
message: "Preparing removal…",
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const result = await deleteSyncedEventsFromGoogleCalendar(
|
||||||
|
location.origin,
|
||||||
|
getAccessTokenFromBackground,
|
||||||
|
{ onProgress: handleSyncProgress },
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
showToastMessage(result.error ?? "Could not remove calendar events.", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const removed = result.deleted ?? 0;
|
||||||
|
showDeleteEvents = false;
|
||||||
|
menuOpen = false;
|
||||||
|
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() {
|
async function confirmDisconnect() {
|
||||||
if (isBusy) return;
|
if (isBusy) return;
|
||||||
busy = "disconnect";
|
busy = "disconnect";
|
||||||
@@ -198,7 +285,12 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
|
void refreshStatus().then(() => {
|
||||||
|
void maybeRunDueWeeklySync((message, isError) => {
|
||||||
|
showToastMessage(message, isError);
|
||||||
void refreshStatus();
|
void refreshStatus();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
const themeKeys = [
|
const themeKeys = [
|
||||||
"selectedColor",
|
"selectedColor",
|
||||||
@@ -241,7 +333,7 @@
|
|||||||
<div class="bsplus-cal-sync" bind:this={rootEl}>
|
<div class="bsplus-cal-sync" bind:this={rootEl}>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="bsplus-cal-trigger"
|
class="uiButton bsplus-cal-trigger iconFamily"
|
||||||
bind:this={triggerEl}
|
bind:this={triggerEl}
|
||||||
class:bsplus-cal-trigger--open={menuOpen}
|
class:bsplus-cal-trigger--open={menuOpen}
|
||||||
class:bsplus-cal-trigger--connected={status.connected}
|
class:bsplus-cal-trigger--connected={status.connected}
|
||||||
@@ -254,27 +346,11 @@
|
|||||||
if (!isBusy) toggleMenu();
|
if (!isBusy) toggleMenu();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<span class="bsplus-cal-trigger-label" aria-hidden="true">
|
<span class="bsplus-cal-trigger-icon" aria-hidden="true"></span>
|
||||||
<span class="bsplus-google-word">
|
<span class="bsplus-cal-trigger-text">Calendar</span>
|
||||||
<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 class="bsplus-cal-word">Calendar</span>
|
|
||||||
</span>
|
|
||||||
{#if status.connected}
|
{#if status.connected}
|
||||||
<span class="bsplus-cal-status-dot" aria-hidden="true"></span>
|
<span class="bsplus-cal-status-dot" aria-hidden="true"></span>
|
||||||
{/if}
|
{/if}
|
||||||
<span class="bsplus-cal-chevron" aria-hidden="true">
|
|
||||||
<svg viewBox="0 0 20 20" fill="currentColor">
|
|
||||||
<path
|
|
||||||
fill-rule="evenodd"
|
|
||||||
d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.94a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z"
|
|
||||||
clip-rule="evenodd"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
</span>
|
|
||||||
{#if isBusy}
|
|
||||||
<span class="bsplus-cal-spinner" aria-hidden="true"></span>
|
|
||||||
{/if}
|
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{#if menuOpen}
|
{#if menuOpen}
|
||||||
@@ -332,6 +408,38 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{#if status.connected}
|
||||||
|
<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">
|
||||||
|
Keeps a rolling {syncWeeksAhead}-week window. Each week adds the next week and removes the oldest.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<CalendarSyncProgress progress={syncProgress} />
|
||||||
|
|
||||||
<div class="bsplus-cal-provider-actions">
|
<div class="bsplus-cal-provider-actions">
|
||||||
{#if !status.connected}
|
{#if !status.connected}
|
||||||
<button
|
<button
|
||||||
@@ -355,6 +463,17 @@
|
|||||||
>
|
>
|
||||||
{busy === "sync" ? "Syncing…" : "Sync now"}
|
{busy === "sync" ? "Syncing…" : "Sync now"}
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="bsplus-cal-action bsplus-cal-action--ghost"
|
||||||
|
role="menuitem"
|
||||||
|
disabled={isBusy}
|
||||||
|
onclick={() => {
|
||||||
|
showDeleteEvents = true;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{busy === "delete" ? "Removing…" : "Remove from calendar"}
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="bsplus-cal-action bsplus-cal-action--ghost"
|
class="bsplus-cal-action bsplus-cal-action--ghost"
|
||||||
@@ -377,6 +496,15 @@
|
|||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
<CalendarDeleteEventsModal
|
||||||
|
open={showDeleteEvents}
|
||||||
|
busy={busy === "delete"}
|
||||||
|
onCancel={() => {
|
||||||
|
if (busy !== "delete") showDeleteEvents = false;
|
||||||
|
}}
|
||||||
|
onConfirm={confirmDeleteEvents}
|
||||||
|
/>
|
||||||
|
|
||||||
<CalendarDisconnectModal
|
<CalendarDisconnectModal
|
||||||
open={showDisconnect}
|
open={showDisconnect}
|
||||||
busy={busy === "disconnect"}
|
busy={busy === "disconnect"}
|
||||||
@@ -402,7 +530,7 @@
|
|||||||
.bsplus-cal-sync {
|
.bsplus-cal-sync {
|
||||||
position: relative;
|
position: relative;
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
font-family: Rubik, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||||
color: var(--bsplus-cal-text, var(--text-primary, #111));
|
color: var(--bsplus-cal-text, var(--text-primary, #111));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -411,33 +539,31 @@
|
|||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: 8px;
|
gap: 6px;
|
||||||
min-width: 188px;
|
min-width: auto;
|
||||||
height: 42px;
|
height: auto;
|
||||||
padding: 0 12px 0 14px;
|
padding: 0 10px;
|
||||||
border: 1px solid color-mix(in srgb, var(--bsplus-cal-text, #111) 14%, transparent);
|
margin-left: 4px;
|
||||||
border-radius: 10px;
|
border-radius: 16px !important;
|
||||||
background: color-mix(in srgb, var(--bsplus-cal-surface, #fff) 88%, transparent);
|
|
||||||
color: var(--bsplus-cal-text, var(--text-primary, #111));
|
|
||||||
cursor: pointer;
|
|
||||||
transition: all 0.2s ease;
|
transition: all 0.2s ease;
|
||||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-cal-trigger-label {
|
.bsplus-cal-trigger-icon {
|
||||||
display: inline-flex;
|
font-size: 16px;
|
||||||
align-items: baseline;
|
line-height: 1;
|
||||||
gap: 6px;
|
opacity: 0.9;
|
||||||
font-size: 17px;
|
}
|
||||||
font-weight: 700;
|
|
||||||
letter-spacing: -0.01em;
|
.bsplus-cal-trigger-text {
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
line-height: 1;
|
line-height: 1;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-google-word {
|
.bsplus-google-word {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
font-size: 18px;
|
font-size: 13px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
letter-spacing: -0.02em;
|
letter-spacing: -0.02em;
|
||||||
}
|
}
|
||||||
@@ -464,34 +590,20 @@
|
|||||||
color: #34a853;
|
color: #34a853;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-cal-word {
|
|
||||||
color: var(--bsplus-cal-text, var(--text-primary, #111));
|
|
||||||
font-weight: 700;
|
|
||||||
}
|
|
||||||
|
|
||||||
.bsplus-cal-trigger:hover:not(.bsplus-cal-trigger--busy) {
|
.bsplus-cal-trigger:hover:not(.bsplus-cal-trigger--busy) {
|
||||||
transform: scale(1.03);
|
transform: scale(1.03);
|
||||||
border-color: color-mix(in srgb, var(--bsplus-cal-accent, var(--better-main, #3b82f6)) 45%, transparent);
|
|
||||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-cal-trigger:active:not(.bsplus-cal-trigger--busy) {
|
.bsplus-cal-trigger:active:not(.bsplus-cal-trigger--busy) {
|
||||||
transform: scale(0.97);
|
transform: scale(0.97);
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-cal-trigger:focus-visible {
|
|
||||||
outline: none;
|
|
||||||
box-shadow: 0 0 0 2px var(--bsplus-cal-surface, #fff),
|
|
||||||
0 0 0 4px var(--bsplus-cal-accent, var(--better-main, #3b82f6));
|
|
||||||
}
|
|
||||||
|
|
||||||
.bsplus-cal-trigger--open {
|
.bsplus-cal-trigger--open {
|
||||||
border-color: color-mix(in srgb, var(--bsplus-cal-accent, var(--better-main, #3b82f6)) 55%, transparent);
|
background: color-mix(in srgb, var(--bsplus-cal-accent, var(--better-main, #3b82f6)) 14%, transparent) !important;
|
||||||
background: color-mix(in srgb, var(--bsplus-cal-accent, var(--better-main, #3b82f6)) 10%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-cal-trigger--connected {
|
.bsplus-cal-trigger--connected .bsplus-cal-status-dot {
|
||||||
border-color: color-mix(in srgb, #22c55e 50%, transparent);
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-cal-trigger--busy {
|
.bsplus-cal-trigger--busy {
|
||||||
@@ -501,45 +613,61 @@
|
|||||||
|
|
||||||
.bsplus-cal-status-dot {
|
.bsplus-cal-status-dot {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 7px;
|
top: 4px;
|
||||||
right: 26px;
|
right: 4px;
|
||||||
width: 7px;
|
width: 7px;
|
||||||
height: 7px;
|
height: 7px;
|
||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
background: #22c55e;
|
background: #22c55e;
|
||||||
box-shadow: 0 0 0 2px var(--bsplus-cal-surface, #fff);
|
box-shadow: 0 0 0 2px var(--bsplus-cal-surface, #fff);
|
||||||
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-cal-chevron {
|
.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;
|
display: flex;
|
||||||
flex: 0 0 auto;
|
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;
|
width: 16px;
|
||||||
height: 16px;
|
height: 16px;
|
||||||
margin-left: auto;
|
accent-color: var(--bsplus-cal-accent, var(--better-main, #3b82f6));
|
||||||
opacity: 0.6;
|
|
||||||
pointer-events: none;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-cal-chevron svg {
|
.bsplus-cal-setting-hint {
|
||||||
width: 100%;
|
margin: 0;
|
||||||
height: 100%;
|
font-size: 10px;
|
||||||
}
|
line-height: 1.4;
|
||||||
|
color: color-mix(in srgb, var(--bsplus-cal-text, #111) 58%, transparent);
|
||||||
.bsplus-cal-spinner {
|
|
||||||
position: absolute;
|
|
||||||
right: 10px;
|
|
||||||
width: 16px;
|
|
||||||
height: 16px;
|
|
||||||
border-radius: 999px;
|
|
||||||
border: 2px solid color-mix(in srgb, var(--bsplus-cal-accent, #3b82f6) 25%, transparent);
|
|
||||||
border-top-color: var(--bsplus-cal-accent, #3b82f6);
|
|
||||||
animation: bsplus-cal-spin 0.7s linear infinite;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes bsplus-cal-spin {
|
|
||||||
to {
|
|
||||||
transform: rotate(360deg);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-cal-menu {
|
.bsplus-cal-menu {
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { mount, unmount } from "svelte";
|
import { mount, unmount } from "svelte";
|
||||||
import CalendarSyncControl from "./CalendarSyncControl.svelte";
|
import CalendarSyncControl from "./CalendarSyncControl.svelte";
|
||||||
import { syncCalendarSyncTheme } from "./calendarSyncTheme";
|
import { syncCalendarSyncTheme } from "./calendarSyncTheme";
|
||||||
|
import { registerGoogleCalendarContentHandlers } from "@/seqta/utils/googleCalendar/calendarSyncListener";
|
||||||
import hostStyles from "./calendarSyncHost.css?inline";
|
import hostStyles from "./calendarSyncHost.css?inline";
|
||||||
|
|
||||||
const CONTROLS_CLASS = "timetable-calendar-controls";
|
const CONTROLS_CLASS = "timetable-calendar-controls";
|
||||||
@@ -35,6 +36,7 @@ export async function mountGoogleCalendarButton(): Promise<void> {
|
|||||||
if (!toolbar) return;
|
if (!toolbar) return;
|
||||||
|
|
||||||
ensureHostStyles();
|
ensureHostStyles();
|
||||||
|
registerGoogleCalendarContentHandlers();
|
||||||
|
|
||||||
const controls = document.createElement("div");
|
const controls = document.createElement("div");
|
||||||
controls.className = `${CONTROLS_CLASS} bsplus-timetable-control`;
|
controls.className = `${CONTROLS_CLASS} bsplus-timetable-control`;
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import { shouldRunWeeklySync } from "@/seqta/utils/googleCalendar/syncSettings";
|
||||||
|
import {
|
||||||
|
formatSyncResultMessage,
|
||||||
|
runGoogleCalendarSync,
|
||||||
|
} from "@/seqta/utils/googleCalendar/syncRunner";
|
||||||
|
import type { GoogleCalendarSyncResult } from "@/seqta/utils/googleCalendar/types";
|
||||||
|
|
||||||
|
let listenerRegistered = false;
|
||||||
|
|
||||||
|
export function registerGoogleCalendarContentHandlers(): void {
|
||||||
|
if (listenerRegistered) return;
|
||||||
|
listenerRegistered = true;
|
||||||
|
|
||||||
|
browser.runtime.onMessage.addListener((request, _sender, sendResponse) => {
|
||||||
|
if (request?.type !== "googleCalendarRunWeeklySync") return false;
|
||||||
|
void runGoogleCalendarSync({ mode: "incremental", silent: true })
|
||||||
|
.then((result: GoogleCalendarSyncResult) => sendResponse(result))
|
||||||
|
.catch((err: unknown) => {
|
||||||
|
sendResponse({
|
||||||
|
success: false,
|
||||||
|
error: err instanceof Error ? err.message : "Weekly sync failed",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function maybeRunDueWeeklySync(
|
||||||
|
onComplete?: (message: string, isError?: boolean) => void,
|
||||||
|
): Promise<void> {
|
||||||
|
if (!(await shouldRunWeeklySync())) return;
|
||||||
|
|
||||||
|
const result = await runGoogleCalendarSync({ mode: "incremental", silent: true });
|
||||||
|
if (!onComplete) return;
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
onComplete(result.error ?? "Weekly calendar sync failed.", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const changed =
|
||||||
|
(result.created ?? 0) + (result.updated ?? 0) + (result.deleted ?? 0) > 0;
|
||||||
|
if (changed) {
|
||||||
|
onComplete(formatSyncResultMessage(result));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
export interface GoogleCalendarEventMapEntry {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeEventMapEntry(
|
||||||
|
value: string | GoogleCalendarEventMapEntry | undefined,
|
||||||
|
): GoogleCalendarEventMapEntry | undefined {
|
||||||
|
if (value == null) return undefined;
|
||||||
|
if (typeof value === "string") return { id: value, date: "" };
|
||||||
|
if (typeof value.id === "string" && value.id.length > 0) {
|
||||||
|
return { id: value.id, date: value.date ?? "" };
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getStoredEventId(
|
||||||
|
value: string | GoogleCalendarEventMapEntry | undefined,
|
||||||
|
): string | undefined {
|
||||||
|
return normalizeEventMapEntry(value)?.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function lessonDateFromSeqtaKey(seqtaKey: string): string | undefined {
|
||||||
|
const parts = seqtaKey.split(":");
|
||||||
|
for (const part of parts) {
|
||||||
|
if (/^\d{4}-\d{2}-\d{2}$/.test(part)) return part;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
@@ -1,17 +1,7 @@
|
|||||||
import { GOOGLE_CALENDAR_SYNC_WEEKS } from "@/config/googleCalendar";
|
import type { SyncDateRange } from "./syncDateRange";
|
||||||
import { toISODate, weekRangeContaining } from "@/seqta/utils/Loaders/engageParentTimetable";
|
import { syncWindowRange } from "./syncDateRange";
|
||||||
import type { SeqtaTimetableLesson } from "./types";
|
import type { SeqtaTimetableLesson } from "./types";
|
||||||
|
|
||||||
export function syncDateRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS): {
|
|
||||||
from: string;
|
|
||||||
until: string;
|
|
||||||
} {
|
|
||||||
const { from } = weekRangeContaining(new Date());
|
|
||||||
const end = new Date(from + "T12:00:00");
|
|
||||||
end.setDate(end.getDate() + weeksAhead * 7 - 1);
|
|
||||||
return { from, until: toISODate(end) };
|
|
||||||
}
|
|
||||||
|
|
||||||
async function postSeqtaJson<T>(path: string, body: Record<string, unknown>): Promise<T> {
|
async function postSeqtaJson<T>(path: string, body: Record<string, unknown>): Promise<T> {
|
||||||
const res = await fetch(`${location.origin}${path}`, {
|
const res = await fetch(`${location.origin}${path}`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -50,8 +40,10 @@ function isEngageParentContext(): boolean {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchTimetableForSync(): Promise<SeqtaTimetableLesson[]> {
|
export async function fetchTimetableLessons(
|
||||||
const { from, until } = syncDateRange();
|
range: SyncDateRange,
|
||||||
|
): Promise<SeqtaTimetableLesson[]> {
|
||||||
|
const { from, until } = range;
|
||||||
|
|
||||||
if (isEngageParentContext()) {
|
if (isEngageParentContext()) {
|
||||||
const listJson = await postSeqtaJson<{ payload?: { id?: string | number }[] }>(
|
const listJson = await postSeqtaJson<{ payload?: { id?: string | number }[] }>(
|
||||||
@@ -80,3 +72,9 @@ export async function fetchTimetableForSync(): Promise<SeqtaTimetableLesson[]> {
|
|||||||
);
|
);
|
||||||
return Array.isArray(data?.payload?.items) ? data.payload.items : [];
|
return Array.isArray(data?.payload?.items) ? data.payload.items : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function fetchTimetableForSync(weeksAhead?: number): Promise<SeqtaTimetableLesson[]> {
|
||||||
|
return fetchTimetableLessons(syncWindowRange(weeksAhead));
|
||||||
|
}
|
||||||
|
|
||||||
|
export { syncWindowRange, trailingWeekRange, droppedWeekRange } from "./syncDateRange";
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import browser from "webextension-polyfill";
|
import browser from "webextension-polyfill";
|
||||||
|
import type { GoogleCalendarEventMapEntry } from "./eventMapEntry";
|
||||||
|
|
||||||
/** Never uploaded to BetterSEQTA Cloud (OAuth tokens + per-device event map). */
|
/** Never uploaded to BetterSEQTA Cloud (OAuth tokens + per-device event map). */
|
||||||
export const BSPLUS_GOOGLE_CALENDAR_STORAGE_KEY = "bsplus_google_calendar";
|
export const BSPLUS_GOOGLE_CALENDAR_STORAGE_KEY = "bsplus_google_calendar";
|
||||||
@@ -9,9 +10,13 @@ export interface GoogleCalendarStoredState {
|
|||||||
expiresAt?: number;
|
expiresAt?: number;
|
||||||
connectedAt?: number;
|
connectedAt?: number;
|
||||||
lastSyncAt?: number;
|
lastSyncAt?: number;
|
||||||
|
lastWeeklySyncAt?: number;
|
||||||
lastSyncOrigin?: string;
|
lastSyncOrigin?: string;
|
||||||
/** `${origin}::${seqtaKey}` → Google Calendar event id */
|
syncWeeksAhead?: number;
|
||||||
eventMap?: Record<string, string>;
|
autoSyncWeekly?: boolean;
|
||||||
|
pendingWeeklySync?: boolean;
|
||||||
|
/** `${origin}::${seqtaKey}` → Google event id (+ lesson date when known) */
|
||||||
|
eventMap?: Record<string, string | GoogleCalendarEventMapEntry>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function readGoogleCalendarState(): Promise<GoogleCalendarStoredState> {
|
export async function readGoogleCalendarState(): Promise<GoogleCalendarStoredState> {
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { describe, expect, it } from "@jest/globals";
|
||||||
|
import {
|
||||||
|
droppedWeekRange,
|
||||||
|
syncWindowRange,
|
||||||
|
trailingWeekRange,
|
||||||
|
} from "./syncDateRange";
|
||||||
|
|
||||||
|
describe("syncDateRange", () => {
|
||||||
|
it("builds a 12-week rolling window from the current week", () => {
|
||||||
|
const range = syncWindowRange(12);
|
||||||
|
expect(range.from <= range.until).toBe(true);
|
||||||
|
|
||||||
|
const start = new Date(`${range.from}T12:00:00`);
|
||||||
|
const end = new Date(`${range.until}T12:00:00`);
|
||||||
|
const days = Math.round((end.getTime() - start.getTime()) / 86_400_000) + 1;
|
||||||
|
expect(days).toBe(12 * 7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("places the trailing week at the end of the window", () => {
|
||||||
|
const window = syncWindowRange(12);
|
||||||
|
const trailing = trailingWeekRange(12);
|
||||||
|
expect(trailing.from >= window.from).toBe(true);
|
||||||
|
expect(trailing.until <= window.until).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("places the dropped week before the window start", () => {
|
||||||
|
const window = syncWindowRange(12);
|
||||||
|
const dropped = droppedWeekRange(12);
|
||||||
|
expect(dropped.until < window.from).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import {
|
||||||
|
GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT,
|
||||||
|
} from "@/config/googleCalendar";
|
||||||
|
import { toISODate, weekRangeContaining } from "@/seqta/utils/Loaders/engageParentTimetable";
|
||||||
|
|
||||||
|
export interface SyncDateRange {
|
||||||
|
from: string;
|
||||||
|
until: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseLocalDate(iso: string): Date {
|
||||||
|
return new Date(`${iso}T12:00:00`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Full rolling sync window from the start of the current week. */
|
||||||
|
export function syncWindowRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT): SyncDateRange {
|
||||||
|
const { from } = weekRangeContaining(new Date());
|
||||||
|
const end = parseLocalDate(from);
|
||||||
|
end.setDate(end.getDate() + weeksAhead * 7 - 1);
|
||||||
|
return { from, until: toISODate(end) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The trailing week at the end of the sync window (added each weekly roll). */
|
||||||
|
export function trailingWeekRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT): SyncDateRange {
|
||||||
|
const { from: windowStart } = syncWindowRange(weeksAhead);
|
||||||
|
const start = parseLocalDate(windowStart);
|
||||||
|
start.setDate(start.getDate() + (weeksAhead - 1) * 7);
|
||||||
|
const end = new Date(start);
|
||||||
|
end.setDate(end.getDate() + 6);
|
||||||
|
return { from: toISODate(start), until: toISODate(end) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The week that rolled off when the window advances (removed each weekly roll). */
|
||||||
|
export function droppedWeekRange(weeksAhead = GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT): SyncDateRange {
|
||||||
|
const { from: windowStart } = syncWindowRange(weeksAhead);
|
||||||
|
const end = parseLocalDate(windowStart);
|
||||||
|
end.setDate(end.getDate() - 1);
|
||||||
|
const start = new Date(end);
|
||||||
|
start.setDate(start.getDate() - 6);
|
||||||
|
return { from: toISODate(start), until: toISODate(end) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDateInRange(date: string, range: SyncDateRange): boolean {
|
||||||
|
return date >= range.from && date <= range.until;
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||||
|
import type { SeqtaTimetableLesson } from "./types";
|
||||||
|
|
||||||
|
jest.mock("@/config/googleCalendar", () => ({
|
||||||
|
isGoogleCalendarConfigured: jest.fn(() => true),
|
||||||
|
}));
|
||||||
|
|
||||||
|
jest.mock("@/utils/verboseLog", () => ({
|
||||||
|
verboseLog: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
jest.mock("@/seqta/utils/googleCalendar/storage", () => ({
|
||||||
|
eventMapKey: (origin: string, seqtaKey: string) => `${origin}::${seqtaKey}`,
|
||||||
|
readGoogleCalendarState: jest.fn(),
|
||||||
|
writeGoogleCalendarState: jest.fn(async (patch: unknown) => patch),
|
||||||
|
}));
|
||||||
|
|
||||||
|
jest.mock("@/seqta/utils/googleCalendar/syncSettings", () => ({
|
||||||
|
getSyncWeeksAhead: jest.fn(async () => 12),
|
||||||
|
}));
|
||||||
|
|
||||||
|
jest.mock("@/seqta/utils/googleCalendar/upsertEvent", () => ({
|
||||||
|
upsertGoogleCalendarEvent: jest.fn(),
|
||||||
|
deleteGoogleCalendarEvent: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { readGoogleCalendarState } from "@/seqta/utils/googleCalendar/storage";
|
||||||
|
import {
|
||||||
|
deleteGoogleCalendarEvent,
|
||||||
|
upsertGoogleCalendarEvent,
|
||||||
|
} from "@/seqta/utils/googleCalendar/upsertEvent";
|
||||||
|
import { deleteSyncedEventsFromGoogleCalendar, syncLessonsToGoogleCalendar } from "./syncEngine";
|
||||||
|
|
||||||
|
const ORIGIN = "https://school.seqta.com.au";
|
||||||
|
const getAccessToken = async () => "test-token";
|
||||||
|
|
||||||
|
const baseLesson: SeqtaTimetableLesson = {
|
||||||
|
date: "2026-06-27",
|
||||||
|
from: "09:00:00",
|
||||||
|
until: "10:00:00",
|
||||||
|
description: "10 Mathematics",
|
||||||
|
staff: "Mr Smith",
|
||||||
|
room: "MA1",
|
||||||
|
code: "10MAT",
|
||||||
|
type: "class",
|
||||||
|
calendarid: 12345,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("syncLessonsToGoogleCalendar", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||||
|
refreshToken: "refresh",
|
||||||
|
eventMap: {
|
||||||
|
[`${ORIGIN}::${ORIGIN}:cal:12345`]: { id: "google-existing", date: "2026-06-27" },
|
||||||
|
[`${ORIGIN}::${ORIGIN}:cal:99999`]: { id: "google-stale", date: "2020-01-06" },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-existing");
|
||||||
|
jest.mocked(deleteGoogleCalendarEvent).mockResolvedValue(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("updates existing events and removes stale tracked events on full sync", async () => {
|
||||||
|
const result = await syncLessonsToGoogleCalendar(
|
||||||
|
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
|
||||||
|
getAccessToken,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(deleteGoogleCalendarEvent).toHaveBeenCalled();
|
||||||
|
expect(upsertGoogleCalendarEvent).toHaveBeenCalledTimes(1);
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
success: true,
|
||||||
|
created: 0,
|
||||||
|
updated: 1,
|
||||||
|
failed: 0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("creates events that are not yet tracked", async () => {
|
||||||
|
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||||
|
refreshToken: "refresh",
|
||||||
|
eventMap: {},
|
||||||
|
});
|
||||||
|
jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-new");
|
||||||
|
|
||||||
|
const result = await syncLessonsToGoogleCalendar(
|
||||||
|
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
|
||||||
|
getAccessToken,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(deleteGoogleCalendarEvent).not.toHaveBeenCalled();
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
success: true,
|
||||||
|
created: 1,
|
||||||
|
updated: 0,
|
||||||
|
deleted: 0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports progress while syncing", async () => {
|
||||||
|
const progress: Array<{ phase: string; current: number; total: number }> = [];
|
||||||
|
await syncLessonsToGoogleCalendar(
|
||||||
|
{ origin: ORIGIN, lessons: [baseLesson], mode: "full" },
|
||||||
|
getAccessToken,
|
||||||
|
{
|
||||||
|
onProgress: (entry) => progress.push(entry),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(progress.some((entry) => entry.phase === "upserting")).toBe(true);
|
||||||
|
expect(progress.at(-1)?.phase).toBe("done");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("deleteSyncedEventsFromGoogleCalendar", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||||
|
refreshToken: "refresh",
|
||||||
|
eventMap: {
|
||||||
|
[`${ORIGIN}::${ORIGIN}:cal:12345`]: { id: "google-1", date: "2026-06-27" },
|
||||||
|
[`${ORIGIN}::${ORIGIN}:cal:99999`]: { id: "google-2", date: "2026-06-28" },
|
||||||
|
"https://other.seqta.com.au::other:key": { id: "google-other", date: "2026-06-28" },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
jest.mocked(deleteGoogleCalendarEvent).mockResolvedValue(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("deletes only events for the requested origin", async () => {
|
||||||
|
const result = await deleteSyncedEventsFromGoogleCalendar(ORIGIN, getAccessToken);
|
||||||
|
|
||||||
|
expect(deleteGoogleCalendarEvent).toHaveBeenCalledTimes(2);
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
success: true,
|
||||||
|
deleted: 2,
|
||||||
|
failed: 0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,20 +1,154 @@
|
|||||||
import { verboseLog } from "@/utils/verboseLog";
|
import { verboseLog } from "@/utils/verboseLog";
|
||||||
import { isGoogleCalendarConfigured } from "@/config/googleCalendar";
|
import { isGoogleCalendarConfigured } from "@/config/googleCalendar";
|
||||||
import { googleApiEventBody, mapLessonsToGoogleEvents } from "@/seqta/utils/googleCalendar/eventMapper";
|
import { googleApiEventBody, mapLessonsToGoogleEvents } from "@/seqta/utils/googleCalendar/eventMapper";
|
||||||
|
import {
|
||||||
|
getStoredEventId,
|
||||||
|
lessonDateFromSeqtaKey,
|
||||||
|
normalizeEventMapEntry,
|
||||||
|
} from "@/seqta/utils/googleCalendar/eventMapEntry";
|
||||||
|
import {
|
||||||
|
droppedWeekRange,
|
||||||
|
isDateInRange,
|
||||||
|
syncWindowRange,
|
||||||
|
} from "@/seqta/utils/googleCalendar/syncDateRange";
|
||||||
|
import { getSyncWeeksAhead } from "@/seqta/utils/googleCalendar/syncSettings";
|
||||||
import {
|
import {
|
||||||
eventMapKey,
|
eventMapKey,
|
||||||
readGoogleCalendarState,
|
readGoogleCalendarState,
|
||||||
writeGoogleCalendarState,
|
writeGoogleCalendarState,
|
||||||
} from "@/seqta/utils/googleCalendar/storage";
|
} from "@/seqta/utils/googleCalendar/storage";
|
||||||
import type { GoogleCalendarSyncRequest, GoogleCalendarSyncResult } from "@/seqta/utils/googleCalendar/types";
|
import type {
|
||||||
import { upsertGoogleCalendarEvent } from "@/seqta/utils/googleCalendar/upsertEvent";
|
GoogleCalendarDeleteResult,
|
||||||
|
GoogleCalendarSyncOptions,
|
||||||
|
GoogleCalendarSyncProgress,
|
||||||
|
GoogleCalendarSyncRequest,
|
||||||
|
GoogleCalendarSyncResult,
|
||||||
|
} from "@/seqta/utils/googleCalendar/types";
|
||||||
|
import {
|
||||||
|
deleteGoogleCalendarEvent,
|
||||||
|
upsertGoogleCalendarEvent,
|
||||||
|
} from "@/seqta/utils/googleCalendar/upsertEvent";
|
||||||
|
|
||||||
const EVENT_MAP_PERSIST_EVERY = 10;
|
const EVENT_MAP_PERSIST_EVERY = 10;
|
||||||
|
const CALENDAR_ID = "primary";
|
||||||
|
|
||||||
|
type DeleteTrackedEventsResult = {
|
||||||
|
deleted: number;
|
||||||
|
failed: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function reportProgress(
|
||||||
|
onProgress: GoogleCalendarSyncOptions["onProgress"],
|
||||||
|
progress: GoogleCalendarSyncProgress,
|
||||||
|
) {
|
||||||
|
onProgress?.(progress);
|
||||||
|
}
|
||||||
|
|
||||||
|
function lessonDateForEvent(startDateTime: string, seqtaKey: string): string {
|
||||||
|
return startDateTime.slice(0, 10) || lessonDateFromSeqtaKey(seqtaKey) || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteTrackedEventsFromGoogle(
|
||||||
|
entries: Array<[string, string]>,
|
||||||
|
eventMap: Record<string, string | { id: string; date: string }>,
|
||||||
|
getAccessToken: () => Promise<string>,
|
||||||
|
persistProgress = false,
|
||||||
|
onProgress?: GoogleCalendarSyncOptions["onProgress"],
|
||||||
|
progressOffset = 0,
|
||||||
|
progressTotal = 0,
|
||||||
|
): Promise<DeleteTrackedEventsResult> {
|
||||||
|
if (entries.length === 0) return { deleted: 0, failed: 0 };
|
||||||
|
|
||||||
|
let accessToken = await getAccessToken();
|
||||||
|
let deleted = 0;
|
||||||
|
let failed = 0;
|
||||||
|
|
||||||
|
for (let i = 0; i < entries.length; i++) {
|
||||||
|
const [mapKey, eventId] = entries[i];
|
||||||
|
try {
|
||||||
|
await deleteGoogleCalendarEvent(accessToken, CALENDAR_ID, eventId, async () => {
|
||||||
|
accessToken = await getAccessToken();
|
||||||
|
return accessToken;
|
||||||
|
});
|
||||||
|
delete eventMap[mapKey];
|
||||||
|
deleted += 1;
|
||||||
|
|
||||||
|
reportProgress(onProgress, {
|
||||||
|
phase: "deleting",
|
||||||
|
current: progressOffset + deleted + failed,
|
||||||
|
total: progressTotal,
|
||||||
|
message: `Removing old events (${deleted + failed}/${entries.length})…`,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (persistProgress && (deleted + failed) % EVENT_MAP_PERSIST_EVERY === 0) {
|
||||||
|
await writeGoogleCalendarState({ eventMap });
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
verboseLog("[BetterSEQTA+] Google Calendar event delete failed:", err);
|
||||||
|
failed += 1;
|
||||||
|
reportProgress(onProgress, {
|
||||||
|
phase: "deleting",
|
||||||
|
current: progressOffset + deleted + failed,
|
||||||
|
total: progressTotal,
|
||||||
|
message: `Removing old events (${deleted + failed}/${entries.length})…`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { deleted, failed };
|
||||||
|
}
|
||||||
|
|
||||||
|
function originEventMapEntries(
|
||||||
|
eventMap: Record<string, string | { id: string; date: string }>,
|
||||||
|
origin: string,
|
||||||
|
): Array<[string, string]> {
|
||||||
|
const prefix = `${origin}::`;
|
||||||
|
const entries: Array<[string, string]> = [];
|
||||||
|
for (const [key, value] of Object.entries(eventMap)) {
|
||||||
|
if (!key.startsWith(prefix)) continue;
|
||||||
|
const id = getStoredEventId(value);
|
||||||
|
if (id) entries.push([key, id]);
|
||||||
|
}
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
function entriesToPrune(
|
||||||
|
eventMap: Record<string, string | { id: string; date: string }>,
|
||||||
|
origin: string,
|
||||||
|
mode: "full" | "incremental",
|
||||||
|
weeksAhead: number,
|
||||||
|
currentMapKeys: Set<string>,
|
||||||
|
): Array<[string, string]> {
|
||||||
|
const window = syncWindowRange(weeksAhead);
|
||||||
|
const dropped = droppedWeekRange(weeksAhead);
|
||||||
|
const prefix = `${origin}::`;
|
||||||
|
const entries: Array<[string, string]> = [];
|
||||||
|
|
||||||
|
for (const [mapKey, raw] of Object.entries(eventMap)) {
|
||||||
|
if (!mapKey.startsWith(prefix)) continue;
|
||||||
|
const entry = normalizeEventMapEntry(raw);
|
||||||
|
if (!entry) continue;
|
||||||
|
|
||||||
|
let shouldDelete = false;
|
||||||
|
if (mode === "incremental") {
|
||||||
|
shouldDelete = !!entry.date && isDateInRange(entry.date, dropped);
|
||||||
|
} else if (entry.date) {
|
||||||
|
shouldDelete = !isDateInRange(entry.date, window);
|
||||||
|
} else {
|
||||||
|
shouldDelete = !currentMapKeys.has(mapKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldDelete) entries.push([mapKey, entry.id]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
/** Runs in the content script tab so long syncs are not killed by the MV3 service worker. */
|
/** Runs in the content script tab so long syncs are not killed by the MV3 service worker. */
|
||||||
export async function syncLessonsToGoogleCalendar(
|
export async function syncLessonsToGoogleCalendar(
|
||||||
request: GoogleCalendarSyncRequest,
|
request: GoogleCalendarSyncRequest,
|
||||||
getAccessToken: () => Promise<string>,
|
getAccessToken: () => Promise<string>,
|
||||||
|
options: GoogleCalendarSyncOptions = {},
|
||||||
): Promise<GoogleCalendarSyncResult> {
|
): Promise<GoogleCalendarSyncResult> {
|
||||||
if (!isGoogleCalendarConfigured()) {
|
if (!isGoogleCalendarConfigured()) {
|
||||||
return {
|
return {
|
||||||
@@ -29,9 +163,12 @@ export async function syncLessonsToGoogleCalendar(
|
|||||||
return { success: false, configured: true, connected: false, error: "Connect Google Calendar first." };
|
return { success: false, configured: true, connected: false, error: "Connect Google Calendar first." };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const mode = request.mode ?? "full";
|
||||||
|
const weeksAhead = request.weeksAhead ?? (await getSyncWeeksAhead());
|
||||||
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
||||||
const events = mapLessonsToGoogleEvents(request.origin, request.lessons, timeZone);
|
const events = mapLessonsToGoogleEvents(request.origin, request.lessons, timeZone);
|
||||||
if (events.length === 0) {
|
|
||||||
|
if (events.length === 0 && mode === "full") {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
configured: true,
|
configured: true,
|
||||||
@@ -40,23 +177,42 @@ export async function syncLessonsToGoogleCalendar(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
reportProgress(options.onProgress, {
|
||||||
|
phase: "preparing",
|
||||||
|
current: 0,
|
||||||
|
total: Math.max(events.length, 1),
|
||||||
|
message: mode === "incremental" ? "Preparing weekly sync…" : "Preparing sync…",
|
||||||
|
});
|
||||||
|
|
||||||
let accessToken = await getAccessToken();
|
let accessToken = await getAccessToken();
|
||||||
const calendarId = "primary";
|
|
||||||
const eventMap = { ...(state.eventMap ?? {}) };
|
const eventMap = { ...(state.eventMap ?? {}) };
|
||||||
|
const currentMapKeys = new Set(events.map((event) => eventMapKey(request.origin, event.seqtaKey)));
|
||||||
|
const staleEntries = entriesToPrune(eventMap, request.origin, mode, weeksAhead, currentMapKeys);
|
||||||
|
const totalSteps = staleEntries.length + events.length;
|
||||||
|
|
||||||
|
const staleResult = await deleteTrackedEventsFromGoogle(
|
||||||
|
staleEntries,
|
||||||
|
eventMap,
|
||||||
|
getAccessToken,
|
||||||
|
false,
|
||||||
|
options.onProgress,
|
||||||
|
0,
|
||||||
|
totalSteps,
|
||||||
|
);
|
||||||
|
|
||||||
let created = 0;
|
let created = 0;
|
||||||
let updated = 0;
|
let updated = 0;
|
||||||
let failed = 0;
|
let failed = staleResult.failed;
|
||||||
const lastSyncAt = Date.now();
|
const lastSyncAt = Date.now();
|
||||||
|
|
||||||
for (let i = 0; i < events.length; i++) {
|
for (let i = 0; i < events.length; i++) {
|
||||||
const event = events[i];
|
const event = events[i];
|
||||||
const mapKey = eventMapKey(request.origin, event.seqtaKey);
|
const mapKey = eventMapKey(request.origin, event.seqtaKey);
|
||||||
const existingId = eventMap[mapKey];
|
const existingId = getStoredEventId(eventMap[mapKey]);
|
||||||
try {
|
try {
|
||||||
const googleId = await upsertGoogleCalendarEvent(
|
const googleId = await upsertGoogleCalendarEvent(
|
||||||
accessToken,
|
accessToken,
|
||||||
calendarId,
|
CALENDAR_ID,
|
||||||
existingId,
|
existingId,
|
||||||
googleApiEventBody(event),
|
googleApiEventBody(event),
|
||||||
async () => {
|
async () => {
|
||||||
@@ -66,7 +222,17 @@ export async function syncLessonsToGoogleCalendar(
|
|||||||
);
|
);
|
||||||
if (existingId) updated += 1;
|
if (existingId) updated += 1;
|
||||||
else created += 1;
|
else created += 1;
|
||||||
eventMap[mapKey] = googleId;
|
eventMap[mapKey] = {
|
||||||
|
id: googleId,
|
||||||
|
date: lessonDateForEvent(event.startDateTime, event.seqtaKey),
|
||||||
|
};
|
||||||
|
|
||||||
|
reportProgress(options.onProgress, {
|
||||||
|
phase: "upserting",
|
||||||
|
current: staleEntries.length + i + 1,
|
||||||
|
total: totalSteps,
|
||||||
|
message: `Syncing events (${i + 1}/${events.length})…`,
|
||||||
|
});
|
||||||
|
|
||||||
if ((i + 1) % EVENT_MAP_PERSIST_EVERY === 0 || i === events.length - 1) {
|
if ((i + 1) % EVENT_MAP_PERSIST_EVERY === 0 || i === events.length - 1) {
|
||||||
await writeGoogleCalendarState({
|
await writeGoogleCalendarState({
|
||||||
@@ -78,15 +244,37 @@ export async function syncLessonsToGoogleCalendar(
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
verboseLog("[BetterSEQTA+] Google Calendar event sync failed:", err);
|
verboseLog("[BetterSEQTA+] Google Calendar event sync failed:", err);
|
||||||
failed += 1;
|
failed += 1;
|
||||||
|
reportProgress(options.onProgress, {
|
||||||
|
phase: "upserting",
|
||||||
|
current: staleEntries.length + i + 1,
|
||||||
|
total: totalSteps,
|
||||||
|
message: `Syncing events (${i + 1}/${events.length})…`,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const syncResult: GoogleCalendarSyncResult = {
|
if (staleResult.deleted > 0 || staleEntries.length > 0 || events.length > 0) {
|
||||||
|
await writeGoogleCalendarState({
|
||||||
|
eventMap,
|
||||||
|
lastSyncAt,
|
||||||
|
lastSyncOrigin: request.origin,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
reportProgress(options.onProgress, {
|
||||||
|
phase: "done",
|
||||||
|
current: totalSteps,
|
||||||
|
total: totalSteps,
|
||||||
|
message: "Sync complete",
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
success: failed === 0,
|
success: failed === 0,
|
||||||
configured: true,
|
configured: true,
|
||||||
connected: true,
|
connected: true,
|
||||||
created,
|
created,
|
||||||
updated,
|
updated,
|
||||||
|
deleted: staleResult.deleted,
|
||||||
skipped: 0,
|
skipped: 0,
|
||||||
failed,
|
failed,
|
||||||
lastSyncAt,
|
lastSyncAt,
|
||||||
@@ -95,6 +283,68 @@ export async function syncLessonsToGoogleCalendar(
|
|||||||
? `Synced with ${failed} error${failed === 1 ? "" : "s"}. Check the console for details.`
|
? `Synced with ${failed} error${failed === 1 ? "" : "s"}. Check the console for details.`
|
||||||
: undefined,
|
: undefined,
|
||||||
};
|
};
|
||||||
|
}
|
||||||
return syncResult;
|
|
||||||
|
/** Delete all tracked BetterSEQTA+ events for this SEQTA origin from Google Calendar. */
|
||||||
|
export async function deleteSyncedEventsFromGoogleCalendar(
|
||||||
|
origin: string,
|
||||||
|
getAccessToken: () => Promise<string>,
|
||||||
|
options: GoogleCalendarSyncOptions = {},
|
||||||
|
): Promise<GoogleCalendarDeleteResult> {
|
||||||
|
if (!isGoogleCalendarConfigured()) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
configured: false,
|
||||||
|
error: "Google Calendar is not configured in this extension build.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const state = await readGoogleCalendarState();
|
||||||
|
if (!state.refreshToken && !state.accessToken) {
|
||||||
|
return { success: false, configured: true, connected: false, error: "Connect Google Calendar first." };
|
||||||
|
}
|
||||||
|
|
||||||
|
const entries = originEventMapEntries(state.eventMap ?? {}, origin);
|
||||||
|
if (entries.length === 0) {
|
||||||
|
return { success: true, configured: true, connected: true, deleted: 0, failed: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
reportProgress(options.onProgress, {
|
||||||
|
phase: "preparing",
|
||||||
|
current: 0,
|
||||||
|
total: entries.length,
|
||||||
|
message: "Preparing removal…",
|
||||||
|
});
|
||||||
|
|
||||||
|
const eventMap = { ...(state.eventMap ?? {}) };
|
||||||
|
const { deleted, failed } = await deleteTrackedEventsFromGoogle(
|
||||||
|
entries,
|
||||||
|
eventMap,
|
||||||
|
getAccessToken,
|
||||||
|
true,
|
||||||
|
options.onProgress,
|
||||||
|
0,
|
||||||
|
entries.length,
|
||||||
|
);
|
||||||
|
|
||||||
|
await writeGoogleCalendarState({ eventMap });
|
||||||
|
|
||||||
|
reportProgress(options.onProgress, {
|
||||||
|
phase: "done",
|
||||||
|
current: entries.length,
|
||||||
|
total: entries.length,
|
||||||
|
message: "Removal complete",
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: failed === 0,
|
||||||
|
configured: true,
|
||||||
|
connected: true,
|
||||||
|
deleted,
|
||||||
|
failed,
|
||||||
|
error:
|
||||||
|
failed > 0
|
||||||
|
? `Removed ${deleted} event${deleted === 1 ? "" : "s"} with ${failed} error${failed === 1 ? "" : "s"}.`
|
||||||
|
: undefined,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import {
|
||||||
|
fetchTimetableForSync,
|
||||||
|
fetchTimetableLessons,
|
||||||
|
trailingWeekRange,
|
||||||
|
} from "@/seqta/utils/googleCalendar/fetchTimetable";
|
||||||
|
import {
|
||||||
|
getSyncWeeksAhead,
|
||||||
|
markWeeklySyncComplete,
|
||||||
|
} from "@/seqta/utils/googleCalendar/syncSettings";
|
||||||
|
import { syncLessonsToGoogleCalendar } from "@/seqta/utils/googleCalendar/syncEngine";
|
||||||
|
import type {
|
||||||
|
GoogleCalendarSyncOptions,
|
||||||
|
GoogleCalendarSyncProgress,
|
||||||
|
GoogleCalendarSyncResult,
|
||||||
|
} from "@/seqta/utils/googleCalendar/types";
|
||||||
|
|
||||||
|
export type GoogleCalendarRunMode = "full" | "incremental";
|
||||||
|
|
||||||
|
export interface RunGoogleCalendarSyncParams {
|
||||||
|
mode?: GoogleCalendarRunMode;
|
||||||
|
silent?: boolean;
|
||||||
|
onProgress?: (progress: GoogleCalendarSyncProgress) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getAccessTokenFromBackground(): Promise<string> {
|
||||||
|
const res = (await browser.runtime.sendMessage({
|
||||||
|
type: "googleCalendarGetAccessToken",
|
||||||
|
})) as { success?: boolean; accessToken?: string; error?: string };
|
||||||
|
if (!res?.success || !res.accessToken) {
|
||||||
|
throw new Error(res?.error ?? "Could not get Google Calendar access token.");
|
||||||
|
}
|
||||||
|
return res.accessToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runGoogleCalendarSync(
|
||||||
|
params: RunGoogleCalendarSyncParams = {},
|
||||||
|
): Promise<GoogleCalendarSyncResult> {
|
||||||
|
const mode = params.mode ?? "full";
|
||||||
|
const weeksAhead = await getSyncWeeksAhead();
|
||||||
|
|
||||||
|
params.onProgress?.({
|
||||||
|
phase: "preparing",
|
||||||
|
current: 0,
|
||||||
|
total: 1,
|
||||||
|
message: mode === "incremental" ? "Fetching new week…" : "Fetching timetable…",
|
||||||
|
});
|
||||||
|
|
||||||
|
const lessons =
|
||||||
|
mode === "incremental"
|
||||||
|
? await fetchTimetableLessons(trailingWeekRange(weeksAhead))
|
||||||
|
: await fetchTimetableForSync(weeksAhead);
|
||||||
|
|
||||||
|
const options: GoogleCalendarSyncOptions = { onProgress: params.onProgress };
|
||||||
|
const result = await syncLessonsToGoogleCalendar(
|
||||||
|
{
|
||||||
|
origin: location.origin,
|
||||||
|
lessons,
|
||||||
|
mode,
|
||||||
|
weeksAhead,
|
||||||
|
},
|
||||||
|
getAccessTokenFromBackground,
|
||||||
|
options,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.success && mode === "incremental") {
|
||||||
|
await markWeeklySyncComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatSyncResultMessage(result: GoogleCalendarSyncResult): string {
|
||||||
|
const created = result.created ?? 0;
|
||||||
|
const updated = result.updated ?? 0;
|
||||||
|
const deleted = result.deleted ?? 0;
|
||||||
|
const parts: string[] = [];
|
||||||
|
if (created > 0) parts.push(`${created} new`);
|
||||||
|
if (updated > 0) parts.push(`${updated} updated`);
|
||||||
|
if (deleted > 0) parts.push(`${deleted} removed`);
|
||||||
|
if (parts.length === 0) return "Google Calendar is up to date.";
|
||||||
|
return `Google Calendar updated (${parts.join(", ")}).`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import {
|
||||||
|
GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT,
|
||||||
|
GOOGLE_CALENDAR_SYNC_WEEKS_MAX,
|
||||||
|
GOOGLE_CALENDAR_SYNC_WEEKS_MIN,
|
||||||
|
} from "@/config/googleCalendar";
|
||||||
|
import { readGoogleCalendarState, writeGoogleCalendarState } from "./storage";
|
||||||
|
|
||||||
|
export const GOOGLE_CALENDAR_WEEKLY_ALARM = "bsplus_google_calendar_weekly";
|
||||||
|
export const WEEKLY_SYNC_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
export function clampSyncWeeks(weeks: number): number {
|
||||||
|
if (!Number.isFinite(weeks)) return GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT;
|
||||||
|
return Math.min(
|
||||||
|
GOOGLE_CALENDAR_SYNC_WEEKS_MAX,
|
||||||
|
Math.max(GOOGLE_CALENDAR_SYNC_WEEKS_MIN, Math.round(weeks)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getSyncWeeksAhead(): Promise<number> {
|
||||||
|
const state = await readGoogleCalendarState();
|
||||||
|
return clampSyncWeeks(state.syncWeeksAhead ?? GOOGLE_CALENDAR_SYNC_WEEKS_DEFAULT);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setSyncWeeksAhead(weeks: number): Promise<number> {
|
||||||
|
const syncWeeksAhead = clampSyncWeeks(weeks);
|
||||||
|
await writeGoogleCalendarState({ syncWeeksAhead });
|
||||||
|
return syncWeeksAhead;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAutoSyncWeekly(): Promise<boolean> {
|
||||||
|
const state = await readGoogleCalendarState();
|
||||||
|
return state.autoSyncWeekly !== false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setAutoSyncWeekly(enabled: boolean): Promise<void> {
|
||||||
|
await writeGoogleCalendarState({ autoSyncWeekly: enabled });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function shouldRunWeeklySync(): Promise<boolean> {
|
||||||
|
const state = await readGoogleCalendarState();
|
||||||
|
if (!state.refreshToken && !state.accessToken) return false;
|
||||||
|
if (state.autoSyncWeekly === false) return false;
|
||||||
|
if (state.pendingWeeklySync) return true;
|
||||||
|
const last = state.lastWeeklySyncAt ?? state.lastSyncAt ?? 0;
|
||||||
|
return Date.now() - last >= WEEKLY_SYNC_INTERVAL_MS;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function markWeeklySyncComplete(): Promise<void> {
|
||||||
|
await writeGoogleCalendarState({
|
||||||
|
lastWeeklySyncAt: Date.now(),
|
||||||
|
pendingWeeklySync: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function markWeeklySyncPending(): Promise<void> {
|
||||||
|
await writeGoogleCalendarState({ pendingWeeklySync: true });
|
||||||
|
}
|
||||||
@@ -25,6 +25,21 @@ export interface GoogleCalendarEventInput {
|
|||||||
export interface GoogleCalendarSyncRequest {
|
export interface GoogleCalendarSyncRequest {
|
||||||
origin: string;
|
origin: string;
|
||||||
lessons: SeqtaTimetableLesson[];
|
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 {
|
export interface GoogleCalendarSyncResult {
|
||||||
@@ -33,6 +48,7 @@ export interface GoogleCalendarSyncResult {
|
|||||||
configured?: boolean;
|
configured?: boolean;
|
||||||
created?: number;
|
created?: number;
|
||||||
updated?: number;
|
updated?: number;
|
||||||
|
deleted?: number;
|
||||||
skipped?: number;
|
skipped?: number;
|
||||||
failed?: number;
|
failed?: number;
|
||||||
lastSyncAt?: number;
|
lastSyncAt?: number;
|
||||||
@@ -43,5 +59,17 @@ export interface GoogleCalendarStatus {
|
|||||||
configured: boolean;
|
configured: boolean;
|
||||||
connected: boolean;
|
connected: boolean;
|
||||||
lastSyncAt?: number;
|
lastSyncAt?: number;
|
||||||
|
lastWeeklySyncAt?: number;
|
||||||
lastSyncOrigin?: string;
|
lastSyncOrigin?: string;
|
||||||
|
syncWeeksAhead?: number;
|
||||||
|
autoSyncWeekly?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GoogleCalendarDeleteResult {
|
||||||
|
success: boolean;
|
||||||
|
configured?: boolean;
|
||||||
|
connected?: boolean;
|
||||||
|
deleted?: number;
|
||||||
|
failed?: number;
|
||||||
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,3 +42,22 @@ export async function upsertGoogleCalendarEvent(
|
|||||||
}
|
}
|
||||||
return json.id;
|
return json.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function deleteGoogleCalendarEvent(
|
||||||
|
accessToken: string,
|
||||||
|
calendarId: string,
|
||||||
|
eventId: string,
|
||||||
|
refreshAccessToken?: () => Promise<string>,
|
||||||
|
): Promise<void> {
|
||||||
|
const res = await fetch(
|
||||||
|
`${GOOGLE_CALENDAR_API}/calendars/${encodeURIComponent(calendarId)}/events/${encodeURIComponent(eventId)}`,
|
||||||
|
{ method: "DELETE", headers: { Authorization: `Bearer ${accessToken}` } },
|
||||||
|
);
|
||||||
|
if (res.status === 401 && refreshAccessToken) {
|
||||||
|
const nextToken = await refreshAccessToken();
|
||||||
|
return deleteGoogleCalendarEvent(nextToken, calendarId, eventId);
|
||||||
|
}
|
||||||
|
if (res.ok || res.status === 404 || res.status === 410) return;
|
||||||
|
const err = (await res.json().catch(() => ({}))) as { error?: { message?: string } };
|
||||||
|
throw new Error(err?.error?.message ?? `Google Calendar delete failed (${res.status})`);
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user