54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
|
|
import { google } from 'googleapis'
|
||
|
|
import { DateTime } from 'luxon'
|
||
|
|
import { service } from '../service'
|
||
|
|
import { googleAuthService } from './googleAuth'
|
||
|
|
|
||
|
|
export type CalendarService = Awaited<
|
||
|
|
ReturnType<ReturnType<typeof calendarService>>
|
||
|
|
>
|
||
|
|
|
||
|
|
export const calendarService = service((ctx) => async () => {
|
||
|
|
const googleAuth = await googleAuthService(ctx)()
|
||
|
|
const auth = await googleAuth.getAuth()
|
||
|
|
const calendar = google.calendar({ version: 'v3', auth })
|
||
|
|
|
||
|
|
return {
|
||
|
|
calendars: async () => {
|
||
|
|
const calendars = await calendar.calendarList.list()
|
||
|
|
|
||
|
|
return calendars.data.items
|
||
|
|
},
|
||
|
|
|
||
|
|
events: async (calendars: string[]) => {
|
||
|
|
const results = []
|
||
|
|
const timeMin = DateTime.now().setZone(ctx.config.timeZone).startOf('day')
|
||
|
|
const timeMax = DateTime.now().setZone(ctx.config.timeZone).endOf('day')
|
||
|
|
|
||
|
|
if (!timeMin.isValid) {
|
||
|
|
throw new Error('Invalid time')
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!timeMax.isValid) {
|
||
|
|
throw new Error('Invalid time')
|
||
|
|
}
|
||
|
|
|
||
|
|
for (const calendarId of calendars) {
|
||
|
|
const res = await calendar.events.list({
|
||
|
|
calendarId,
|
||
|
|
timeMin: timeMin.toISO(),
|
||
|
|
timeMax: timeMax.toISO(),
|
||
|
|
maxResults: 10,
|
||
|
|
singleEvents: true,
|
||
|
|
orderBy: 'startTime',
|
||
|
|
})
|
||
|
|
|
||
|
|
if (res.data.items) {
|
||
|
|
results.push(...res.data.items)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return results
|
||
|
|
},
|
||
|
|
}
|
||
|
|
})
|