60 lines
1.6 KiB
JavaScript
60 lines
1.6 KiB
JavaScript
const jsonfile = require('jsonfile');
|
|
const config = require('../../config/config.json');
|
|
const Fitbit = require('fitbit-oauth2');
|
|
|
|
const logger = require('log4js').getLogger();
|
|
|
|
require('sugar-date');
|
|
|
|
const fitbit = new Fitbit(config.fitbit);
|
|
const tokenFile = 'fb-token.json';
|
|
|
|
module.exports = {
|
|
|
|
getYesterdayFitbit: function() {
|
|
return new Promise(function(resolve, reject) {
|
|
const yesterday = Date.create('yesterday').format('{yyyy}-{MM}-{dd}');
|
|
const 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);
|
|
}
|
|
const 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) {
|
|
logger.error('Today Fitbit token failed to load');
|
|
logger.warn(err);
|
|
|
|
}
|
|
else {
|
|
logger.info('Fitbit token loaded...');
|
|
fitbit.setToken(obj);
|
|
|
|
}
|
|
});
|
|
|