-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
467 lines (374 loc) · 13.1 KB
/
app.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// Clayton Smith
// Dont want API keys floating around on the internet
var express = require('express'),
routes = require('./routes'),
api = require('./routes/api'),
http = require('http'),
path = require('path'),
OAuth = require('oauth-1.0a'),
async = require('async'),
cron = require('cron');
var config = require('./config.json');
var FitbitApiClient = require("fitbit-node"),
client = new FitbitApiClient(config.FITBIT_KEY, config.FITBIT_SECRET);
var today = new Date();
var requestTokenSecrets = {};
var app = module.exports = express();
var redirect = module.exports = express();
var mongo = require('mongoskin'),
db = mongo.db(config.mongo_link, {native_parser: true});
// DEPRICATED: update interval
var frequency = 15,
the_interval = frequency * 60 * 1000;
var appData = {
serverVersion: 1.01,
clientVersion: 1.0,
trackerInfo: {
startTime: new Date((new Date()).getUTCFullYear(), (new Date()).getUTCMonth(), (new Date()).getUTCDate(), /*START*/ 5, 0, 0, 0),
endTime: new Date((new Date()).getUTCFullYear(), (new Date()).getUTCMonth(), (new Date()).getUTCDate(), /*END*/ 19, 0, 0, 0)
}
}
api.locals = appData
app.locals(appData);
console.log(appData.trackerInfo.startTime);
console.log(api.locals.trackerInfo.startTime);
var cronJobs = [
{
name: "Quarter hour update",
cronStr: "0 */15 5-19 * * * ", // Every 15 minutes between 5 am and 7 pm
job: function(){ updateDB(); }
},
{
name: "Nightly update",
cronStr: "0 45 23 * * * ",
job: function(){ nightlyUpdate(); }
},
{
name: "Pre-Activity staging",
cronStr: "0 15 0 * * *",
job: function(){ dailyReset(); }
}
]
db.bind('info');
db.bind('keys');
db.bind('users');
db.bind('history');
app.use(function(req, res, next) {
req.db = db;
next();
});
/* EXPRESS SETUP */
app.set('port', process.env.PORT || 3000);
redirect.set('port', 6544);
app.set('views', __dirname + '/views');
// Template engine
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// Stuff
//app.use(express.cookieParser());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
// Floors time to the preveous quarter hour
function floorTimeToQuarter(time){
time = new Date(time);
time.setMilliseconds(Math.floor(time.getMilliseconds() / 1000) * 1000);
time.setSeconds(Math.floor(time.getSeconds() / 60) * 60);
time.setMinutes(Math.floor(time.getMinutes() / 15) * 15);
return time;
}
// (TIME.HOURS * 4 ) + TIME.MINUTES - OFFSET
function getIndexFromTime(time){
time = floorTimeToQuarter(time);
var mid = parseInt(time.getHours() * 4 + (time.getMinutes() / 15));
var offset = parseInt(appData.trackerInfo.startTime.getHours() * 4 + (appData.trackerInfo.startTime.getMinutes()/15)); // int
return mid - offset;
}
// Uses time to find the index
function calcLastUpdateIndex() {
var time = new Date();
return getIndexFromTime(time);
}
function getTimeFromIndex(index) {
var time = new Date( appData.trackerInfo.startTime);
console.log(time);
time.setMinutes(time.getMinutes() + (index * 15));
console.log(time);
return time; // Date obj
}
function getTimeStampFromTime(time){
return time.getHours() + ':' + time.getMinutes(); // Str
}
function getTimeStamp(){
return getTimeStampFromTime(getTimeFromIndex(calcLastUpdateIndex()));
}
function canUpdate(dateX){
var last = new Date( dateX ),
current = new Date();
return (
( last.getFullYear() < current.getFullYear() || // on new year
last.getMonth() < current.getMonth() || // on new month
last.getDate() < current.getDate() || // on new day
getIndexFromTime(last) < getIndexFromTime(current)) && // on new quarter hour
0 <= getIndexFromTime(current)); // Don't update before time slot
}
app.get("/authorize", function (req, res) {
client.getRequestToken().then(function (results) {
console.log('Getting token and redirect');
var token = results[0],
secret = results[1];
requestTokenSecrets[token] = secret;
console.log(token);
res.redirect("http://www.fitbit.com/oauth/authorize?oauth_token=" + token);
}, function (error) {
res.send(error);
});
});
app.get("/thankyou", function (req, res) {
var token = req.query.oauth_token,
secret = requestTokenSecrets[token],
verifier = req.query.oauth_verifier;
console.log('********** Hello!', token, secret, verifier);
client.getAccessToken(token, secret, verifier).then(function (results) {
console.log('test');
var accessToken = results[0],
accessTokenSecret = results[1],
userId = results[2].encoded_user_id;
console.log(accessToken, accessTokenSecret, userID);
routes.index(req, res);
db.keys.findOne(
{atc: accessToken},
function(err, user){
// Server error
if(err){
console.log( "Server error" );
res.status(500).json({error: "Server error."}) ;
}
// User already added
if(user){
console.log( "User already in the database." );
res.status(403).json({error: "User already in the database."}) ;
// Insert new user
} else {
console.log( "User has been added to the team." );
db.keys.insert({
atc: accessToken,
tokens: {
access_token: accessToken,
access_token_secret: accessTokenSecret
}}, {w: 0});
client.requestResource("/profile.json", "GET",
accessToken,
accessTokenSecret).then(function (results) {
console.log(err);
var response = JSON.parse(results[0]);
db.users.insert(
{
"atc": accessToken,
"displayName": response.user.displayName,
"avatar": response.user.avatar,
"distance": 0,
"distances": Array.apply(null,Array(calcLastUpdateIndex())).map(function(el){return null;})
},
{w: 0});
db.history.insert({atc: accessToken, records: []});
client.requestResource("/activities/date/"+ date +".json", "GET",
access_token,
access_token_secret).then(function (results){
var distance = JSON.parse(results[0]).summary.distances[0].distance
db.users.update(
{atc: user.tokens.access_token },
{
$push: {
"distances": {
$each: [ distance ],
$position: calcLastUpdateIndex()
}},
$set: {"distance": distance}
},
{multi: true},
function(err, obj){
// Tell client to get new data
io.emit('db_update', {message: 'A new user has been added. Please update yourself.'});
});
});
});
}
});
routes.index(req, res);
}, function (error) {
res.send(error);
});
});
// development only
if (app.get('env') === 'development') {
app.use(express.errorHandler());
};
// production only
if (app.get('env') === 'production') {
// TODO
};
// Routes
app.get('/partials/:name', routes.partial );
// JSON API
app.get('/api/info', api.info);
app.get('/api/update', api.update);
app.post('/api/add_user', api.addUser);
app.post('/api/add_user_to_group', api.addUserToGroup);
// redirect all others to the index (HTML5 history)
//May not be needed
app.get('/', function(req, res) {
routes.index(req, res);
});
app.get('*', function(req, res) {
console.log('*', req.url);
routes.index(req, res);
res.end();
});
redirect.get('*', function(req, res) {
console.log('*', req.url);
res.writeHead(302, {'Location': 'http://localhost:3000' + req.url});
res.end();
});
// Socket setup
/******* BACKGROUND STUFF *******/
// Update DB every X minutes
var updateChain = []
function getFitbitData( user, done){
if( !user ) {
console.log('Im out');
//done();
return ;
}
var today = new Date();
// Date string. Find better way.
var date = 'Y-m-d'
.replace('Y', today.getFullYear())
.replace('m', today.getMonth()+1)
.replace('d', today.getDate());
var currentIndex = calcLastUpdateIndex();
client.requestResource("/activities/date/"+ date +".json", "GET",
user.tokens.access_token,
user.tokens.access_token_secret
).then(function (results) {
var obj = {};
var distance = JSON.parse(results[0]).summary.distances[0].distance
obj["distances." + calcLastUpdateIndex().toString()] = distance;
obj["distance"] = distance;
db.users.update(
{atc: user.tokens.access_token },
{
$set: obj
},
{multi: true},
function(err, obj){
hackyThing -= 1;
console.log(hackyThing);
if( hackyThing === 1 ){ // off by one because extra user in keys set
console.log('*********************** DB updated.');
io.emit('db_update', {message: 'New data from Fitbit. Please update yourself.'});
done();
}
});
});
}
var hackyThing = 0;
function updateDB() {
db.info.findOne(
{info: "lastUpdateTime"},
function(err, lastUpdate){ // lastUpdateTime will prevent multiple servers from updating a sing database.
console.log('looking for last update time');
if(err){
condole.log('bad server error');
}
var currentUpdateTime = new Date();
var lastUpdateTime = 0;
if(!lastUpdate){
console.log('Set first update time');
db.info.insert({
info: "lastUpdateTime",
lastUpdateTime: currentUpdateTime
}, {w: 0});
lastUpdateTime = currentUpdateTime;
} else {
console.log( 'Last updated: ', lastUpdate.lastUpdateTime);
lastUpdateTime = lastUpdate.lastUpdateTime;
}
// Do not update if already updated
if( canUpdate(lastUpdateTime) ){
console.log('The database is updating.');
db.keys.find({}).toArray(function(err, result){
hackyThing = result.length;
async.forEach(result, getFitbitData, function(err){
console.log(err);
});
})
db.info.update(
{ "info": "lastUpdateTime",},
{ $set: { "lastUpdateTime": new Date()}},
{ multi: true},
function(err, obj){
console.log(err, obj);
});
} else {
console.log('No updates needed at this time');
// THIS server might not have updated the DB but someone did.
// Lets let the clients know there is an update
io.emit('db_update', {message: 'New data might exist from Fitbit. Please update yourself.'});
}
});
}
function nightlyUpdate(){
var dat = Date((new Date()).getUTCFullYear(), (new Date()).getUTCMonth(), (new Date()).getUTCDate(), 0, 0, 0, 0)
var obj = {};
db.users.find({}).toArray(function(err, result){
if(!result) return ;
obj[date] = {
distance: result.distance,
distances: result.distances
};
db.history.update(
{atc: result.atc},
{$push: {records: obj}},
{multi: false},
function(err, thing){});
});
};
function morningReset(){
db.users.update(
{},
{ $set: {
"distance": 0,
"distances": Array.apply(null, Array((appData.trackerInfo.endTime.getHours()
- appData.trackerInfo.startTime.getHours()) *4)).map(function(el){return null;})
}},
{multi: true},
function(err, obj){
console.log(err, obj);
}
);
}
/************* START SERVER STUFF :) *************/
// Init update
//
updateDB();
// Start monitors
cronJobs.forEach(function(obj){
console.log('Launching tast', obj.name);
cron.job(obj.cronStr, obj.job).start();
});
// Start Server and init socket
var io = require('socket.io').listen(
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
console.log( "Current update time: ", getTimeStamp());
console.log( "Current update index: ", calcLastUpdateIndex());
}));
// Fitbit callback puts users on port 6544 on localhost. Listen on port 6544 and redirect users to port 3000
// so they may make API calls.
// ^^ This only applies if the Fitbit redirect URL has not been set. ^^
http.createServer(redirect).listen(redirect.get('port'), function () {
console.log('Express server listening on port ' + redirect.get('port'));
});