-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathindex.js
executable file
·294 lines (282 loc) · 7.89 KB
/
index.js
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const google = require('googleapis');
const argv = require('minimist')(process.argv.slice(2));
const Sherlock = require('sherlockjs');
const chalk = require('chalk');
const moment = require('moment');
const conf = require('./conf');
const help = require('./help');
/**
* Get absolute path
* @param {string} rawPath
*/
const getPath = (rawPath) => {
if (path.isAbsolute(rawPath)) {
return rawPath;
} else {
return path.join(process.cwd(), rawPath);
}
};
/**
* Error handler
* @param {Object} err
*/
const errHandler = (err) => {
if (argv.debug) {
console.error(`[ERROR] ${err.code} ${err.stack}`);
} else {
console.error(`[ERROR] ${err.message}`);
}
};
/**
* Get Oauth2 Client
*/
const getOauth2Client = () => {
const content = fs.readFileSync(conf.CRED_PATH);
const {
client_id: clientId,
client_secret: clientSecret,
redirect_uris: redirectUris
} = JSON.parse(content).installed;
return new google.auth.OAuth2(clientId, clientSecret, redirectUris[0]);
};
/**
* Get Calendar Client
* @returns {Promise}
*/
const getClient = async () => {
const oauth2Client = getOauth2Client();
const tokens = fs.readFileSync(conf.TOKEN_PATH);
oauth2Client.setCredentials(JSON.parse(tokens));
return google.calendar({ version: 'v3', auth: oauth2Client });
};
/**
* Generate consent page URL
* @returns {Promise}
*/
const generateUrl = async () => {
const oauth2Client = getOauth2Client();
const authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: conf.SCOPES
});
console.log(authUrl);
};
/**
* Store token
* @param {string} code
* @returns {Promise}
*/
const storeToken = async (code) => {
const oauth2Client = getOauth2Client();
const tokens = await promisify(oauth2Client.getToken).bind(oauth2Client)(code);
// oauth2Client.setCredentials(tokens);
fs.writeFileSync(conf.TOKEN_PATH, JSON.stringify(tokens));
console.log(`Token stored in ${conf.TOKEN_PATH}`);
};
/**
* List events
* @param {string} [naturalInfo]
* @param {Object} [options]
* @param {string} options.from
* @param {string} options.to
* @param {boolean} options.showId
* @returns {Promise}
*/
const list = async (naturalInfo, options) => {
const { from, to, showId } = options;
const params = {
calendarId: conf.CALENDAR_ID,
singleEvents: true,
orderBy: conf.LIST_ORDER
};
if (naturalInfo) {
const { startDate, endDate, isAllDay } = Sherlock.parse(naturalInfo);
params.timeMin = moment(startDate).format() || moment().format();
if (endDate && !isAllDay) {
params.timeMax = moment(endDate).format();
} else if (endDate && isAllDay) {
params.timeMax = moment(endDate).endOf('day').format();
} else if (!endDate && isAllDay) {
params.timeMax = moment(startDate).endOf('day').format();
}
} else if (from || to) {
if (from) {
params.timeMin = moment(from).format();
}
if (to) {
params.timeMax = moment(to).format();
}
} else {
params.timeMin = moment().startOf('day').format();
params.timeMax = moment().endOf('day').format();
}
const calendar = await getClient();
const { items: events } = await promisify(calendar.events.list)(params);
if (events.length === 0) {
console.log(`No upcoming events found (${params.timeMin} ~ ${params.timeMax || ''})`);
return;
}
console.log(`Upcoming events (${params.timeMin} ~ ${params.timeMax || ''})`);
events.forEach(event => {
let start;
if (event.start.dateTime) {
start = moment(event.start.dateTime).format(conf.LIST_FORMAT_DATETIME);
} else {
start = moment(event.start.date).format(conf.LIST_FORMAT_DATE);
}
if (showId) {
console.log(` ${start} - ${chalk.bold(event.summary)} (${event.id})`);
} else {
console.log(` ${start} - ${chalk.bold(event.summary)}`);
}
});
};
/**
* Insert event
* @param {string} [naturalInfo]
* @param {Object} [options]
* @param {string} options.summary
* @param {string} options.date
* @param {string} options.time
* @param {string} options.duration
* @returns {Promise}
*/
const insert = async (naturalInfo, options) => {
const event = {};
if (naturalInfo) {
const { eventTitle, startDate, endDate, isAllDay } = Sherlock.parse(naturalInfo);
event.summary = eventTitle;
if (isAllDay) {
event.start = {
date: moment(startDate).format('YYYY-MM-DD')
};
event.end = {
date: endDate ? moment(endDate).add(1, 'd').format('YYYY-MM-DD') : moment(startDate).format('YYYY-MM-DD')
};
} else {
event.start = {
dateTime: moment(startDate).format()
};
event.end = {
dateTime: endDate ? moment(endDate).format() : moment(startDate).add(conf.EVENT_DURATION, 'm').format()
};
}
} else {
const { summary, date, time, duration } = options;
event.summary = summary;
const isAllDay = !time;
if (isAllDay) {
event.start = {
date: moment(date).format('YYYY-MM-DD')
};
event.end = {
date: duration ?
moment(date).add(duration.slice(0, -1), duration.slice(-1)).format('YYYY-MM-DD') :
moment(date).add(1, 'd').format('YYYY-MM-DD')
};
} else {
const dateTime = `${date} ${time}`;
event.start = {
dateTime: moment(dateTime).format()
};
event.end = {
dateTime: duration ?
moment(dateTime).add(duration.slice(0, -1), duration.slice(-1)).format() :
moment(dateTime).add(conf.EVENT_DURATION, 'm').format()
};
}
}
const params = {
calendarId: conf.CALENDAR_ID,
resource: event
};
const calendar = await getClient();
const { summary: insertedSummary, start, end, htmlLink } = await promisify(calendar.events.insert)(params);
console.log(`${insertedSummary || 'no-summary'}: ${start.date || start.dateTime} ~ ${end.date || end.dateTime}`);
console.log(htmlLink);
};
/**
* Insert events in bulk
* @param {string} eventsPath
* @returns {Promise}
*/
const bulk = async (eventsPath) => {
const events = require(eventsPath);
const calendar = await getClient();
const insert = promisify(calendar.events.insert);
const promises = events.map(async event => {
try {
const result = await insert(event);
console.log('Event inserted');
conf.BULK_RESULT.forEach(property => {
if (result[property]) {
console.log(` ${property}: ${result[property]}`);
}
});
} catch (err) {
console.error(`[ERROR] Error inserting event: ${event.summary || ''}`);
errHandler(err);
}
});
await Promise.all(promises);
};
// main
(async function () {
const command = argv._[0];
const configPath = argv.config || argv.C;
if (configPath) {
const configFile = require(getPath(configPath));
Object.assign(conf, configFile);
}
switch (command) {
case 'generateUrl': {
await generateUrl();
break;
}
case 'storeToken': {
const code = argv._[1];
await storeToken(code);
break;
}
case 'list': {
const naturalInfo = argv._[1];
const params = {
from: argv.from || argv.f,
to: argv.to || argv.t,
showId: argv['show-id'] || argv.i
};
await list(naturalInfo, params);
break;
}
case 'insert': {
const naturalInfo = argv._[1];
const params = {
summary: argv.summary || argv.s,
date: argv.date || argv.d,
time: argv.time || argv.t,
duration: argv.duration || argv.D
};
await insert(naturalInfo, params);
break;
}
case 'bulk': {
const eventsPath = getPath(argv.events || argv.e);
await bulk(eventsPath);
break;
}
case 'help': {
console.log(help);
break;
}
default: {
console.log('Command not found\n');
console.log(help);
break;
}
}
})().catch(errHandler);