|
| 1 | +import type { EventDetails } from "../types"; |
| 2 | +import { getSettings } from "./storage"; |
| 3 | +import { sanitize, truncateForAPI } from "./utils"; |
| 4 | + |
| 5 | +const API_BASE = "https://generativelanguage.googleapis.com/v1beta/models"; |
| 6 | + |
| 7 | +function buildPrompt(extra: string): string { |
| 8 | + const today = new Date().toISOString().split("T")[0]; |
| 9 | + return `You are a calendar event parser. Today's date is ${today}. |
| 10 | +${extra} |
| 11 | +Return a JSON object with exactly these fields: |
| 12 | +- "title": string (event name/title) |
| 13 | +- "date": string (YYYY-MM-DD format) |
| 14 | +- "startTime": string (HH:MM in 24-hour format, or null if all-day) |
| 15 | +- "endTime": string (HH:MM in 24-hour format, or null if unknown) |
| 16 | +- "location": string (or null if not found) |
| 17 | +- "description": string (brief summary, or null) |
| 18 | +- "isAllDay": boolean |
| 19 | +
|
| 20 | +If multiple events are found, return only the most prominent one. |
| 21 | +If a field cannot be determined, use null. |
| 22 | +Return ONLY valid JSON, no markdown fences, no explanation.`; |
| 23 | +} |
| 24 | + |
| 25 | +async function callGemini( |
| 26 | + contents: unknown[], |
| 27 | + retries = 2, |
| 28 | +): Promise<EventDetails> { |
| 29 | + const { geminiApiKey, geminiModel } = await getSettings(); |
| 30 | + if (!geminiApiKey) { |
| 31 | + throw new Error( |
| 32 | + "Gemini API key not configured. Open extension options to set it.", |
| 33 | + ); |
| 34 | + } |
| 35 | + |
| 36 | + const model = geminiModel || "gemini-2.5-flash"; |
| 37 | + const url = `${API_BASE}/${model}:generateContent?key=${geminiApiKey}`; |
| 38 | + |
| 39 | + const body = JSON.stringify({ |
| 40 | + contents: [{ parts: contents }], |
| 41 | + generationConfig: { |
| 42 | + temperature: 0.1, |
| 43 | + responseMimeType: "application/json", |
| 44 | + }, |
| 45 | + }); |
| 46 | + |
| 47 | + let lastError: Error = new Error("Gemini request failed."); |
| 48 | + |
| 49 | + for (let attempt = 0; attempt <= retries; attempt++) { |
| 50 | + try { |
| 51 | + const response = await fetch(url, { |
| 52 | + method: "POST", |
| 53 | + headers: { "Content-Type": "application/json" }, |
| 54 | + body, |
| 55 | + }); |
| 56 | + |
| 57 | + if (response.status === 429) { |
| 58 | + lastError = mapApiError(429, ""); |
| 59 | + const waitMs = Math.pow(2, attempt) * 1000; |
| 60 | + await new Promise((r) => setTimeout(r, waitMs)); |
| 61 | + continue; |
| 62 | + } |
| 63 | + |
| 64 | + if (!response.ok) { |
| 65 | + const errorBody = await response.json().catch(() => ({})); |
| 66 | + const msg = |
| 67 | + (errorBody as { error?: { message?: string } }).error?.message ?? ""; |
| 68 | + throw mapApiError(response.status, msg); |
| 69 | + } |
| 70 | + |
| 71 | + const data = await response.json(); |
| 72 | + const rawText = ( |
| 73 | + data as { |
| 74 | + candidates?: { content?: { parts?: { text?: string }[] } }[]; |
| 75 | + } |
| 76 | + ).candidates?.[0]?.content?.parts?.[0]?.text; |
| 77 | + if (!rawText) throw new Error("Gemini returned no content."); |
| 78 | + |
| 79 | + return parseAndValidate(rawText); |
| 80 | + } catch (err) { |
| 81 | + lastError = err instanceof Error ? err : new Error(String(err)); |
| 82 | + if (attempt < retries && isRetryable(lastError)) { |
| 83 | + const waitMs = Math.pow(2, attempt) * 1000; |
| 84 | + await new Promise((r) => setTimeout(r, waitMs)); |
| 85 | + continue; |
| 86 | + } |
| 87 | + throw lastError; |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + throw lastError; |
| 92 | +} |
| 93 | + |
| 94 | +function parseAndValidate(raw: string): EventDetails { |
| 95 | + const parsed = JSON.parse(raw); |
| 96 | + if (!parsed || typeof parsed !== "object") { |
| 97 | + throw new Error("Gemini returned invalid JSON."); |
| 98 | + } |
| 99 | + |
| 100 | + const title = typeof parsed.title === "string" ? sanitize(parsed.title) : ""; |
| 101 | + const date = |
| 102 | + typeof parsed.date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(parsed.date) |
| 103 | + ? parsed.date |
| 104 | + : new Date().toISOString().split("T")[0]; |
| 105 | + const startTime = |
| 106 | + typeof parsed.startTime === "string" && |
| 107 | + /^\d{2}:\d{2}$/.test(parsed.startTime) |
| 108 | + ? parsed.startTime |
| 109 | + : null; |
| 110 | + const endTime = |
| 111 | + typeof parsed.endTime === "string" && /^\d{2}:\d{2}$/.test(parsed.endTime) |
| 112 | + ? parsed.endTime |
| 113 | + : null; |
| 114 | + |
| 115 | + return { |
| 116 | + title: title || "Untitled Event", |
| 117 | + date, |
| 118 | + startTime, |
| 119 | + endTime, |
| 120 | + location: |
| 121 | + typeof parsed.location === "string" ? sanitize(parsed.location) : null, |
| 122 | + description: |
| 123 | + typeof parsed.description === "string" |
| 124 | + ? sanitize(parsed.description) |
| 125 | + : null, |
| 126 | + isAllDay: typeof parsed.isAllDay === "boolean" ? parsed.isAllDay : !startTime, |
| 127 | + }; |
| 128 | +} |
| 129 | + |
| 130 | +function mapApiError(status: number, msg: string): Error { |
| 131 | + switch (status) { |
| 132 | + case 400: |
| 133 | + return new Error( |
| 134 | + "Bad request to Gemini API. The content may be too long or unsupported.", |
| 135 | + ); |
| 136 | + case 401: |
| 137 | + return new Error( |
| 138 | + "Invalid Gemini API key. Check your key in extension options.", |
| 139 | + ); |
| 140 | + case 403: |
| 141 | + return new Error( |
| 142 | + "Gemini API access denied. Verify the API is enabled and billing is active.", |
| 143 | + ); |
| 144 | + case 429: |
| 145 | + return new Error( |
| 146 | + "Gemini API rate limit exceeded. Please wait and try again.", |
| 147 | + ); |
| 148 | + case 500: |
| 149 | + case 503: |
| 150 | + return new Error("Gemini API is temporarily unavailable. Try again later."); |
| 151 | + default: |
| 152 | + return new Error(`Gemini API error (${status}): ${msg}`); |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +function isRetryable(err: Error): boolean { |
| 157 | + return ( |
| 158 | + err.message.includes("rate limit") || |
| 159 | + err.message.includes("temporarily unavailable") || |
| 160 | + err.message.includes("Failed to fetch") |
| 161 | + ); |
| 162 | +} |
| 163 | + |
| 164 | +export async function parseEventFromText( |
| 165 | + text: string, |
| 166 | +): Promise<EventDetails> { |
| 167 | + const truncated = truncateForAPI(text); |
| 168 | + const prompt = buildPrompt( |
| 169 | + `Extract event details from the following text.\n\nText:\n${truncated}`, |
| 170 | + ); |
| 171 | + return callGemini([{ text: prompt }]); |
| 172 | +} |
| 173 | + |
| 174 | +export async function parseEventFromImage( |
| 175 | + dataUrl: string, |
| 176 | +): Promise<EventDetails> { |
| 177 | + const prompt = buildPrompt( |
| 178 | + "Look at this image and extract event details from it.", |
| 179 | + ); |
| 180 | + const pureBase64 = dataUrl.replace(/^data:image\/\w+;base64,/, ""); |
| 181 | + return callGemini([ |
| 182 | + { inlineData: { mimeType: "image/png", data: pureBase64 } }, |
| 183 | + { text: prompt }, |
| 184 | + ]); |
| 185 | +} |
0 commit comments