Wallet/js/models/core/WalletLock.js

61 lines
1.5 KiB
JavaScript
Raw Normal View History

2014-08-14 18:25:53 -04:00
'use strict';
var preconditions = require('preconditions').singleton();
function WalletLock(storage, walletId, timeoutMin) {
preconditions.checkArgument(storage);
preconditions.checkArgument(walletId);
this.sessionId = storage.getSessionId();
this.storage = storage;
this.timeoutMin = timeoutMin || 5;
this.key = WalletLock._keyFor(walletId);
2014-09-03 01:25:08 -03:00
this._setLock(function() {});
2014-08-14 18:25:53 -04:00
}
2014-08-15 18:55:26 -04:00
2014-08-14 18:25:53 -04:00
WalletLock._keyFor = function(walletId) {
return 'lock' + '::' + walletId;
};
2014-09-03 01:25:08 -03:00
WalletLock.prototype._isLockedByOther = function(cb) {
var self=this;
this.storage.getGlobal(this.key, function(json) {
var wl = json ? JSON.parse(json) : null;
var t = wl ? (Date.now() - wl.expireTs) : false;
// is not locked?
if (!wl || t > 0 || wl.sessionId === self.sessionId)
return cb(false);
// Seconds remainding
return cb(parseInt(-t / 1000.));
});
2014-08-14 18:25:53 -04:00
};
2014-09-03 01:25:08 -03:00
WalletLock.prototype._setLock = function(cb) {
this.storage.setGlobal(this.key, {
sessionId: this.sessionId,
expireTs: Date.now() + this.timeoutMin * 60 * 1000,
2014-09-03 01:25:08 -03:00
}, cb);
};
2014-09-03 01:25:08 -03:00
WalletLock.prototype.keepAlive = function(cb) {
2014-08-14 18:25:53 -04:00
preconditions.checkState(this.sessionId);
2014-09-03 01:25:08 -03:00
var self = this;
2014-08-14 18:25:53 -04:00
2014-09-03 01:25:08 -03:00
this._isLockedByOther(function(t) {
if (t)
return cb(new Error('Wallet is already open. Close it to proceed or wait ' + t + ' seconds if you close it already'));
self._setLock(cb);
});
2014-08-14 18:25:53 -04:00
};
2014-09-03 01:25:08 -03:00
WalletLock.prototype.release = function(cb) {
this.storage.removeGlobal(this.key, cb);
2014-08-14 18:25:53 -04:00
};
module.exports = WalletLock;