silvrgit/lib/btc.js
2017-08-18 15:08:28 +01:00

142 lines
3.2 KiB
JavaScript

const http = require('http');
const https = require('https');
const LimitedArray = require('limitedarray');
const trend = require('trend');
const logger = require('log4js').getLogger('btc');
let btcCache = {};
let balanceCache = {};
let history = new LimitedArray(288); // one days worth in 5 minute chunks
function getBitcoin () {
logger.info('>> getting bitcoin');
function btcQuery (callback) {
const options = {
host: 'api.coindesk.com',
// port: 80,
path: '/v1/bpi/currentprice.json',
// method: 'GET',
headers: {
/* 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)*/
}
};
try {
http.request(options).on('response', response => {
let data = '';
response.on('data', chunk => {
data += chunk;
});
response.on('end', () => {
let cData = {};
try {
cData = JSON.parse(data);
} catch (e) {
logger.error(e);
} finally{
callback(cData);
}
});
response.on('error', e => {
logger.error(e);
});
}).end();
} catch (e) {
logger.error(e);
}
}
btcQuery(a => {
// logger.info(a);
logger.info('Got btc data. Storing it');
btcCache = a;
history.push(a.bpi.USD.rate_float);
btcCache.history = history.get();
btcCache.trend = trend(btcCache.history, {avgPoints: 12});
GLOBAL.lastcheck = new Date();
});
}
function getBalance() {
logger.info('>> getting Balance');
function balanceQuery (callback, r) {
try {
https.get('https://blockexplorer.com/api/addr/18sLVW5Aswp2KWLr4hMFZsuSPtvAauFiif').on('response', response => {
let data = '';
response.on('data', chunk => {
data += chunk;
});
response.on('end', () => {
let cData = {};
try {
cData = JSON.parse(data);
} catch (e) {
logger.error(e);
} finally{
callback(cData, r);
}
});
response.on('error', e => {
logger.error(e);
});
}).end();
} catch (e) {
logger.error(e);
}
}
balanceQuery(a => {
logger.info('Got balance data. Storing it');
balanceCache = a;
});
}
exports.doBTC = (req, res) => {
logger.info('Bitcoin request');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(btcCache));
};
exports.doBalance = (req, res) => {
logger.info('Balance request');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(balanceCache));
};
function updateBitcoin() {
logger.warn('updateBitcoin');
getBitcoin();
const now = new Date();
const mod = 300000 - (now.getTime() % 300000);
let btcupdateFn = () => {
updateBitcoin();
};
setTimeout(btcupdateFn.bind(this), mod + 10);
}
function updateBalance() {
logger.warn('updateBalance');
getBalance();
const now = new Date();
const mod = 3.6e+6 - (now.getTime() % 3.6e+6);
let balanceUpdateFn = () => {
updateBalance();
};
setTimeout(balanceUpdateFn.bind(this), mod + 10);
}
updateBitcoin();
updateBalance();