index.js
3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
'use strict';
const google = require('googleapis');
const googleAuth = require('google-auth-library');
const calendar = google.calendar('v3');
const fs = require('fs');
const path = require('path');
const yamlConfig = require('node-yaml-config');
const config = yamlConfig.load(path.join(__dirname, '/../../config/config.yml'));
const CALENDAR_ID = config.calendarID
const SCOPES = ['https://www.googleapis.com/auth/calendar'];
const TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/';
const TOKEN_PATH = TOKEN_DIR + 'calendar-nodejs-quickstart.json';
module.exports = {
authorize: (callback) => {
fs.readFile('client_secret.json', (err, content) => {
if (err) return callback(err);
let credentials = JSON.parse(content);
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return callback(err);
oauth2Client.credentials = JSON.parse(token);
return callback(null, oauth2Client);
});
});
},
listEvents: (auth, callback) => {
calendar.events.list({
auth: auth,
calendarId: CALENDAR_ID || 'primary',
timeMin: (new Date()).toISOString(),
maxResults: 50,
singleEvents: true,
orderBy: 'startTime'
}, (err, response) => {
if (err) return callback(err);
return callback(null, response);
});
},
createEvent: (options, callback) => {
calendar.events.insert({
auth: options.auth,
calendarId: CALENDAR_ID || 'primary',
resource: options
}, (err, response) => {
if (err) return callback(err);
return callback(null, response);
});
},
deleteEvent: (options, callback) => {
calendar.events.delete({
auth: options.auth,
calendarId: CALENDAR_ID || 'primary',
eventId: options.eventId
}, (err, response) => {
if (err) return callback(err);
return callback(null, response);
});
},
eventBuilder: (payload) => {
return {
summary: payload.summary,
description: payload.description,
start: {
dateTime: payload.startDate,
timeZone: 'Asia/Bangkok'
},
end: {
dateTime: payload.endDate,
timeZone: 'Asia/Bangkok'
},
attendees: [
{ email: payload.email }
],
reminders: {
useDefault: false,
overrides: [
{
method: 'email',
minutes: 24 * 60
}
]
}
}
}
}