|
| 1 | +import { createAuth } from "../../lib/auth"; |
| 2 | +import type { CalendarEvent, TodayEventsResult } from "./google-calendar.types"; |
| 3 | + |
| 4 | +// --------------------------------------------------------------------------- |
| 5 | +// Token helpers |
| 6 | +// --------------------------------------------------------------------------- |
| 7 | + |
| 8 | +const GOOGLE_PROVIDER_ID = "google"; |
| 9 | + |
| 10 | +/** |
| 11 | + * Retrieve a valid Google access token for the given user. |
| 12 | + * |
| 13 | + * Better Auth handles token decryption / refresh internally. We should always |
| 14 | + * use the public `getAccessToken` API instead of reading `account` rows |
| 15 | + * directly. |
| 16 | + */ |
| 17 | +async function getGoogleAccessToken( |
| 18 | + env: Env, |
| 19 | + userId: string, |
| 20 | +): Promise<string | null> { |
| 21 | + const auth = createAuth(env); |
| 22 | + try { |
| 23 | + const tokenPayload = await auth.api.getAccessToken({ |
| 24 | + body: { |
| 25 | + providerId: GOOGLE_PROVIDER_ID, |
| 26 | + userId, |
| 27 | + }, |
| 28 | + }); |
| 29 | + |
| 30 | + if ( |
| 31 | + !tokenPayload || |
| 32 | + typeof tokenPayload.accessToken !== "string" || |
| 33 | + tokenPayload.accessToken.trim().length === 0 |
| 34 | + ) { |
| 35 | + return null; |
| 36 | + } |
| 37 | + |
| 38 | + return tokenPayload.accessToken; |
| 39 | + } catch (error) { |
| 40 | + console.error("Failed to get Google access token:", error); |
| 41 | + return null; |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// --------------------------------------------------------------------------- |
| 46 | +// Calendar API |
| 47 | +// --------------------------------------------------------------------------- |
| 48 | + |
| 49 | +/** |
| 50 | + * Fetch today's events from the authenticated user's primary Google Calendar. |
| 51 | + * |
| 52 | + * Time zone is fixed to `Asia/Tokyo` (JST). |
| 53 | + */ |
| 54 | +export async function getTodayEvents( |
| 55 | + env: Env, |
| 56 | + userId: string, |
| 57 | +): Promise<TodayEventsResult> { |
| 58 | + // Compute "today" in JST |
| 59 | + const jstNow = new Date(Date.now() + 9 * 60 * 60 * 1000); |
| 60 | + const date = jstNow.toISOString().split("T")[0] as string; |
| 61 | + |
| 62 | + const accessToken = await getGoogleAccessToken(env, userId); |
| 63 | + if (!accessToken) { |
| 64 | + return { date, events: [], earliestEvent: null }; |
| 65 | + } |
| 66 | + |
| 67 | + const timeMin = new Date(`${date}T00:00:00+09:00`).toISOString(); |
| 68 | + const timeMax = new Date(`${date}T23:59:59+09:00`).toISOString(); |
| 69 | + |
| 70 | + const params = new URLSearchParams({ |
| 71 | + timeMin, |
| 72 | + timeMax, |
| 73 | + singleEvents: "true", |
| 74 | + orderBy: "startTime", |
| 75 | + timeZone: "Asia/Tokyo", |
| 76 | + }); |
| 77 | + |
| 78 | + const res = await fetch( |
| 79 | + `https://www.googleapis.com/calendar/v3/calendars/primary/events?${params}`, |
| 80 | + { headers: { Authorization: `Bearer ${accessToken}` } }, |
| 81 | + ); |
| 82 | + |
| 83 | + if (!res.ok) { |
| 84 | + console.error("Google Calendar API error:", res.status, await res.text()); |
| 85 | + return { date, events: [], earliestEvent: null }; |
| 86 | + } |
| 87 | + |
| 88 | + // biome-ignore lint/suspicious/noExplicitAny: Google Calendar API response |
| 89 | + const data = (await res.json()) as any; |
| 90 | + |
| 91 | + const events: CalendarEvent[] = (data.items ?? []) |
| 92 | + // biome-ignore lint/suspicious/noExplicitAny: Google Calendar event |
| 93 | + .filter((item: any) => item.status !== "cancelled") |
| 94 | + // biome-ignore lint/suspicious/noExplicitAny: Google Calendar event |
| 95 | + .map((item: any) => ({ |
| 96 | + id: item.id as string, |
| 97 | + summary: (item.summary as string) ?? "(無題)", |
| 98 | + location: (item.location as string) ?? null, |
| 99 | + start: item.start?.dateTime ?? item.start?.date ?? "", |
| 100 | + end: item.end?.dateTime ?? item.end?.date ?? "", |
| 101 | + isAllDay: !item.start?.dateTime, |
| 102 | + })); |
| 103 | + |
| 104 | + const timedEvents = events.filter((e) => !e.isAllDay); |
| 105 | + const earliestEvent = |
| 106 | + timedEvents.length > 0 ? (timedEvents[0] ?? null) : null; |
| 107 | + |
| 108 | + return { date, events, earliestEvent }; |
| 109 | +} |
0 commit comments