Use async store

pull/1/head
yflory 7 years ago
parent 0840570fbf
commit b3688db202

@ -1,15 +1,12 @@
define([ define([
'jquery',
'/bower_components/chainpad-crypto/crypto.js', '/bower_components/chainpad-crypto/crypto.js',
'/common/curve.js',
'/common/common-hash.js', '/common/common-hash.js',
'/common/common-util.js', '/common/common-util.js',
'/common/common-constants.js', '/common/common-constants.js',
'/customize/messages.js', '/customize/messages.js',
'/bower_components/marked/marked.min.js',
'/common/common-realtime.js', '/common/common-realtime.js',
], function ($, Crypto, Curve, Hash, Util, Constants, Messages, Marked, Realtime) { ], function (Crypto, Hash, Util, Constants, Messages, Realtime) {
var Msg = { var Msg = {
inputs: [], inputs: [],
}; };
@ -51,9 +48,8 @@ define([
}); });
}; };
Msg.getFriendChannelsList = function (common) { Msg.getFriendChannelsList = function (proxy) {
var list = []; var list = [];
var proxy = common.getProxy();
eachFriend(proxy.friends, function (friend) { eachFriend(proxy.friends, function (friend) {
list.push(friend.channel); list.push(friend.channel);
}); });
@ -61,7 +57,7 @@ define([
}; };
// TODO make this internal to the messenger // TODO make this internal to the messenger
var channels = Msg.channels = window.channels = {}; var channels = Msg.channels = {};
Msg.getLatestMessages = function () { Msg.getLatestMessages = function () {
Object.keys(channels).forEach(function (id) { Object.keys(channels).forEach(function (id) {
@ -74,8 +70,8 @@ define([
// Invitation // Invitation
// FIXME there are too many functions with this name // FIXME there are too many functions with this name
var addToFriendList = Msg.addToFriendList = function (common, data, cb) { var addToFriendList = Msg.addToFriendList = function (cfg, data, cb) {
var proxy = common.getProxy(); var proxy = cfg.proxy;
var friends = getFriendList(proxy); var friends = getFriendList(proxy);
var pubKey = data.curvePublic; // todo validata data var pubKey = data.curvePublic; // todo validata data
@ -83,19 +79,19 @@ define([
friends[pubKey] = data; friends[pubKey] = data;
Realtime.whenRealtimeSyncs(common.getRealtime(), function () { Realtime.whenRealtimeSyncs(cfg.realtime, function () {
cb(); cb();
common.pinPads([data.channel], function (e) { cfg.pinPads([data.channel], function (res) {
if (e) { console.error(e); } if (res.error) { console.error(res.error); }
}); });
}); });
common.changeDisplayName(proxy[Constants.displayNameKey]); cfg.updateMetadata();
}; };
/* Used to accept friend requests within apps other than /contacts/ */ /* Used to accept friend requests within apps other than /contacts/ */
Msg.addDirectMessageHandler = function (common) { Msg.addDirectMessageHandler = function (cfg) {
var network = common.getNetwork(); var network = cfg.network;
var proxy = common.getProxy(); var proxy = cfg.proxy;
if (!network) { return void console.error('Network not ready'); } if (!network) { return void console.error('Network not ready'); }
network.on('message', function (message, sender) { network.on('message', function (message, sender) {
var msg; var msg;
@ -138,8 +134,7 @@ define([
var confirmMsg = Messages._getKey('contacts_request', [ var confirmMsg = Messages._getKey('contacts_request', [
Util.fixHTML(msgData.displayName) Util.fixHTML(msgData.displayName)
]); ]);
common.onFriendRequest(confirmMsg, todo); cfg.friendRequest(confirmMsg, todo);
//UI.confirm(confirmMsg, todo, null, true);
return; return;
} }
if (msg[0] === "FRIEND_REQ_OK") { if (msg[0] === "FRIEND_REQ_OK") {
@ -147,14 +142,14 @@ define([
if (idx !== -1) { pendingRequests.splice(idx, 1); } if (idx !== -1) { pendingRequests.splice(idx, 1); }
// FIXME clarify this function's name // FIXME clarify this function's name
addToFriendList(common, msgData, function (err) { addToFriendList(cfg, msgData, function (err) {
if (err) { if (err) {
return void common.onFriendComplete({ return void cfg.friendComplete({
logText: Messages.contacts_addError, logText: Messages.contacts_addError,
netfluxId: sender netfluxId: sender
}); });
} }
common.onFriendComplete({ cfg.friendComplete({
logText: Messages.contacts_added, logText: Messages.contacts_added,
netfluxId: sender netfluxId: sender
}); });
@ -167,24 +162,24 @@ define([
if (msg[0] === "FRIEND_REQ_NOK") { if (msg[0] === "FRIEND_REQ_NOK") {
var i = pendingRequests.indexOf(sender); var i = pendingRequests.indexOf(sender);
if (i !== -1) { pendingRequests.splice(i, 1); } if (i !== -1) { pendingRequests.splice(i, 1); }
common.onFriendComplete({ cfg.friendComplete({
logText: Messages.contacts_rejected, logText: Messages.contacts_rejected,
netfluxId: sender netfluxId: sender
}); });
common.changeDisplayName(proxy[Constants.displayNameKey]); cfg.updateMetadata();
return; return;
} }
if (msg[0] === "FRIEND_REQ_ACK") { if (msg[0] === "FRIEND_REQ_ACK") {
var data = pending[sender]; var data = pending[sender];
if (!data) { return; } if (!data) { return; }
addToFriendList(common, data, function (err) { addToFriendList(cfg, data, function (err) {
if (err) { if (err) {
return void common.onFriendComplete({ return void cfg.friendComplete({
logText: Messages.contacts_addError, logText: Messages.contacts_addError,
netfluxId: sender netfluxId: sender
}); });
} }
common.onFriendComplete({ cfg.friendComplete({
logText: Messages.contacts_added, logText: Messages.contacts_added,
netfluxId: sender netfluxId: sender
}); });
@ -198,17 +193,14 @@ define([
}); });
}; };
Msg.getPending = function () { Msg.inviteFromUserlist = function (cfg, data, cb) {
return pendingRequests; var network = cfg.network;
}; var netfluxId = data.netfluxId;
var parsed = Hash.parsePadUrl(data.href);
Msg.inviteFromUserlist = function (common, netfluxId) {
var network = common.getNetwork();
var parsed = Hash.parsePadUrl(window.location.href);
if (!parsed.hashData) { return; } if (!parsed.hashData) { return; }
// Message // Message
var chan = parsed.hashData.channel; var chan = parsed.hashData.channel;
var myData = createData(common.getProxy()); var myData = createData(cfg.proxy);
var msg = ["FRIEND_REQ", chan, myData]; var msg = ["FRIEND_REQ", chan, myData];
// Encryption // Encryption
var keyStr = parsed.hashData.key; var keyStr = parsed.hashData.key;
@ -218,12 +210,10 @@ define([
// Send encrypted message // Send encrypted message
if (pendingRequests.indexOf(netfluxId) === -1) { if (pendingRequests.indexOf(netfluxId) === -1) {
pendingRequests.push(netfluxId); pendingRequests.push(netfluxId);
var proxy = common.getProxy(); cfg.updateMetadata(); // redraws the userlist in pad
// this redraws the userlist after a change has occurred
// TODO rename this function to reflect its purpose
common.changeDisplayName(proxy[Constants.displayNameKey]);
} }
network.sendto(netfluxId, msgStr); network.sendto(netfluxId, msgStr);
cb();
}; };
return Msg; return Msg;

@ -1,18 +1,6 @@
define([ define([], function () {
//'/customize/application_config.js',
//'/customize/messages.js',
//'/common/common-interface.js',
], function (/*AppConfig, Messages, UI*/) {
var common = {}; var common = {};
//common.infiniteSpinnerDetected = false;
//var BAD_STATE_TIMEOUT = typeof(AppConfig.badStateTimeout) === 'number'?
// AppConfig.badStateTimeout: 30000;
//var connected = false;
//var intr;
//var infiniteSpinnerHandlers = [];
/* /*
TODO make this not blow up when disconnected or lagging... TODO make this not blow up when disconnected or lagging...
*/ */
@ -20,7 +8,7 @@ define([
if (typeof(realtime.getAuthDoc) !== 'function') { if (typeof(realtime.getAuthDoc) !== 'function') {
return void console.error('improper use of this function'); return void console.error('improper use of this function');
} }
self.setTimeout(function () { setTimeout(function () {
if (realtime.getAuthDoc() === realtime.getUserDoc()) { if (realtime.getAuthDoc() === realtime.getUserDoc()) {
return void cb(); return void cb();
} else { } else {
@ -29,38 +17,5 @@ define([
}, 0); }, 0);
}; };
/*
common.beginDetectingInfiniteSpinner = function (realtime) {
if (intr) { return; }
intr = window.setInterval(function () {
var l;
try {
l = realtime.getLag();
} catch (e) {
throw new Error("ChainPad.getLag() does not exist, please `bower update`");
}
if (l.lag < BAD_STATE_TIMEOUT || !connected) { return; }
realtime.abort();
// don't launch more than one popup
if (common.infiniteSpinnerDetected) { return; }
infiniteSpinnerHandlers.forEach(function (ish) { ish(); });
// inform the user their session is in a bad state
UI.confirm(Messages.realtime_unrecoverableError, function (yes) {
if (!yes) { return; }
window.parent.location.reload();
});
common.infiniteSpinnerDetected = true;
}, 2000);
};
*/
//common.onInfiniteSpinner = function (f) { infiniteSpinnerHandlers.push(f); };
/*common.setConnectionState = function (bool) {
if (typeof(bool) !== 'boolean') { return; }
connected = bool;
};*/
return common; return common;
}); });

@ -73,12 +73,12 @@ define([
realtime.contentUpdate(doc); realtime.contentUpdate(doc);
var to = self.setTimeout(function () { var to = setTimeout(function () {
cb(new Error("Timeout")); cb(new Error("Timeout"));
}, 5000); }, 5000);
Realtime.whenRealtimeSyncs(realtime, function () { Realtime.whenRealtimeSyncs(realtime, function () {
self.clearTimeout(to); clearTimeout(to);
realtime.abort(); realtime.abort();
finish(Session, void 0); finish(Session, void 0);
}); });

@ -2,7 +2,6 @@ define([
'jquery', 'jquery',
'/api/config', '/api/config',
'/customize/messages.js', '/customize/messages.js',
'/common/fsStore.js',
'/common/common-util.js', '/common/common-util.js',
'/common/common-hash.js', '/common/common-hash.js',
'/common/common-messaging.js', '/common/common-messaging.js',
@ -16,7 +15,7 @@ define([
'/common/pinpad.js', '/common/pinpad.js',
'/customize/application_config.js', '/customize/application_config.js',
'/bower_components/nthen/index.js', '/bower_components/nthen/index.js',
], function ($, Config, Messages, Store, Util, Hash, ], function ($, Config, Messages, Util, Hash,
Messaging, Realtime, Language, Constants, Feedback, LocalStore, AStore, Messaging, Realtime, Language, Constants, Feedback, LocalStore, AStore,
Pinpad, AppConfig, Nthen) { Pinpad, AppConfig, Nthen) {
@ -49,24 +48,6 @@ define([
var PINNING_ENABLED = AppConfig.enablePinning; var PINNING_ENABLED = AppConfig.enablePinning;
var store;
var rpc;
var anon_rpc;
var getProxy = common.getProxy = function () {
if (store && store.getProxy()) {
return store.getProxy().proxy;
}
};
var getNetwork = common.getNetwork = function () {
if (store) {
if (store.getProxy() && store.getProxy().info) {
return store.getProxy().info.network;
}
}
return;
};
// RESTRICTED // RESTRICTED
// Settings only // Settings only
common.getUserObject = function (cb) { common.getUserObject = function (cb) {
@ -116,7 +97,27 @@ define([
value: profile value: profile
}, function () {}); }, function () {});
}; };
common.setAvatar = function (data, cb) {
var postData = {
key: ['profile', 'avatar']
};
// If we don't have "data", it means we want to remove the avatar and we should not have a
// "postData.value", even set to undefined (JSON.stringify transforms undefined to null)
if (data) { postData.value = data; }
postMessage("SET", postData, cb);
};
// Todo
common.getTodoHash = function (cb) {
postMessage("GET", ['todo'], function (obj) {
cb(obj);
});
};
common.setTodoHash = function (hash) {
postMessage("SET", {
key: ['todo'],
value: hash
}, function () {});
};
// REFACTOR pull language directly? // REFACTOR pull language directly?
@ -127,7 +128,6 @@ define([
Language.setLanguage(l, null, cb); Language.setLanguage(l, null, cb);
}; };
// REAFCTOR store.getProfile should be store.get(['profile'])
common.getMetadata = function (cb) { common.getMetadata = function (cb) {
postMessage("GET_METADATA", null, function (obj) { postMessage("GET_METADATA", null, function (obj) {
if (obj.error) { return void cb(obj.error); } if (obj.error) { return void cb(obj.error); }
@ -135,37 +135,6 @@ define([
}); });
}; };
var getRealtime = common.getRealtime = function () {
if (store && store.getProxy() && store.getProxy().info) {
return store.getProxy().info.realtime;
}
return;
};
// TODO not needed with async store
common.hasSigningKeys = function (proxy) {
return typeof(proxy) === 'object' &&
typeof(proxy.edPrivate) === 'string' &&
typeof(proxy.edPublic) === 'string';
};
// TODO not needed with async store
common.hasCurveKeys = function (proxy) {
return typeof(proxy) === 'object' &&
typeof(proxy.curvePrivate) === 'string' &&
typeof(proxy.curvePublic) === 'string';
};
var makePad = common.makePad = function (href, title) {
var now = +new Date();
return {
href: href,
atime: now,
ctime: now,
title: title || Hash.getDefaultName(Hash.parsePadUrl(href)),
};
};
common.setDisplayName = function (value, cb) { common.setDisplayName = function (value, cb) {
postMessage("SET_DISPLAY_NAME", value, cb); postMessage("SET_DISPLAY_NAME", value, cb);
}; };
@ -214,7 +183,7 @@ define([
// Tags // Tags
common.resetTags = function (href, tags, cb) { common.resetTags = function (href, tags, cb) {
// set pad attribute // set pad attribute
cb = cb || $.noop; cb = cb || function () {};
if (!Array.isArray(tags)) { return void cb('INVALID_TAGS'); } if (!Array.isArray(tags)) { return void cb('INVALID_TAGS'); }
common.setPadAttribute('tags', tags.slice(), cb, href); common.setPadAttribute('tags', tags.slice(), cb, href);
}; };
@ -350,29 +319,15 @@ define([
}); });
}; };
common.arePinsSynced = function (cb) {
postMessage("ARE_PINS_SYNCED", null, function (obj) {
if (obj.error) { return void cb(obj.error); }
cb();
});
};
common.resetPins = function (cb) {
postMessage("RESET_PINS", null, function (obj) {
if (obj.error) { return void cb(obj.error); }
cb();
});
};
common.pinPads = function (pads, cb) { common.pinPads = function (pads, cb) {
postMessage("PIN_PADS", {pads: pads}, function (obj) { postMessage("PIN_PADS", pads, function (obj) {
if (obj.error) { return void cb(obj.error); } if (obj.error) { return void cb(obj.error); }
cb(); cb();
}); });
}; };
common.unpinPads = function (pads, cb) { common.unpinPads = function (pads, cb) {
postMessage("UNPIN_PADS", {pads: pads}, function (obj) { postMessage("UNPIN_PADS", pads, function (obj) {
if (obj.error) { return void cb(obj.error); } if (obj.error) { return void cb(obj.error); }
cb(); cb();
}); });
@ -392,14 +347,14 @@ define([
msg: msg, msg: msg,
data: data data: data
}, function (obj) { }, function (obj) {
if (obj.error) { return void cb(obj.error); } if (obj && obj.error) { return void cb(obj.error); }
cb(); cb(null, obj);
}); });
}; };
common.getFileSize = function (href, cb) { common.getFileSize = function (href, cb) {
postMessage("GET_FILE_SIZE", {href: href}, function (obj) { postMessage("GET_FILE_SIZE", {href: href}, function (obj) {
if (obj.error) { return void cb(obj.error); } if (obj && obj.error) { return void cb(obj.error); }
cb(undefined, obj.size); cb(undefined, obj.size);
}); });
}; };
@ -473,17 +428,29 @@ define([
}); });
}; };
// Messaging
common.inviteFromUserlist = function (netfluxId, cb) {
postMessage("INVITE_FROM_USERLIST", {
netfluxId: netfluxId,
href: window.location.href
}, function (obj) {
if (obj.error) { return void cb(obj.error); }
cb();
});
};
// HERE // HERE
common.getShareHashes = function (secret, cb) { common.getShareHashes = function (secret, cb) {
var hashes;
if (!window.location.hash) { if (!window.location.hash) {
var hashes = Hash.getHashes(secret.channel, secret); hashes = Hash.getHashes(secret.channel, secret);
return void cb(null, hashes); return void cb(null, hashes);
} }
var parsed = Hash.parsePadUrl(window.location.href); var parsed = Hash.parsePadUrl(window.location.href);
if (!parsed.type || !parsed.hashData) { return void cb('E_INVALID_HREF'); } if (!parsed.type || !parsed.hashData) { return void cb('E_INVALID_HREF'); }
if (parsed.type === 'file') { secret.channel = Util.base64ToHex(secret.channel); } if (parsed.type === 'file') { secret.channel = Util.base64ToHex(secret.channel); }
var hashes = Hash.getHashes(secret.channel, secret); hashes = Hash.getHashes(secret.channel, secret);
if (!hashes.editHash && !hashes.viewHash && parsed.hashData && !parsed.hashData.mode) { if (!hashes.editHash && !hashes.viewHash && parsed.hashData && !parsed.hashData.mode) {
// It means we're using an old hash // It means we're using an old hash
@ -492,7 +459,7 @@ define([
} }
postMessage("GET_STRONGER_HASH", { postMessage("GET_STRONGER_HASH", {
href: href href: window.location.href
}, function (hash) { }, function (hash) {
if (hash) { hashes.editHash = hash; } if (hash) { hashes.editHash = hash; }
cb(null, hashes); cb(null, hashes);
@ -555,6 +522,16 @@ define([
if (localToken !== data.token) { requestLogin(); } if (localToken !== data.token) { requestLogin(); }
break; break;
} }
case 'Q_FRIEND_REQUEST': {
if (!common.onFriendRequest) { break; }
common.onFriendRequest(data, cb);
break;
}
case 'EV_FRIEND_COMPLETE': {
if (!common.onFriendComplete) { break; }
common.onFriendComplete(data);
break;
}
} }
}; };
@ -664,8 +641,10 @@ define([
if (PINNING_ENABLED && LocalStore.isLoggedIn()) { if (PINNING_ENABLED && LocalStore.isLoggedIn()) {
console.log("logged in. pads will be pinned"); console.log("logged in. pads will be pinned");
postMessage("INIT_RPC", null, waitFor(function () { postMessage("INIT_RPC", null, waitFor(function (obj) {
console.log('RPC handshake complete'); console.log('RPC handshake complete');
if (obj.error) { return; }
localStorage.plan = obj.plan;
})); }));
} else if (PINNING_ENABLED) { } else if (PINNING_ENABLED) {
console.log('not logged in. pads will not be pinned'); console.log('not logged in. pads will not be pinned');
@ -703,9 +682,9 @@ define([
}()); }());
// MAGIC that happens implicitly // MAGIC that happens implicitly
$(function () { /*$(function () {
Language.applyTranslation(); Language.applyTranslation();
}); });*/
return common; return common;
}); });

@ -315,7 +315,7 @@ define([
exp.realtime = rt.realtime; exp.realtime = rt.realtime;
exp.proxy = rt.proxy; exp.proxy = rt.proxy;
exp.loggedIn = Cryptpad.isLoggedIn() exp.loggedIn = Cryptpad.isLoggedIn();
rt.proxy.on('create', function (info) { rt.proxy.on('create', function (info) {
exp.info = info; exp.info = info;
if (!LocalStore.getUserHash()) { if (!LocalStore.getUserHash()) {

@ -6,24 +6,17 @@ define([
'/common/common-constants.js', '/common/common-constants.js',
'/common/common-feedback.js', '/common/common-feedback.js',
'/common/common-realtime.js', '/common/common-realtime.js',
'/common/common-messaging.js',
'/common/outer/network-config.js', '/common/outer/network-config.js',
'/bower_components/chainpad-crypto/crypto.js?v=0.1.5', '/bower_components/chainpad-crypto/crypto.js?v=0.1.5',
'/bower_components/chainpad/chainpad.dist.js', '/bower_components/chainpad/chainpad.dist.js',
'/bower_components/chainpad-listmap/chainpad-listmap.js', '/bower_components/chainpad-listmap/chainpad-listmap.js',
], function (UserObject, Migrate, Hash, Util, Constants, Feedback, Realtime, NetConfig, ], function (UserObject, Migrate, Hash, Util, Constants, Feedback, Realtime, Messaging, NetConfig,
Crypto, ChainPad, Listmap) { Crypto, ChainPad, Listmap) {
var Store = {}; var Store = {};
var postMessage = function (cmd, data, cb) {}; var postMessage = function () {};
var tryParsing = function (x) {
try { return JSON.parse(x); }
catch (e) {
console.error(e);
return null;
}
};
var storeHash; var storeHash;
@ -43,7 +36,11 @@ define([
var key = path.pop(); var key = path.pop();
var obj = Util.find(store.proxy, path); var obj = Util.find(store.proxy, path);
if (!obj || typeof(obj) !== "object") { return void cb({error: 'INVALID_PATH'}); } if (!obj || typeof(obj) !== "object") { return void cb({error: 'INVALID_PATH'}); }
obj[key] = data.value; if (typeof data.value === "undefined") {
delete obj[key];
} else {
obj[key] = data.value;
}
onSync(cb); onSync(cb);
}; };
@ -82,11 +79,10 @@ define([
if (avatarChan) { list.push(avatarChan); } if (avatarChan) { list.push(avatarChan); }
} }
// TODO if (store.proxy.friends) {
/*if (store.proxy.friends) { var fList = Messaging.getFriendChannelsList(store.proxy);
var fList = Messaging.getFriendChannelsList(common);
list = list.concat(fList); list = list.concat(fList);
}*/ }
list.push(Util.base64ToHex(userChannel)); list.push(Util.base64ToHex(userChannel));
list.sort(); list.sort();
@ -102,34 +98,13 @@ define([
/////////////////////// RPC ////////////////////////////////////// /////////////////////// RPC //////////////////////////////////////
////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////
Store.arePinsSynced = function (cb) {
if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); }
var list = getCanonicalChannelList();
var local = Hash.hashChannelList(list);
store.rpc.getServerHash(function (e, hash) {
if (e) { return void cb({error: e}); }
cb({synced: hash === local});
});
};
Store.resetPins = function (data, cb) {
if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); }
var list = getCanonicalChannelList();
store.rpc.reset(list, function (e, hash) {
if (e) { return void cb({error: e}); }
cb({hash: hash});
});
};
Store.pinPads = function (data, cb) { Store.pinPads = function (data, cb) {
if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); } if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); }
if (typeof(cb) !== 'function') { if (typeof(cb) !== 'function') {
console.error('expected a callback'); console.error('expected a callback');
} }
store.rpc.pin(data.pads, function (e, hash) { store.rpc.pin(data, function (e, hash) {
if (e) { return void cb({error: e}); } if (e) { return void cb({error: e}); }
cb({hash: hash}); cb({hash: hash});
}); });
@ -138,7 +113,7 @@ define([
Store.unpinPads = function (data, cb) { Store.unpinPads = function (data, cb) {
if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); } if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); }
store.rpc.unpin(data.pads, function (e, hash) { store.rpc.unpin(data, function (e, hash) {
if (e) { return void cb({error: e}); } if (e) { return void cb({error: e}); }
cb({hash: hash}); cb({hash: hash});
}); });
@ -158,7 +133,7 @@ define([
}; };
// Update for all users from accounts and return current user limits // Update for all users from accounts and return current user limits
Store.updatePinLimit = function (cb) { Store.updatePinLimit = function (data, cb) {
if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); } if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); }
store.rpc.updatePinLimits(function (e, limit, plan, note) { store.rpc.updatePinLimits(function (e, limit, plan, note) {
if (e) { return void cb({error: e}); } if (e) { return void cb({error: e}); }
@ -169,7 +144,7 @@ define([
}); });
}; };
// Get current user limits // Get current user limits
Store.getPinLimit = function (cb) { Store.getPinLimit = function (data, cb) {
if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); } if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); }
var ALWAYS_REVALIDATE = true; var ALWAYS_REVALIDATE = true;
@ -189,42 +164,63 @@ define([
Store.clearOwnedChannel = function (data, cb) { Store.clearOwnedChannel = function (data, cb) {
if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); } if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); }
rpc.clearOwnedChannel(data.channel, cb); store.rpc.clearOwnedChannel(data.channel, cb);
}; };
Store.uploadComplete = function (data, cb) { Store.uploadComplete = function (data, cb) {
if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); } if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); }
rpc.uploadComplete(cb); store.rpc.uploadComplete(cb);
}; };
Store.uploadStatus = function (data, cb) { Store.uploadStatus = function (data, cb) {
if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); } if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); }
rpc.uploadStatus(data.size, cb); store.rpc.uploadStatus(data.size, cb);
}; };
Store.uploadCancel = function (data, cb) { Store.uploadCancel = function (data, cb) {
if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); } if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); }
rpc.uploadCancel(cb); store.rpc.uploadCancel(cb);
};
var arePinsSynced = function (cb) {
if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); }
var list = getCanonicalChannelList();
var local = Hash.hashChannelList(list);
store.rpc.getServerHash(function (e, hash) {
if (e) { return void cb(e); }
cb(null, hash === local);
});
};
var resetPins = function (cb) {
if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); }
var list = getCanonicalChannelList();
store.rpc.reset(list, function (e, hash) {
if (e) { return void cb(e); }
cb(null, hash);
});
}; };
Store.initRpc = function (data, cb) { Store.initRpc = function (data, cb) {
require(['/common/pinpad.js', function (Pinpad) { require(['/common/pinpad.js'], function (Pinpad) {
Pinpad.create(store.network, store.proxy, function (e, call) { Pinpad.create(store.network, store.proxy, function (e, call) {
if (e) { return void cb({error: e}); } if (e) { return void cb({error: e}); }
store.rpc = call; store.rpc = call;
common.getPinLimit(function (e, limit, plan, note) { Store.getPinLimit(null, function (obj) {
if (e) { return void console.error(e); } if (obj.error) { console.error(obj.error); }
common.account.limit = limit; account.limit = obj.limit;
localStorage.plan = common.account.plan = plan; account.plan = obj.plan;
common.account.note = note; account.note = obj.note;
cb(); cb(obj);
}); });
common.arePinsSynced(function (err, yes) { arePinsSynced(function (err, yes) {
if (!yes) { if (!yes) {
common.resetPins(function (err) { resetPins(function (err) {
if (err) { return console.error(err); } if (err) { return console.error(err); }
console.log('RESET DONE'); console.log('RESET DONE');
}); });
@ -239,10 +235,14 @@ define([
////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////
Store.anonRpcMsg = function (data, cb) { Store.anonRpcMsg = function (data, cb) {
if (!store.anon_rpc) { return void cb({error: 'ANON_RPC_NOT_READY'}); } if (!store.anon_rpc) { return void cb({error: 'ANON_RPC_NOT_READY'}); }
store.anon_rpc.send(data.msg, data.data, cb); store.anon_rpc.send(data.msg, data.data, function (err, res) {
if (err) { return void cb({error: err}); }
cb(res);
});
}; };
Store.getFileSize = function (data, cb) { Store.getFileSize = function (data, cb) {
console.log(data, cb);
if (!store.anon_rpc) { return void cb({error: 'ANON_RPC_NOT_READY'}); } if (!store.anon_rpc) { return void cb({error: 'ANON_RPC_NOT_READY'}); }
var channelId = Hash.hrefToHexChannelId(data.href); var channelId = Hash.hrefToHexChannelId(data.href);
@ -367,19 +367,19 @@ define([
if (typeof attr === "string") { if (typeof attr === "string") {
console.error('DEPRECATED: use setAttribute with an array, not a string'); console.error('DEPRECATED: use setAttribute with an array, not a string');
return { return {
obj: storeObj.settings, obj: store.proxy.settings,
key: attr key: attr
}; };
} }
if (!Array.isArray(attr)) { throw new Error("Attribute must be string or array"); } if (!Array.isArray(attr)) { return void console.error("Attribute must be string or array"); }
if (attr.length === 0) { throw new Error("Attribute can't be empty"); } if (attr.length === 0) { return void console.error("Attribute can't be empty"); }
var obj = storeObj.settings; var obj = store.proxy.settings;
attr.forEach(function (el, i) { attr.forEach(function (el, i) {
if (i === attr.length-1) { return; } if (i === attr.length-1) { return; }
if (!obj[el]) { if (!obj[el]) {
obj[el] = {}; obj[el] = {};
} }
else if (typeof obj[el] !== "object") { throw new Error("Wrong attribute"); } else if (typeof obj[el] !== "object") { return void console.error("Wrong attribute"); }
obj = obj[el]; obj = obj[el];
}); });
return { return {
@ -402,12 +402,12 @@ define([
* - value (String) * - value (String)
*/ */
Store.setPadAttribute = function (data, cb) { Store.setPadAttribute = function (data, cb) {
store.userObject.setPadAttribute(data.href, date.attr, data.value, function () { store.userObject.setPadAttribute(data.href, data.attr, data.value, function () {
onSync(cb); onSync(cb);
}); });
}; };
Store.getPadAttribute = function (data, cb) { Store.getPadAttribute = function (data, cb) {
filesOp.getPadAttribute(data.href, data.attr, function (err, val) { store.userObject.getPadAttribute(data.href, data.attr, function (err, val) {
if (err) { return void cb({error: err}); } if (err) { return void cb({error: err}); }
cb(val); cb(val);
}); });
@ -443,7 +443,7 @@ define([
cb(all); cb(all);
}; };
var makePad = common.makePad = function (href, title) { var makePad = function (href, title) {
var now = +new Date(); var now = +new Date();
return { return {
href: href, href: href,
@ -465,13 +465,13 @@ define([
// Templates // Templates
Store.getTemplates = function (data, cb) { Store.getTemplates = function (data, cb) {
var templateFiles = filesOp.getFiles(['template']); var templateFiles = store.userObject.getFiles(['template']);
var res = []; var res = [];
templateFiles.forEach(function (f) { templateFiles.forEach(function (f) {
var data = filesOp.getFileData(f); var data = store.userObject.getFileData(f);
res.push(JSON.parse(JSON.stringify(data))); res.push(JSON.parse(JSON.stringify(data)));
}); });
return res; cb(res);
}; };
// Pads // Pads
@ -496,7 +496,7 @@ define([
// Update all pads that use the same channel but with a weaker hash // Update all pads that use the same channel but with a weaker hash
// Edit > Edit (present) > View > View (present) // Edit > Edit (present) > View > View (present)
for (var id in allPads) { for (var id in allPads) {
var pad = recent[id]; var pad = allPads[id];
if (!pad.href) { continue; } if (!pad.href) { continue; }
var p2 = Hash.parsePadUrl(pad.href); var p2 = Hash.parsePadUrl(pad.href);
@ -539,7 +539,7 @@ define([
if (isStronger) { if (isStronger) {
// If we have a stronger url, remove the possible weaker from the trash. // If we have a stronger url, remove the possible weaker from the trash.
// If all of the weaker ones were in the trash, add the stronger to ROOT // If all of the weaker ones were in the trash, add the stronger to ROOT
store.userObject.restoreHref(obj.n); store.userObject.restoreHref(href);
} }
// Add the pad if it does not exist in our drive // Add the pad if it does not exist in our drive
@ -585,7 +585,7 @@ define([
}; };
// Get hashes for the share button // Get hashes for the share button
common.getStrongerHash = function (data, cb) { Store.getStrongerHash = function (data, cb) {
var allPads = Util.find(store.proxy, ['drive', 'filesData']) || {}; var allPads = Util.find(store.proxy, ['drive', 'filesData']) || {};
// If we have a stronger version in drive, add it and add a redirect button // If we have a stronger version in drive, add it and add a redirect button
@ -597,6 +597,29 @@ define([
cb(); cb();
}; };
// Messaging
var getMessagingCfg = function () {
console.log(store, store.network);
return {
proxy: store.proxy,
realtime: store.realtime,
network: store.network,
updateMetadata: function () {
postMessage("UPDATE_METADATA");
},
pinPads: Store.pinPads,
friendComplete: function (data, cb) {
postMessage("Q_FRIEND_COMPLETE", data, cb);
},
friendRequest: function (data) {
postMessage("EV_FRIEND_REQUEST", data);
},
};
};
Store.inviteFromUserlist = function (data, cb) {
var messagingCfg = getMessagingCfg();
Messaging.inviteFromUserlist(messagingCfg, data, cb);
};
var onReady = function (returned, cb) { var onReady = function (returned, cb) {
var proxy = store.proxy; var proxy = store.proxy;
@ -605,9 +628,9 @@ define([
loggedIn: store.loggedIn loggedIn: store.loggedIn
}); });
var todo = function () { var todo = function () {
fo.fixFiles(); userObject.fixFiles();
Migrate(proxy, Cryptpad); Migrate(proxy);
var requestLogin = function () { var requestLogin = function () {
postMessage("REQUEST_LOGIN"); postMessage("REQUEST_LOGIN");
@ -624,7 +647,7 @@ define([
} }
returned[Constants.tokenKey] = proxy[Constants.tokenKey]; returned[Constants.tokenKey] = proxy[Constants.tokenKey];
if (store.data.localToken && store.data.localToken !== proxy[tokenKey]) { if (store.data.localToken && store.data.localToken !== proxy[Constants.tokenKey]) {
// the local number doesn't match that in // the local number doesn't match that in
// the user object, request that they reauthenticate. // the user object, request that they reauthenticate.
return void requestLogin(); return void requestLogin();
@ -665,6 +688,9 @@ define([
// Trigger userlist update when the friendlist has changed // Trigger userlist update when the friendlist has changed
postMessage("UPDATE_METADATA"); postMessage("UPDATE_METADATA");
}); });
proxy.on('change', ['settings'], function () {
postMessage("UPDATE_METADATA");
});
proxy.on('change', [Constants.tokenKey], function () { proxy.on('change', [Constants.tokenKey], function () {
postMessage("UPDATE_TOKEN", { data: proxy[Constants.tokenKey] }); postMessage("UPDATE_TOKEN", { data: proxy[Constants.tokenKey] });
}); });
@ -692,14 +718,13 @@ define([
classic: true, classic: true,
}; };
var rt = Listmap.create(listmapConfig); var rt = Listmap.create(listmapConfig);
store.proxy = rt.proxy, store.proxy = rt.proxy;
store.realtime = rt.realtime;
store.network = rt.network;
store.loggedIn = typeof(data.userHash) !== "undefined"; store.loggedIn = typeof(data.userHash) !== "undefined";
var returned = {}; var returned = {};
rt.proxy.on('create', function (info) { rt.proxy.on('create', function (info) {
exp.info = info; store.realtime = info.realtime;
store.network = info.network;
if (!data.userHash) { if (!data.userHash) {
returned.anonHash = Hash.getEditHashFromKeys(info.channel, secret.keys); returned.anonHash = Hash.getEditHashFromKeys(info.channel, secret.keys);
} }
@ -743,18 +768,24 @@ define([
}); });
} }
initialized = true; initialized = true;
postMessage = function (cmd, data, cb) { postMessage = function (cmd, d, cb) {
setTimeout(function () { setTimeout(function () {
data.query(cmd, data, cb); // TODO temporary, will be rzplaced by webworker channel data.query(cmd, d, cb); // TODO temporary, will be rzplaced by webworker channel
}); });
}; };
store.data = data;
connect(data, function (ret) { connect(data, function (ret) {
if (Object.keys(store.proxy).length === 1) { if (Object.keys(store.proxy).length === 1) {
Feedback.send("FIRST_APP_USE", true); Feedback.send("FIRST_APP_USE", true);
} }
callback(ret); callback(ret);
var messagingCfg = getMessagingCfg();
Messaging.addDirectMessageHandler(messagingCfg);
}); });
}; };

@ -40,12 +40,6 @@ define([
case 'UPLOAD_CANCEL': { case 'UPLOAD_CANCEL': {
Store.uploadCancel(data, cb); break; Store.uploadCancel(data, cb); break;
} }
case 'ARE_PINS_SYNCED': {
Store.arePinsSynced(data, cb); break;
}
case 'RESET_PINS': {
Store.resetPins(data, cb); break;
}
case 'PIN_PADS': { case 'PIN_PADS': {
Store.pinPads(data, cb); break; Store.pinPads(data, cb); break;
} }
@ -117,6 +111,11 @@ define([
case 'GET_STRONGER_HASH': { case 'GET_STRONGER_HASH': {
Store.getStrongerHash(data, cb); break; Store.getStrongerHash(data, cb); break;
} }
// Messaging
case 'INVITE_FROM_USERLIST': {
Store.inviteFromUserlist(data, cb); break;
}
default: { default: {
break; break;

@ -3,13 +3,13 @@ define([
], function (Rpc) { ], function (Rpc) {
var create = function (network, proxy, cb) { var create = function (network, proxy, cb) {
if (!network) { if (!network) {
self.setTimeout(function () { setTimeout(function () {
cb('INVALID_NETWORK'); cb('INVALID_NETWORK');
}); });
return; return;
} }
if (!proxy) { if (!proxy) {
self.setTimeout(function () { setTimeout(function () {
cb('INVALID_PROXY'); cb('INVALID_PROXY');
}); });
return; return;
@ -19,7 +19,7 @@ define([
var edPublic = proxy.edPublic; var edPublic = proxy.edPublic;
if (!(edPrivate && edPublic)) { if (!(edPrivate && edPublic)) {
self.setTimeout(function () { setTimeout(function () {
cb('INVALID_KEYS'); cb('INVALID_KEYS');
}); });
return; return;
@ -39,7 +39,7 @@ define([
// you can ask the server to pin a particular channel for you // you can ask the server to pin a particular channel for you
exp.pin = function (channels, cb) { exp.pin = function (channels, cb) {
if (!Array.isArray(channels)) { if (!Array.isArray(channels)) {
self.setTimeout(function () { setTimeout(function () {
cb('[TypeError] pin expects an array'); cb('[TypeError] pin expects an array');
}); });
return; return;
@ -50,7 +50,7 @@ define([
// you can also ask to unpin a particular channel // you can also ask to unpin a particular channel
exp.unpin = function (channels, cb) { exp.unpin = function (channels, cb) {
if (!Array.isArray(channels)) { if (!Array.isArray(channels)) {
self.setTimeout(function () { setTimeout(function () {
cb('[TypeError] pin expects an array'); cb('[TypeError] pin expects an array');
}); });
return; return;
@ -71,7 +71,7 @@ define([
// if local and remote hashes don't match, send a reset // if local and remote hashes don't match, send a reset
exp.reset = function (channels, cb) { exp.reset = function (channels, cb) {
if (!Array.isArray(channels)) { if (!Array.isArray(channels)) {
self.setTimeout(function () { setTimeout(function () {
cb('[TypeError] pin expects an array'); cb('[TypeError] pin expects an array');
}); });
return; return;
@ -163,7 +163,7 @@ define([
exp.uploadStatus = function (size, cb) { exp.uploadStatus = function (size, cb) {
if (typeof(size) !== 'number') { if (typeof(size) !== 'number') {
return void self.setTimeout(function () { return void setTimeout(function () {
cb('INVALID_SIZE'); cb('INVALID_SIZE');
}); });
} }

@ -2,7 +2,7 @@ define([
'/common/common-util.js', '/common/common-util.js',
'/bower_components/tweetnacl/nacl-fast.min.js', '/bower_components/tweetnacl/nacl-fast.min.js',
], function (Util) { ], function (Util) {
var Nacl = self.nacl; var Nacl = window.nacl;
var uid = Util.uid; var uid = Util.uid;
var signMsg = function (data, signKey) { var signMsg = function (data, signKey) {
@ -140,7 +140,7 @@ types of messages:
var send = ctx.send = function (type, msg, cb) { var send = ctx.send = function (type, msg, cb) {
if (!ctx.connected && type !== 'COOKIE') { if (!ctx.connected && type !== 'COOKIE') {
return void self.setTimeout(function () { return void setTimeout(function () {
cb('DISCONNECTED'); cb('DISCONNECTED');
}); });
} }
@ -185,7 +185,7 @@ types of messages:
send.unauthenticated = function (type, msg, cb) { send.unauthenticated = function (type, msg, cb) {
if (!ctx.connected) { if (!ctx.connected) {
return void self.setTimeout(function () { return void setTimeout(function () {
cb('DISCONNECTED'); cb('DISCONNECTED');
}); });
} }
@ -276,7 +276,7 @@ types of messages:
var send = ctx.send = function (type, msg, cb) { var send = ctx.send = function (type, msg, cb) {
if (!ctx.connected) { if (!ctx.connected) {
return void self.setTimeout(function () { return void setTimeout(function () {
cb('DISCONNECTED'); cb('DISCONNECTED');
}); });
} }

@ -9,6 +9,7 @@ define([
common.start = function (cfg) { common.start = function (cfg) {
cfg = cfg || {}; cfg = cfg || {};
var realtime = !cfg.noRealtime; var realtime = !cfg.noRealtime;
var network;
var secret; var secret;
var hashes; var hashes;
var CpNfOuter; var CpNfOuter;
@ -18,7 +19,7 @@ define([
var SFrameChannel; var SFrameChannel;
var sframeChan; var sframeChan;
var FilePicker; var FilePicker;
var Messenger; //var Messenger;
var Messaging; var Messaging;
var Notifier; var Notifier;
var Utils = {}; var Utils = {};
@ -32,7 +33,7 @@ define([
'/common/cryptget.js', '/common/cryptget.js',
'/common/sframe-channel.js', '/common/sframe-channel.js',
'/filepicker/main.js', '/filepicker/main.js',
'/common/common-messenger.js', //'/common/common-messenger.js',
'/common/common-messaging.js', '/common/common-messaging.js',
'/common/common-notifier.js', '/common/common-notifier.js',
'/common/common-hash.js', '/common/common-hash.js',
@ -41,16 +42,18 @@ define([
'/common/common-constants.js', '/common/common-constants.js',
'/common/common-feedback.js', '/common/common-feedback.js',
'/common/outer/local-store.js', '/common/outer/local-store.js',
'/common/outer/network-config.js',
'/bower_components/netflux-websocket/netflux-client.js',
], waitFor(function (_CpNfOuter, _Cryptpad, _Crypto, _Cryptget, _SFrameChannel, ], waitFor(function (_CpNfOuter, _Cryptpad, _Crypto, _Cryptget, _SFrameChannel,
_FilePicker, _Messenger, _Messaging, _Notifier, _Hash, _Util, _Realtime, _FilePicker, /*_Messenger,*/ _Messaging, _Notifier, _Hash, _Util, _Realtime,
_Constants, _Feedback, _LocalStore) { _Constants, _Feedback, _LocalStore, NetConfig, Netflux) {
CpNfOuter = _CpNfOuter; CpNfOuter = _CpNfOuter;
Cryptpad = _Cryptpad; Cryptpad = _Cryptpad;
Crypto = _Crypto; Crypto = _Crypto;
Cryptget = _Cryptget; Cryptget = _Cryptget;
SFrameChannel = _SFrameChannel; SFrameChannel = _SFrameChannel;
FilePicker = _FilePicker; FilePicker = _FilePicker;
Messenger = _Messenger; //Messenger = _Messenger;
Messaging = _Messaging; Messaging = _Messaging;
Notifier = _Notifier; Notifier = _Notifier;
Utils.Hash = _Hash; Utils.Hash = _Hash;
@ -85,6 +88,12 @@ define([
sframeChan = sfc; sframeChan = sfc;
}), false, { cache: cache, localStore: localStore, language: Cryptpad.getLanguage() }); }), false, { cache: cache, localStore: localStore, language: Cryptpad.getLanguage() });
Cryptpad.ready(waitFor()); Cryptpad.ready(waitFor());
if (!cfg.newNetwork) {
Netflux.connect(NetConfig.getWebsocketURL()).then(waitFor(function (nw) {
network = nw;
}));
}
})); }));
}).nThen(function (waitFor) { }).nThen(function (waitFor) {
$('#sbox-iframe').focus(); $('#sbox-iframe').focus();
@ -123,7 +132,6 @@ define([
var parsed = Utils.Hash.parsePadUrl(window.location.href); var parsed = Utils.Hash.parsePadUrl(window.location.href);
if (!parsed.type) { throw new Error(); } if (!parsed.type) { throw new Error(); }
var defaultTitle = Utils.Hash.getDefaultName(parsed); var defaultTitle = Utils.Hash.getDefaultName(parsed);
var proxy = Cryptpad.getProxy();
var updateMeta = function () { var updateMeta = function () {
//console.log('EV_METADATA_UPDATE'); //console.log('EV_METADATA_UPDATE');
var metaObj, isTemplate; var metaObj, isTemplate;
@ -137,7 +145,7 @@ define([
isTemplate = t; isTemplate = t;
})); }));
}).nThen(function (/*waitFor*/) { }).nThen(function (/*waitFor*/) {
metaObj.doc: { metaObj.doc = {
defaultTitle: defaultTitle, defaultTitle: defaultTitle,
type: parsed.type type: parsed.type
}; };
@ -167,7 +175,6 @@ define([
}; };
Cryptpad.onMetadataChanged(updateMeta); Cryptpad.onMetadataChanged(updateMeta);
sframeChan.onReg('EV_METADATA_UPDATE', updateMeta); sframeChan.onReg('EV_METADATA_UPDATE', updateMeta);
proxy.on('change', 'settings', updateMeta);
Utils.LocalStore.onLogout(function () { Utils.LocalStore.onLogout(function () {
sframeChan.event('EV_LOGOUT'); sframeChan.event('EV_LOGOUT');
@ -285,7 +292,6 @@ define([
}; };
sframeChan.on('Q_GET_FULL_HISTORY', function (data, cb) { sframeChan.on('Q_GET_FULL_HISTORY', function (data, cb) {
var network = Cryptpad.getNetwork();
var hkn = network.historyKeeper; var hkn = network.historyKeeper;
var crypto = Crypto.createEncryptor(secret.keys); var crypto = Crypto.createEncryptor(secret.keys);
// Get the history messages and send them to the iframe // Get the history messages and send them to the iframe
@ -493,7 +499,8 @@ define([
} }
if (cfg.messaging) { if (cfg.messaging) {
var messenger = Messenger.messenger(Cryptpad); // TODO make messenger work with async store
/*var messenger = Messenger.messenger(Cryptpad);
sframeChan.on('Q_CONTACTS_GET_FRIEND_LIST', function (data, cb) { sframeChan.on('Q_CONTACTS_GET_FRIEND_LIST', function (data, cb) {
messenger.getFriendList(function (e, keys) { messenger.getFriendList(function (e, keys) {
@ -604,7 +611,7 @@ define([
sframeChan.event('EV_CONTACTS_UNFRIEND', { sframeChan.event('EV_CONTACTS_UNFRIEND', {
curvePublic: curvePublic, curvePublic: curvePublic,
}); });
}); });*/
} }
sframeChan.ready(); sframeChan.ready();
@ -628,7 +635,7 @@ define([
CpNfOuter.start({ CpNfOuter.start({
sframeChan: sframeChan, sframeChan: sframeChan,
channel: secret.channel, channel: secret.channel,
network: cfg.newNetwork || Cryptpad.getNetwork(), network: cfg.newNetwork || network,
validateKey: secret.keys.validateKey || undefined, validateKey: secret.keys.validateKey || undefined,
readOnly: readOnly, readOnly: readOnly,
crypto: Crypto.createEncryptor(secret.keys), crypto: Crypto.createEncryptor(secret.keys),

@ -122,6 +122,7 @@ define([
funcs.getFileSize = function (href, cb) { funcs.getFileSize = function (href, cb) {
var channelId = Hash.hrefToHexChannelId(href); var channelId = Hash.hrefToHexChannelId(href);
funcs.sendAnonRpcMsg("GET_FILE_SIZE", channelId, function (data) { funcs.sendAnonRpcMsg("GET_FILE_SIZE", channelId, function (data) {
console.log(data);
if (!data) { return void cb("No response"); } if (!data) { return void cb("No response"); }
if (data.error) { return void cb(data.error); } if (data.error) { return void cb(data.error); }
if (data.response && data.response.length && typeof(data.response[0]) === 'number') { if (data.response && data.response.length && typeof(data.response[0]) === 'number') {

@ -5,9 +5,7 @@ define([
'jquery', 'jquery',
'/common/requireconfig.js', '/common/requireconfig.js',
'/common/sframe-common-outer.js', '/common/sframe-common-outer.js',
'/common/outer/network-config.js', ], function (nThen, ApiConfig, $, RequireConfig, SFCommonO) {
'/bower_components/netflux-websocket/netflux-client.js',
], function (nThen, ApiConfig, $, RequireConfig, SFCommonO, NetConfig, Netflux) {
var requireConfig = RequireConfig(); var requireConfig = RequireConfig();
// Loaded in load #2 // Loaded in load #2
@ -38,10 +36,10 @@ define([
}; };
window.addEventListener('message', onMsg); window.addEventListener('message', onMsg);
}).nThen(function (/*waitFor*/) { }).nThen(function (/*waitFor*/) {
var getSecrets = function (Cryptpad, Utils) { var getSecrets = function (Cryptpad, Utils, cb) {
var hash = window.location.hash.slice(1) || Utils.LocalStore.getUserHash() || var hash = window.location.hash.slice(1) || Utils.LocalStore.getUserHash() ||
Utils.LocalStore.getFSHash(); Utils.LocalStore.getFSHash();
return Utils.Hash.getSecrets('drive', hash); cb(null, Utils.Hash.getSecrets('drive', hash));
}; };
var addRpc = function (sframeChan, Cryptpad, Utils) { var addRpc = function (sframeChan, Cryptpad, Utils) {
sframeChan.on('EV_BURN_ANON_DRIVE', function () { sframeChan.on('EV_BURN_ANON_DRIVE', function () {
@ -51,13 +49,13 @@ define([
window.location.reload(); window.location.reload();
}); });
}; };
Netflux.connect(NetConfig.getWebsocketURL()).then(function (network) { //Netflux.connect(NetConfig.getWebsocketURL()).then(function (network) {
SFCommonO.start({ SFCommonO.start({
getSecrets: getSecrets, getSecrets: getSecrets,
newNetwork: network, //newNetwork: network,
noHash: true, noHash: true,
addRpc: addRpc addRpc: addRpc
}); });
}, function (err) { console.error(err); }); //}, function (err) { console.error(err); });
}); });
}); });

@ -46,7 +46,6 @@ define([
sframeChan = sfc; sframeChan = sfc;
})); }));
}).nThen(function () { }).nThen(function () {
var proxy = Cryptpad.getProxy();
var updateMeta = function () { var updateMeta = function () {
//console.log('EV_METADATA_UPDATE'); //console.log('EV_METADATA_UPDATE');
var metaObj; var metaObj;
@ -56,7 +55,7 @@ define([
metaObj = n; metaObj = n;
})); }));
}).nThen(function (/*waitFor*/) { }).nThen(function (/*waitFor*/) {
metaObj.doc: {}; metaObj.doc = {};
var additionalPriv = { var additionalPriv = {
accountName: Utils.LocalStore.getAccountName(), accountName: Utils.LocalStore.getAccountName(),
origin: window.location.origin, origin: window.location.origin,
@ -71,7 +70,6 @@ define([
}; };
Cryptpad.onMetadataChanged(updateMeta); Cryptpad.onMetadataChanged(updateMeta);
sframeChan.onReg('EV_METADATA_UPDATE', updateMeta); sframeChan.onReg('EV_METADATA_UPDATE', updateMeta);
proxy.on('change', 'settings', updateMeta);
config.addCommonRpc(sframeChan); config.addCommonRpc(sframeChan);

@ -78,18 +78,14 @@ define([
var chanId = Utils.Hash.hrefToHexChannelId(data); var chanId = Utils.Hash.hrefToHexChannelId(data);
Cryptpad.pinPads([chanId], function (e) { Cryptpad.pinPads([chanId], function (e) {
if (e) { return void cb(e); } if (e) { return void cb(e); }
Cryptpad.getProxy().profile.avatar = data; Cryptpad.setAvatar(data, cb);
Utils.Realtime.whenRealtimeSyncs(Cryptpad.getRealtime(), function () {
cb();
});
}); });
}); });
// Removing the avatar from the profile: unpin it // Removing the avatar from the profile: unpin it
sframeChan.on('Q_PROFILE_AVATAR_REMOVE', function (data, cb) { sframeChan.on('Q_PROFILE_AVATAR_REMOVE', function (data, cb) {
var chanId = Utils.Hash.hrefToHexChannelId(data); var chanId = Utils.Hash.hrefToHexChannelId(data);
Cryptpad.unpinPads([chanId], function (e) { Cryptpad.unpinPads([chanId], function () {
delete Cryptpad.getProxy().profile.avatar; Cryptpad.setAvatar(undefined, cb);
cb(e);
}); });
}); });
}; };

@ -36,12 +36,12 @@ define([
}; };
window.addEventListener('message', onMsg); window.addEventListener('message', onMsg);
}).nThen(function (/*waitFor*/) { }).nThen(function (/*waitFor*/) {
var getSecrets = function (Cryptpad, Utils) { var getSecrets = function (Cryptpad, Utils, cb) {
var proxy = Cryptpad.getProxy(); Cryptpad.getTodoHash(function (hash) {
var hash = proxy.todo || Utils.Hash.createRandomHash(); var nHash = hash || Utils.Hash.createRandomHash();
if (!proxy.todo) { proxy.todo = hash; } if (!hash) { Cryptpad.setTodoHash(nHash); }
cb(null, Utils.Hash.getSecrets('todo', hash));
return Utils.Hash.getSecrets('todo', hash); });
}; };
SFCommonO.start({ SFCommonO.start({
getSecrets: getSecrets, getSecrets: getSecrets,

Loading…
Cancel
Save