haifa-reminder/src/GoogleCalendar.ts
2023-08-06 00:35:07 +03:00

98 lines
3 KiB
TypeScript

import { JWT } from "google-auth-library";
import { google } from "googleapis";
import { GoogleCalendarEvent } from "./types/index";
require("dotenv").config();
const env = process.env;
export default class GoogleCalendar {
gamesMap: any = {};
clientSecret: string = env.GOOGLE_CLIENT_SECRET;
clientId: string = env.GOOGLE_CLIENT_ID;
calenderId: string = env.GOOGLE_CALENDAR_ID;
calendar: any;
clientEmail: string = env.GOOGLE_CLIENT_EMAIL;
googlePrivateKey: string = env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, "\n");
token: any;
JWT_client: JWT;
async init() {
console.log("INIT GOOGLE CALENDAR");
const jwtClient = await this.authorize();
this.calendar = google.calendar({ version: "v3", auth: jwtClient });
}
async authorize() {
console.log("AUTHORIZE GOOGLE CALENDAR");
this.JWT_client = new JWT({
email: this.clientEmail,
key: this.googlePrivateKey,
scopes: ["https://www.googleapis.com/auth/calendar"],
});
const { access_token } = await this.JWT_client.authorize();
this.token = access_token;
if (!this.token) {
throw new Error("Failed to connect to google calendar");
}
console.log("GOOGLE CALENDAR AUTHORIZED SUCCESSFULLY");
return this.JWT_client;
}
async updateNewEvent(upcomingEvents: GoogleCalendarEvent[]) {
// console.log(upcomingEvents)
setTimeout(async () => {
upcomingEvents.forEach(async (event: GoogleCalendarEvent) => {
console.log("UPDATE NEW EVENT", upcomingEvents);
const options = {
auth: this.JWT_client,
calendarId: this.calenderId,
resource: {
summary: event.summary,
location: event.location,
description: event.description,
start: {
dateTime: event.start.dateTime,
timeZone: "Asia/Jerusalem",
},
end: { dateTime: event.end.dateTime, timeZone: "Asia/Jerusalem" },
sendNotifications: true,
},
};
await this.calendar.events.insert(
options,
function (err: any, event: any) {
if (err) {
console.log(
"There was an error contacting the Calendar service: " + err
);
return;
}
console.log(event.description + " created");
}
);
});
}, 3000);
}
async isDuplicateEvent(startTime: string, endTime: string, title: string) {
if (this.gamesMap[startTime]) {
console.log("duplicate event");
return true;
}
this.gamesMap[startTime] = true;
console.log("checking for duplicate event");
try {
const response = await this.calendar.events.list({
calendarId: this.calenderId,
timeMin: startTime,
timeMax: endTime,
q: title, // Search for events with the same title
});
return response.data.items.length > 0;
} catch (error) {
console.error(error.message);
return false;
}
}
}