index.js
3.08 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
'use strict';
const google = require('googleapis');
const googleAuth = require('google-auth-library');
const calendar = google.calendar('v3');
const fs = require('fs');
const SCOPES = [process.env.SCOPES];
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', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
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);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function (err, token) {
if (err) {
return callback(err);
} else {
oauth2Client.credentials = JSON.parse(token);
return callback(null, oauth2Client);
}
});
});
},
getNewToken: (oauth2Client, callback) => {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function (code) {
rl.close();
oauth2Client.getToken(code, function (err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
},
listEvents: (auth, callback) => {
calendar.events.list({
auth: auth,
calendarId: process.env.CALENDAR_ID,
timeMin: (new Date()).toISOString(),
maxResults: 50,
singleEvents: true,
orderBy: 'startTime'
}, (err, response) => {
if (err) {
return callback(err);
}
return callback(null, response);
});
},
createEvent: (auth, event, callback) => {
calendar.events.insert({
auth: auth,
calendarId: process.env.CALENDAR_ID,
resource: event,
}, (err, event) => {
if (err) {
return callback('There was an error contacting the Calendar service: ' + err);
}
return callback(null, event.htmlLink);
});
}
}