2023-03-22 11:15:35 +00:00
|
|
|
import { JWT } from 'google-auth-library';
|
|
|
|
import { google } from 'googleapis';
|
|
|
|
import { GoogleCalendarEvent } from './types/index';
|
|
|
|
|
2023-03-21 17:17:36 +00:00
|
|
|
require('dotenv').config();
|
|
|
|
const env = process.env;
|
2023-03-22 11:15:35 +00:00
|
|
|
|
2023-03-21 17:17:36 +00:00
|
|
|
|
|
|
|
export default class GoogleCalendar {
|
2023-03-22 11:15:35 +00:00
|
|
|
client_secret: string;
|
|
|
|
client_id: string;
|
|
|
|
calender_id: string;
|
2023-03-21 17:17:36 +00:00
|
|
|
calendar: any;
|
2023-03-22 11:15:35 +00:00
|
|
|
clientEmail: string;
|
|
|
|
googlePrivateKey: string;
|
|
|
|
token: any;
|
2023-03-21 17:17:36 +00:00
|
|
|
|
2023-03-22 11:15:35 +00:00
|
|
|
constructor() {
|
|
|
|
this.client_secret = env.GOOGLE_CLIENT_SECRET;
|
|
|
|
this.client_id = env.GOOGLE_CLIENT_ID;
|
|
|
|
this.calender_id = env.GOOGLE_CALENDAR_ID;
|
|
|
|
this.clientEmail = env.GOOGLE_CLIENT_EMAIL
|
|
|
|
this.googlePrivateKey = env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n');
|
|
|
|
// this.redirect_uris = env.GOOGLE_REDIRECT_URIS;
|
|
|
|
}
|
2023-03-21 17:17:36 +00:00
|
|
|
|
2023-03-22 11:15:35 +00:00
|
|
|
async init() {
|
|
|
|
const jwtClient = await this.authorize();
|
|
|
|
this.calendar = google.calendar({ version: 'v3', auth: jwtClient });
|
|
|
|
}
|
2023-03-21 17:17:36 +00:00
|
|
|
|
2023-03-22 11:15:35 +00:00
|
|
|
async authorize() {
|
|
|
|
const client = new JWT({
|
|
|
|
email: this.clientEmail,
|
|
|
|
key: this.googlePrivateKey,
|
|
|
|
scopes: 'https://www.googleapis.com/auth/calendar.events'
|
|
|
|
});
|
|
|
|
const { access_token } = await client.authorize();
|
|
|
|
this.token = access_token;
|
|
|
|
if(!this.token) {
|
|
|
|
throw new Error('Failed to connect to google calendar');
|
2023-03-21 17:17:36 +00:00
|
|
|
}
|
2023-03-22 11:15:35 +00:00
|
|
|
return client;
|
2023-03-21 17:17:36 +00:00
|
|
|
}
|
|
|
|
|
2023-03-22 11:15:35 +00:00
|
|
|
updateNewEvent(upcomingEvents: GoogleCalendarEvent[]) {
|
|
|
|
this.calendar.event.insert({
|
|
|
|
auth: this.token,
|
|
|
|
calendarId: this.calender_id,
|
|
|
|
resource: upcomingEvents[0],
|
|
|
|
}, function (err: any, event: any) {
|
2023-03-21 17:17:36 +00:00
|
|
|
if (err) {
|
2023-03-22 11:15:35 +00:00
|
|
|
console.log('There was an error contacting the Calendar service: ' + err);
|
|
|
|
return;
|
2023-03-21 17:17:36 +00:00
|
|
|
}
|
2023-03-22 11:15:35 +00:00
|
|
|
console.log('Event created: %s', event.htmlLink);
|
|
|
|
});
|
2023-03-21 17:17:36 +00:00
|
|
|
}
|
2023-03-22 11:15:35 +00:00
|
|
|
}
|