|
| 1 | +/** |
| 2 | + * PostHog analytics client for main process. |
| 3 | + * |
| 4 | + * Privacy-friendly analytics to track: |
| 5 | + * - Daily active users |
| 6 | + * - App version usage |
| 7 | + * - Basic feature usage (opt-in via settings) |
| 8 | + * |
| 9 | + * All events use an anonymous user ID generated at first run. |
| 10 | + * Users can disable analytics completely in settings. |
| 11 | + */ |
| 12 | + |
| 13 | +import { randomUUID } from "crypto"; |
| 14 | +import { app } from "electron"; |
| 15 | +import { getAppSettings, setAppSettings } from "./app-settings"; |
| 16 | +import { log } from "./logger"; |
| 17 | + |
| 18 | +// Lazy-loaded PostHog client |
| 19 | +let PostHogCtor: typeof import("posthog-node").PostHog | null = null; |
| 20 | +let client: import("posthog-node").PostHog | null = null; |
| 21 | +let userId: string | null = null; |
| 22 | +let lastDailyActiveCheck: string | null = null; |
| 23 | + |
| 24 | +/** |
| 25 | + * Initialize PostHog client based on current settings. |
| 26 | + * Call this once at app startup, after settings are loaded. |
| 27 | + */ |
| 28 | +export async function initPostHog(): Promise<void> { |
| 29 | + const settings = getAppSettings(); |
| 30 | + |
| 31 | + // Don't initialize if analytics is disabled |
| 32 | + if (!settings.analyticsEnabled) { |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + // Generate or load anonymous user ID |
| 37 | + userId = generateUserId(); |
| 38 | + |
| 39 | + try { |
| 40 | + // PostHog project API keys are public (client-side) — safe to embed in source. |
| 41 | + // Override via POSTHOG_API_KEY env var if needed (e.g. for a fork's own project). |
| 42 | + const apiKey = process.env.POSTHOG_API_KEY || "phc_lOKFRov0SWy2R71BNJ2t978tmNYc3ND7WwueOteV5vw"; |
| 43 | + if (!apiKey) { |
| 44 | + log("POSTHOG", "API key not configured — analytics disabled"); |
| 45 | + return; |
| 46 | + } |
| 47 | + |
| 48 | + // Lazy-load posthog-node |
| 49 | + const posthogModule = await import("posthog-node"); |
| 50 | + PostHogCtor = posthogModule.PostHog; |
| 51 | + |
| 52 | + // Initialize client with public PostHog project |
| 53 | + client = new PostHogCtor(apiKey, { |
| 54 | + host: "https://us.i.posthog.com", |
| 55 | + // Flush events every 10 seconds or 20 events, whichever comes first |
| 56 | + flushAt: 20, |
| 57 | + flushInterval: 10000, |
| 58 | + }); |
| 59 | + |
| 60 | + log("POSTHOG", `Initialized (userId=${userId})`); |
| 61 | + |
| 62 | + // Track app start event |
| 63 | + await captureEvent("app_started", { |
| 64 | + version: app.getVersion(), |
| 65 | + platform: process.platform, |
| 66 | + arch: process.arch, |
| 67 | + }); |
| 68 | + |
| 69 | + // Track daily active user (once per day) |
| 70 | + await trackDailyActive(); |
| 71 | + } catch (err) { |
| 72 | + // Non-fatal - analytics is optional |
| 73 | + log("POSTHOG", `Failed to initialize: ${err instanceof Error ? err.message : String(err)}`); |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + * Generate or retrieve the anonymous user ID. |
| 79 | + * Stored in app settings for persistence across sessions. |
| 80 | + */ |
| 81 | +function generateUserId(): string { |
| 82 | + const settings = getAppSettings(); |
| 83 | + |
| 84 | + // Use existing ID if present |
| 85 | + if (settings.analyticsUserId) { |
| 86 | + return settings.analyticsUserId; |
| 87 | + } |
| 88 | + |
| 89 | + // Generate new anonymous ID |
| 90 | + const newId = randomUUID(); |
| 91 | + |
| 92 | + // Persist to settings |
| 93 | + setAppSettings({ analyticsUserId: newId }); |
| 94 | + |
| 95 | + return newId; |
| 96 | +} |
| 97 | + |
| 98 | +/** |
| 99 | + * Track daily active user event (once per day). |
| 100 | + * Persists the last-sent date to settings to deduplicate across app restarts. |
| 101 | + */ |
| 102 | +async function trackDailyActive(): Promise<void> { |
| 103 | + const today = new Date().toISOString().split("T")[0]; // YYYY-MM-DD |
| 104 | + const settings = getAppSettings(); |
| 105 | + |
| 106 | + // Skip if already tracked today (check both in-memory and persisted) |
| 107 | + if (lastDailyActiveCheck === today || settings.analyticsLastDailyActiveDate === today) { |
| 108 | + lastDailyActiveCheck = today; |
| 109 | + return; |
| 110 | + } |
| 111 | + |
| 112 | + lastDailyActiveCheck = today; |
| 113 | + setAppSettings({ analyticsLastDailyActiveDate: today }); |
| 114 | + |
| 115 | + await captureEvent("daily_active_user", { |
| 116 | + date: today, |
| 117 | + }); |
| 118 | +} |
| 119 | + |
| 120 | +/** |
| 121 | + * Capture a custom event with properties. |
| 122 | + */ |
| 123 | +export async function captureEvent( |
| 124 | + event: string, |
| 125 | + properties?: Record<string, unknown> |
| 126 | +): Promise<void> { |
| 127 | + if (!client || !userId) return; |
| 128 | + |
| 129 | + try { |
| 130 | + client.capture({ |
| 131 | + distinctId: userId, |
| 132 | + event, |
| 133 | + properties: { |
| 134 | + ...properties, |
| 135 | + // Always include version in all events |
| 136 | + app_version: app.getVersion(), |
| 137 | + }, |
| 138 | + }); |
| 139 | + } catch (err) { |
| 140 | + // Non-fatal - analytics should never break the app |
| 141 | + log("POSTHOG", `Failed to capture event: ${err instanceof Error ? err.message : String(err)}`); |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +/** |
| 146 | + * Update user properties (for identifying user characteristics). |
| 147 | + */ |
| 148 | +export async function identifyUser( |
| 149 | + properties: Record<string, unknown> |
| 150 | +): Promise<void> { |
| 151 | + if (!client || !userId) return; |
| 152 | + |
| 153 | + try { |
| 154 | + client.identify({ |
| 155 | + distinctId: userId, |
| 156 | + properties, |
| 157 | + }); |
| 158 | + } catch (err) { |
| 159 | + log("POSTHOG", `Failed to identify user: ${err instanceof Error ? err.message : String(err)}`); |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | +/** |
| 164 | + * Shutdown PostHog client (flush pending events, close connections). |
| 165 | + * Call this on app quit. |
| 166 | + */ |
| 167 | +export async function shutdownPostHog(): Promise<void> { |
| 168 | + if (!client) return; |
| 169 | + |
| 170 | + try { |
| 171 | + await client.shutdown(); |
| 172 | + client = null; |
| 173 | + } catch (err) { |
| 174 | + log("POSTHOG", `Failed to shutdown: ${err instanceof Error ? err.message : String(err)}`); |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +/** |
| 179 | + * Re-initialize PostHog when settings change. |
| 180 | + * Call this when user toggles analytics on/off. |
| 181 | + */ |
| 182 | +export async function reinitPostHog(): Promise<void> { |
| 183 | + // Shutdown existing client if any |
| 184 | + if (client) { |
| 185 | + await shutdownPostHog(); |
| 186 | + } |
| 187 | + |
| 188 | + // Re-initialize if enabled |
| 189 | + await initPostHog(); |
| 190 | +} |
| 191 | + |
| 192 | +/** |
| 193 | + * Check if analytics is currently enabled and initialized. |
| 194 | + */ |
| 195 | +export function isPostHogEnabled(): boolean { |
| 196 | + return client !== null; |
| 197 | +} |
0 commit comments