refactory of the socket service

This commit is contained in:
Mario Colque 2014-04-18 19:08:01 -03:00
commit 0455d5ee69
12 changed files with 94 additions and 137 deletions

View file

@ -211,7 +211,7 @@
<h3>Address</h3> <h3>Address</h3>
<div class="row"> <div class="row">
<div class="large-6 columns"> <div class="large-6 columns">
<a class="panel db" ng-repeat="addr in addrs" ng-click="selectAddr(addr)">{{addr}} <span class="right">{{balanceByAddr[addr] || 0}} BTC &gt;</span></a> <a class="panel db" ng-repeat="addr in addrs" ng-click="selectAddr(addr)">{{addr}} <span class="right">{{$root.balanceByAddr[addr] || 0}} BTC &gt;</span></a>
</div> </div>
<div class="large-3 columns line-dashed-v text-center"> <div class="large-3 columns line-dashed-v text-center">
<qrcode size="160" data="{{selectedAddr}}"></qrcode> <qrcode size="160" data="{{selectedAddr}}"></qrcode>

View file

@ -1,9 +1,7 @@
'use strict'; 'use strict';
angular.module('copay.backup').controller('BackupController', angular.module('copay.backup').controller('BackupController',
function($scope, $rootScope, $location, $window, $timeout, Socket, controllerUtils) { function($scope, $rootScope, $location, $window, $timeout) {
controllerUtils.handleTransactionByAddress($scope);
$scope.title = 'Backup'; $scope.title = 'Backup';
var filename = $rootScope.wallet.id + '.json.aes'; var filename = $rootScope.wallet.id + '.json.aes';

View file

@ -24,6 +24,12 @@ angular.module('copay.header').controller('HeaderController',
'link': '#/backup' 'link': '#/backup'
}]; }];
$rootScope.$watch('wallet', function(wallet) {
if (wallet) {
controllerUtils.setSocketHandlers();
}
});
$scope.isActive = function(item) { $scope.isActive = function(item) {
if (item.link && item.link.replace('#','') == $location.path()) { if (item.link && item.link.replace('#','') == $location.path()) {
return true; return true;

View file

@ -1,7 +1,7 @@
'use strict'; 'use strict';
angular.module('copay.home').controller('HomeController', angular.module('copay.home').controller('HomeController',
function($scope, $rootScope, $location, Socket, controllerUtils) { function($scope, $rootScope, controllerUtils) {
$scope.title = 'Home'; $scope.title = 'Home';
$scope.oneAtATime = true; $scope.oneAtATime = true;
$scope.addrBalance = {}; $scope.addrBalance = {};
@ -10,18 +10,19 @@ angular.module('copay.home').controller('HomeController',
var _updateBalance = function () { var _updateBalance = function () {
w.getBalance(function (balance, balanceByAddr) { w.getBalance(function (balance, balanceByAddr) {
$scope.balanceByAddr = balanceByAddr; $rootScope.$apply(function() {
$scope.addrs = Object.keys(balanceByAddr); $rootScope.balanceByAddr = balanceByAddr;
$scope.selectedAddr = $scope.addrs[0]; $scope.addrs = Object.keys(balanceByAddr);
$scope.$digest(); $scope.selectedAddr = $scope.addrs[0];
});
}); });
var socket = Socket($scope);
controllerUtils.handleTransactionByAddress($scope, _updateBalance);
}; };
$scope.newAddr = function() { $scope.newAddr = function() {
var a = w.generateAddress().toString(); w.generateAddress().toString();
_updateBalance(); _updateBalance();
controllerUtils.setSocketHandlers();
}; };
$scope.selectAddr = function(addr) { $scope.selectAddr = function(addr) {

View file

@ -1,7 +1,6 @@
'use strict'; 'use strict';
angular.module('copay.peer').controller('PeerController', angular.module('copay.peer').controller('PeerController',
function($scope, $rootScope, $location, $routeParams, Socket, controllerUtils) { function($scope, $rootScope, $location, $routeParams) {
controllerUtils.handleTransactionByAddress($scope);
}); });

View file

@ -1,11 +1,9 @@
'use strict'; 'use strict';
angular.module('copay.send').controller('SendController', angular.module('copay.send').controller('SendController',
function($scope, $rootScope, $location, Socket, controllerUtils) { function($scope, $rootScope, $location) {
$scope.title = 'Send'; $scope.title = 'Send';
controllerUtils.handleTransactionByAddress($scope);
$scope.sendTest = function() { $scope.sendTest = function() {
var w = $rootScope.wallet; var w = $rootScope.wallet;
w.createTx( 'mimoZNLcP2rrMRgdeX5PSnR7AjCqQveZZ4', '12345',function() { w.createTx( 'mimoZNLcP2rrMRgdeX5PSnR7AjCqQveZZ4', '12345',function() {

View file

@ -24,7 +24,7 @@ angular.module('copay.setup').controller('SetupController',
$scope.$watch('totalCopayers', function(tc) { $scope.$watch('totalCopayers', function(tc) {
updateRCSelect(tc); updateRCSelect(tc);
}) });
$scope.create = function(totalCopayers, requiredCopayers) { $scope.create = function(totalCopayers, requiredCopayers) {
$scope.loading = true; $scope.loading = true;

View file

@ -2,15 +2,8 @@
angular.module('copay.signin').controller('SigninController', angular.module('copay.signin').controller('SigninController',
function($scope, $rootScope, $location, walletFactory, controllerUtils) { function($scope, $rootScope, $location, walletFactory, controllerUtils) {
// var peerData = Storage.get($rootScope.walletId, 'peerData');
// $rootScope.peerId = peerData ? peerData.peerId : null;
//
$scope.loading = false; $scope.loading = false;
$scope.walletIds = walletFactory.getWalletIds(); $scope.walletIds = walletFactory.getWalletIds();
$scope.selectedWalletId = $scope.walletIds.length ? $scope.walletIds[0]:null; $scope.selectedWalletId = $scope.walletIds.length ? $scope.walletIds[0]:null;
$scope.create = function() { $scope.create = function() {
@ -25,39 +18,15 @@ angular.module('copay.signin').controller('SigninController',
w.netStart(); w.netStart();
}; };
$scope.join = function(cid) { $scope.join = function(peerId) {
$scope.loading = true; $scope.loading = true;
walletFactory.network.on('openError', function() { walletFactory.network.on('openError', function() {
controllerUtils.onError($scope); controllerUtils.onError($scope);
$rootScope.$digest(); $rootScope.$digest();
}); });
walletFactory.connectTo(cid, function(w) { walletFactory.connectTo(peerId, function(w) {
controllerUtils.setupUxHandlers(w); controllerUtils.setupUxHandlers(w);
w.netStart(); w.netStart();
}); });
}; };
//
// if (cid) {
// var w = walletFactory.(walletId);
//TODO
// Network.init(null, function() {
// Network.connect(cid,
// function() {
// $location.path('peer');
// $rootScope.$digest();
// }, function() {
// $rootScope.flashMessage = { message: 'Connection refussed', type: 'error'};
// $location.path('home');
// $rootScope.$digest();
// });
// });
// }
// if (peerData && peerData.peerId && peerData.connectedPeers.length > 0) {
// $rootScope.peerId = peerData.peerId;
// $scope.join(peerData.connectedPeers);
// }
}); });

View file

@ -1,7 +1,7 @@
'use strict'; 'use strict';
angular.module('copay.transactions').controller('TransactionsController', angular.module('copay.transactions').controller('TransactionsController',
function($scope, $rootScope, $location, Socket, controllerUtils) { function($scope, $rootScope, $location) {
$scope.title = 'Transactions'; $scope.title = 'Transactions';
$scope.oneAtATime = true; $scope.oneAtATime = true;
@ -35,8 +35,6 @@ angular.module('copay.transactions').controller('TransactionsController',
}; };
_updateTxs(); _updateTxs();
var socket = Socket($scope);
socket.on('connect', controllerUtils.handleTransactionByAddress($scope));
$scope.sign = function (ntxid) { $scope.sign = function (ntxid) {
var w = $rootScope.wallet; var w = $rootScope.wallet;

View file

@ -7,31 +7,40 @@ angular
$routeProvider $routeProvider
.when('/', { .when('/', {
templateUrl: 'signin.html' templateUrl: 'signin.html',
validate: false
}) })
.when('/signin', { .when('/signin', {
templateUrl: 'signin.html' templateUrl: 'signin.html',
validate: false
}) })
.when('/setup', { .when('/setup', {
templateUrl: 'setup.html' templateUrl: 'setup.html',
validate: false
}) })
.when('/home', { .when('/home', {
templateUrl: 'home.html' templateUrl: 'home.html',
validate: true
}) })
.when('/join/:id', { .when('/join/:id', {
templateUrl: 'join.html' templateUrl: 'join.html',
validate: true
}) })
.when('/peer', { .when('/peer', {
templateUrl: 'peer.html' templateUrl: 'peer.html',
validate: true
}) })
.when('/transactions', { .when('/transactions', {
templateUrl: 'transactions.html' templateUrl: 'transactions.html',
validate: true
}) })
.when('/send', { .when('/send', {
templateUrl: 'send.html' templateUrl: 'send.html',
validate: true
}) })
.when('/backup', { .when('/backup', {
templateUrl: 'backup.html' templateUrl: 'backup.html',
validate: true
}) })
.otherwise({ .otherwise({
templateUrl: '404.html' templateUrl: '404.html'
@ -47,9 +56,8 @@ angular
//.hashPrefix('!'); //.hashPrefix('!');
}) })
.run(function($rootScope, $location) { .run(function($rootScope, $location) {
$rootScope.$on('$routeChangeStart', function() { $rootScope.$on('$routeChangeStart', function(event, next, current) {
if (!$rootScope.wallet || !$rootScope.wallet.id) { if ((!$rootScope.wallet || !$rootScope.wallet.id) && next.validate) {
console.log('############ no wallet');
$location.path('signin'); $location.path('signin');
} }
}); });

View file

@ -21,9 +21,7 @@ angular.module('copay.controllerUtils').factory('controllerUtils', function ($ro
$rootScope.$digest(); $rootScope.$digest();
} }
root.setupUxHandlers = function(w) { root.setupUxHandlers = function(w) {
w.on('badMessage', function(peerId) { w.on('badMessage', function(peerId) {
$rootScope.flashMessage = {type:'error', message: 'Received wrong message from peer id:' + peerId}; $rootScope.flashMessage = {type:'error', message: 'Received wrong message from peer id:' + peerId};
}); });
@ -45,19 +43,24 @@ angular.module('copay.controllerUtils').factory('controllerUtils', function ($ro
w.on('close', root.onErrorDigest); w.on('close', root.onErrorDigest);
}; };
root.handleTransactionByAddress = function(scope, cb) { root.setSocketHandlers = function(cb) {
var socket = Socket(scope); Socket.removeAllListeners();
var addrs = $rootScope.wallet.getAddressesStr(); var addrs = $rootScope.wallet.getAddressesStr();
for(var i=0;i<addrs.length;i++) { for(var i = 0; i < addrs.length; i++) {
socket.emit('subscribe', addrs[i]); console.log('### SUBSCRIBE TO', addrs[i]);
Socket.emit('subscribe', addrs[i]);
} }
addrs.forEach(function(addr) { addrs.forEach(function(addr) {
socket.on(addr, function(txid) { Socket.on(addr, function(txid) {
console.log('Received!', txid); console.log('Received!', txid);
$rootScope.wallet.getBalance(function(balance) { $rootScope.wallet.getBalance(function(balance, balanceByAddr) {
scope.$apply(function() { $rootScope.$apply(function() {
$rootScope.totalBalance = balance; $rootScope.totalBalance = balance;
$rootScope.balanceByAddr = balanceByAddr;
}); });
console.log('New balance:', balance); console.log('New balance:', balance);
if (typeof cb === 'function') return cb(); if (typeof cb === 'function') return cb();
}); });

View file

@ -1,72 +1,49 @@
'use strict'; 'use strict';
var ScopedSocket = function(socket, $rootScope) {
this.socket = socket;
this.$rootScope = $rootScope;
this.listeners = [];
};
ScopedSocket.prototype.removeAllListeners = function(opts) {
if (!opts) opts = {};
for (var i = 0; i < this.listeners.length; i++) {
var details = this.listeners[i];
if (opts.skipConnect && details.event === 'connect') {
continue;
}
this.socket.removeListener(details.event, details.fn);
}
this.listeners = [];
};
ScopedSocket.prototype.on = function(event, callback) {
var socket = this.socket;
var $rootScope = this.$rootScope;
var wrapped_callback = function() {
var args = arguments;
$rootScope.$apply(function() {
callback.apply(socket, args);
});
};
socket.on(event, wrapped_callback);
this.listeners.push({
event: event,
fn: wrapped_callback
});
};
ScopedSocket.prototype.emit = function(event, data, callback) {
var socket = this.socket;
var $rootScope = this.$rootScope;
socket.emit(event, data, function() {
var args = arguments;
$rootScope.$apply(function() {
if (callback) {
callback.apply(socket, args);
}
});
});
};
angular.module('copay.socket').factory('Socket', angular.module('copay.socket').factory('Socket',
function($rootScope) { function($rootScope) {
var server = 'http://' + config.socket.host + ':' + config.socket.port; var listeners = [];
var socket = io.connect(server, { var url = 'http://' + config.socket.host + ':' + config.socket.port;
var socket = io.connect(url, {
'reconnect': true, 'reconnect': true,
'reconnection delay': 500, 'reconnection delay': 500,
}); });
return function(scope) {
var scopedSocket = new ScopedSocket(socket, $rootScope); return {
scope.$on('$destroy', function() { on: function(event, callback) {
scopedSocket.removeAllListeners(); var wrappedCallback = function() {
}); var args = arguments;
socket.on('connect', function() { $rootScope.$apply(function() {
scopedSocket.removeAllListeners({ callback.apply(socket, args);
skipConnect: true });
};
socket.on(event, wrappedCallback);
if (event !== 'connect') {
listeners.push({
event: event,
fn: wrappedCallback
});
}
},
emit: function(event, data, callback) {
socket.emit(event, data, function() {
var args = arguments;
$rootScope.$apply(function() {
if (callback) {
callback.apply(socket, args);
}
});
}); });
}); },
return scopedSocket; removeAllListeners: function() {
for (var i = 0; i < listeners.length; i++) {
var details = listeners[i];
socket.removeListener(details.event, details.fn);
}
listeners = [];
}
}; };
}); });