const express = require('express'); const path = require('path'); const apicache = require('apicache'); const http = require('http'); const fx = require('./lib/fx'); const btc = require('./lib/btc'); const train = require('./lib/train'); const password = require('./lib/password'); const clean = require('./lib/clean'); const events = require('./lib/events'); // const today = require('./lib/today'); const morgan = require('morgan'); const cookieParser = require('cookie-parser'); const session = require('express-session'); // const methodoverride = require('method-override'); const bodyparser = require('body-parser'); const errorhandler = require('errorhandler'); const jsonfile = require('jsonfile'); const Events = require('events'); const busEmitter = new Events.EventEmitter(); const weather = require('./lib/weather'); // busEmitter.on('update', today.broadcast); const WebSocket = require('ws'); // const wss = new WebSocketServer({ 'server': server }); const SocketHandler = require('./lib/wshandlerv2'); // const webSocket = new SocketHandler(busEmitter, wss); btc.setEmitter(busEmitter); // today.setEmitter(busEmitter); // train = require('lib/train') /* ,submit = require('./routes/mongo/submit') */ const fs = require('fs'); const config = require('./config/config.json'); const Fitbit = require('fitbit-oauth2'); const polys = require('./lib/poly.js'); const logger = require('log4js').getLogger('web-server'); logger.level = 'debug'; const app = express(); global.lastcheck = 0; global.fxLastCheck = 0; let btcCache = {}, fxCache = {}, trainCache = {}; const port = process.env.PORT || 9000; // apicache.options({ 'debug': true }); const cache = apicache.middleware; // app.configure(function () { app.set('port', port); app.set('view engine', 'ejs'); app.use(morgan('dev')); app.use(cookieParser('your secret here')); app.use(session({ 'secret': 'd2jRT6ZpYFsXsF3kGS21ZszKbPAaEa', 'resave': false, 'saveUninitialized': false })); /* 'default', 'short', 'tiny', 'dev' */ // app.use(methodoverride()); app.use(bodyparser.urlencoded({ 'extended': false })); // parse application/json app.use(bodyparser.json()); app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); next(); }); // app.use(app.router); app.use(express.static(path.join(__dirname, 'dist'))); app.use('/slack/gfx', express.static(path.join(__dirname, 'dist/gfx'))); app.get('/slack', function(req, res) { res.sendFile(path.join(`${__dirname }/views/index.html`)); }); app.use(errorhandler({ 'dumpExceptions': true, 'showStack': true })); app.use('/btc', btc.doBTC); app.use('/balance', btc.doBalance); app.use('/fx', fx.doFx); app.use('/dbeglq', train.dbe_glq); app.use('/glqdbe', train.glq_dbe); app.use('/gettrains', train.getTrainTimes); app.use('/getnexttraintimes', train.getNextTrainTimes); app.use('/getroute', train.getRoute); app.use('/generate', password.generate); app.use('/cleanit', clean.cleanit); app.use('/events', events.getEvents); app.get('/cinema/:id', events.getCinema); app.route('/poly').get(polys); /* app.get('/slack', function(req, res) { res.render('pages/slackV3'); });*/ app.get('/temp', function(req, res) { res.render('pages/temp'); }); app.get('/cleaner', function(req, res) { res.render('pages/cleaner'); }); app.get('/weather', /* cache('1 hour'),*/ (req, res) => { weather.doGetOpenWeather() .then((d) => { res.send(d); }).catch((e) => { console.error(e); res.status(500).send('There was an error!'); }); }); const tfile = 'fb-token.json'; // Instanciate a fitbit client. See example config below. // const fitbit = new Fitbit(config.fitbit); // In a browser, http://localhost:4000/fitbit to authorize a user for the first time. // app.get('/fitbit', function(req, res) { res.redirect(fitbit.authorizeURL()); }); app.get( '/fb-profile', function( req, res, next ) { fitbit.request({ 'uri': 'https://api.fitbit.com/1/user/-/profile.json', 'method': 'GET' }, function( err, body, token ) { if ( err ) return next( 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 ) persist.write( tfile, token, function( err ) { if ( err ) return next( err ); res.send( `
${ JSON.stringify( profile, null, 2 ) }
` ); }); else res.send( `
${ JSON.stringify( profile, null, 2 ) }
` ); }); }); app.get( '/fb-today', function( req, res, next ) { const today = Date.create('today').format('{yyyy}-{MM}-{dd}'); const url = `https://api.fitbit.com/1/user/-/activities/date/${ today }.json`; fitbit.request({ 'uri': url, 'method': 'GET' }, function( err, body, token ) { if ( err ) return next( 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 ) persist.write( tfile, token, function( err ) { if ( err ) return next( err ); res.send( `
${ JSON.stringify( profile, null, 2 ) }
` ); }); else res.send( `
${ JSON.stringify( profile, null, 2 ) }
` ); }); }); // Callback service parsing the authorization token and asking for the access token. This // endpoint is refered to in config.fitbit.authorization_uri.redirect_uri. See example // config below. // app.get('/fitbit_auth_callback', function(req, res, next) { const code = req.query.code; fitbit.fetchToken(code, function(err, token) { if (err) return next(err); // persist the token jsonfile.writeFile(tfile, token, function(err) { if (err) return next(err); console.log('!!!! Fitbit token saved'); res.redirect('/fb-profile'); }); }); }); jsonfile.readFile('./fb-token.json', function(err, obj) { if (err) logger.error(err); else fitbit.setToken(obj); }); // }); /** * create the server */ /* http.createServer(app).listen(app.get('port'), function () { logger.warn("Express server listening on port " + app.get('port')); //console.log("Express server listening on port " + app.get('port')); }); */ const server = http.createServer(app); let wss; let webSocket; wss = new WebSocket.Server({ server }); webSocket = new SocketHandler(busEmitter, wss); // server.on('request', app); server.listen(port, () => { logger.info(`New server listening on ${ server.address().port}`); });