76 lines
2.6 KiB
TypeScript
76 lines
2.6 KiB
TypeScript
export const dynamic = 'force-dynamic'
|
|
import { NextResponse } from 'next/server'
|
|
import { google } from 'googleapis'
|
|
|
|
export async function GET(req: Request) {
|
|
const { searchParams } = new URL(req.url)
|
|
const range = searchParams.get('range') || 'today'
|
|
|
|
const clientId = process.env.GOOGLE_CLIENT_ID
|
|
const clientSecret = process.env.GOOGLE_CLIENT_SECRET
|
|
const refreshToken = process.env.GOOGLE_REFRESH_TOKEN
|
|
const svetaCalendarId = process.env.SVETA_CALENDAR_ID
|
|
|
|
if (!clientId || !clientSecret || !refreshToken) {
|
|
return NextResponse.json({ events: [], error: 'not_configured' })
|
|
}
|
|
|
|
const auth = new google.auth.OAuth2(clientId, clientSecret)
|
|
auth.setCredentials({ refresh_token: refreshToken })
|
|
|
|
const now = new Date()
|
|
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
|
|
let timeMin = todayStart.toISOString()
|
|
let timeMax: string
|
|
|
|
if (range === 'today') {
|
|
timeMax = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).toISOString()
|
|
} else if (range === 'week') {
|
|
timeMax = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 7).toISOString()
|
|
} else {
|
|
timeMax = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59).toISOString()
|
|
timeMin = new Date(now.getFullYear(), now.getMonth(), 1).toISOString()
|
|
}
|
|
|
|
const calendarClient = google.calendar({ version: 'v3', auth })
|
|
|
|
const calendars = [
|
|
{ id: 'daniilklimov25@gmail.com', owner: 'daniil', color: '#6366f1', name: 'Даниил' },
|
|
...(svetaCalendarId ? [{ id: svetaCalendarId, owner: 'sveta', color: '#ec4899', name: 'Света' }] : [])
|
|
]
|
|
|
|
const results = await Promise.allSettled(
|
|
calendars.map(cal =>
|
|
calendarClient.events.list({
|
|
calendarId: cal.id,
|
|
timeMin,
|
|
timeMax,
|
|
singleEvents: true,
|
|
orderBy: 'startTime',
|
|
maxResults: 100,
|
|
}).then(r => ({ ...cal, events: r.data.items || [] }))
|
|
)
|
|
)
|
|
|
|
const allEvents = results
|
|
.filter(r => r.status === 'fulfilled')
|
|
.flatMap(r => {
|
|
const val = (r as PromiseFulfilledResult<any>).value
|
|
return val.events.map((e: any) => ({
|
|
id: e.id,
|
|
title: e.summary || '(без названия)',
|
|
start: e.start?.dateTime || e.start?.date,
|
|
end: e.end?.dateTime || e.end?.date,
|
|
allDay: !e.start?.dateTime,
|
|
description: e.description || null,
|
|
location: e.location || null,
|
|
owner: val.owner,
|
|
ownerName: val.name,
|
|
color: val.color,
|
|
}))
|
|
})
|
|
.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
|
|
|
|
return NextResponse.json({ events: allEvents, fetchedAt: new Date().toISOString() })
|
|
}
|