-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgoogleauthy.js
352 lines (309 loc) · 10.4 KB
/
googleauthy.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
const {google} = require('googleapis')
var opn = require('opn');
const notifier = require('node-notifier')
const moment = require('moment')
const remote = require('electron').remote
const fs = remote.require('fs')
const path = remote.require('path')
const storage = remote.require('electron-storage')
/* scope for calendar api and token storage*/
const SCOPES = ['https://www.googleapis.com/auth/calendar']
const TOKEN_PATH = 'token.json';
/* Event listeners for:
1- setting alarm
2- adding event
3- showing and updating event
*/
const elAlarm = document.querySelector('.alarm-time')
elAlarm.addEventListener('change', onAlarmTextChange,false)
const eventadder = document.querySelector('.submitdata')
eventadder.addEventListener('click', addEventsUser)
const displayevents = document.getElementById('displayeventschedule')
displayevents.addEventListener('click',checkEventsUser)
const weatherforecast = document.getElementById('displayweather')
weatherforecast.addEventListener('click',checkWeather)
/* alarm time variables */
let time = moment()
let alarmTime
/* Function calls for triggering everything
1- starts the calendar api
2- start the alarm
*/
checkEventsUser()
timer()
/* authorize app and call list events to show events and update changes on table*/
function checkEventsUser(event)
{
console.log("Check event working")
var d = new Date();
document.getElementById("day").innerHTML = d.getDate();
document.getElementById("month").innerHTML = d.getMonth();
document.getElementById("year").innerHTML = d.getFullYear();
fs.readFile(path.join(__dirname,'../../credentials.json'), (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Calendar API
authorize(JSON.parse(content), listEvents);
});
}
/* authorize app and call add events to add a new event triggered by click of a submit button */
function addEventsUser(event)
{
console.log("EVENT ADDING")
fs.readFile(path.join(__dirname,'../../credentials.json'), (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Calendar API
authorize(JSON.parse(content), addEvents);
});
}
/* authorizes the user */
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
storage.get(TOKEN_PATH, (err, data) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(data);
callback(oAuth2Client);
});
}
/* automatically opens default browser and wait token from user to use calendar api
otherwise app closes itself
*/
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
opn(authUrl);
const prompt = require('electron-prompt');
prompt({
title: 'TOKEN',
label: 'Please give the token that you take from browser:',
value: '',
inputAttrs: {
type: 'text'
},
type: 'input'
})
.then((r) => {
if(r === null) {
console.log('user cancelled');
var window = remote.getCurrentWindow();
window.close();
} else {
console.log('result', r);
oAuth2Client.getToken(r, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
storage.set(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) {
console.error(err)
}
else
{
console.log("Token setted");
}
});
callback(oAuth2Client);
});
}
})
.catch(console.error);
}
/* gets all events from calendar then calls getEvents function */
function listEvents(auth) {
var data = []
const calendar = google.calendar({version: 'v3', auth});
calendar.events.list({
calendarId: 'primary',
timeMin: (new Date()).toISOString(),
maxResults: 10,
singleEvents: true,
orderBy: 'startTime',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const events = res.data.items;
if (events.length)
{
events.map((event, i) => {
const start = event.start.dateTime || event.start.date;
data.push([`${start}`,`${event.summary}`]);
});
document.getElementById("event-status").innerHTML = "Add A New Event";
getEvents(data);
}
else
{
document.getElementById("event-status").innerHTML = "No upcoming events found.";
console.log('No upcoming events found.');
}
});
}
/* updates the table content with calendar events */
function getEvents(data)
{
const summary1 = document.querySelector('.event1');
const timing1 = document.querySelector('.time1');
const summary2 = document.querySelector('.event2');
const timing2 = document.querySelector('.time2');
const summary3 = document.querySelector('.event3');
const timing3 = document.querySelector('.time3');
const summary4 = document.querySelector('.event4');
const timing4 = document.querySelector('.time4');
const summary5 = document.querySelector('.event5');
const timing5 = document.querySelector('.time5');
const summary6 = document.querySelector('.event6');
const timing6 = document.querySelector('.time6');
const summary7 = document.querySelector('.event7');
const timing7 = document.querySelector('.time7');
const summary8 = document.querySelector('.event8');
const timing8 = document.querySelector('.time8');
const summary9 = document.querySelector('.event9');
const timing9 = document.querySelector('.time9');
const summary10 = document.querySelector('.event10');
const timing10 = document.querySelector('.time10');
if (data[0])
{
summary1.innerHTML = data[0][1];
timing1.innerHTML = new Date(Date.parse(data[0][0])).toLocaleString();
}
if (data[1])
{
summary2.innerHTML = data[1][1];
timing2.innerHTML = new Date(Date.parse(data[1][0])).toLocaleString();
}
if (data[2])
{
summary3.innerHTML = data[2][1];
timing3.innerHTML = new Date(Date.parse(data[2][0])).toLocaleString();
}
if (data[3])
{
summary4.innerHTML = data[3][1];
timing4.innerHTML = new Date(Date.parse(data[3][0])).toLocaleString();
}
if (data[4])
{
summary5.innerHTML = data[4][1];
timing5.innerHTML = new Date(Date.parse(data[4][0])).toLocaleString();
}
if (data[5])
{
summary6.innerHTML = data[5][1];
timing6.innerHTML = new Date(Date.parse(data[5][0])).toLocaleString();
}
if (data[6])
{
summary7.innerHTML = data[6][1];
timing7.innerHTML = new Date(Date.parse(data[6][0])).toLocaleString();
}
if (data[7])
{
summary8.innerHTML = data[7][1];
timing8.innerHTML = new Date(Date.parse(data[7][0])).toLocaleString();
}
if (data[8])
{
summary9.innerHTML = data[8][1];
timing9.innerHTML = new Date(Date.parse(data[8][0])).toLocaleString();
}
if (data[9])
{
summary10.innerHTML = data[9][1];
timing10.innerHTML = new Date(Date.parse(data[9][0])).toLocaleString();
}
}
/* creates a new event and adds to google calendar and to event bar */
function addEvents(auth)
{
const eventnamedata = document.getElementById('eventnamedata').value;
const starttimedata = document.getElementById('starttimedata').value;
const endtimedata = document.getElementById('endtimedata').value;
const startdatedata = document.getElementById('startdatedata').value;
const enddatedata = document.getElementById('enddatedata').value;
const startdatetime = startdatedata+"T"+starttimedata+":00";
const enddatetime = enddatedata+"T"+endtimedata+":00";
var newevent = {
'summary': eventnamedata,
'location': '',
'description': '',
'start': {
'dateTime': startdatetime,
'timeZone': 'Europe/Istanbul',
},
'end': {
'dateTime': enddatetime,
'timeZone': 'Europe/Istanbul',
},
'recurrence': [
'RRULE:FREQ=DAILY;COUNT=2'
],
'reminders': {
'useDefault': false,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
};
const calendar = google.calendar({version: 'v3', auth});
calendar.events.insert({
auth: auth,
calendarId: 'primary',
resource: newevent,
}, function(err, newevent) {
if (err) {
console.log('There was an error contacting the Calendar service: ' + err);
document.getElementById("event-status").innerHTML = "There was an error contacting the Calendar";
return;
}
document.getElementById("event-status").innerHTML = "Event created successfully";
console.log('Event created: %s', newevent.htmlLink);
});
}
/* always check for if an alarm set */
function timer() {
time = moment().format('HH:mm:ss')
nowTime = time
check()
setTimeout(() => {
timer()
}, 1000)
}
/* check the current time alarm time then call for notifier */
function check() {
const diff = moment(nowTime, 'HH:mm:ss').diff(moment(alarmTime, 'HH:mm:ss'))
if (diff === 0) {
notice(`It's ${alarmTime}. Time To Wake!`)
}
}
/* push notification function for alarm */
function notice(msg) {
/** Show Form */
const window = remote.getCurrentWindow()
const noise = new Audio(path.join(__dirname, '../audio/alarm.wav'))
window.restore()
window.show()
notifier.notify({
title: 'ALARM',
message: msg,
displayTime: 9000,
icon: path.join(__dirname, '../images/clock.ico'),
sound: false,
})
noise.play();
notifier.on('close', function (notifier, options) {
noise.pause();
});
notifier.on('timeout', function (notifier, options) {
noise.pause();
});
}
/* change the alarm time, triggered by elAlarm */
function onAlarmTextChange(event) {
alarmTime = event.target.value
}
function checkWeather(event)
{
document.getElementById('weatherforecastimage').src = "https://w.bookcdn.com/weather/picture/13_18319_1_1_ffffff_158_fff5d9_333333_08488D_3_fff5d9_333333_0_6.png?scode=2&domid=w209&anc_id=41069"
}