bitcore-wallet-service/lib/wsapp.js

81 lines
2.0 KiB
JavaScript
Raw Normal View History

2015-03-23 14:26:47 -07:00
'use strict';
var $ = require('preconditions').singleton();
var _ = require('lodash');
var async = require('async');
var log = require('npmlog');
2015-03-30 15:44:16 -07:00
log.debug = log.verbose;
2015-03-23 14:26:47 -07:00
var Uuid = require('uuid');
var WalletService = require('./server');
var Notification = require('./model/notification');
2015-03-23 14:26:47 -07:00
log.level = 'debug';
2015-05-04 14:23:56 -07:00
var io, messageQueue;
2015-03-23 14:26:47 -07:00
var WsApp = function() {};
2015-04-01 17:34:36 -07:00
WsApp._unauthorized = function(socket) {
2015-03-23 15:07:06 -07:00
socket.emit('unauthorized');
socket.disconnect();
};
2015-05-04 14:23:56 -07:00
// WsApp._handleNotification = function(notification) {
// console.log('*** [wsapp.js ln26] notification:', notification); // TODO
2015-05-04 14:23:56 -07:00
// io.to(notification.walletId).emit('notification', notification);
// };
2015-03-23 14:26:47 -07:00
2015-05-04 14:23:56 -07:00
WsApp._initMessageQueue = function(cb) {
2015-03-30 15:44:16 -07:00
function handleNotification(notification) {
io.to(notification.walletId).emit('notification', notification);
};
2015-03-30 08:40:58 -07:00
2015-05-04 14:23:56 -07:00
messageQueue = require('socket.io-client').connect('http://localhost:3380', {
'force new connection': true,
});
messageQueue.on('connect_error', function(err) {
log.warn('Could not connect to message queue server');
});
messageQueue.on('notification', handleNotification);
2015-03-23 14:26:47 -07:00
2015-05-04 14:23:56 -07:00
messageQueue.on('connect', function() {
return cb();
});
};
WsApp.start = function(server, config, cb) {
io = require('socket.io')(server);
2015-03-23 14:26:47 -07:00
2015-05-04 14:23:56 -07:00
async.series([
2015-03-23 15:07:06 -07:00
2015-05-04 14:23:56 -07:00
function(done) {
WsApp._initMessageQueue(done);
},
function(done) {
io.on('connection', function(socket) {
socket.nonce = Uuid.v4();
socket.on('authorize', function(data) {
if (data.message != socket.nonce) return WsApp._unauthorized(socket);
2015-03-23 15:07:06 -07:00
2015-05-04 14:23:56 -07:00
WalletService.getInstanceWithAuth(data, function(err, service) {
if (err) return WsApp._unauthorized(socket);
2015-03-30 08:40:58 -07:00
2015-05-04 14:23:56 -07:00
socket.join(service.walletId);
socket.emit('authorized');
});
2015-03-31 08:04:02 -07:00
});
2015-05-04 14:23:56 -07:00
socket.emit('challenge', socket.nonce);
done();
2015-03-23 14:26:47 -07:00
});
2015-05-04 14:23:56 -07:00
},
], function(err) {
if (cb) return cb(err);
2015-03-23 14:26:47 -07:00
});
};
module.exports = WsApp;