-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
291 lines (239 loc) · 8.28 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
// Initialization
var express = require('express');
var http = require('http');
var path = require('path');
var bodyParser = require('body-parser');
var validator = require('validator'); // See documentation at https://github.com/chriso/validator.js
var app = express();
var moment = require('moment');
// See https://stackoverflow.com/questions/5710358/how-to-get-post-query-in-express-node-js
app.use(bodyParser.json());
// See https://stackoverflow.com/questions/25471856/express-throws-error-as-body-parser-deprecated-undefined-extended
app.use(bodyParser.urlencoded({ extended: true }));
// End basic Initialization
// Mongo initialization and connect to database
var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/pavloknew';
var MongoClient = require('mongodb').MongoClient, format = require('util').format;
var db = MongoClient.connect(mongoUri, function(error, databaseConnection) {
db = databaseConnection;
});
// Mongodb connection now available
// Google calendar API and oAuth initialization
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var calendar = google.calendar('v3');
var clientId = "752476311485-bcf3kvfqdqqv62208gt030ul7mv4080k.apps.googleusercontent.com";
var clientSecret = "eBafXPCThZ9wFyLwzgI-j9qx";
var redirectUrl = "https://pavlok-cal.herokuapp.com/oauth2callback";
var SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];
// Google calendar initialized
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Make sure oAuth client is ready
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
// we have an authorization URL, Calendar API is ready to go
var key;
// Enabling CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// CORS enabled
// when user requests to add their calendar, send a URL they can go to to authorize the app
app.get('/addCal', function(request, response) {
key = request.query.key;
console.log(key);
var url = JSON.stringify(authUrl);
response.send(url);
});
// receive an oAuth token when a user authorizes the app through Google APIs
app.get('/oauth2callback', function(request, response) {
var code = request.query.code;
console.log(code);
getNewToken(oauth2Client, code);
response.set('Content-type', 'text/html');
response.send("Thank you for using our app! Your Pavlok will now give you reminders for your calendar events");
});
// helper function to get a new user's oAuth token
function getNewToken(oauth2Client, code) {
oauth2Client.getToken(code, function(err, tokens) {
if (err) {
console.log('Error trying to get token');
return;
}
storeToken(token);
});
}
// stores a new oAuth token in the database
function storeToken(token) {
db.collection('users', function(er, collection) {
if (!er) {
var toInsert = {
"key": key,
"token": token,
};
collection.insert(toInsert, function(err, saved) {
if (err) {
console.log("Insert err");
} else {
console.log("Success");
console.log(JSON.stringify(toInsert));
}
});
}
});
}
// every 60000 milliseconds, iterate through database entries and call getEvents on each user calendar
var j = setInterval(function() {
db.collection('users', function(er, collection) {
if (!er) {
collection.find().toArray(function(err, cursor) {
if (!err) {
for (var i = 0; i < cursor.length; i++) {
getEvents(cursor[i]);
}
}
});
}
});
}, 60000);
// given a database entry, gets the next 10 events for that user
// for each event, if the event is now, or 5, 15, or 30 minutes away, send a request to the Pavlok API
// If event is 30 minutes away, wristband will beep
// If event is 15 minutes away, wristband will beep and vibrate
// If event is 5 minutes away, wristband will vibrate
// If event is now, wristband will shock user
function getEvents(entry) {
if (entry.token == null || entry.token == undefined) return;
var timeStart = new Date();
var apikey = entry.key;
var thirtyMin = moment().add(30, 'minutes').format("dddd, MMMM Do YYYY, h:mm a");
var fifteenMin = moment().add(15, 'minutes').format("dddd, MMMM Do YYYY, h:mm a");
var fiveMin = moment().add(5, 'minutes').format("dddd, MMMM Do YYYY, h:mm a");
var now = moment().format("dddd, MMMM Do YYYY, h:mm a");
oauth2Client.credentials = entry.token;
calendar.events.list({
auth: oauth2Client,
calendarId: 'primary',
timeMin: timeStart.toISOString(),
maxResults: 10,
singleEvents: true,
orderBy: 'startTime'
}, function(err, response) {
if (err) {
console.log('Err contact cal');
return;
}
var events = response.items;
if (events.length == 0) {
console.log('No upcoming events found.');
} else {
console.log('Upcoming 10 events:');
for (var i = 0; i < events.length; i++) {
var time = events[i].start.dateTime || events[i].start.date;
time = moment(time).format("dddd, MMMM Do YYYY, h:mm a");
if (thirtyMin == time) {
console.log("Found a match!");
var options = {
host: 'pavlok.herokuapp.com',
path: '/api/' + apikey + '/beep/3'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
}
if (fifteenMin == time) {
console.log("Found a match!");
var options = {
host: 'pavlok.herokuapp.com',
path: '/api/' + apikey + '/vibrate/64'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
var options = {
host: 'pavlok.herokuapp.com',
path: '/api/' + apikey + '/beep/3'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
}
if (fiveMin == time) {
console.log("Found a match!");
var options = {
host: 'pavlok.herokuapp.com',
path: '/api/' + apikey + '/vibrate/128'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
}
if (now == time) {
console.log("Found a match!");
var options = {
host: 'pavlok.herokuapp.com',
path: '/api/' + apikey + '/shock/255'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
}
}
}
});
}
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});