diff --git a/www/common/common-messaging.js b/www/common/common-messaging.js index da5ac004a..13d132219 100644 --- a/www/common/common-messaging.js +++ b/www/common/common-messaging.js @@ -1,15 +1,12 @@ define([ - 'jquery', '/bower_components/chainpad-crypto/crypto.js', - '/common/curve.js', '/common/common-hash.js', '/common/common-util.js', '/common/common-constants.js', '/customize/messages.js', - '/bower_components/marked/marked.min.js', '/common/common-realtime.js', -], function ($, Crypto, Curve, Hash, Util, Constants, Messages, Marked, Realtime) { +], function (Crypto, Hash, Util, Constants, Messages, Realtime) { var Msg = { inputs: [], }; @@ -51,9 +48,8 @@ define([ }); }; - Msg.getFriendChannelsList = function (common) { + Msg.getFriendChannelsList = function (proxy) { var list = []; - var proxy = common.getProxy(); eachFriend(proxy.friends, function (friend) { list.push(friend.channel); }); @@ -61,7 +57,7 @@ define([ }; // TODO make this internal to the messenger - var channels = Msg.channels = window.channels = {}; + var channels = Msg.channels = {}; Msg.getLatestMessages = function () { Object.keys(channels).forEach(function (id) { @@ -74,8 +70,8 @@ define([ // Invitation // FIXME there are too many functions with this name - var addToFriendList = Msg.addToFriendList = function (common, data, cb) { - var proxy = common.getProxy(); + var addToFriendList = Msg.addToFriendList = function (cfg, data, cb) { + var proxy = cfg.proxy; var friends = getFriendList(proxy); var pubKey = data.curvePublic; // todo validata data @@ -83,19 +79,19 @@ define([ friends[pubKey] = data; - Realtime.whenRealtimeSyncs(common.getRealtime(), function () { + Realtime.whenRealtimeSyncs(cfg.realtime, function () { cb(); - common.pinPads([data.channel], function (e) { - if (e) { console.error(e); } + cfg.pinPads([data.channel], function (res) { + if (res.error) { console.error(res.error); } }); }); - common.changeDisplayName(proxy[Constants.displayNameKey]); + cfg.updateMetadata(); }; /* Used to accept friend requests within apps other than /contacts/ */ - Msg.addDirectMessageHandler = function (common) { - var network = common.getNetwork(); - var proxy = common.getProxy(); + Msg.addDirectMessageHandler = function (cfg) { + var network = cfg.network; + var proxy = cfg.proxy; if (!network) { return void console.error('Network not ready'); } network.on('message', function (message, sender) { var msg; @@ -138,8 +134,7 @@ define([ var confirmMsg = Messages._getKey('contacts_request', [ Util.fixHTML(msgData.displayName) ]); - common.onFriendRequest(confirmMsg, todo); - //UI.confirm(confirmMsg, todo, null, true); + cfg.friendRequest(confirmMsg, todo); return; } if (msg[0] === "FRIEND_REQ_OK") { @@ -147,14 +142,14 @@ define([ if (idx !== -1) { pendingRequests.splice(idx, 1); } // FIXME clarify this function's name - addToFriendList(common, msgData, function (err) { + addToFriendList(cfg, msgData, function (err) { if (err) { - return void common.onFriendComplete({ + return void cfg.friendComplete({ logText: Messages.contacts_addError, netfluxId: sender }); } - common.onFriendComplete({ + cfg.friendComplete({ logText: Messages.contacts_added, netfluxId: sender }); @@ -167,24 +162,24 @@ define([ if (msg[0] === "FRIEND_REQ_NOK") { var i = pendingRequests.indexOf(sender); if (i !== -1) { pendingRequests.splice(i, 1); } - common.onFriendComplete({ + cfg.friendComplete({ logText: Messages.contacts_rejected, netfluxId: sender }); - common.changeDisplayName(proxy[Constants.displayNameKey]); + cfg.updateMetadata(); return; } if (msg[0] === "FRIEND_REQ_ACK") { var data = pending[sender]; if (!data) { return; } - addToFriendList(common, data, function (err) { + addToFriendList(cfg, data, function (err) { if (err) { - return void common.onFriendComplete({ + return void cfg.friendComplete({ logText: Messages.contacts_addError, netfluxId: sender }); } - common.onFriendComplete({ + cfg.friendComplete({ logText: Messages.contacts_added, netfluxId: sender }); @@ -198,17 +193,14 @@ define([ }); }; - Msg.getPending = function () { - return pendingRequests; - }; - - Msg.inviteFromUserlist = function (common, netfluxId) { - var network = common.getNetwork(); - var parsed = Hash.parsePadUrl(window.location.href); + Msg.inviteFromUserlist = function (cfg, data, cb) { + var network = cfg.network; + var netfluxId = data.netfluxId; + var parsed = Hash.parsePadUrl(data.href); if (!parsed.hashData) { return; } // Message var chan = parsed.hashData.channel; - var myData = createData(common.getProxy()); + var myData = createData(cfg.proxy); var msg = ["FRIEND_REQ", chan, myData]; // Encryption var keyStr = parsed.hashData.key; @@ -218,12 +210,10 @@ define([ // Send encrypted message if (pendingRequests.indexOf(netfluxId) === -1) { pendingRequests.push(netfluxId); - var proxy = common.getProxy(); - // this redraws the userlist after a change has occurred - // TODO rename this function to reflect its purpose - common.changeDisplayName(proxy[Constants.displayNameKey]); + cfg.updateMetadata(); // redraws the userlist in pad } network.sendto(netfluxId, msgStr); + cb(); }; return Msg; diff --git a/www/common/common-realtime.js b/www/common/common-realtime.js index 87a92064b..21c0728e2 100644 --- a/www/common/common-realtime.js +++ b/www/common/common-realtime.js @@ -1,18 +1,6 @@ -define([ - //'/customize/application_config.js', - //'/customize/messages.js', - //'/common/common-interface.js', -], function (/*AppConfig, Messages, UI*/) { +define([], function () { 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... */ @@ -20,7 +8,7 @@ define([ if (typeof(realtime.getAuthDoc) !== 'function') { return void console.error('improper use of this function'); } - self.setTimeout(function () { + setTimeout(function () { if (realtime.getAuthDoc() === realtime.getUserDoc()) { return void cb(); } else { @@ -29,38 +17,5 @@ define([ }, 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; }); diff --git a/www/common/cryptget.js b/www/common/cryptget.js index 12bdd195e..686c69884 100644 --- a/www/common/cryptget.js +++ b/www/common/cryptget.js @@ -73,12 +73,12 @@ define([ realtime.contentUpdate(doc); - var to = self.setTimeout(function () { + var to = setTimeout(function () { cb(new Error("Timeout")); }, 5000); Realtime.whenRealtimeSyncs(realtime, function () { - self.clearTimeout(to); + clearTimeout(to); realtime.abort(); finish(Session, void 0); }); diff --git a/www/common/cryptpad-common.js b/www/common/cryptpad-common.js index d558f9e28..f1b0eff31 100644 --- a/www/common/cryptpad-common.js +++ b/www/common/cryptpad-common.js @@ -2,7 +2,6 @@ define([ 'jquery', '/api/config', '/customize/messages.js', - '/common/fsStore.js', '/common/common-util.js', '/common/common-hash.js', '/common/common-messaging.js', @@ -16,7 +15,7 @@ define([ '/common/pinpad.js', '/customize/application_config.js', '/bower_components/nthen/index.js', -], function ($, Config, Messages, Store, Util, Hash, +], function ($, Config, Messages, Util, Hash, Messaging, Realtime, Language, Constants, Feedback, LocalStore, AStore, Pinpad, AppConfig, Nthen) { @@ -49,24 +48,6 @@ define([ 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 // Settings only common.getUserObject = function (cb) { @@ -116,7 +97,27 @@ define([ value: profile }, 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? @@ -127,7 +128,6 @@ define([ Language.setLanguage(l, null, cb); }; - // REAFCTOR store.getProfile should be store.get(['profile']) common.getMetadata = function (cb) { postMessage("GET_METADATA", null, function (obj) { 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) { postMessage("SET_DISPLAY_NAME", value, cb); }; @@ -214,7 +183,7 @@ define([ // Tags common.resetTags = function (href, tags, cb) { // set pad attribute - cb = cb || $.noop; + cb = cb || function () {}; if (!Array.isArray(tags)) { return void cb('INVALID_TAGS'); } 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) { - postMessage("PIN_PADS", {pads: pads}, function (obj) { + postMessage("PIN_PADS", pads, function (obj) { if (obj.error) { return void cb(obj.error); } 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); } cb(); }); @@ -392,14 +347,14 @@ define([ msg: msg, data: data }, function (obj) { - if (obj.error) { return void cb(obj.error); } - cb(); + if (obj && obj.error) { return void cb(obj.error); } + cb(null, obj); }); }; common.getFileSize = function (href, cb) { 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); }); }; @@ -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 common.getShareHashes = function (secret, cb) { + var hashes; if (!window.location.hash) { - var hashes = Hash.getHashes(secret.channel, secret); + hashes = Hash.getHashes(secret.channel, secret); return void cb(null, hashes); } var parsed = Hash.parsePadUrl(window.location.href); if (!parsed.type || !parsed.hashData) { return void cb('E_INVALID_HREF'); } 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) { // It means we're using an old hash @@ -492,7 +459,7 @@ define([ } postMessage("GET_STRONGER_HASH", { - href: href + href: window.location.href }, function (hash) { if (hash) { hashes.editHash = hash; } cb(null, hashes); @@ -555,6 +522,16 @@ define([ if (localToken !== data.token) { requestLogin(); } 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()) { 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'); + if (obj.error) { return; } + localStorage.plan = obj.plan; })); } else if (PINNING_ENABLED) { console.log('not logged in. pads will not be pinned'); @@ -703,9 +682,9 @@ define([ }()); // MAGIC that happens implicitly - $(function () { + /*$(function () { Language.applyTranslation(); - }); + });*/ return common; }); diff --git a/www/common/fsStore.js b/www/common/fsStore.js index 3c502a0ee..27ed42d34 100644 --- a/www/common/fsStore.js +++ b/www/common/fsStore.js @@ -315,7 +315,7 @@ define([ exp.realtime = rt.realtime; exp.proxy = rt.proxy; - exp.loggedIn = Cryptpad.isLoggedIn() + exp.loggedIn = Cryptpad.isLoggedIn(); rt.proxy.on('create', function (info) { exp.info = info; if (!LocalStore.getUserHash()) { diff --git a/www/common/outer/async-store.js b/www/common/outer/async-store.js index 46e8ba2a9..116e0cdd7 100644 --- a/www/common/outer/async-store.js +++ b/www/common/outer/async-store.js @@ -6,24 +6,17 @@ define([ '/common/common-constants.js', '/common/common-feedback.js', '/common/common-realtime.js', + '/common/common-messaging.js', '/common/outer/network-config.js', '/bower_components/chainpad-crypto/crypto.js?v=0.1.5', '/bower_components/chainpad/chainpad.dist.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) { var Store = {}; - var postMessage = function (cmd, data, cb) {}; - var tryParsing = function (x) { - try { return JSON.parse(x); } - catch (e) { - console.error(e); - return null; - } - }; - + var postMessage = function () {}; var storeHash; @@ -43,7 +36,11 @@ define([ var key = path.pop(); var obj = Util.find(store.proxy, 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); }; @@ -82,11 +79,10 @@ define([ if (avatarChan) { list.push(avatarChan); } } - // TODO - /*if (store.proxy.friends) { - var fList = Messaging.getFriendChannelsList(common); + if (store.proxy.friends) { + var fList = Messaging.getFriendChannelsList(store.proxy); list = list.concat(fList); - }*/ + } list.push(Util.base64ToHex(userChannel)); list.sort(); @@ -102,34 +98,13 @@ define([ /////////////////////// 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) { if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); } if (typeof(cb) !== 'function') { 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}); } cb({hash: hash}); }); @@ -138,7 +113,7 @@ define([ Store.unpinPads = function (data, cb) { 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}); } cb({hash: hash}); }); @@ -158,7 +133,7 @@ define([ }; // 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'}); } store.rpc.updatePinLimits(function (e, limit, plan, note) { if (e) { return void cb({error: e}); } @@ -169,7 +144,7 @@ define([ }); }; // Get current user limits - Store.getPinLimit = function (cb) { + Store.getPinLimit = function (data, cb) { if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); } var ALWAYS_REVALIDATE = true; @@ -189,42 +164,63 @@ define([ Store.clearOwnedChannel = function (data, cb) { 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) { if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); } - rpc.uploadComplete(cb); + store.rpc.uploadComplete(cb); }; Store.uploadStatus = function (data, cb) { 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) { 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) { - require(['/common/pinpad.js', function (Pinpad) { + require(['/common/pinpad.js'], function (Pinpad) { Pinpad.create(store.network, store.proxy, function (e, call) { if (e) { return void cb({error: e}); } store.rpc = call; - common.getPinLimit(function (e, limit, plan, note) { - if (e) { return void console.error(e); } - common.account.limit = limit; - localStorage.plan = common.account.plan = plan; - common.account.note = note; - cb(); + Store.getPinLimit(null, function (obj) { + if (obj.error) { console.error(obj.error); } + account.limit = obj.limit; + account.plan = obj.plan; + account.note = obj.note; + cb(obj); }); - common.arePinsSynced(function (err, yes) { + arePinsSynced(function (err, yes) { if (!yes) { - common.resetPins(function (err) { + resetPins(function (err) { if (err) { return console.error(err); } console.log('RESET DONE'); }); @@ -239,10 +235,14 @@ define([ ////////////////////////////////////////////////////////////////// Store.anonRpcMsg = function (data, cb) { 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) { + console.log(data, cb); if (!store.anon_rpc) { return void cb({error: 'ANON_RPC_NOT_READY'}); } var channelId = Hash.hrefToHexChannelId(data.href); @@ -367,19 +367,19 @@ define([ if (typeof attr === "string") { console.error('DEPRECATED: use setAttribute with an array, not a string'); return { - obj: storeObj.settings, + obj: store.proxy.settings, key: attr }; } - if (!Array.isArray(attr)) { throw new Error("Attribute must be string or array"); } - if (attr.length === 0) { throw new Error("Attribute can't be empty"); } - var obj = storeObj.settings; + if (!Array.isArray(attr)) { return void console.error("Attribute must be string or array"); } + if (attr.length === 0) { return void console.error("Attribute can't be empty"); } + var obj = store.proxy.settings; attr.forEach(function (el, i) { if (i === attr.length-1) { return; } if (!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]; }); return { @@ -402,12 +402,12 @@ define([ * - value (String) */ 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); }); }; 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}); } cb(val); }); @@ -443,7 +443,7 @@ define([ cb(all); }; - var makePad = common.makePad = function (href, title) { + var makePad = function (href, title) { var now = +new Date(); return { href: href, @@ -465,13 +465,13 @@ define([ // Templates Store.getTemplates = function (data, cb) { - var templateFiles = filesOp.getFiles(['template']); + var templateFiles = store.userObject.getFiles(['template']); var res = []; templateFiles.forEach(function (f) { - var data = filesOp.getFileData(f); + var data = store.userObject.getFileData(f); res.push(JSON.parse(JSON.stringify(data))); }); - return res; + cb(res); }; // Pads @@ -496,7 +496,7 @@ define([ // Update all pads that use the same channel but with a weaker hash // Edit > Edit (present) > View > View (present) for (var id in allPads) { - var pad = recent[id]; + var pad = allPads[id]; if (!pad.href) { continue; } var p2 = Hash.parsePadUrl(pad.href); @@ -539,7 +539,7 @@ define([ if (isStronger) { // 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 - store.userObject.restoreHref(obj.n); + store.userObject.restoreHref(href); } // Add the pad if it does not exist in our drive @@ -585,7 +585,7 @@ define([ }; // Get hashes for the share button - common.getStrongerHash = function (data, cb) { + Store.getStrongerHash = function (data, cb) { var allPads = Util.find(store.proxy, ['drive', 'filesData']) || {}; // If we have a stronger version in drive, add it and add a redirect button @@ -597,6 +597,29 @@ define([ 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 proxy = store.proxy; @@ -605,9 +628,9 @@ define([ loggedIn: store.loggedIn }); var todo = function () { - fo.fixFiles(); + userObject.fixFiles(); - Migrate(proxy, Cryptpad); + Migrate(proxy); var requestLogin = function () { postMessage("REQUEST_LOGIN"); @@ -624,7 +647,7 @@ define([ } 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 user object, request that they reauthenticate. return void requestLogin(); @@ -665,6 +688,9 @@ define([ // Trigger userlist update when the friendlist has changed postMessage("UPDATE_METADATA"); }); + proxy.on('change', ['settings'], function () { + postMessage("UPDATE_METADATA"); + }); proxy.on('change', [Constants.tokenKey], function () { postMessage("UPDATE_TOKEN", { data: proxy[Constants.tokenKey] }); }); @@ -692,14 +718,13 @@ define([ classic: true, }; var rt = Listmap.create(listmapConfig); - store.proxy = rt.proxy, - store.realtime = rt.realtime; - store.network = rt.network; + store.proxy = rt.proxy; store.loggedIn = typeof(data.userHash) !== "undefined"; var returned = {}; rt.proxy.on('create', function (info) { - exp.info = info; + store.realtime = info.realtime; + store.network = info.network; if (!data.userHash) { returned.anonHash = Hash.getEditHashFromKeys(info.channel, secret.keys); } @@ -743,18 +768,24 @@ define([ }); } initialized = true; - postMessage = function (cmd, data, cb) { + postMessage = function (cmd, d, cb) { 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) { if (Object.keys(store.proxy).length === 1) { Feedback.send("FIRST_APP_USE", true); } callback(ret); + + var messagingCfg = getMessagingCfg(); + Messaging.addDirectMessageHandler(messagingCfg); + + }); }; diff --git a/www/common/outer/store-rpc.js b/www/common/outer/store-rpc.js index 5a49f31c4..7479b3025 100644 --- a/www/common/outer/store-rpc.js +++ b/www/common/outer/store-rpc.js @@ -40,12 +40,6 @@ define([ case 'UPLOAD_CANCEL': { 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': { Store.pinPads(data, cb); break; } @@ -117,6 +111,11 @@ define([ case 'GET_STRONGER_HASH': { Store.getStrongerHash(data, cb); break; } + // Messaging + case 'INVITE_FROM_USERLIST': { + Store.inviteFromUserlist(data, cb); break; + } + default: { break; diff --git a/www/common/pinpad.js b/www/common/pinpad.js index 07f55b5a2..47eb97892 100644 --- a/www/common/pinpad.js +++ b/www/common/pinpad.js @@ -3,13 +3,13 @@ define([ ], function (Rpc) { var create = function (network, proxy, cb) { if (!network) { - self.setTimeout(function () { + setTimeout(function () { cb('INVALID_NETWORK'); }); return; } if (!proxy) { - self.setTimeout(function () { + setTimeout(function () { cb('INVALID_PROXY'); }); return; @@ -19,7 +19,7 @@ define([ var edPublic = proxy.edPublic; if (!(edPrivate && edPublic)) { - self.setTimeout(function () { + setTimeout(function () { cb('INVALID_KEYS'); }); return; @@ -39,7 +39,7 @@ define([ // you can ask the server to pin a particular channel for you exp.pin = function (channels, cb) { if (!Array.isArray(channels)) { - self.setTimeout(function () { + setTimeout(function () { cb('[TypeError] pin expects an array'); }); return; @@ -50,7 +50,7 @@ define([ // you can also ask to unpin a particular channel exp.unpin = function (channels, cb) { if (!Array.isArray(channels)) { - self.setTimeout(function () { + setTimeout(function () { cb('[TypeError] pin expects an array'); }); return; @@ -71,7 +71,7 @@ define([ // if local and remote hashes don't match, send a reset exp.reset = function (channels, cb) { if (!Array.isArray(channels)) { - self.setTimeout(function () { + setTimeout(function () { cb('[TypeError] pin expects an array'); }); return; @@ -163,7 +163,7 @@ define([ exp.uploadStatus = function (size, cb) { if (typeof(size) !== 'number') { - return void self.setTimeout(function () { + return void setTimeout(function () { cb('INVALID_SIZE'); }); } diff --git a/www/common/rpc.js b/www/common/rpc.js index 929be4795..e86615111 100644 --- a/www/common/rpc.js +++ b/www/common/rpc.js @@ -2,7 +2,7 @@ define([ '/common/common-util.js', '/bower_components/tweetnacl/nacl-fast.min.js', ], function (Util) { - var Nacl = self.nacl; + var Nacl = window.nacl; var uid = Util.uid; var signMsg = function (data, signKey) { @@ -140,7 +140,7 @@ types of messages: var send = ctx.send = function (type, msg, cb) { if (!ctx.connected && type !== 'COOKIE') { - return void self.setTimeout(function () { + return void setTimeout(function () { cb('DISCONNECTED'); }); } @@ -185,7 +185,7 @@ types of messages: send.unauthenticated = function (type, msg, cb) { if (!ctx.connected) { - return void self.setTimeout(function () { + return void setTimeout(function () { cb('DISCONNECTED'); }); } @@ -276,7 +276,7 @@ types of messages: var send = ctx.send = function (type, msg, cb) { if (!ctx.connected) { - return void self.setTimeout(function () { + return void setTimeout(function () { cb('DISCONNECTED'); }); } diff --git a/www/common/sframe-common-outer.js b/www/common/sframe-common-outer.js index c9eeb009e..a32cecf3f 100644 --- a/www/common/sframe-common-outer.js +++ b/www/common/sframe-common-outer.js @@ -9,6 +9,7 @@ define([ common.start = function (cfg) { cfg = cfg || {}; var realtime = !cfg.noRealtime; + var network; var secret; var hashes; var CpNfOuter; @@ -18,7 +19,7 @@ define([ var SFrameChannel; var sframeChan; var FilePicker; - var Messenger; + //var Messenger; var Messaging; var Notifier; var Utils = {}; @@ -32,7 +33,7 @@ define([ '/common/cryptget.js', '/common/sframe-channel.js', '/filepicker/main.js', - '/common/common-messenger.js', + //'/common/common-messenger.js', '/common/common-messaging.js', '/common/common-notifier.js', '/common/common-hash.js', @@ -41,16 +42,18 @@ define([ '/common/common-constants.js', '/common/common-feedback.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, - _FilePicker, _Messenger, _Messaging, _Notifier, _Hash, _Util, _Realtime, - _Constants, _Feedback, _LocalStore) { + _FilePicker, /*_Messenger,*/ _Messaging, _Notifier, _Hash, _Util, _Realtime, + _Constants, _Feedback, _LocalStore, NetConfig, Netflux) { CpNfOuter = _CpNfOuter; Cryptpad = _Cryptpad; Crypto = _Crypto; Cryptget = _Cryptget; SFrameChannel = _SFrameChannel; FilePicker = _FilePicker; - Messenger = _Messenger; + //Messenger = _Messenger; Messaging = _Messaging; Notifier = _Notifier; Utils.Hash = _Hash; @@ -85,6 +88,12 @@ define([ sframeChan = sfc; }), false, { cache: cache, localStore: localStore, language: Cryptpad.getLanguage() }); Cryptpad.ready(waitFor()); + + if (!cfg.newNetwork) { + Netflux.connect(NetConfig.getWebsocketURL()).then(waitFor(function (nw) { + network = nw; + })); + } })); }).nThen(function (waitFor) { $('#sbox-iframe').focus(); @@ -123,7 +132,6 @@ define([ var parsed = Utils.Hash.parsePadUrl(window.location.href); if (!parsed.type) { throw new Error(); } var defaultTitle = Utils.Hash.getDefaultName(parsed); - var proxy = Cryptpad.getProxy(); var updateMeta = function () { //console.log('EV_METADATA_UPDATE'); var metaObj, isTemplate; @@ -137,7 +145,7 @@ define([ isTemplate = t; })); }).nThen(function (/*waitFor*/) { - metaObj.doc: { + metaObj.doc = { defaultTitle: defaultTitle, type: parsed.type }; @@ -167,7 +175,6 @@ define([ }; Cryptpad.onMetadataChanged(updateMeta); sframeChan.onReg('EV_METADATA_UPDATE', updateMeta); - proxy.on('change', 'settings', updateMeta); Utils.LocalStore.onLogout(function () { sframeChan.event('EV_LOGOUT'); @@ -285,7 +292,6 @@ define([ }; sframeChan.on('Q_GET_FULL_HISTORY', function (data, cb) { - var network = Cryptpad.getNetwork(); var hkn = network.historyKeeper; var crypto = Crypto.createEncryptor(secret.keys); // Get the history messages and send them to the iframe @@ -493,7 +499,8 @@ define([ } 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) { messenger.getFriendList(function (e, keys) { @@ -604,7 +611,7 @@ define([ sframeChan.event('EV_CONTACTS_UNFRIEND', { curvePublic: curvePublic, }); - }); + });*/ } sframeChan.ready(); @@ -628,7 +635,7 @@ define([ CpNfOuter.start({ sframeChan: sframeChan, channel: secret.channel, - network: cfg.newNetwork || Cryptpad.getNetwork(), + network: cfg.newNetwork || network, validateKey: secret.keys.validateKey || undefined, readOnly: readOnly, crypto: Crypto.createEncryptor(secret.keys), diff --git a/www/common/sframe-common.js b/www/common/sframe-common.js index 1d21acb92..ee2589727 100644 --- a/www/common/sframe-common.js +++ b/www/common/sframe-common.js @@ -122,6 +122,7 @@ define([ funcs.getFileSize = function (href, cb) { var channelId = Hash.hrefToHexChannelId(href); funcs.sendAnonRpcMsg("GET_FILE_SIZE", channelId, function (data) { + console.log(data); if (!data) { return void cb("No response"); } if (data.error) { return void cb(data.error); } if (data.response && data.response.length && typeof(data.response[0]) === 'number') { diff --git a/www/drive/main.js b/www/drive/main.js index 1e3ff3589..01fc98554 100644 --- a/www/drive/main.js +++ b/www/drive/main.js @@ -5,9 +5,7 @@ define([ 'jquery', '/common/requireconfig.js', '/common/sframe-common-outer.js', - '/common/outer/network-config.js', - '/bower_components/netflux-websocket/netflux-client.js', -], function (nThen, ApiConfig, $, RequireConfig, SFCommonO, NetConfig, Netflux) { +], function (nThen, ApiConfig, $, RequireConfig, SFCommonO) { var requireConfig = RequireConfig(); // Loaded in load #2 @@ -38,10 +36,10 @@ define([ }; window.addEventListener('message', onMsg); }).nThen(function (/*waitFor*/) { - var getSecrets = function (Cryptpad, Utils) { + var getSecrets = function (Cryptpad, Utils, cb) { var hash = window.location.hash.slice(1) || Utils.LocalStore.getUserHash() || Utils.LocalStore.getFSHash(); - return Utils.Hash.getSecrets('drive', hash); + cb(null, Utils.Hash.getSecrets('drive', hash)); }; var addRpc = function (sframeChan, Cryptpad, Utils) { sframeChan.on('EV_BURN_ANON_DRIVE', function () { @@ -51,13 +49,13 @@ define([ window.location.reload(); }); }; - Netflux.connect(NetConfig.getWebsocketURL()).then(function (network) { + //Netflux.connect(NetConfig.getWebsocketURL()).then(function (network) { SFCommonO.start({ getSecrets: getSecrets, - newNetwork: network, + //newNetwork: network, noHash: true, addRpc: addRpc }); - }, function (err) { console.error(err); }); + //}, function (err) { console.error(err); }); }); }); diff --git a/www/filepicker/main.js b/www/filepicker/main.js index 738e40773..8b7ab2b60 100644 --- a/www/filepicker/main.js +++ b/www/filepicker/main.js @@ -46,7 +46,6 @@ define([ sframeChan = sfc; })); }).nThen(function () { - var proxy = Cryptpad.getProxy(); var updateMeta = function () { //console.log('EV_METADATA_UPDATE'); var metaObj; @@ -56,7 +55,7 @@ define([ metaObj = n; })); }).nThen(function (/*waitFor*/) { - metaObj.doc: {}; + metaObj.doc = {}; var additionalPriv = { accountName: Utils.LocalStore.getAccountName(), origin: window.location.origin, @@ -71,7 +70,6 @@ define([ }; Cryptpad.onMetadataChanged(updateMeta); sframeChan.onReg('EV_METADATA_UPDATE', updateMeta); - proxy.on('change', 'settings', updateMeta); config.addCommonRpc(sframeChan); diff --git a/www/profile/main.js b/www/profile/main.js index bdee640bf..a77829242 100644 --- a/www/profile/main.js +++ b/www/profile/main.js @@ -78,18 +78,14 @@ define([ var chanId = Utils.Hash.hrefToHexChannelId(data); Cryptpad.pinPads([chanId], function (e) { if (e) { return void cb(e); } - Cryptpad.getProxy().profile.avatar = data; - Utils.Realtime.whenRealtimeSyncs(Cryptpad.getRealtime(), function () { - cb(); - }); + Cryptpad.setAvatar(data, cb); }); }); // Removing the avatar from the profile: unpin it sframeChan.on('Q_PROFILE_AVATAR_REMOVE', function (data, cb) { var chanId = Utils.Hash.hrefToHexChannelId(data); - Cryptpad.unpinPads([chanId], function (e) { - delete Cryptpad.getProxy().profile.avatar; - cb(e); + Cryptpad.unpinPads([chanId], function () { + Cryptpad.setAvatar(undefined, cb); }); }); }; diff --git a/www/todo/main.js b/www/todo/main.js index 3f6d1cd5f..9caeb16ef 100644 --- a/www/todo/main.js +++ b/www/todo/main.js @@ -36,12 +36,12 @@ define([ }; window.addEventListener('message', onMsg); }).nThen(function (/*waitFor*/) { - var getSecrets = function (Cryptpad, Utils) { - var proxy = Cryptpad.getProxy(); - var hash = proxy.todo || Utils.Hash.createRandomHash(); - if (!proxy.todo) { proxy.todo = hash; } - - return Utils.Hash.getSecrets('todo', hash); + var getSecrets = function (Cryptpad, Utils, cb) { + Cryptpad.getTodoHash(function (hash) { + var nHash = hash || Utils.Hash.createRandomHash(); + if (!hash) { Cryptpad.setTodoHash(nHash); } + cb(null, Utils.Hash.getSecrets('todo', hash)); + }); }; SFCommonO.start({ getSecrets: getSecrets,