Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

feat: Google Calendar integration with meeting recording

Gabriel Stein02d9a56d4c09
diff --git a/main.js b/main.js
index 1481d86c7..d2cfb9763 100644
--- a/main.js
+++ b/main.js
@@ -161,6 +161,7 @@ const GlobeKeyManager = require("./src/helpers/globeKeyManager");
const DevServerManager = require("./src/helpers/devServerManager");
const WindowsKeyManager = require("./src/helpers/windowsKeyManager");
const WhisperCudaManager = require("./src/helpers/whisperCudaManager");
+const GoogleCalendarManager = require("./src/helpers/googleCalendarManager");
const { i18nMain, changeLanguage } = require("./src/helpers/i18nMain");
// Manager instances - initialized after app.whenReady()
@@ -177,6 +178,7 @@ let updateManager = null;
let globeKeyManager = null;
let windowsKeyManager = null;
let whisperCudaManager = null;
+let googleCalendarManager = null;
let globeKeyAlertShown = false;
let authBridgeServer = null;
@@ -239,6 +241,7 @@ function initializeCoreManagers() {
whisperCudaManager = new WhisperCudaManager();
}
parakeetManager = new ParakeetManager();
+ googleCalendarManager = new GoogleCalendarManager(databaseManager, windowManager);
updateManager = new UpdateManager();
windowsKeyManager = new WindowsKeyManager();
@@ -253,6 +256,7 @@ function initializeCoreManagers() {
updateManager,
windowsKeyManager,
whisperCudaManager,
+ googleCalendarManager,
getTrayManager: () => trayManager,
});
}
@@ -289,6 +293,8 @@ function initializeDeferredManagers() {
});
});
}
+
+ googleCalendarManager.start();
}
app.on("open-url", (event, url) => {
@@ -485,6 +491,13 @@ async function startApp() {
// Phase 2: Initialize remaining managers after windows are visible
initializeDeferredManagers();
+ const { powerMonitor } = require("electron");
+ powerMonitor.on("resume", () => {
+ if (googleCalendarManager) {
+ googleCalendarManager.onWakeFromSleep();
+ }
+ });
+
// Non-blocking server pre-warming
const whisperSettings = {
localTranscriptionProvider: process.env.LOCAL_TRANSCRIPTION_PROVIDER || "",
@@ -909,6 +922,9 @@ if (gotSingleInstanceLock) {
if (windowsKeyManager) {
windowsKeyManager.stop();
}
+ if (googleCalendarManager) {
+ googleCalendarManager.stop();
+ }
if (updateManager) {
updateManager.cleanup();
}
diff --git a/preload.js b/preload.js
index d52819c18..c137ce277 100644
--- a/preload.js
+++ b/preload.js
@@ -436,4 +436,40 @@ contextBridge.exposeInMainWorld("electronAPI", {
// Auto-start management
getAutoStartEnabled: () => ipcRenderer.invoke("get-auto-start-enabled"),
setAutoStartEnabled: (enabled) => ipcRenderer.invoke("set-auto-start-enabled", enabled),
+
+ // Google Calendar
+ gcalStartOAuth: () => ipcRenderer.invoke("gcal-start-oauth"),
+ gcalDisconnect: () => ipcRenderer.invoke("gcal-disconnect"),
+ gcalGetConnectionStatus: () => ipcRenderer.invoke("gcal-get-connection-status"),
+ gcalGetCalendars: () => ipcRenderer.invoke("gcal-get-calendars"),
+ gcalSetCalendarSelection: (calendarId, isSelected) =>
+ ipcRenderer.invoke("gcal-set-calendar-selection", calendarId, isSelected),
+ gcalSyncEvents: () => ipcRenderer.invoke("gcal-sync-events"),
+ gcalGetUpcomingEvents: (windowMinutes) =>
+ ipcRenderer.invoke("gcal-get-upcoming-events", windowMinutes),
+
+ // Desktop audio capture
+ getDesktopSources: (types) => ipcRenderer.invoke("get-desktop-sources", types),
+
+ // Google Calendar event listeners
+ onGcalMeetingStarting: registerListener(
+ "gcal-meeting-starting",
+ (callback) => (_event, data) => callback(data)
+ ),
+ onGcalMeetingEnded: registerListener(
+ "gcal-meeting-ended",
+ (callback) => (_event, data) => callback(data)
+ ),
+ onGcalStartRecording: registerListener(
+ "gcal-start-recording",
+ (callback) => (_event, data) => callback(data)
+ ),
+ onGcalConnectionChanged: registerListener(
+ "gcal-connection-changed",
+ (callback) => (_event, data) => callback(data)
+ ),
+ onGcalEventsSynced: registerListener(
+ "gcal-events-synced",
+ (callback) => (_event, data) => callback(data)
+ ),
});
diff --git a/src/App.jsx b/src/App.jsx
index bb266fd24..6279ac31f 100644
--- a/src/App.jsx
+++ b/src/App.jsx
@@ -9,6 +9,7 @@ import { useWindowDrag } from "./hooks/useWindowDrag";
import { useAudioRecording } from "./hooks/useAudioRecording";
import { useAuth } from "./hooks/useAuth";
import { useSettingsStore } from "./stores/settingsStore";
+import { useMeetingRecording } from "./hooks/useMeetingRecording";
// Sound Wave Icon Component (for idle/hover states)
const SoundWaveIcon = ({ size = 16 }) => {
@@ -80,6 +81,7 @@ export default function App() {
const { hotkey } = useHotkey();
const { isDragging, handleMouseDown, handleMouseUp } = useWindowDrag();
const { isSignedIn } = useAuth();
+ useMeetingRecording();
const [dragStartPos, setDragStartPos] = useState(null);
const [hasDragged, setHasDragged] = useState(false);
diff --git a/src/components/CalendarSettings.tsx b/src/components/CalendarSettings.tsx
new file mode 100644
index 000000000..020f2490d
--- /dev/null
+++ b/src/components/CalendarSettings.tsx
@@ -0,0 +1,304 @@
+import React, { useState, useEffect, useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import { Calendar, LogOut, RefreshCw, Loader2 } from "lucide-react";
+import { SettingsRow } from "./ui/SettingsSection";
+import { Button } from "./ui/button";
+import { Badge } from "./ui/badge";
+import { Toggle } from "./ui/toggle";
+import { useSettingsStore } from "../stores/settingsStore";
+import type { GoogleCalendar, CalendarEvent } from "../types/calendar";
+
+function SettingsPanel({
+ children,
+ className = "",
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <div
+ className={`rounded-lg border border-border/50 dark:border-border-subtle/70 bg-card/50 dark:bg-surface-2/50 backdrop-blur-sm divide-y divide-border/30 dark:divide-border-subtle/50 ${className}`}
+ >
+ {children}
+ </div>
+ );
+}
+
+function SettingsPanelRow({
+ children,
+ className = "",
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return <div className={`px-4 py-3 ${className}`}>{children}</div>;
+}
+
+function SectionHeader({ title, description }: { title: string; description?: string }) {
+ return (
+ <div className="mb-3">
+ <h3 className="text-xs font-semibold text-foreground tracking-tight">{title}</h3>
+ {description && (
+ <p className="text-xs text-muted-foreground/80 mt-0.5 leading-relaxed">{description}</p>
+ )}
+ </div>
+ );
+}
+
+function formatEventTime(startTime: string): string {
+ const date = new Date(startTime);
+ const now = new Date();
+ const tomorrow = new Date(now);
+ tomorrow.setDate(tomorrow.getDate() + 1);
+
+ const timeStr = new Intl.DateTimeFormat(undefined, {
+ hour: "numeric",
+ minute: "2-digit",
+ }).format(date);
+
+ if (date.toDateString() === now.toDateString()) {
+ return `Today ${timeStr}`;
+ }
+ if (date.toDateString() === tomorrow.toDateString()) {
+ return `Tomorrow ${timeStr}`;
+ }
+ return new Intl.DateTimeFormat(undefined, {
+ weekday: "short",
+ hour: "numeric",
+ minute: "2-digit",
+ }).format(date);
+}
+
+export default function CalendarSettings() {
+ const { t } = useTranslation();
+ const { gcalConnected, gcalEmail, setGcalConnected, setGcalEmail } = useSettingsStore();
+ const [calendars, setCalendars] = useState<GoogleCalendar[]>([]);
+ const [upcomingEvents, setUpcomingEvents] = useState<CalendarEvent[]>([]);
+ const [isConnecting, setIsConnecting] = useState(false);
+ const [isDisconnecting, setIsDisconnecting] = useState(false);
+ const [isSyncing, setIsSyncing] = useState(false);
+
+ const loadData = useCallback(async () => {
+ if (!gcalConnected) return;
+ try {
+ const [calsResult, eventsResult] = await Promise.all([
+ window.electronAPI?.gcalGetCalendars?.(),
+ window.electronAPI?.gcalGetUpcomingEvents?.(60),
+ ]);
+ if (calsResult?.calendars) setCalendars(calsResult.calendars);
+ if (eventsResult?.events) setUpcomingEvents(eventsResult.events);
+ } catch {
+ // non-fatal
+ }
+ }, [gcalConnected]);
+
+ useEffect(() => {
+ loadData();
+ }, [loadData]);
+
+ useEffect(() => {
+ const unsubConnection = window.electronAPI?.onGcalConnectionChanged?.(
+ (data: { connected: boolean; email: string | null }) => {
+ setGcalConnected(data.connected);
+ setGcalEmail(data.email ?? "");
+ if (data.connected) loadData();
+ }
+ );
+ const unsubSync = window.electronAPI?.onGcalEventsSynced?.(() => {
+ loadData();
+ });
+ return () => {
+ unsubConnection?.();
+ unsubSync?.();
+ };
+ }, [loadData, setGcalConnected, setGcalEmail]);
+
+ const handleConnect = useCallback(async () => {
+ setIsConnecting(true);
+ try {
+ const result = await window.electronAPI?.gcalStartOAuth?.();
+ if (result?.success) {
+ setGcalConnected(true);
+ setGcalEmail(result.email ?? "");
+ }
+ } finally {
+ setIsConnecting(false);
+ }
+ }, [setGcalConnected, setGcalEmail]);
+
+ const handleDisconnect = useCallback(async () => {
+ setIsDisconnecting(true);
+ try {
+ await window.electronAPI?.gcalDisconnect?.();
+ setGcalConnected(false);
+ setGcalEmail("");
+ setCalendars([]);
+ setUpcomingEvents([]);
+ } finally {
+ setIsDisconnecting(false);
+ }
+ }, [setGcalConnected, setGcalEmail]);
+
+ const handleSync = useCallback(async () => {
+ setIsSyncing(true);
+ try {
+ await window.electronAPI?.gcalSyncEvents?.();
+ await loadData();
+ } finally {
+ setIsSyncing(false);
+ }
+ }, [loadData]);
+
+ const handleToggleCalendar = useCallback(async (calendarId: string, isSelected: boolean) => {
+ setCalendars((prev) =>
+ prev.map((c) => (c.id === calendarId ? { ...c, is_selected: isSelected ? 1 : 0 } : c))
+ );
+ try {
+ await window.electronAPI?.gcalSetCalendarSelection?.(calendarId, isSelected);
+ } catch {
+ setCalendars((prev) =>
+ prev.map((c) => (c.id === calendarId ? { ...c, is_selected: isSelected ? 0 : 1 } : c))
+ );
+ }
+ }, []);
+
+ if (!gcalConnected) {
+ return (
+ <div className="space-y-5">
+ <SectionHeader title={t("calendar.title")} />
+
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <SettingsRow
+ label={t("calendar.status")}
+ description={t("calendar.notConnectedDescription")}
+ >
+ <Badge variant="outline">{t("calendar.disconnected")}</Badge>
+ </SettingsRow>
+ </SettingsPanelRow>
+ </SettingsPanel>
+
+ <div className="rounded-lg border border-primary/20 dark:border-primary/15 bg-primary/3 dark:bg-primary/6 p-4">
+ <div className="flex items-start gap-3">
+ <div className="w-8 h-8 rounded-md bg-primary/10 dark:bg-primary/15 flex items-center justify-center shrink-0 mt-0.5">
+ <Calendar className="w-4 h-4 text-primary" />
+ </div>
+ <div className="min-w-0 flex-1 space-y-2.5">
+ <div>
+ <p className="text-xs font-medium text-foreground">
+ {t("calendar.connectCta.title")}
+ </p>
+ <p className="text-xs text-muted-foreground leading-relaxed mt-0.5">
+ {t("calendar.connectCta.description")}
+ </p>
+ </div>
+ <Button onClick={handleConnect} disabled={isConnecting} size="sm" className="w-full">
+ {isConnecting ? (
+ <>
+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
+ {t("calendar.connecting")}
+ </>
+ ) : (
+ <>
+ <Calendar className="mr-1.5 h-3.5 w-3.5" />
+ {t("calendar.connect")}
+ </>
+ )}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-5">
+ <SectionHeader title={t("calendar.title")} />
+
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <div className="flex items-center gap-3">
+ <div className="w-10 h-10 rounded-full bg-primary/10 dark:bg-primary/15 flex items-center justify-center shrink-0">
+ <Calendar className="w-5 h-5 text-primary" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="text-xs font-medium text-foreground truncate">{gcalEmail}</p>
+ </div>
+ <Badge variant="success">{t("calendar.connected")}</Badge>
+ </div>
+ </SettingsPanelRow>
+ </SettingsPanel>
+
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <div className="flex items-center gap-2">
+ <Button variant="outline" size="sm" onClick={handleSync} disabled={isSyncing}>
+ <RefreshCw className={`mr-1.5 h-3.5 w-3.5 ${isSyncing ? "animate-spin" : ""}`} />
+ {isSyncing ? t("calendar.syncing") : t("calendar.sync")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleDisconnect}
+ disabled={isDisconnecting}
+ className="text-destructive border-destructive/30 hover:bg-destructive/10 hover:border-destructive/50"
+ >
+ <LogOut className="mr-1.5 h-3.5 w-3.5" />
+ {isDisconnecting ? t("calendar.disconnecting") : t("calendar.disconnect")}
+ </Button>
+ </div>
+ </SettingsPanelRow>
+ </SettingsPanel>
+
+ {calendars.length > 0 && (
+ <div>
+ <SectionHeader title={t("calendar.calendarsTitle")} />
+ <SettingsPanel>
+ {calendars.map((cal) => (
+ <SettingsPanelRow key={cal.id}>
+ <div className="flex items-center justify-between gap-4">
+ <div className="flex items-center gap-2 min-w-0 flex-1">
+ {cal.background_color && (
+ <span
+ className="w-2.5 h-2.5 rounded-full shrink-0"
+ style={{ backgroundColor: cal.background_color }}
+ />
+ )}
+ <span className="text-xs font-medium text-foreground truncate">
+ {cal.summary}
+ </span>
+ </div>
+ <Toggle
+ checked={cal.is_selected === 1}
+ onChange={(checked) => handleToggleCalendar(cal.id, checked)}
+ />
+ </div>
+ </SettingsPanelRow>
+ ))}
+ </SettingsPanel>
+ </div>
+ )}
+
+ {upcomingEvents.length > 0 && (
+ <div>
+ <SectionHeader title={t("calendar.upcomingTitle")} />
+ <SettingsPanel>
+ {upcomingEvents.slice(0, 3).map((event) => (
+ <SettingsPanelRow key={event.id}>
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-xs font-medium text-foreground truncate min-w-0 flex-1">
+ {event.summary || "—"}
+ </span>
+ <span className="text-xs text-muted-foreground shrink-0">
+ {formatEventTime(event.start_time)}
+ </span>
+ </div>
+ </SettingsPanelRow>
+ ))}
+ </SettingsPanel>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index b1f889b7a..344c14a88 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -7,6 +7,7 @@ import {
UserCircle,
Wrench,
Keyboard,
+ Calendar,
CreditCard,
Shield,
} from "lucide-react";
@@ -64,6 +65,13 @@ export default function SettingsModal({ open, onOpenChange, initialSection }: Se
description: t("settingsModal.sections.hotkeys.description"),
group: t("settingsModal.groups.app"),
},
+ {
+ id: "calendar",
+ label: t("settingsModal.sections.calendar.label"),
+ icon: Calendar,
+ description: t("settingsModal.sections.calendar.description"),
+ group: t("settingsModal.groups.app"),
+ },
{
id: "transcription",
label: t("settingsModal.sections.transcription.label"),
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 891249474..51073a90b 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -51,6 +51,7 @@ import { getPlatform, getCachedPlatform } from "../utils/platform";
import { getDefaultHotkey, formatHotkeyLabel } from "../utils/hotkeys";
import { ActivationModeSelector } from "./ui/ActivationModeSelector";
import { Toggle } from "./ui/toggle";
+import CalendarSettings from "./CalendarSettings";
import DeveloperSection from "./DeveloperSection";
import LanguageSelector from "./ui/LanguageSelector";
import { Skeleton } from "./ui/skeleton";
@@ -68,6 +69,7 @@ export type SettingsSectionType =
| "plansBilling"
| "general"
| "hotkeys"
+ | "calendar"
| "transcription"
| "intelligence"
| "privacyData"
@@ -1761,6 +1763,9 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage
</div>
);
+ case "calendar":
+ return <CalendarSettings />;
+
case "transcription":
return (
<TranscriptionSection
diff --git a/src/helpers/database.js b/src/helpers/database.js
index 423c8faa7..061149c04 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -141,6 +141,59 @@ class DatabaseManager {
)
.run("notes.actions.builtin.cleanupNotes", "Clean Up Notes");
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS google_calendar_tokens (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ google_email TEXT NOT NULL,
+ access_token TEXT NOT NULL,
+ refresh_token TEXT NOT NULL,
+ expires_at INTEGER NOT NULL,
+ scope TEXT NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )
+ `);
+
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS google_calendars (
+ id TEXT PRIMARY KEY,
+ summary TEXT NOT NULL,
+ description TEXT,
+ background_color TEXT,
+ is_selected INTEGER NOT NULL DEFAULT 1,
+ sync_token TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )
+ `);
+
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS calendar_events (
+ id TEXT PRIMARY KEY,
+ calendar_id TEXT NOT NULL,
+ summary TEXT,
+ start_time TEXT NOT NULL,
+ end_time TEXT NOT NULL,
+ is_all_day INTEGER NOT NULL DEFAULT 0,
+ status TEXT NOT NULL DEFAULT 'confirmed',
+ hangout_link TEXT,
+ conference_data TEXT,
+ organizer_email TEXT,
+ attendees_count INTEGER DEFAULT 0,
+ synced_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )
+ `);
+
+ try {
+ this.db.exec("ALTER TABLE notes ADD COLUMN transcript TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+ try {
+ this.db.exec("ALTER TABLE notes ADD COLUMN calendar_event_id TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+
return true;
} catch (error) {
debugLogger.error("Database initialization failed", { error: error.message }, "database");
@@ -258,10 +311,11 @@ class DatabaseManager {
throw new Error("Database not initialized");
}
if (!folderId) {
- const personal = this.db
- .prepare("SELECT id FROM folders WHERE name = 'Personal' AND is_default = 1")
- .get();
- folderId = personal?.id || null;
+ const defaultFolderName = noteType === "meeting" ? "Meetings" : "Personal";
+ const defaultFolder = this.db
+ .prepare("SELECT id FROM folders WHERE name = ? AND is_default = 1")
+ .get(defaultFolderName);
+ folderId = defaultFolder?.id || null;
}
const stmt = this.db.prepare(
"INSERT INTO notes (title, content, note_type, source_file, audio_duration_seconds, folder_id) VALUES (?, ?, ?, ?, ?, ?)"
@@ -326,6 +380,8 @@ class DatabaseManager {
"enhancement_prompt",
"enhanced_at_content_hash",
"folder_id",
+ "transcript",
+ "calendar_event_id",
];
const fields = [];
const values = [];
@@ -530,6 +586,211 @@ class DatabaseManager {
}
}
+ saveGoogleTokens(tokens) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db.prepare("DELETE FROM google_calendar_tokens").run();
+ const stmt = this.db.prepare(
+ "INSERT INTO google_calendar_tokens (google_email, access_token, refresh_token, expires_at, scope) VALUES (?, ?, ?, ?, ?)"
+ );
+ stmt.run(
+ tokens.google_email,
+ tokens.access_token,
+ tokens.refresh_token,
+ tokens.expires_at,
+ tokens.scope
+ );
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error saving Google tokens", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
+ getGoogleTokens() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db.prepare("SELECT * FROM google_calendar_tokens LIMIT 1").get() || null;
+ } catch (error) {
+ debugLogger.error("Error getting Google tokens", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
+ deleteGoogleTokens() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db.prepare("DELETE FROM google_calendar_tokens").run();
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error deleting Google tokens", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
+ saveGoogleCalendars(calendars) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const stmt = this.db.prepare(
+ "INSERT INTO google_calendars (id, summary, description, background_color) VALUES (?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET summary = excluded.summary, description = excluded.description, background_color = excluded.background_color"
+ );
+ for (const cal of calendars) {
+ stmt.run(cal.id, cal.summary, cal.description || null, cal.background_color || null);
+ }
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error saving Google calendars", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
+ getGoogleCalendars() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db.prepare("SELECT * FROM google_calendars").all();
+ } catch (error) {
+ debugLogger.error("Error getting Google calendars", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
+ updateCalendarSelection(calendarId, isSelected) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db
+ .prepare("UPDATE google_calendars SET is_selected = ? WHERE id = ?")
+ .run(isSelected ? 1 : 0, calendarId);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error updating calendar selection", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
+ getSelectedCalendars() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db.prepare("SELECT * FROM google_calendars WHERE is_selected = 1").all();
+ } catch (error) {
+ debugLogger.error("Error getting selected calendars", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
+ upsertCalendarEvents(events) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const transaction = this.db.transaction((eventList) => {
+ const stmt = this.db.prepare(
+ "INSERT OR REPLACE INTO calendar_events (id, calendar_id, summary, start_time, end_time, is_all_day, status, hangout_link, conference_data, organizer_email, attendees_count, synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)"
+ );
+ for (const e of eventList) {
+ stmt.run(
+ e.id,
+ e.calendar_id,
+ e.summary || null,
+ e.start_time,
+ e.end_time,
+ e.is_all_day ? 1 : 0,
+ e.status || "confirmed",
+ e.hangout_link || null,
+ e.conference_data || null,
+ e.organizer_email || null,
+ e.attendees_count || 0
+ );
+ }
+ });
+ transaction(events);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error upserting calendar events", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
+ getActiveEvents() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db
+ .prepare(
+ "SELECT * FROM calendar_events WHERE datetime(start_time) <= datetime('now') AND datetime(end_time) > datetime('now') AND is_all_day = 0 AND status = 'confirmed' ORDER BY start_time ASC"
+ )
+ .all();
+ } catch (error) {
+ debugLogger.error("Error getting active events", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
+ getUpcomingEvents(windowMinutes = 1440) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db
+ .prepare(
+ "SELECT * FROM calendar_events WHERE datetime(start_time) > datetime('now') AND datetime(start_time) <= datetime('now', '+' || ? || ' minutes') AND is_all_day = 0 AND status = 'confirmed' ORDER BY start_time ASC"
+ )
+ .all(windowMinutes);
+ } catch (error) {
+ debugLogger.error("Error getting upcoming events", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
+ clearCalendarData() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const transaction = this.db.transaction(() => {
+ this.db.prepare("DELETE FROM calendar_events").run();
+ this.db.prepare("DELETE FROM google_calendars").run();
+ this.db.prepare("DELETE FROM google_calendar_tokens").run();
+ });
+ transaction();
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error clearing calendar data", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
+ updateCalendarSyncToken(calendarId, syncToken) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db
+ .prepare("UPDATE google_calendars SET sync_token = ? WHERE id = ?")
+ .run(syncToken, calendarId);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error updating sync token", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
+ removeCalendarEvents(eventIds) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const placeholders = eventIds.map(() => "?").join(", ");
+ this.db.prepare(`DELETE FROM calendar_events WHERE id IN (${placeholders})`).run(...eventIds);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error removing calendar events", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
+ getMeetingsFolder() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return (
+ this.db
+ .prepare("SELECT id FROM folders WHERE name = 'Meetings' AND is_default = 1")
+ .get() || null
+ );
+ } catch (error) {
+ debugLogger.error("Error getting meetings folder", { error: error.message }, "gcal");
+ throw error;
+ }
+ }
+
cleanup() {
try {
const dbPath = path.join(
diff --git a/src/helpers/googleCalendarManager.js b/src/helpers/googleCalendarManager.js
new file mode 100644
index 000000000..52536fe30
--- /dev/null
+++ b/src/helpers/googleCalendarManager.js
@@ -0,0 +1,338 @@
+const https = require("https");
+const { Notification, BrowserWindow } = require("electron");
+const debugLogger = require("./debugLogger");
+const GoogleCalendarOAuth = require("./googleCalendarOAuth");
+
+const CALENDAR_API_BASE = "https://www.googleapis.com/calendar/v3";
+
+class GoogleCalendarManager {
+ constructor(databaseManager, windowManager) {
+ this.databaseManager = databaseManager;
+ this.windowManager = windowManager;
+ this.oauth = new GoogleCalendarOAuth(databaseManager);
+ this.syncInterval = null;
+ this.nextMeetingTimer = null;
+ this.meetingEndTimer = null;
+ this.activeMeeting = null;
+ this.notifiedMeetings = new Set();
+ this.SYNC_INTERVAL_MS = 10 * 60 * 1000;
+ }
+
+ start() {
+ if (!this.isConnected()) return;
+
+ this.syncEvents()
+ .then(() => this.scheduleNextMeeting())
+ .catch((err) =>
+ debugLogger.error("Initial calendar sync failed", { error: err.message }, "gcal")
+ );
+
+ this.syncInterval = setInterval(() => {
+ this.syncEvents()
+ .then(() => this.scheduleNextMeeting())
+ .catch((err) => debugLogger.error("Calendar sync failed", { error: err.message }, "gcal"));
+ }, this.SYNC_INTERVAL_MS);
+ }
+
+ stop() {
+ if (this.syncInterval) {
+ clearInterval(this.syncInterval);
+ this.syncInterval = null;
+ }
+ if (this.nextMeetingTimer) {
+ clearTimeout(this.nextMeetingTimer);
+ this.nextMeetingTimer = null;
+ }
+ if (this.meetingEndTimer) {
+ clearTimeout(this.meetingEndTimer);
+ this.meetingEndTimer = null;
+ }
+ this.activeMeeting = null;
+ }
+
+ isConnected() {
+ return !!this.databaseManager.getGoogleTokens();
+ }
+
+ async startOAuth() {
+ const result = await this.oauth.startOAuthFlow();
+ await this.fetchCalendars();
+ await this.syncEvents();
+ this.scheduleNextMeeting();
+
+ if (this.syncInterval) clearInterval(this.syncInterval);
+ this.syncInterval = setInterval(() => {
+ this.syncEvents()
+ .then(() => this.scheduleNextMeeting())
+ .catch((err) => debugLogger.error("Calendar sync failed", { error: err.message }, "gcal"));
+ }, this.SYNC_INTERVAL_MS);
+
+ this.broadcastToWindows("gcal-connection-changed", { connected: true, email: result.email });
+ return result;
+ }
+
+ disconnect() {
+ this.stop();
+ this.databaseManager.clearCalendarData();
+ this.notifiedMeetings.clear();
+ this.broadcastToWindows("gcal-connection-changed", { connected: false, email: null });
+ }
+
+ getConnectionStatus() {
+ const tokens = this.databaseManager.getGoogleTokens();
+ return {
+ connected: !!tokens,
+ email: tokens?.google_email || null,
+ expiresAt: tokens?.expires_at || null,
+ };
+ }
+
+ async fetchCalendars() {
+ const data = await this._apiGet("/users/me/calendarList");
+ const calendars = (data.items || []).map((item) => ({
+ id: item.id,
+ summary: item.summary,
+ description: item.description || null,
+ background_color: item.backgroundColor || null,
+ }));
+ this.databaseManager.saveGoogleCalendars(calendars);
+ return calendars;
+ }
+
+ async syncEvents() {
+ const selectedCalendars = this.databaseManager.getSelectedCalendars();
+ if (selectedCalendars.length === 0) return;
+
+ for (const calendar of selectedCalendars) {
+ try {
+ await this._syncCalendar(calendar);
+ } catch (err) {
+ debugLogger.error(
+ "Error syncing calendar",
+ {
+ calendarId: calendar.id,
+ error: err.message,
+ },
+ "gcal"
+ );
+ }
+ }
+
+ this.broadcastToWindows("gcal-events-synced", {});
+ this.scheduleNextMeeting();
+ }
+
+ async _syncCalendar(calendar) {
+ const params = new URLSearchParams({
+ singleEvents: "true",
+ orderBy: "startTime",
+ timeMin: new Date().toISOString(),
+ timeMax: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
+ });
+
+ if (calendar.sync_token) {
+ params.delete("timeMin");
+ params.delete("timeMax");
+ params.delete("orderBy");
+ params.set("syncToken", calendar.sync_token);
+ }
+
+ let data;
+ try {
+ data = await this._apiGet(
+ `/calendars/${encodeURIComponent(calendar.id)}/events?${params.toString()}`
+ );
+ } catch (err) {
+ // 410 Gone means syncToken is invalid; fall back to full sync
+ if (err.statusCode === 410) {
+ const fullParams = new URLSearchParams({
+ singleEvents: "true",
+ orderBy: "startTime",
+ timeMin: new Date().toISOString(),
+ timeMax: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
+ });
+ data = await this._apiGet(
+ `/calendars/${encodeURIComponent(calendar.id)}/events?${fullParams.toString()}`
+ );
+ } else {
+ throw err;
+ }
+ }
+
+ const toUpsert = [];
+ const toRemove = [];
+
+ for (const item of data.items || []) {
+ if (item.status === "cancelled") {
+ toRemove.push(item.id);
+ continue;
+ }
+
+ const isAllDay = !item.start?.dateTime;
+ toUpsert.push({
+ id: item.id,
+ calendar_id: calendar.id,
+ summary: item.summary || null,
+ start_time: item.start?.dateTime || item.start?.date,
+ end_time: item.end?.dateTime || item.end?.date,
+ is_all_day: isAllDay,
+ status: item.status || "confirmed",
+ hangout_link: item.hangoutLink || null,
+ conference_data: item.conferenceData ? JSON.stringify(item.conferenceData) : null,
+ organizer_email: item.organizer?.email || null,
+ attendees_count: item.attendees?.length || 0,
+ });
+ }
+
+ if (toUpsert.length > 0) this.databaseManager.upsertCalendarEvents(toUpsert);
+ if (toRemove.length > 0) this.databaseManager.removeCalendarEvents(toRemove);
+ if (data.nextSyncToken)
+ this.databaseManager.updateCalendarSyncToken(calendar.id, data.nextSyncToken);
+ }
+
+ scheduleNextMeeting() {
+ if (this.nextMeetingTimer) {
+ clearTimeout(this.nextMeetingTimer);
+ this.nextMeetingTimer = null;
+ }
+
+ const upcoming = this.databaseManager.getUpcomingEvents(1440);
+ const next = upcoming.find((e) => !this.notifiedMeetings.has(e.id));
+ if (!next) return;
+
+ const delay = new Date(next.start_time).getTime() - Date.now();
+ if (delay <= 0) {
+ this.onMeetingStart(next);
+ return;
+ }
+
+ this.nextMeetingTimer = setTimeout(() => {
+ this.onMeetingStart(next);
+ }, delay);
+ }
+
+ onMeetingStart(event) {
+ const events = this.databaseManager.getActiveEvents();
+ const stillExists =
+ events.some((e) => e.id === event.id) ||
+ this.databaseManager.getUpcomingEvents(1).some((e) => e.id === event.id);
+
+ if (!stillExists) {
+ this.scheduleNextMeeting();
+ return;
+ }
+
+ this.activeMeeting = event;
+ this.notifiedMeetings.add(event.id);
+
+ const notif = new Notification({
+ title: event.summary || "Meeting",
+ body: "Meeting starting now",
+ });
+ notif.on("click", () => {
+ this.broadcastToWindows("gcal-start-recording", { event });
+ });
+ notif.show();
+
+ this.broadcastToWindows("gcal-meeting-starting", { event });
+
+ if (this.meetingEndTimer) {
+ clearTimeout(this.meetingEndTimer);
+ }
+ const endDelay = new Date(event.end_time).getTime() - Date.now();
+ if (endDelay > 0) {
+ this.meetingEndTimer = setTimeout(() => {
+ this.onMeetingEnd();
+ }, endDelay);
+ }
+
+ this.scheduleNextMeeting();
+ }
+
+ onMeetingEnd() {
+ this.broadcastToWindows("gcal-meeting-ended", { event: this.activeMeeting });
+ this.activeMeeting = null;
+ if (this.meetingEndTimer) {
+ clearTimeout(this.meetingEndTimer);
+ this.meetingEndTimer = null;
+ }
+ this.scheduleNextMeeting();
+ }
+
+ onWakeFromSleep() {
+ const activeEvents = this.databaseManager.getActiveEvents();
+ if (activeEvents.length > 0 && !this.activeMeeting) {
+ this.onMeetingStart(activeEvents[0]);
+ }
+ this.scheduleNextMeeting();
+
+ this.syncEvents().catch((err) =>
+ debugLogger.error("Post-wake sync failed", { error: err.message }, "gcal")
+ );
+ }
+
+ getCalendars() {
+ return this.databaseManager.getGoogleCalendars();
+ }
+
+ async setCalendarSelection(calendarId, isSelected) {
+ this.databaseManager.updateCalendarSelection(calendarId, isSelected);
+ await this.syncEvents();
+ this.scheduleNextMeeting();
+ }
+
+ async getUpcomingEvents(windowMinutes) {
+ return this.databaseManager.getUpcomingEvents(windowMinutes);
+ }
+
+ broadcastToWindows(channel, data) {
+ const windows = BrowserWindow.getAllWindows();
+ windows.forEach((win) => {
+ if (!win.isDestroyed()) {
+ win.webContents.send(channel, data);
+ }
+ });
+ }
+
+ async _apiGet(path) {
+ const accessToken = await this.oauth.getValidAccessToken();
+ const urlString = path.startsWith("http") ? path : `${CALENDAR_API_BASE}${path}`;
+ const url = new URL(urlString);
+
+ return new Promise((resolve, reject) => {
+ const req = https.request(
+ {
+ hostname: url.hostname,
+ port: 443,
+ path: url.pathname + url.search,
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ },
+ },
+ (res) => {
+ let data = "";
+ res.on("data", (chunk) => (data += chunk));
+ res.on("end", () => {
+ try {
+ const parsed = JSON.parse(data);
+ if (res.statusCode >= 400) {
+ const err = new Error(parsed.error?.message || `API error ${res.statusCode}`);
+ err.statusCode = res.statusCode;
+ reject(err);
+ return;
+ }
+ resolve(parsed);
+ } catch (e) {
+ reject(new Error(`Invalid JSON response: ${data.slice(0, 200)}`));
+ }
+ });
+ }
+ );
+ req.on("error", reject);
+ req.end();
+ });
+ }
+}
+
+module.exports = GoogleCalendarManager;
diff --git a/src/helpers/googleCalendarOAuth.js b/src/helpers/googleCalendarOAuth.js
new file mode 100644
index 000000000..773071d4c
--- /dev/null
+++ b/src/helpers/googleCalendarOAuth.js
@@ -0,0 +1,245 @@
+const http = require("http");
+const https = require("https");
+const crypto = require("crypto");
+const { shell } = require("electron");
+
+const GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
+const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
+const GOOGLE_USERINFO_URL = "https://www.googleapis.com/oauth2/v2/userinfo";
+const CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar.readonly";
+const OAUTH_TIMEOUT_MS = 120000;
+
+class GoogleCalendarOAuth {
+ constructor(databaseManager) {
+ this.databaseManager = databaseManager;
+ }
+
+ getClientId() {
+ return process.env.GOOGLE_CALENDAR_CLIENT_ID;
+ }
+
+ getClientSecret() {
+ return process.env.GOOGLE_CALENDAR_CLIENT_SECRET;
+ }
+
+ startOAuthFlow() {
+ return new Promise((resolve, reject) => {
+ const codeVerifier = crypto.randomBytes(32).toString("base64url").slice(0, 43);
+ const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
+ const state = crypto.randomBytes(32).toString("hex");
+
+ const server = http.createServer(async (req, res) => {
+ try {
+ const url = new URL(req.url, `http://127.0.0.1`);
+ const returnedState = url.searchParams.get("state");
+ const code = url.searchParams.get("code");
+ const error = url.searchParams.get("error");
+
+ if (error) {
+ res.writeHead(200, { "Content-Type": "text/html" });
+ res.end(
+ "<html><body><h3>Authentication failed. You can close this tab.</h3></body></html>"
+ );
+ cleanup();
+ reject(new Error(`OAuth error: ${error}`));
+ return;
+ }
+
+ if (!code || returnedState !== state) {
+ res.writeHead(400, { "Content-Type": "text/html" });
+ res.end("<html><body><h3>Invalid request. You can close this tab.</h3></body></html>");
+ return;
+ }
+
+ const redirectUri = `http://127.0.0.1:${server.address().port}`;
+ const tokenData = await this.exchangeCodeForTokens(code, redirectUri, codeVerifier);
+
+ if (tokenData.error) {
+ res.writeHead(200, { "Content-Type": "text/html" });
+ res.end(
+ "<html><body><h3>Authentication failed. You can close this tab.</h3></body></html>"
+ );
+ cleanup();
+ reject(
+ new Error(`Token exchange failed: ${tokenData.error_description || tokenData.error}`)
+ );
+ return;
+ }
+
+ const userInfo = await this._httpsGet(GOOGLE_USERINFO_URL, {
+ Authorization: `Bearer ${tokenData.access_token}`,
+ });
+
+ const expiresAt = Date.now() + tokenData.expires_in * 1000;
+ this.databaseManager.saveGoogleTokens({
+ google_email: userInfo.email,
+ access_token: tokenData.access_token,
+ refresh_token: tokenData.refresh_token,
+ expires_at: expiresAt,
+ scope: tokenData.scope || CALENDAR_SCOPE,
+ });
+
+ res.writeHead(200, { "Content-Type": "text/html" });
+ res.end(
+ "<html><body><h3>Authentication successful! You can close this tab.</h3></body></html>"
+ );
+ cleanup();
+ resolve({ success: true, email: userInfo.email });
+ } catch (err) {
+ res.writeHead(500, { "Content-Type": "text/html" });
+ res.end("<html><body><h3>An error occurred. You can close this tab.</h3></body></html>");
+ cleanup();
+ reject(err);
+ }
+ });
+
+ let timeoutId;
+
+ const cleanup = () => {
+ clearTimeout(timeoutId);
+ server.close();
+ };
+
+ server.listen(0, "127.0.0.1", () => {
+ const port = server.address().port;
+ const redirectUri = `http://127.0.0.1:${port}`;
+
+ const params = new URLSearchParams({
+ client_id: this.getClientId(),
+ redirect_uri: redirectUri,
+ response_type: "code",
+ scope: CALENDAR_SCOPE,
+ access_type: "offline",
+ prompt: "consent",
+ state,
+ code_challenge: codeChallenge,
+ code_challenge_method: "S256",
+ });
+
+ shell.openExternal(`${GOOGLE_AUTH_URL}?${params.toString()}`);
+ });
+
+ timeoutId = setTimeout(() => {
+ server.close();
+ reject(new Error("OAuth flow timed out"));
+ }, OAUTH_TIMEOUT_MS);
+
+ server.on("error", (err) => {
+ cleanup();
+ reject(err);
+ });
+ });
+ }
+
+ async exchangeCodeForTokens(code, redirectUri, codeVerifier) {
+ const body = new URLSearchParams({
+ code,
+ client_id: this.getClientId(),
+ client_secret: this.getClientSecret(),
+ redirect_uri: redirectUri,
+ grant_type: "authorization_code",
+ code_verifier: codeVerifier,
+ }).toString();
+
+ return this._httpsPost(GOOGLE_TOKEN_URL, body);
+ }
+
+ async refreshAccessToken(refreshToken) {
+ const body = new URLSearchParams({
+ client_id: this.getClientId(),
+ client_secret: this.getClientSecret(),
+ refresh_token: refreshToken,
+ grant_type: "refresh_token",
+ }).toString();
+
+ return this._httpsPost(GOOGLE_TOKEN_URL, body);
+ }
+
+ async getValidAccessToken() {
+ const tokens = this.databaseManager.getGoogleTokens();
+ if (!tokens) throw new Error("No Google tokens found");
+
+ const fiveMinutes = 5 * 60 * 1000;
+ if (tokens.expires_at - fiveMinutes < Date.now()) {
+ const refreshed = await this.refreshAccessToken(tokens.refresh_token);
+ if (refreshed.error) {
+ throw new Error(`Token refresh failed: ${refreshed.error_description || refreshed.error}`);
+ }
+
+ const newExpiresAt = Date.now() + refreshed.expires_in * 1000;
+ this.databaseManager.saveGoogleTokens({
+ google_email: tokens.google_email,
+ access_token: refreshed.access_token,
+ refresh_token: tokens.refresh_token,
+ expires_at: newExpiresAt,
+ scope: tokens.scope,
+ });
+
+ return refreshed.access_token;
+ }
+
+ return tokens.access_token;
+ }
+
+ _httpsPost(urlString, body) {
+ const url = new URL(urlString);
+ return new Promise((resolve, reject) => {
+ const req = https.request(
+ {
+ hostname: url.hostname,
+ port: 443,
+ path: url.pathname,
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ "Content-Length": Buffer.byteLength(body),
+ },
+ },
+ (res) => {
+ let data = "";
+ res.on("data", (chunk) => (data += chunk));
+ res.on("end", () => {
+ try {
+ resolve(JSON.parse(data));
+ } catch (e) {
+ reject(new Error(`Invalid JSON response: ${data.slice(0, 200)}`));
+ }
+ });
+ }
+ );
+ req.on("error", reject);
+ req.write(body);
+ req.end();
+ });
+ }
+
+ _httpsGet(urlString, headers = {}) {
+ const url = new URL(urlString);
+ return new Promise((resolve, reject) => {
+ const req = https.request(
+ {
+ hostname: url.hostname,
+ port: 443,
+ path: url.pathname + url.search,
+ method: "GET",
+ headers,
+ },
+ (res) => {
+ let data = "";
+ res.on("data", (chunk) => (data += chunk));
+ res.on("end", () => {
+ try {
+ resolve(JSON.parse(data));
+ } catch (e) {
+ reject(new Error(`Invalid JSON response: ${data.slice(0, 200)}`));
+ }
+ });
+ }
+ );
+ req.on("error", reject);
+ req.end();
+ });
+ }
+}
+
+module.exports = GoogleCalendarOAuth;
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index c28314afe..69fca254f 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -95,6 +95,7 @@ class IPCHandlers {
this.windowsKeyManager = managers.windowsKeyManager;
this.getTrayManager = managers.getTrayManager;
this.whisperCudaManager = managers.whisperCudaManager;
+ this.googleCalendarManager = managers.googleCalendarManager;
this.sessionId = crypto.randomUUID();
this.assemblyAiStreaming = null;
this.deepgramStreaming = null;
@@ -2566,6 +2567,86 @@ class IPCHandlers {
}
return this.deepgramStreaming.getStatus();
});
+
+ // Google Calendar
+ ipcMain.handle("gcal-start-oauth", async () => {
+ try {
+ return await this.googleCalendarManager.startOAuth();
+ } catch (error) {
+ debugLogger.error("Google Calendar OAuth failed", { error: error.message }, "calendar");
+ return { success: false, error: error.message };
+ }
+ });
+
+ ipcMain.handle("gcal-disconnect", async () => {
+ try {
+ this.googleCalendarManager.disconnect();
+ return { success: true };
+ } catch (error) {
+ debugLogger.error(
+ "Google Calendar disconnect failed",
+ { error: error.message },
+ "calendar"
+ );
+ return { success: false, error: error.message };
+ }
+ });
+
+ ipcMain.handle("gcal-get-connection-status", async () => {
+ try {
+ return this.googleCalendarManager.getConnectionStatus();
+ } catch (error) {
+ return { connected: false, email: null };
+ }
+ });
+
+ ipcMain.handle("gcal-get-calendars", async () => {
+ try {
+ return { success: true, calendars: this.googleCalendarManager.getCalendars() };
+ } catch (error) {
+ return { success: false, calendars: [] };
+ }
+ });
+
+ ipcMain.handle("gcal-set-calendar-selection", async (_event, calendarId, isSelected) => {
+ try {
+ await this.googleCalendarManager.setCalendarSelection(calendarId, isSelected);
+ return { success: true };
+ } catch (error) {
+ return { success: false, error: error.message };
+ }
+ });
+
+ ipcMain.handle("gcal-sync-events", async () => {
+ try {
+ await this.googleCalendarManager.syncEvents();
+ return { success: true };
+ } catch (error) {
+ return { success: false, error: error.message };
+ }
+ });
+
+ ipcMain.handle("gcal-get-upcoming-events", async (_event, windowMinutes) => {
+ try {
+ return {
+ success: true,
+ events: await this.googleCalendarManager.getUpcomingEvents(windowMinutes),
+ };
+ } catch (error) {
+ return { success: false, events: [] };
+ }
+ });
+
+ ipcMain.handle("get-desktop-sources", async (_event, types) => {
+ try {
+ const { desktopCapturer } = require("electron");
+ const sources = await desktopCapturer.getSources({ types: types || ["screen"] });
+ return sources.map((s) => ({ id: s.id, name: s.name }));
+ } catch (error) {
+ debugLogger.error("Failed to get desktop sources", { error: error.message }, "calendar");
+ return [];
+ }
+ });
}
broadcastToWindows(channel, payload) {
diff --git a/src/hooks/useMeetingRecording.ts b/src/hooks/useMeetingRecording.ts
new file mode 100644
index 000000000..8b2f8efdc
--- /dev/null
+++ b/src/hooks/useMeetingRecording.ts
@@ -0,0 +1,239 @@
+import { useState, useEffect, useRef, useCallback } from "react";
+import logger from "../utils/logger";
+import type { CalendarEvent } from "../types/calendar";
+
+const SAFETY_TIMEOUT_BUFFER_MS = 30 * 60 * 1000;
+
+interface UseMeetingRecordingReturn {
+ isRecording: boolean;
+ isProcessing: boolean;
+ activeMeeting: CalendarEvent | null;
+ startRecording: (event: CalendarEvent) => Promise<void>;
+ stopRecording: () => Promise<void>;
+}
+
+const getSystemAudioStream = async (): Promise<MediaStream | null> => {
+ try {
+ const sources = await window.electronAPI?.getDesktopSources(["screen"]);
+ if (!sources?.length) return null;
+
+ const stream = await navigator.mediaDevices.getUserMedia({
+ audio: {
+ mandatory: {
+ chromeMediaSource: "desktop",
+ chromeMediaSourceId: sources[0].id,
+ },
+ } as any,
+ video: {
+ mandatory: {
+ chromeMediaSource: "desktop",
+ chromeMediaSourceId: sources[0].id,
+ minWidth: 1,
+ maxWidth: 1,
+ minHeight: 1,
+ maxHeight: 1,
+ },
+ } as any,
+ });
+
+ stream.getVideoTracks().forEach((t) => t.stop());
+ return new MediaStream(stream.getAudioTracks());
+ } catch (err) {
+ logger.error("Failed to capture system audio", { error: (err as Error).message }, "meeting");
+ return null;
+ }
+};
+
+export function useMeetingRecording(): UseMeetingRecordingReturn {
+ const [isRecording, setIsRecording] = useState(false);
+ const [isProcessing, setIsProcessing] = useState(false);
+ const [activeMeeting, setActiveMeeting] = useState<CalendarEvent | null>(null);
+
+ const mediaRecorderRef = useRef<MediaRecorder | null>(null);
+ const audioChunksRef = useRef<Blob[]>([]);
+ const recordingStartTimeRef = useRef<number | null>(null);
+ const safetyTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const activeMeetingRef = useRef<CalendarEvent | null>(null);
+ const streamRef = useRef<MediaStream | null>(null);
+
+ const cleanup = useCallback(() => {
+ if (safetyTimeoutRef.current) {
+ clearTimeout(safetyTimeoutRef.current);
+ safetyTimeoutRef.current = null;
+ }
+ if (mediaRecorderRef.current?.state === "recording") {
+ mediaRecorderRef.current.stop();
+ }
+ if (streamRef.current) {
+ streamRef.current.getTracks().forEach((t) => t.stop());
+ streamRef.current = null;
+ }
+ mediaRecorderRef.current = null;
+ audioChunksRef.current = [];
+ recordingStartTimeRef.current = null;
+ }, []);
+
+ const stopRecording = useCallback(async () => {
+ if (!mediaRecorderRef.current || mediaRecorderRef.current.state !== "recording") return;
+
+ if (safetyTimeoutRef.current) {
+ clearTimeout(safetyTimeoutRef.current);
+ safetyTimeoutRef.current = null;
+ }
+
+ return new Promise<void>((resolve) => {
+ const recorder = mediaRecorderRef.current!;
+ const event = activeMeetingRef.current;
+ const mimeType = recorder.mimeType || "audio/webm";
+
+ recorder.onstop = async () => {
+ setIsRecording(false);
+ setIsProcessing(true);
+
+ const audioBlob = new Blob(audioChunksRef.current, { type: mimeType });
+ const durationSeconds = recordingStartTimeRef.current
+ ? (Date.now() - recordingStartTimeRef.current) / 1000
+ : 0;
+
+ if (streamRef.current) {
+ streamRef.current.getTracks().forEach((t) => t.stop());
+ streamRef.current = null;
+ }
+ mediaRecorderRef.current = null;
+ audioChunksRef.current = [];
+ recordingStartTimeRef.current = null;
+
+ try {
+ const arrayBuffer = await audioBlob.arrayBuffer();
+ const result = await window.electronAPI?.cloudTranscribe(arrayBuffer, {
+ useCase: "meeting" as any,
+ diarization: true as any,
+ });
+
+ if (result?.success && result.text) {
+ const title = event?.summary || "Meeting Recording";
+ const noteResult = await window.electronAPI?.saveNote(
+ title,
+ "",
+ "meeting",
+ null,
+ Math.round(durationSeconds),
+ null
+ );
+
+ if (noteResult?.success && noteResult.note) {
+ await window.electronAPI?.updateNote(noteResult.note.id, {
+ transcript: result.text,
+ calendar_event_id: event?.id ?? null,
+ });
+ logger.info(
+ "Meeting transcription saved",
+ { noteId: noteResult.note.id, eventId: event?.id },
+ "meeting"
+ );
+ }
+ } else {
+ logger.error("Meeting transcription failed", { error: result?.error }, "meeting");
+ }
+ } catch (err) {
+ logger.error(
+ "Meeting recording processing failed",
+ { error: (err as Error).message },
+ "meeting"
+ );
+ } finally {
+ setIsProcessing(false);
+ setActiveMeeting(null);
+ activeMeetingRef.current = null;
+ resolve();
+ }
+ };
+
+ recorder.stop();
+ });
+ }, []);
+
+ const startRecording = useCallback(
+ async (event: CalendarEvent) => {
+ if (isRecording || isProcessing) return;
+
+ const stream = await getSystemAudioStream();
+ if (!stream) {
+ logger.error("Could not capture system audio for meeting", {}, "meeting");
+ return;
+ }
+
+ streamRef.current = stream;
+ const recorder = new MediaRecorder(stream);
+ mediaRecorderRef.current = recorder;
+ audioChunksRef.current = [];
+ recordingStartTimeRef.current = Date.now();
+ activeMeetingRef.current = event;
+
+ recorder.ondataavailable = (e) => {
+ if (e.data.size > 0) audioChunksRef.current.push(e.data);
+ };
+
+ recorder.start();
+ setIsRecording(true);
+ setActiveMeeting(event);
+
+ const eventDurationMs =
+ new Date(event.end_time).getTime() - new Date(event.start_time).getTime();
+ const safetyMs = Math.max(eventDurationMs, 0) + SAFETY_TIMEOUT_BUFFER_MS;
+
+ safetyTimeoutRef.current = setTimeout(() => {
+ logger.info("Safety timeout reached, auto-stopping meeting recording", {}, "meeting");
+ stopRecording();
+ }, safetyMs);
+
+ logger.info(
+ "Meeting recording started",
+ { eventId: event.id, summary: event.summary },
+ "meeting"
+ );
+ },
+ [isRecording, isProcessing, stopRecording]
+ );
+
+ useEffect(() => {
+ const cleanups: Array<() => void> = [];
+
+ const meetingStartingCleanup = window.electronAPI?.onGcalMeetingStarting?.((data: any) => {
+ logger.info("Meeting starting notification", { eventId: data?.event?.id }, "meeting");
+ });
+ if (meetingStartingCleanup) cleanups.push(meetingStartingCleanup);
+
+ const meetingEndedCleanup = window.electronAPI?.onGcalMeetingEnded?.((data: any) => {
+ if (activeMeetingRef.current && data?.event?.id === activeMeetingRef.current.id) {
+ logger.info(
+ "Meeting ended, auto-stopping recording",
+ { eventId: data.event.id },
+ "meeting"
+ );
+ stopRecording();
+ }
+ });
+ if (meetingEndedCleanup) cleanups.push(meetingEndedCleanup);
+
+ const startRecordingCleanup = window.electronAPI?.onGcalStartRecording?.((data: any) => {
+ if (data?.event && !activeMeetingRef.current) {
+ startRecording(data.event);
+ }
+ });
+ if (startRecordingCleanup) cleanups.push(startRecordingCleanup);
+
+ return () => {
+ cleanups.forEach((fn) => fn());
+ cleanup();
+ };
+ }, [startRecording, stopRecording, cleanup]);
+
+ return {
+ isRecording,
+ isProcessing,
+ activeMeeting,
+ startRecording,
+ stopRecording,
+ };
+}
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 29734035e..abc4be067 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -488,6 +488,29 @@
"welcomeTitle": "Welcome to OpenWhispr",
"sessionExpired": "Session expired. Please restart the sign-up process."
},
+ "calendar": {
+ "title": "Google Calendar",
+ "status": "Status",
+ "connected": "Connected",
+ "disconnected": "Disconnected",
+ "notConnectedDescription": "Connect to detect and record meetings",
+ "connectCta": {
+ "title": "Calendar Integration",
+ "description": "Auto-detect meetings and record with speaker diarization"
+ },
+ "connect": "Connect Google Calendar",
+ "connecting": "Connecting...",
+ "disconnect": "Disconnect",
+ "disconnecting": "Disconnecting...",
+ "sync": "Sync",
+ "syncing": "Syncing...",
+ "calendarsTitle": "Calendars",
+ "upcomingTitle": "Upcoming",
+ "noUpcoming": "No upcoming events",
+ "meetingStarting": "Meeting starting now",
+ "today": "Today",
+ "tomorrow": "Tomorrow"
+ },
"cleanupPrompt": "Cleanup",
"developerSection": {
"currentLogFile": "Current log file",
@@ -810,6 +833,10 @@
"description": "Dictation hotkey & activation",
"label": "Hotkeys"
},
+ "calendar": {
+ "label": "Calendar",
+ "description": "Google Calendar integration"
+ },
"transcription": {
"description": "Speech-to-text engine",
"label": "Transcription"
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index fae211f3f..a6d18e386 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -55,6 +55,7 @@ const BOOLEAN_SETTINGS = new Set([
"telemetryEnabled",
"audioCuesEnabled",
"floatingIconAutoHide",
+ "gcalConnected",
"isSignedIn",
]);
@@ -84,6 +85,8 @@ export interface SettingsState
isSignedIn: boolean;
audioCuesEnabled: boolean;
floatingIconAutoHide: boolean;
+ gcalConnected: boolean;
+ gcalEmail: string;
setUseLocalWhisper: (value: boolean) => void;
setWhisperModel: (value: string) => void;
@@ -125,6 +128,8 @@ export interface SettingsState
setTelemetryEnabled: (value: boolean) => void;
setAudioCuesEnabled: (value: boolean) => void;
setFloatingIconAutoHide: (enabled: boolean) => void;
+ setGcalConnected: (value: boolean) => void;
+ setGcalEmail: (value: string) => void;
setIsSignedIn: (value: boolean) => void;
updateTranscriptionSettings: (settings: Partial<TranscriptionSettings>) => void;
@@ -236,6 +241,8 @@ export const useSettingsStore = create<SettingsState>()((set) => ({
telemetryEnabled: readBoolean("telemetryEnabled", false),
audioCuesEnabled: readBoolean("audioCuesEnabled", true),
floatingIconAutoHide: readBoolean("floatingIconAutoHide", false),
+ gcalConnected: readBoolean("gcalConnected", false),
+ gcalEmail: readString("gcalEmail", ""),
isSignedIn: readBoolean("isSignedIn", false),
setUseLocalWhisper: createBooleanSetter("useLocalWhisper"),
@@ -368,6 +375,9 @@ export const useSettingsStore = create<SettingsState>()((set) => ({
}
},
+ setGcalConnected: createBooleanSetter("gcalConnected"),
+ setGcalEmail: createStringSetter("gcalEmail"),
+
setIsSignedIn: (value: boolean) => {
if (isBrowser) localStorage.setItem("isSignedIn", String(value));
set({ isSignedIn: value });
diff --git a/src/types/calendar.ts b/src/types/calendar.ts
new file mode 100644
index 000000000..7fa0760ee
--- /dev/null
+++ b/src/types/calendar.ts
@@ -0,0 +1,27 @@
+export interface GoogleCalendar {
+ id: string;
+ summary: string;
+ description: string | null;
+ background_color: string | null;
+ is_selected: number;
+ sync_token: string | null;
+}
+
+export interface CalendarEvent {
+ id: string;
+ calendar_id: string;
+ summary: string | null;
+ start_time: string;
+ end_time: string;
+ is_all_day: number;
+ status: string;
+ hangout_link: string | null;
+ conference_data: string | null;
+ organizer_email: string | null;
+ attendees_count: number;
+}
+
+export interface CalendarConnectionStatus {
+ connected: boolean;
+ email: string | null;
+}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 60e02d070..ffdef7e4c 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -18,6 +18,8 @@ export interface NoteItem {
source_file: string | null;
audio_duration_seconds: number | null;
folder_id: number | null;
+ transcript: string | null;
+ calendar_event_id: string | null;
created_at: string;
updated_at: string;
}
@@ -304,6 +306,8 @@ declare global {
enhancement_prompt?: string | null;
enhanced_at_content_hash?: string | null;
folder_id?: number | null;
+ transcript?: string | null;
+ calendar_event_id?: string | null;
}
) => Promise<{ success: boolean; note?: NoteItem }>;
deleteNote: (id: number) => Promise<{ success: boolean }>;
@@ -672,7 +676,7 @@ declare global {
// OpenWhispr Cloud API
cloudTranscribe?: (
audioBuffer: ArrayBuffer,
- opts: { language?: string; prompt?: string }
+ opts: { language?: string; prompt?: string; useCase?: string; diarization?: boolean }
) => Promise<{
success: boolean;
text?: string;
@@ -859,6 +863,30 @@ declare global {
onDeepgramSessionEnd?: (
callback: (data: { audioDuration?: number; text?: string }) => void
) => () => void;
+
+ // Google Calendar
+ gcalStartOAuth?: () => Promise<{ success: boolean; email?: string; error?: string }>;
+ gcalDisconnect?: () => Promise<{ success: boolean; error?: string }>;
+ gcalGetConnectionStatus?: () => Promise<{ connected: boolean; email: string | null }>;
+ gcalGetCalendars?: () => Promise<{ success: boolean; calendars: any[] }>;
+ gcalSetCalendarSelection?: (
+ calendarId: string,
+ isSelected: boolean
+ ) => Promise<{ success: boolean; error?: string }>;
+ gcalSyncEvents?: () => Promise<{ success: boolean; error?: string }>;
+ gcalGetUpcomingEvents?: (
+ windowMinutes?: number
+ ) => Promise<{ success: boolean; events: any[] }>;
+
+ // Desktop audio capture
+ getDesktopSources?: (types: string[]) => Promise<Array<{ id: string; name: string }>>;
+
+ // Google Calendar event listeners
+ onGcalMeetingStarting?: (callback: (data: any) => void) => () => void;
+ onGcalMeetingEnded?: (callback: (data: any) => void) => () => void;
+ onGcalStartRecording?: (callback: (data: any) => void) => () => void;
+ onGcalConnectionChanged?: (callback: (data: any) => void) => () => void;
+ onGcalEventsSynced?: (callback: (data: any) => void) => () => void;
};
api?: {