2016-04-11 13:46:07 +00:00
|
|
|
var jsonfile = require('jsonfile');
|
|
|
|
var config = require('../../config/config.json');
|
|
|
|
var Fitbit = require('fitbit-oauth2');
|
|
|
|
var dateFormat = require('dateformat');
|
|
|
|
|
|
|
|
var logger = require('log4js').getLogger();
|
|
|
|
|
|
|
|
require('sugar-date');
|
|
|
|
|
|
|
|
var fitbit = new Fitbit(config.fitbit);
|
2016-08-05 10:44:16 +00:00
|
|
|
var tokenFile = '../../fb-token.json';
|
2016-04-11 13:46:07 +00:00
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
|
|
|
|
getYesterdayFitbit: function() {
|
|
|
|
return new Promise(function(resolve, reject) {
|
|
|
|
var yesterday = Date.create('yesterday').format('{yyyy}-{MM}-{dd}');
|
|
|
|
var url = 'https://api.fitbit.com/1/user/-/activities/date/' + yesterday +'.json';
|
|
|
|
|
|
|
|
logger.info('Getting fitbit for: ', yesterday);
|
|
|
|
logger.debug(url);
|
|
|
|
fitbit.request({
|
|
|
|
uri: url,
|
|
|
|
method: 'GET'
|
|
|
|
}, function( err, body, token ) {
|
|
|
|
if ( err ) {
|
|
|
|
return reject(err);
|
|
|
|
}
|
|
|
|
var profile = JSON.parse( body );
|
|
|
|
// if token is not null, a refesh has happened and we need to persist the new token
|
|
|
|
if ( token )
|
|
|
|
jsonfile.writeFile(tokenFile, token, function( err ) {
|
|
|
|
if ( err ) {
|
|
|
|
return reject(err);
|
|
|
|
}
|
|
|
|
return resolve(profile);
|
|
|
|
});
|
|
|
|
else
|
|
|
|
{
|
|
|
|
return resolve(profile);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
jsonfile.readFile(tokenFile, function(err, obj) {
|
|
|
|
if (err) {
|
2016-04-11 14:12:44 +00:00
|
|
|
logger.error('Today Fitbit token failed to load');
|
|
|
|
logger.warn(err);
|
2016-04-11 13:46:07 +00:00
|
|
|
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
logger.info('Fitbit token loaded...');
|
|
|
|
fitbit.setToken(obj);
|
|
|
|
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|