From 130b330ede16e1c01e19bd54e1ff99e9a7805d11 Mon Sep 17 00:00:00 2001 From: ansuz Date: Wed, 16 Aug 2017 10:04:50 +0200 Subject: [PATCH 01/12] refactor messaging --- www/common/common-messaging2.js | 692 ++++++++++++++++++++++++++++++++ 1 file changed, 692 insertions(+) create mode 100644 www/common/common-messaging2.js diff --git a/www/common/common-messaging2.js b/www/common/common-messaging2.js new file mode 100644 index 000000000..5f3d9af39 --- /dev/null +++ b/www/common/common-messaging2.js @@ -0,0 +1,692 @@ +define([ + 'jquery', + '/bower_components/chainpad-crypto/crypto.js', + '/common/curve.js', + '/common/common-hash.js', + '/common/common-realtime.js' +// '/bower_components/marked/marked.min.js' +], function ($, Crypto, Curve, Hash, Realtime) { + var Msg = { + inputs: [], + }; + + var Types = { + message: 'MSG', + update: 'UPDATE', + unfriend: 'UNFRIEND', + mapId: 'MAP_ID', + mapIdAck: 'MAP_ID_ACK' + }; + + // TODO + // - mute a channel (hide notifications or don't open it?) + + var ready = []; + var pending = {}; + var pendingRequests = []; + + var createData = Msg.createData = function (proxy, hash) { + return { + channel: hash || Hash.createChannelId(), + displayName: proxy['cryptpad.username'], + profile: proxy.profile && proxy.profile.view, + edPublic: proxy.edPublic, + curvePublic: proxy.curvePublic, + avatar: proxy.profile && proxy.profile.avatar + }; + }; + + var getFriend = function (proxy, pubkey) { + if (pubkey === proxy.curvePublic) { + var data = createData(proxy); + delete data.channel; + return data; + } + return proxy.friends ? proxy.friends[pubkey] : undefined; + }; + + var removeFromFriendList = function (proxy, realtime, curvePublic, cb) { + if (!proxy.friends) { return; } + var friends = proxy.friends; + delete friends[curvePublic]; + Realtime.whenRealtimeSyncs(realtime, cb); + }; + + var getFriendList = Msg.getFriendList = function (proxy) { + if (!proxy.friends) { proxy.friends = {}; } + return proxy.friends; + }; + + var eachFriend = function (friends, cb) { + Object.keys(friends).forEach(function (id) { + if (id === 'me') { return; } + cb(friends[id], id, friends); + }); + }; + + Msg.getFriendChannelsList = function (proxy) { + var list = []; + eachFriend(proxy, function (friend) { + list.push(friend.channel); + }); + return list; + }; + + var msgAlreadyKnown = function (channel, sig) { + return channel.messages.some(function (message) { + return message[0] === sig; + }); + }; + + var getMoreHistory = function (network, chan, hash, count) { + var msg = [ 'GET_HISTORY_RANGE', chan.id, { + from: hash, + count: count, + } + ]; + + network.sendto(network.historyKeeper, JSON.stringify(msg)).then(function () { + }, function (err) { + throw new Error(err); + }); + }; + + var getChannelMessagesSince = function (network, proxy, chan, data, keys) { + var cfg = { + validateKey: keys.validateKey, + owners: [proxy.edPublic, data.edPublic], + lastKnownHash: data.lastKnownHash + }; + var msg = ['GET_HISTORY', chan.id, cfg]; + network.sendto(network.historyKeeper, JSON.stringify(msg)) + .then($.noop, function (err) { + throw new Error(err); + }); + }; + + Msg.messenger = function (common) { + var messenger = {}; + + var DEBUG = function (label) { + console.log('event:' + label); + }; + + var channels = messenger.channels = {}; + + // declare common variables + var network = common.getNetwork(); + var proxy = common.getProxy(); + var realtime = common.getRealtime(); + Msg.hk = network.historyKeeper; + var friends = getFriendList(proxy); + + // Id message allows us to map a netfluxId with a public curve key + var onIdMessage = function (msg, sender) { + var channel; + var isId = Object.keys(channels).some(function (chanId) { + if (channels[chanId].userList.indexOf(sender) !== -1) { + channel = channels[chanId]; + return true; + } + }); + + if (!isId) { return; } + + var decryptedMsg = channel.encryptor.decrypt(msg); + + if (decryptedMsg === null) { + // console.error('unable to decrypt message'); + // console.error('potentially meant for yourself'); + + // message failed to parse, meaning somebody sent it to you but + // encrypted it with the wrong key, or you're sending a message to + // yourself in a different tab. + return; + } + + if (!decryptedMsg) { + console.error('decrypted message was falsey but not null'); + return; + } + + var parsed; + try { + parsed = JSON.parse(decryptedMsg); + } catch (e) { + console.error(decryptedMsg); + return; + } + if (parsed[0] !== Types.mapId && parsed[0] !== Types.mapIdAck) { return; } + + // check that the responding peer's encrypted netflux id matches + // the sender field. This is to prevent replay attacks. + if (parsed[2] !== sender || !parsed[1]) { return; } + channel.mapId[sender] = parsed[1]; + + channel.updateStatus(); + + if (parsed[0] !== Types.mapId) { return; } // Don't send your key if it's already an ACK + // Answer with your own key + var rMsg = [Types.mapIdAck, proxy.curvePublic, channel.wc.myID]; + var rMsgStr = JSON.stringify(rMsg); + var cryptMsg = channel.encryptor.encrypt(rMsgStr); + network.sendto(sender, cryptMsg); + }; + + var pushMsg = function (channel, cryptMsg) { + var msg = channel.encryptor.decrypt(cryptMsg); + + // TODO emit new message event or something + // extension point for other apps + console.log(msg); + + var sig = cryptMsg.slice(0, 64); + if (msgAlreadyKnown(channel, sig)) { return; } + + var parsedMsg = JSON.parse(msg); + if (parsedMsg[0] === Types.message) { + // TODO validate messages here + var res = { + type: parsedMsg[0], + sig: sig, + channel: parsedMsg[1], + time: parsedMsg[2], + text: parsedMsg[3], + }; + + channel.messages.push(res); + return true; + } + if (parsedMsg[0] === Types.update) { + if (parsedMsg[1] === proxy.curvePublic) { return; } + var newdata = parsedMsg[3]; + var data = getFriend(proxy, parsedMsg[1]); + var types = []; + Object.keys(newdata).forEach(function (k) { + if (data[k] !== newdata[k]) { + types.push(k); + data[k] = newdata[k]; + } + }); + channel.updateUI(types); + return; + } + if (parsedMsg[0] === Types.unfriend) { + removeFromFriendList(proxy, realtime, channel.friendEd, function () { + channel.wc.leave(Types.unfriend); + channel.removeUI(); + }); + return; + } + }; + + /* Broadcast a display name, profile, or avatar change to all contacts + */ + var updateMyData = function (proxy) { + var friends = getFriendList(proxy); + var mySyncData = friends.me; + var myData = createData(proxy); + if (!mySyncData || mySyncData.displayName !== myData.displayName + || mySyncData.profile !== myData.profile + || mySyncData.avatar !== myData.avatar) { + delete myData.channel; + Object.keys(channels).forEach(function (chan) { + var channel = channels[chan]; + var msg = [Types.update, myData.curvePublic, +new Date(), myData]; + var msgStr = JSON.stringify(msg); + var cryptMsg = channel.encryptor.encrypt(msgStr); + channel.wc.bcast(cryptMsg).then(function () { + channel.refresh(); + }, function (err) { + console.error(err); + }); + }); + friends.me = myData; + } + }; + + var onChannelReady = function (proxy, chanId) { + if (ready.indexOf(chanId) !== -1) { return; } + ready.push(chanId); + channels[chanId].updateStatus(); // c'est quoi? + var friends = getFriendList(proxy); + if (ready.length === Object.keys(friends).length) { + // All channels are ready + updateMyData(proxy); + } + return ready.length; + }; + + var onDirectMessage = function (common, msg, sender) { + if (sender !== Msg.hk) { return void onIdMessage(msg, sender); } + var parsed = JSON.parse(msg); + if ((parsed.validateKey || parsed.owners) && parsed.channel) { + return; + } + if (parsed.state && parsed.state === 1 && parsed.channel) { + if (channels[parsed.channel]) { + // parsed.channel is Ready + // TODO: call a function that shows that the channel is ready? (remove a spinner, ...) + // channel[parsed.channel].ready(); + channels[parsed.channel].ready = true; + onChannelReady(proxy, parsed.channel); + var updateTypes = channels[parsed.channel].updateOnReady; + if (updateTypes) { + channels[parsed.channel].updateUI(updateTypes); + } + } + return; + } + var chan = parsed[3]; + if (!chan || !channels[chan]) { return; } + pushMsg(channels[chan], parsed[4]); + channels[chan].refresh(); + }; + + var onMessage = function (common, msg, sender, chan) { + if (!channels[chan.id]) { return; } + + var realtime = common.getRealtime(); + var proxy = common.getProxy(); + + var isMessage = pushMsg(channels[chan.id], msg); + if (isMessage) { + // Don't notify for your own messages + if (channels[chan.id].wc.myID !== sender) { + channels[chan.id].notify(); + } + channels[chan.id].refresh(); + } + }; + + // listen for messages... + network.on('message', function(msg, sender) { + onDirectMessage(common, msg, sender); + }); + + // Refresh the active channel + // TODO extract into UI method + var refresh = function (/*curvePublic*/) { + return; + /* + if (messenger.active !== curvePublic) { return; } + var data = friends[curvePublic]; + if (!data) { return; } + var channel = channels[data.channel]; + if (!channel) { return; } + + var $chat = ui.getChannel(curvePublic); + + if (!$chat) { return; } + + // Add new messages + var messages = channel.messages; + var $messages = $chat.find('.messages'); + var msg, name; + var last = typeof(channel.lastDisplayed) === 'number'? channel.lastDisplayed: -1; + for (var i = last + 1; i 10) { + var lastKnownMsg = messages[messages.length - 11]; + channel.setLastMessageRead(lastKnownMsg.sig); + }*/ + }; + // Display a new channel + // TODO extract into UI method + //var display = function (curvePublic) { + //curvePublic = curvePublic; + /* + ui.hideInfo(); + var $chat = ui.getChannel(curvePublic); + if (!$chat) { + $chat = ui.createChat(curvePublic); + ui.createChatBox(proxy, $chat, curvePublic); + } + // Show the correct div + ui.hideChat(); + $chat.show(); + + // TODO set this attr per-messenger + messenger.setActive(curvePublic); + // TODO don't mark messages as read unless you have displayed them + + refresh(curvePublic);*/ + //}; + + // TODO take a callback + var remove = function (curvePublic) { + var data = getFriend(proxy, curvePublic); + var channel = channels[data.channel]; + var msg = [Types.unfriend, proxy.curvePublic, +new Date()]; + var msgStr = JSON.stringify(msg); + var cryptMsg = channel.encryptor.encrypt(msgStr); + channel.wc.bcast(cryptMsg).then(function () { + removeFromFriendList(common, curvePublic, function () { + channel.wc.leave(Types.unfriend); + channel.removeUI(); + }); + }, function (err) { + console.error(err); + }); + }; + + // Open the channels + var openFriendChannel = function (data, f) { + var keys = Curve.deriveKeys(data.curvePublic, proxy.curvePrivate); + var encryptor = Curve.createEncryptor(keys); + network.join(data.channel).then(function (chan) { + var channel = channels[data.channel] = { + sending: false, + friendEd: f, + keys: keys, + encryptor: encryptor, + messages: [], + unfriend: function () { + DEBUG('unfriend'); + remove(data.curvePublic); + }, + refresh: function () { + DEBUG('refresh'); + refresh(data.curvePublic); + }, + notify: function () { + //ui.notify(data.curvePublic); + DEBUG('notify'); + common.notify(); // HERE + }, + unnotify: function () { + DEBUG('unnotify'); + //ui.unnotify(data.curvePublic); + }, + removeUI: function () { + DEBUG('remove-ui'); + //ui.remove(data.curvePublic); + }, + updateUI: function (/*types*/) { + DEBUG('update-ui'); + //ui.update(data.curvePublic, types); + }, + updateStatus: function () { + DEBUG('update-status'); + //ui.updateStatus(data.curvePublic, + //channel.getStatus(data.curvePublic)); + }, + setLastMessageRead: function (hash) { + DEBUG('updateLastKnownHash'); + data.lastKnownHash = hash; + }, + getLastMessageRead: function () { + return data.lastKnownHash; + }, + isActive: function () { + return data.curvePublic === messenger.active; + }, + getMessagesSinceDisconnect: function () { + getChannelMessagesSince(network, proxy, chan, data, keys); + }, + wc: chan, + userList: [], + mapId: {}, + getStatus: function (curvePublic) { + return channel.userList.some(function (nId) { + return channel.mapId[nId] === curvePublic; + }); + }, + getPreviousMessages: function () { + var history = channel.messages; + if (!history || !history.length) { + // TODO ask for default history? + return; + } + + var oldestMessage = history[0]; + if (!oldestMessage) { + return; // nothing to fetch + } + + var messageHash = oldestMessage[0]; + getMoreHistory(network, chan, messageHash, 10); + }, + send: function (payload, cb) { + if (!network.webChannels.some(function (wc) { + if (wc.id === channel.wc.id) { return true; } + })) { + return void cb('NO_SUCH_CHANNEL'); + } + + var msg = [Types.message, proxy.curvePublic, +new Date(), payload]; + var msgStr = JSON.stringify(msg); + var cryptMsg = channel.encryptor.encrypt(msgStr); + + channel.wc.bcast(cryptMsg).then(function () { + pushMsg(channel, cryptMsg); + cb(); + }, function (err) { + cb(err); + }); + }, + }; + chan.on('message', function (msg, sender) { + onMessage(common, msg, sender, chan); + }); + + var onJoining = function (peer) { + if (peer === Msg.hk) { return; } + if (channel.userList.indexOf(peer) !== -1) { return; } + channel.userList.push(peer); + var msg = [Types.mapId, proxy.curvePublic, chan.myID]; + var msgStr = JSON.stringify(msg); + var cryptMsg = channel.encryptor.encrypt(msgStr); + network.sendto(peer, cryptMsg); + channel.updateStatus(); + }; + chan.members.forEach(function (peer) { + if (peer === Msg.hk) { return; } + if (channel.userList.indexOf(peer) !== -1) { return; } + channel.userList.push(peer); + }); + chan.on('join', onJoining); + chan.on('leave', function (peer) { + var i = channel.userList.indexOf(peer); + while (i !== -1) { + channel.userList.splice(i, 1); + i = channel.userList.indexOf(peer); + } + channel.updateStatus(); + }); + + getChannelMessagesSince(network, proxy, chan, data, keys); + }, function (err) { + console.error(err); + }); + }; + + messenger.getLatestMessages = function () { + Object.keys(channels).forEach(function (id) { + if (id === 'me') { return; } + var friend = channels[id]; + friend.getMessagesSinceDisconnect(); + friend.refresh(); + }); + }; + + messenger.cleanFriendChannels = function () { + Object.keys(channels).forEach(function (id) { + delete channels[id]; + }); + }; + + var openFriendChannels = messenger.openFriendChannels = function () { + eachFriend(friends, openFriendChannel); + }; + + //messenger.setEditable = ui.setEditable; + + openFriendChannels(); + + // TODO split loop innards into ui methods + var checkNewFriends = function () { + eachFriend(friends, function (friend, id) { + if (!channels[id]) { + openFriendChannel(friend, id); + } + }); + }; + + common.onDisplayNameChanged(function () { + checkNewFriends(); + updateMyData(proxy); + }); + + return messenger; + }; + + // Invitation + // FIXME there are too many functions with this name + var addToFriendList = Msg.addToFriendList = function (common, data, cb) { + var proxy = common.getProxy(); + var friends = getFriendList(proxy); + var pubKey = data.curvePublic; + + if (pubKey === proxy.curvePublic) { return void cb("E_MYKEY"); } + + friends[pubKey] = data; + + Realtime.whenRealtimeSyncs(common.getRealtime(), function () { + cb(); + common.pinPads([data.channel]); + }); + common.changeDisplayName(proxy[common.displayNameKey]); + }; + + /* Used to accept friend requests within apps other than /contacts/ */ + Msg.addDirectMessageHandler = function (common) { + var network = common.getNetwork(); + var proxy = common.getProxy(); + if (!network) { return void console.error('Network not ready'); } + network.on('message', function (message, sender) { + var msg; + if (sender === network.historyKeeper) { return; } + try { + var parsed = common.parsePadUrl(window.location.href); + if (!parsed.hashData) { return; } + var chan = parsed.hashData.channel; + // Decrypt + var keyStr = parsed.hashData.key; + var cryptor = Crypto.createEditCryptor(keyStr); + var key = cryptor.cryptKey; + var decryptMsg; + try { + decryptMsg = Crypto.decrypt(message, key); + } catch (e) { + // If we can't decrypt, it means it is not a friend request message + } + if (!decryptMsg) { return; } + // Parse + msg = JSON.parse(decryptMsg); + if (msg[1] !== parsed.hashData.channel) { return; } + var msgData = msg[2]; + var msgStr; + if (msg[0] === "FRIEND_REQ") { + msg = ["FRIEND_REQ_NOK", chan]; + var todo = function (yes) { + if (yes) { + pending[sender] = msgData; + msg = ["FRIEND_REQ_OK", chan, createData(common, msgData.channel)]; + } + msgStr = Crypto.encrypt(JSON.stringify(msg), key); + network.sendto(sender, msgStr); + }; + var existing = getFriend(proxy, msgData.curvePublic); + if (existing) { + todo(true); + return; + } + var confirmMsg = common.Messages._getKey('contacts_request', [ + common.fixHTML(msgData.displayName) + ]); + common.confirm(confirmMsg, todo, null, true); + return; + } + if (msg[0] === "FRIEND_REQ_OK") { + var idx = pendingRequests.indexOf(sender); + if (idx !== -1) { pendingRequests.splice(idx, 1); } + + // FIXME clarify this function's name + addToFriendList(common, msgData, function (err) { + if (err) { + return void common.log(common.Messages.contacts_addError); + } + common.log(common.Messages.contacts_added); + var msg = ["FRIEND_REQ_ACK", chan]; + var msgStr = Crypto.encrypt(JSON.stringify(msg), key); + network.sendto(sender, msgStr); + }); + return; + } + if (msg[0] === "FRIEND_REQ_NOK") { + var i = pendingRequests.indexOf(sender); + if (i !== -1) { pendingRequests.splice(i, 1); } + common.log(common.Messages.contacts_rejected); + common.changeDisplayName(proxy[common.displayNameKey]); + return; + } + if (msg[0] === "FRIEND_REQ_ACK") { + var data = pending[sender]; + if (!data) { return; } + addToFriendList(common, data, function (err) { + if (err) { + return void common.log(common.Messages.contacts_addError); + } + common.log(common.Messages.contacts_added); + }); + return; + } + // TODO: timeout ACK: warn the user + } catch (e) { + console.error("Cannot parse direct message", msg || message, "from", sender, e); + } + }); + }; + + Msg.getPending = function () { + return pendingRequests; + }; + + Msg.inviteFromUserlist = function (common, netfluxId) { + var network = common.getNetwork(); + var parsed = common.parsePadUrl(window.location.href); + if (!parsed.hashData) { return; } + // Message + var chan = parsed.hashData.channel; + var myData = createData(common); + var msg = ["FRIEND_REQ", chan, myData]; + // Encryption + var keyStr = parsed.hashData.key; + var cryptor = Crypto.createEditCryptor(keyStr); + var key = cryptor.cryptKey; + var msgStr = Crypto.encrypt(JSON.stringify(msg), key); + // 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[common.displayNameKey]); + } + network.sendto(netfluxId, msgStr); + }; + + return Msg; +}); From 002eed0d6f14721159cc615df596abb03e76c60c Mon Sep 17 00:00:00 2001 From: ansuz Date: Tue, 22 Aug 2017 15:55:00 +0200 Subject: [PATCH 02/12] make most of the messenger api async --- ...mmon-messaging2.js => common-messenger.js} | 630 +++++++++--------- www/contacts/main.less | 1 + 2 files changed, 322 insertions(+), 309 deletions(-) rename www/common/{common-messaging2.js => common-messenger.js} (73%) diff --git a/www/common/common-messaging2.js b/www/common/common-messenger.js similarity index 73% rename from www/common/common-messaging2.js rename to www/common/common-messenger.js index 5f3d9af39..d087294aa 100644 --- a/www/common/common-messaging2.js +++ b/www/common/common-messenger.js @@ -18,12 +18,13 @@ define([ mapIdAck: 'MAP_ID_ACK' }; + var clone = function (o) { + return JSON.parse(JSON.stringify(o)); + }; + // TODO // - mute a channel (hide notifications or don't open it?) - - var ready = []; var pending = {}; - var pendingRequests = []; var createData = Msg.createData = function (proxy, hash) { return { @@ -36,6 +37,7 @@ define([ }; }; + // TODO make this async var getFriend = function (proxy, pubkey) { if (pubkey === proxy.curvePublic) { var data = createData(proxy); @@ -45,6 +47,7 @@ define([ return proxy.friends ? proxy.friends[pubkey] : undefined; }; + // TODO make this async var removeFromFriendList = function (proxy, realtime, curvePublic, cb) { if (!proxy.friends) { return; } var friends = proxy.friends; @@ -52,6 +55,7 @@ define([ Realtime.whenRealtimeSyncs(realtime, cb); }; + // TODO make this async var getFriendList = Msg.getFriendList = function (proxy) { if (!proxy.friends) { proxy.friends = {}; } return proxy.friends; @@ -90,6 +94,7 @@ define([ throw new Error(err); }); }; + getMoreHistory = getMoreHistory; // FIXME var getChannelMessagesSince = function (network, proxy, chan, data, keys) { var cfg = { @@ -104,15 +109,181 @@ define([ }); }; + // Invitation + // FIXME there are too many functions with this name + var addToFriendList = Msg.addToFriendList = function (common, data, cb) { + var proxy = common.getProxy(); + var friends = getFriendList(proxy); + var pubKey = data.curvePublic; + + if (pubKey === proxy.curvePublic) { return void cb("E_MYKEY"); } + + friends[pubKey] = data; + + Realtime.whenRealtimeSyncs(common.getRealtime(), function () { + cb(); + common.pinPads([data.channel]); + }); + common.changeDisplayName(proxy[common.displayNameKey]); + }; + + var pendingRequests = []; + + /* Used to accept friend requests within apps other than /contacts/ */ + // TODO move this into MSG.messenger + // as _openGroupChannel_ + Msg.addDirectMessageHandler = function (common) { + var network = common.getNetwork(); + var proxy = common.getProxy(); + if (!network) { return void console.error('Network not ready'); } + network.on('message', function (message, sender) { + var msg; + if (sender === network.historyKeeper) { return; } + try { + var parsed = common.parsePadUrl(window.location.href); + if (!parsed.hashData) { return; } + var chan = parsed.hashData.channel; + // Decrypt + var keyStr = parsed.hashData.key; + var cryptor = Crypto.createEditCryptor(keyStr); + var key = cryptor.cryptKey; + var decryptMsg; + try { + decryptMsg = Crypto.decrypt(message, key); + } catch (e) { + // If we can't decrypt, it means it is not a friend request message + } + if (!decryptMsg) { return; } + // Parse + msg = JSON.parse(decryptMsg); + if (msg[1] !== parsed.hashData.channel) { return; } + var msgData = msg[2]; + var msgStr; + if (msg[0] === "FRIEND_REQ") { + msg = ["FRIEND_REQ_NOK", chan]; + var todo = function (yes) { + if (yes) { + pending[sender] = msgData; + msg = ["FRIEND_REQ_OK", chan, createData(common, msgData.channel)]; + } + msgStr = Crypto.encrypt(JSON.stringify(msg), key); + network.sendto(sender, msgStr); + }; + var existing = getFriend(proxy, msgData.curvePublic); + if (existing) { + todo(true); + return; + } + var confirmMsg = common.Messages._getKey('contacts_request', [ + common.fixHTML(msgData.displayName) + ]); + common.confirm(confirmMsg, todo, null, true); + return; + } + if (msg[0] === "FRIEND_REQ_OK") { + var idx = pendingRequests.indexOf(sender); + if (idx !== -1) { pendingRequests.splice(idx, 1); } + + // FIXME clarify this function's name + addToFriendList(common, msgData, function (err) { + if (err) { + return void common.log(common.Messages.contacts_addError); + } + common.log(common.Messages.contacts_added); + var msg = ["FRIEND_REQ_ACK", chan]; + var msgStr = Crypto.encrypt(JSON.stringify(msg), key); + network.sendto(sender, msgStr); + }); + return; + } + if (msg[0] === "FRIEND_REQ_NOK") { + var i = pendingRequests.indexOf(sender); + if (i !== -1) { pendingRequests.splice(i, 1); } + common.log(common.Messages.contacts_rejected); + common.changeDisplayName(proxy[common.displayNameKey]); + return; + } + if (msg[0] === "FRIEND_REQ_ACK") { + var data = pending[sender]; + if (!data) { return; } + addToFriendList(common, data, function (err) { + if (err) { + return void common.log(common.Messages.contacts_addError); + } + common.log(common.Messages.contacts_added); + }); + return; + } + // TODO: timeout ACK: warn the user + } catch (e) { + console.error("Cannot parse direct message", msg || message, "from", sender, e); + } + }); + }; + + // TODO somehow fold this into openGroupChannel + Msg.inviteFromUserlist = function (common, netfluxId) { + var network = common.getNetwork(); + var parsed = common.parsePadUrl(window.location.href); + if (!parsed.hashData) { return; } + // Message + var chan = parsed.hashData.channel; + var myData = createData(common); + var msg = ["FRIEND_REQ", chan, myData]; + // Encryption + var keyStr = parsed.hashData.key; + var cryptor = Crypto.createEditCryptor(keyStr); + var key = cryptor.cryptKey; + var msgStr = Crypto.encrypt(JSON.stringify(msg), key); + // 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[common.displayNameKey]); + } + network.sendto(netfluxId, msgStr); + }; + Msg.messenger = function (common) { - var messenger = {}; + var messenger = { + handlers: { + message: [], + join: [], + leave: [], + update: [], + }, + }; + + messenger.on = function (type, f) { + var stack = messenger.handlers[type]; + if (!Array.isArray(stack)) { + return void console.error('unsupported message type'); + } + if (typeof(f) !== 'function') { + return void console.error('expected function'); + } + stack.push(f); + }; + + // TODO openGroupChannel + messenger.openGroupChannel = function (hash, cb) { + // sets up infrastructure for a one to one channel using curve cryptography + cb = cb; + }; + + //var ready = messenger.ready = []; var DEBUG = function (label) { console.log('event:' + label); }; + DEBUG = DEBUG; // FIXME var channels = messenger.channels = {}; + var joining = {}; + // declare common variables var network = common.getNetwork(); var proxy = common.getProxy(); @@ -120,6 +291,33 @@ define([ Msg.hk = network.historyKeeper; var friends = getFriendList(proxy); + var getChannel = function (curvePublic) { + var friend = friends[curvePublic]; + if (!friend) { return; } + var chanId = friend.channel; + if (!chanId) { return; } + return channels[chanId]; + }; + + var getCurveForChannel = function (id) { + var channel = channels[id]; + if (!channel) { return; } + return channel.curve; + }; + + messenger.getChannelHead = function (curvePublic, cb) { + var friend = friends[curvePublic]; + if (!friend) { return void cb('NO_SUCH_FRIEND'); } + cb(void 0, friend.lastKnownHash); + }; + + messenger.setChannelHead = function (curvePublic, hash, cb) { + var friend = friends[curvePublic]; + if (!friend) { return void cb('NO_SUCH_FRIEND'); } + friend.lastKnownHash = hash; + cb(); + }; + // Id message allows us to map a netfluxId with a public curve key var onIdMessage = function (msg, sender) { var channel; @@ -161,9 +359,10 @@ define([ // check that the responding peer's encrypted netflux id matches // the sender field. This is to prevent replay attacks. if (parsed[2] !== sender || !parsed[1]) { return; } - channel.mapId[sender] = parsed[1]; - - channel.updateStatus(); + channel.mapId[sender] = parsed[1]; // HERE + messenger.handlers.join.forEach(function (f) { + f(parsed[1], channel.id); + }); if (parsed[0] !== Types.mapId) { return; } // Don't send your key if it's already an ACK // Answer with your own key @@ -178,7 +377,7 @@ define([ // TODO emit new message event or something // extension point for other apps - console.log(msg); + //console.log(msg); var sig = cryptMsg.slice(0, 64); if (msgAlreadyKnown(channel, sig)) { return; } @@ -192,12 +391,22 @@ define([ channel: parsedMsg[1], time: parsedMsg[2], text: parsedMsg[3], + // this makes debugging a whole lot easier + curve: getCurveForChannel(channel.id), }; + // TODO emit message event channel.messages.push(res); + + messenger.handlers.message.forEach(function (f) { + f(res); + }); + return true; } if (parsedMsg[0] === Types.update) { + // TODO emit update event + if (parsedMsg[1] === proxy.curvePublic) { return; } var newdata = parsedMsg[3]; var data = getFriend(proxy, parsedMsg[1]); @@ -208,13 +417,13 @@ define([ data[k] = newdata[k]; } }); - channel.updateUI(types); + //channel.updateUI(types); return; } if (parsedMsg[0] === Types.unfriend) { removeFromFriendList(proxy, realtime, channel.friendEd, function () { channel.wc.leave(Types.unfriend); - channel.removeUI(); + //channel.removeUI(); }); return; } @@ -222,7 +431,9 @@ define([ /* Broadcast a display name, profile, or avatar change to all contacts */ - var updateMyData = function (proxy) { + + // TODO send event... + messenger.updateMyData = function () { var friends = getFriendList(proxy); var mySyncData = friends.me; var myData = createData(proxy); @@ -245,16 +456,13 @@ define([ } }; - var onChannelReady = function (proxy, chanId) { - if (ready.indexOf(chanId) !== -1) { return; } - ready.push(chanId); - channels[chanId].updateStatus(); // c'est quoi? - var friends = getFriendList(proxy); - if (ready.length === Object.keys(friends).length) { - // All channels are ready - updateMyData(proxy); + var onChannelReady = function (chanId) { + var cb = joining[chanId]; + if (typeof(cb) !== 'function') { + return void console.log('channel ready without callback'); } - return ready.length; + delete joining[chanId]; + return cb(); }; var onDirectMessage = function (common, msg, sender) { @@ -266,13 +474,13 @@ define([ if (parsed.state && parsed.state === 1 && parsed.channel) { if (channels[parsed.channel]) { // parsed.channel is Ready - // TODO: call a function that shows that the channel is ready? (remove a spinner, ...) // channel[parsed.channel].ready(); channels[parsed.channel].ready = true; - onChannelReady(proxy, parsed.channel); + onChannelReady(parsed.channel); var updateTypes = channels[parsed.channel].updateOnReady; if (updateTypes) { - channels[parsed.channel].updateUI(updateTypes); + + //channels[parsed.channel].updateUI(updateTypes); } } return; @@ -280,22 +488,19 @@ define([ var chan = parsed[3]; if (!chan || !channels[chan]) { return; } pushMsg(channels[chan], parsed[4]); - channels[chan].refresh(); }; var onMessage = function (common, msg, sender, chan) { if (!channels[chan.id]) { return; } - var realtime = common.getRealtime(); - var proxy = common.getProxy(); - var isMessage = pushMsg(channels[chan.id], msg); if (isMessage) { - // Don't notify for your own messages if (channels[chan.id].wc.myID !== sender) { - channels[chan.id].notify(); + // Don't notify for your own messages + //channels[chan.id].notify(); } - channels[chan.id].refresh(); + //channels[chan.id].refresh(); + // TODO emit message event } }; @@ -304,160 +509,41 @@ define([ onDirectMessage(common, msg, sender); }); - // Refresh the active channel - // TODO extract into UI method - var refresh = function (/*curvePublic*/) { - return; - /* - if (messenger.active !== curvePublic) { return; } - var data = friends[curvePublic]; - if (!data) { return; } - var channel = channels[data.channel]; - if (!channel) { return; } - - var $chat = ui.getChannel(curvePublic); - - if (!$chat) { return; } - - // Add new messages - var messages = channel.messages; - var $messages = $chat.find('.messages'); - var msg, name; - var last = typeof(channel.lastDisplayed) === 'number'? channel.lastDisplayed: -1; - for (var i = last + 1; i 10) { - var lastKnownMsg = messages[messages.length - 11]; - channel.setLastMessageRead(lastKnownMsg.sig); - }*/ - }; - // Display a new channel - // TODO extract into UI method - //var display = function (curvePublic) { - //curvePublic = curvePublic; - /* - ui.hideInfo(); - var $chat = ui.getChannel(curvePublic); - if (!$chat) { - $chat = ui.createChat(curvePublic); - ui.createChatBox(proxy, $chat, curvePublic); - } - // Show the correct div - ui.hideChat(); - $chat.show(); - - // TODO set this attr per-messenger - messenger.setActive(curvePublic); - // TODO don't mark messages as read unless you have displayed them - - refresh(curvePublic);*/ - //}; - - // TODO take a callback - var remove = function (curvePublic) { + messenger.removeFriend = function (curvePublic, cb) { + // TODO throw if no callback var data = getFriend(proxy, curvePublic); var channel = channels[data.channel]; var msg = [Types.unfriend, proxy.curvePublic, +new Date()]; var msgStr = JSON.stringify(msg); var cryptMsg = channel.encryptor.encrypt(msgStr); channel.wc.bcast(cryptMsg).then(function () { - removeFromFriendList(common, curvePublic, function () { - channel.wc.leave(Types.unfriend); - channel.removeUI(); + delete friends[curvePublic]; + Realtime.whenRealtimeSyncs(realtime, function () { + cb(); }); }, function (err) { console.error(err); + cb(err); }); }; // Open the channels + // TODO (curvePublic, cb) => (e) // READY var openFriendChannel = function (data, f) { var keys = Curve.deriveKeys(data.curvePublic, proxy.curvePrivate); var encryptor = Curve.createEncryptor(keys); network.join(data.channel).then(function (chan) { var channel = channels[data.channel] = { + id: data.channel, sending: false, friendEd: f, keys: keys, + curve: data.curvePublic, encryptor: encryptor, messages: [], - unfriend: function () { - DEBUG('unfriend'); - remove(data.curvePublic); - }, - refresh: function () { - DEBUG('refresh'); - refresh(data.curvePublic); - }, - notify: function () { - //ui.notify(data.curvePublic); - DEBUG('notify'); - common.notify(); // HERE - }, - unnotify: function () { - DEBUG('unnotify'); - //ui.unnotify(data.curvePublic); - }, - removeUI: function () { - DEBUG('remove-ui'); - //ui.remove(data.curvePublic); - }, - updateUI: function (/*types*/) { - DEBUG('update-ui'); - //ui.update(data.curvePublic, types); - }, - updateStatus: function () { - DEBUG('update-status'); - //ui.updateStatus(data.curvePublic, - //channel.getStatus(data.curvePublic)); - }, - setLastMessageRead: function (hash) { - DEBUG('updateLastKnownHash'); - data.lastKnownHash = hash; - }, - getLastMessageRead: function () { - return data.lastKnownHash; - }, - isActive: function () { - return data.curvePublic === messenger.active; - }, - getMessagesSinceDisconnect: function () { - getChannelMessagesSince(network, proxy, chan, data, keys); - }, wc: chan, userList: [], mapId: {}, - getStatus: function (curvePublic) { - return channel.userList.some(function (nId) { - return channel.mapId[nId] === curvePublic; - }); - }, - getPreviousMessages: function () { - var history = channel.messages; - if (!history || !history.length) { - // TODO ask for default history? - return; - } - - var oldestMessage = history[0]; - if (!oldestMessage) { - return; // nothing to fetch - } - - var messageHash = oldestMessage[0]; - getMoreHistory(network, chan, messageHash, 10); - }, send: function (payload, cb) { if (!network.webChannels.some(function (wc) { if (wc.id === channel.wc.id) { return true; } @@ -475,7 +561,7 @@ define([ }, function (err) { cb(err); }); - }, + } }; chan.on('message', function (msg, sender) { onMessage(common, msg, sender, chan); @@ -489,7 +575,6 @@ define([ var msgStr = JSON.stringify(msg); var cryptMsg = channel.encryptor.encrypt(msgStr); network.sendto(peer, cryptMsg); - channel.updateStatus(); }; chan.members.forEach(function (peer) { if (peer === Msg.hk) { return; } @@ -498,12 +583,19 @@ define([ }); chan.on('join', onJoining); chan.on('leave', function (peer) { + var curvePublic = channel.mapId[peer]; + console.log(curvePublic); + var i = channel.userList.indexOf(peer); while (i !== -1) { channel.userList.splice(i, 1); i = channel.userList.indexOf(peer); } - channel.updateStatus(); + // update status + if (!curvePublic) { return; } + messenger.handlers.leave.forEach(function (f) { + f(curvePublic, channel.id); + }); }); getChannelMessagesSince(network, proxy, chan, data, keys); @@ -512,180 +604,100 @@ define([ }); }; + // FIXME don't do this implicitly. + // get messages when a channel is opened, and if it reconnects + /* messenger.getLatestMessages = function () { Object.keys(channels).forEach(function (id) { if (id === 'me') { return; } var friend = channels[id]; - friend.getMessagesSinceDisconnect(); - friend.refresh(); + //friend.getMessagesSinceDisconnect(); + //friend.refresh(); }); - }; + };*/ + // FIXME this shouldn't be necessary + /* messenger.cleanFriendChannels = function () { Object.keys(channels).forEach(function (id) { delete channels[id]; }); + };*/ + + messenger.getFriendList = function (cb) { + var friends = proxy.friends; + if (!friends) { return void cb(void 0, []); } + + cb(void 0, Object.keys(proxy.friends).filter(function (k) { + return k !== 'me'; + })); }; - var openFriendChannels = messenger.openFriendChannels = function () { + messenger.openFriendChannels = function () { eachFriend(friends, openFriendChannel); }; - //messenger.setEditable = ui.setEditable; - openFriendChannels(); + messenger.openFriendChannel = function (curvePublic, cb) { + if (typeof(curvePublic) !== 'string') { return void cb('INVALID_ID'); } + if (typeof(cb) !== 'function') { throw new Error('expected callback'); } - // TODO split loop innards into ui methods - var checkNewFriends = function () { - eachFriend(friends, function (friend, id) { - if (!channels[id]) { - openFriendChannel(friend, id); - } - }); + var friend = clone(friends[curvePublic]); + if (typeof(friend) !== 'object') { + return void cb('NO_FRIEND_DATA'); + } + var channel = friend.channel; + if (!channel) { return void cb('E_NO_CHANNEL'); } + joining[channel] = cb; + openFriendChannel(friend, curvePublic); }; - common.onDisplayNameChanged(function () { - checkNewFriends(); - updateMyData(proxy); - }); - - return messenger; - }; - - // Invitation - // FIXME there are too many functions with this name - var addToFriendList = Msg.addToFriendList = function (common, data, cb) { - var proxy = common.getProxy(); - var friends = getFriendList(proxy); - var pubKey = data.curvePublic; - - if (pubKey === proxy.curvePublic) { return void cb("E_MYKEY"); } + messenger.sendMessage = function (curvePublic, payload, cb) { + var channel = getChannel(curvePublic); + if (!channel) { return void cb('NO_CHANNEL'); } + if (!network.webChannels.some(function (wc) { + if (wc.id === channel.wc.id) { return true; } + })) { + return void cb('NO_SUCH_CHANNEL'); + } - friends[pubKey] = data; + var msg = [Types.message, proxy.curvePublic, +new Date(), payload]; + var msgStr = JSON.stringify(msg); + var cryptMsg = channel.encryptor.encrypt(msgStr); - Realtime.whenRealtimeSyncs(common.getRealtime(), function () { - cb(); - common.pinPads([data.channel]); - }); - common.changeDisplayName(proxy[common.displayNameKey]); - }; + channel.wc.bcast(cryptMsg).then(function () { + pushMsg(channel, cryptMsg); + cb(); + }, function (err) { + cb(err); + }); + }; - /* Used to accept friend requests within apps other than /contacts/ */ - Msg.addDirectMessageHandler = function (common) { - var network = common.getNetwork(); - var proxy = common.getProxy(); - if (!network) { return void console.error('Network not ready'); } - network.on('message', function (message, sender) { - var msg; - if (sender === network.historyKeeper) { return; } - try { - var parsed = common.parsePadUrl(window.location.href); - if (!parsed.hashData) { return; } - var chan = parsed.hashData.channel; - // Decrypt - var keyStr = parsed.hashData.key; - var cryptor = Crypto.createEditCryptor(keyStr); - var key = cryptor.cryptKey; - var decryptMsg; - try { - decryptMsg = Crypto.decrypt(message, key); - } catch (e) { - // If we can't decrypt, it means it is not a friend request message - } - if (!decryptMsg) { return; } - // Parse - msg = JSON.parse(decryptMsg); - if (msg[1] !== parsed.hashData.channel) { return; } - var msgData = msg[2]; - var msgStr; - if (msg[0] === "FRIEND_REQ") { - msg = ["FRIEND_REQ_NOK", chan]; - var todo = function (yes) { - if (yes) { - pending[sender] = msgData; - msg = ["FRIEND_REQ_OK", chan, createData(common, msgData.channel)]; - } - msgStr = Crypto.encrypt(JSON.stringify(msg), key); - network.sendto(sender, msgStr); - }; - var existing = getFriend(proxy, msgData.curvePublic); - if (existing) { - todo(true); - return; - } - var confirmMsg = common.Messages._getKey('contacts_request', [ - common.fixHTML(msgData.displayName) - ]); - common.confirm(confirmMsg, todo, null, true); - return; - } - if (msg[0] === "FRIEND_REQ_OK") { - var idx = pendingRequests.indexOf(sender); - if (idx !== -1) { pendingRequests.splice(idx, 1); } + messenger.getStatus = function (curvePublic, cb) { + var channel = getChannel(curvePublic); + if (!channel) { return void cb('NO_SUCH_CHANNEL'); } + var online = channel.userList.some(function (nId) { + return channel.mapId[nId] === curvePublic; + }); + cb(void 0, online); + }; - // FIXME clarify this function's name - addToFriendList(common, msgData, function (err) { - if (err) { - return void common.log(common.Messages.contacts_addError); - } - common.log(common.Messages.contacts_added); - var msg = ["FRIEND_REQ_ACK", chan]; - var msgStr = Crypto.encrypt(JSON.stringify(msg), key); - network.sendto(sender, msgStr); - }); - return; - } - if (msg[0] === "FRIEND_REQ_NOK") { - var i = pendingRequests.indexOf(sender); - if (i !== -1) { pendingRequests.splice(i, 1); } - common.log(common.Messages.contacts_rejected); - common.changeDisplayName(proxy[common.displayNameKey]); - return; - } - if (msg[0] === "FRIEND_REQ_ACK") { - var data = pending[sender]; - if (!data) { return; } - addToFriendList(common, data, function (err) { - if (err) { - return void common.log(common.Messages.contacts_addError); - } - common.log(common.Messages.contacts_added); - }); - return; + // TODO emit friend-list-changed event + messenger.checkNewFriends = function () { + eachFriend(friends, function (friend, id) { + if (!channels[id]) { + openFriendChannel(friend, id); } - // TODO: timeout ACK: warn the user - } catch (e) { - console.error("Cannot parse direct message", msg || message, "from", sender, e); - } - }); - }; + }); + }; - Msg.getPending = function () { - return pendingRequests; - }; + messenger.getFriendInfo = function (curvePublic, cb) { + var friend = friends[curvePublic]; + if (!friend) { return void cb('NO_SUCH_FRIEND'); } + cb(void 0, friend); + }; - Msg.inviteFromUserlist = function (common, netfluxId) { - var network = common.getNetwork(); - var parsed = common.parsePadUrl(window.location.href); - if (!parsed.hashData) { return; } - // Message - var chan = parsed.hashData.channel; - var myData = createData(common); - var msg = ["FRIEND_REQ", chan, myData]; - // Encryption - var keyStr = parsed.hashData.key; - var cryptor = Crypto.createEditCryptor(keyStr); - var key = cryptor.cryptKey; - var msgStr = Crypto.encrypt(JSON.stringify(msg), key); - // 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[common.displayNameKey]); - } - network.sendto(netfluxId, msgStr); + return messenger; }; return Msg; diff --git a/www/contacts/main.less b/www/contacts/main.less index 6805aa82d..d8d50a41f 100644 --- a/www/contacts/main.less +++ b/www/contacts/main.less @@ -52,6 +52,7 @@ body { width: 350px; height: 100%; background-color: lighten(@bg-color, 10%); + overflow-y: auto; .friend { background: rgba(0,0,0,0.1); padding: 5px; From 89a13d4b2183ebede98c37d1dda2c52687aa34a7 Mon Sep 17 00:00:00 2001 From: ansuz Date: Tue, 22 Aug 2017 15:55:49 +0200 Subject: [PATCH 03/12] work on contacts2 until feature parity is reached --- customize.dist/pages.js | 4 + customize.dist/template.js | 7 +- www/contacts2/index.html | 30 ++++ www/contacts2/inner.html | 17 ++ www/contacts2/inner.js | 13 ++ www/contacts2/main.js | 81 +++++++++ www/contacts2/main.less | 244 +++++++++++++++++++++++++ www/contacts2/messenger-ui.js | 324 ++++++++++++++++++++++++++++++++++ 8 files changed, 718 insertions(+), 2 deletions(-) create mode 100644 www/contacts2/index.html create mode 100644 www/contacts2/inner.html create mode 100644 www/contacts2/inner.js create mode 100644 www/contacts2/main.js create mode 100644 www/contacts2/main.less create mode 100644 www/contacts2/messenger-ui.js diff --git a/customize.dist/pages.js b/customize.dist/pages.js index 9e2759786..aac6ddfa7 100644 --- a/customize.dist/pages.js +++ b/customize.dist/pages.js @@ -635,6 +635,10 @@ define([ return loadingScreen(); }; + Pages['/contacts2/'] = Pages['/contacts2/index.html'] = function () { + return loadingScreen(); + }; + Pages['/pad/'] = Pages['/pad/index.html'] = function () { return loadingScreen(); }; diff --git a/customize.dist/template.js b/customize.dist/template.js index a9067f35f..a980270a3 100644 --- a/customize.dist/template.js +++ b/customize.dist/template.js @@ -9,7 +9,7 @@ define([ $(function () { var $body = $('body'); var isMainApp = function () { - return /^\/(pad|code|slide|poll|whiteboard|file|media|contacts|drive|settings|profile|todo)\/$/.test(location.pathname); + return /^\/(pad|code|slide|poll|whiteboard|file|media|contacts|contacts2|drive|settings|profile|todo)\/$/.test(location.pathname); }; var infoPage = function () { @@ -52,9 +52,12 @@ $(function () { } else if (/\/file\//.test(pathname)) { $('body').append(h('body', Pages[pathname]()).innerHTML); require([ '/file/main.js' ], ready); - } else if (/contacts/.test(pathname)) { + } else if (/^\/contacts\/$/.test(pathname)) { $('body').append(h('body', Pages[pathname]()).innerHTML); require([ '/contacts/main.js' ], ready); + } else if (/contacts2/.test(pathname)) { + $('body').append(h('body', Pages[pathname]()).innerHTML); + require([ '/contacts2/main.js' ], ready); } else if (/pad/.test(pathname)) { $('body').append(h('body', Pages[pathname]()).innerHTML); require([ '/pad/main.js' ], ready); diff --git a/www/contacts2/index.html b/www/contacts2/index.html new file mode 100644 index 000000000..a76879a6d --- /dev/null +++ b/www/contacts2/index.html @@ -0,0 +1,30 @@ + + + + CryptPad + + + + + + + + diff --git a/www/contacts2/inner.html b/www/contacts2/inner.html new file mode 100644 index 000000000..ebfb164c8 --- /dev/null +++ b/www/contacts2/inner.html @@ -0,0 +1,17 @@ + + + + + + + + + +
+
+
+
+
+ + + diff --git a/www/contacts2/inner.js b/www/contacts2/inner.js new file mode 100644 index 000000000..556f37ee3 --- /dev/null +++ b/www/contacts2/inner.js @@ -0,0 +1,13 @@ +define([ + 'jquery', + 'css!/bower_components/components-font-awesome/css/font-awesome.min.css', + 'css!/bower_components/bootstrap/dist/css/bootstrap.min.css', + 'less!/contacts/main.less', + 'less!/customize/src/less/toolbar.less', +], function ($) { + $('.loading-hidden').removeClass('loading-hidden'); + // dirty hack to get rid the flash of the lock background + setTimeout(function () { + $('#app').addClass('ready'); + }, 100); +}); diff --git a/www/contacts2/main.js b/www/contacts2/main.js new file mode 100644 index 000000000..9e318dac9 --- /dev/null +++ b/www/contacts2/main.js @@ -0,0 +1,81 @@ +define([ + 'jquery', + '/bower_components/chainpad-crypto/crypto.js', + '/common/toolbar2.js', + '/common/cryptpad-common.js', + + '/common/common-messenger.js', + '/contacts2/messenger-ui.js', + + 'css!/bower_components/components-font-awesome/css/font-awesome.min.css', + 'less!/customize/src/less/cryptpad.less', +], function ($, Crypto, Toolbar, Cryptpad, Messenger, UI) { + var Messages = Cryptpad.Messages; + + var APP = window.APP = { + Cryptpad: Cryptpad + }; + + $(function () { + + var andThen = function () { + Cryptpad.addLoadingScreen(); + + var ifrw = $('#pad-iframe')[0].contentWindow; + var $iframe = $('#pad-iframe').contents(); + //var $appContainer = $iframe.find('#app'); + var $list = $iframe.find('#friendList'); + var $messages = $iframe.find('#messaging'); + var $bar = $iframe.find('.toolbar-container'); + + var displayed = ['useradmin', 'newpad', 'limit', 'pageTitle']; + + + var configTb = { + displayed: displayed, + ifrw: ifrw, + common: Cryptpad, + $container: $bar, + network: Cryptpad.getNetwork(), + pageTitle: Messages.contacts_title, + }; + var toolbar = APP.toolbar = Toolbar.create(configTb); + toolbar.$rightside.html(''); // Remove the drawer if we don't use it to hide the toolbar + + Cryptpad.getProxy().on('disconnect', function () { + Cryptpad.alert(Messages.common_connectionLost, undefined, true); + Cryptpad.enableMessaging(false); + }); + Cryptpad.getProxy().on('reconnect', function (uid) { + console.error('reconnecting: ', uid); + Cryptpad.findOKButton().click(); + + //APP.messenger.cleanFriendChannels(); + //APP.messenger.openFriendChannels(); + //APP.messenger.setEditable(true); + }); + + var $infoBlock = $('
', {'class': 'info'}).appendTo($messages); + $('

').text(Messages.contacts_info1).appendTo($infoBlock); + var $ul = $('
    ').appendTo($infoBlock); + $('
  • ').text(Messages.contacts_info2).appendTo($ul); + $('
  • ').text(Messages.contacts_info3).appendTo($ul); + //$('
  • ').text(Messages.contacts_info4).appendTo($ul); + + + //var ui = APP.ui = Cryptpad.initMessagingUI(Cryptpad, $list, $messages); + //APP.messenger = Cryptpad.initMessaging(Cryptpad, ui); + + var messenger = window.messenger = Messenger.messenger(Cryptpad); + UI.create(messenger, $list, $messages); + + Cryptpad.removeLoadingScreen(); + }; + + Cryptpad.ready(function () { + andThen(); + Cryptpad.reportAppUsage(); + }); + + }); +}); diff --git a/www/contacts2/main.less b/www/contacts2/main.less new file mode 100644 index 000000000..6805aa82d --- /dev/null +++ b/www/contacts2/main.less @@ -0,0 +1,244 @@ +@import "/customize/src/less/variables.less"; +@import "/customize/src/less/mixins.less"; + +@button-border: 2px; +@bg-color: @toolbar-friends-bg; +@color: @toolbar-friends-color; + +html, body { + margin: 0px; + height: 100%; +} + +#toolbar { + display: flex; // We need this to remove a 3px border at the bottom of the toolbar +} + +body { + display: flex; + flex-flow: column; +} +#app { + flex: 1; + display: flex; + justify-content: center; + align-items: center; + min-height: 0; +} + +#app.ready { + //background: url('/customize/bg3.jpg') no-repeat center center; + background-size: cover; + background-position: center; +} +.cryptpad-toolbar { + padding: 0px; + display: inline-block; +} + + +@keyframes example { + 0% { + background: rgba(0,0,0,0.1); + } + 50% { + background: rgba(0,0,0,0.3); + } + 100% { + background: rgba(0,0,0,0.1); + } +} +#friendList { + width: 350px; + height: 100%; + background-color: lighten(@bg-color, 10%); + .friend { + background: rgba(0,0,0,0.1); + padding: 5px; + margin: 10px; + cursor: pointer; + &:hover { + background-color: rgba(0,0,0,0.3); + } + &.notify { + animation: example 2s ease-in-out infinite; + } + } +} + +#friendList .friend, #messaging .avatar { + .avatar(30px); + &.avatar { + display: flex; + } + cursor: pointer; + color: @color; + media-tag { + img { + color: #000; + } + } + media-tag, .default { + margin-right: 5px; + } + .status { + width: 5px; + display: inline-block; + position: absolute; + right: 0; + top: 0; + bottom: 0; + opacity: 0.7; + background-color: #777; + &.online { + background-color: green; + } + &.offline { + background-color: red; + } + } +} + +#friendList { + .friend { + position: relative; + } + .remove { + cursor: pointer; + width: 20px; + &:hover { + color: darken(@color, 20%); + } + } +} + +.placeholder (@color: #bbb) { + &::-webkit-input-placeholder { /* WebKit, Blink, Edge */ + color: @color; + } + &:-moz-placeholder { /* Mozilla Firefox 4 to 18 */ + color: @color; + opacity: 1; + } + &::-moz-placeholder { /* Mozilla Firefox 19+ */ + color: @color; + opacity: 1; + } + &:-ms-input-placeholder { /* Internet Explorer 10-11 */ + color: @color; + } + &::-ms-input-placeholder { /* Microsoft Edge */ + color: @color; + } +} + +#messaging { + flex: 1; + height: 100%; + background-color: lighten(@bg-color, 20%); + min-width: 0; + + .info { + padding: 20px; + } + .header { + background-color: lighten(@bg-color, 15%); + padding: 0; + display: flex; + justify-content: space-between; + align-items: center; + height: 50px; + + .hover () { + height: 100%; + line-height: 30px; + padding: 10px; + &:hover { + background-color: rgba(50,50,50,0.3); + } + } + + .avatar, + .right-col { + flex:1 1 auto; + } + .remove-history { + .hover; + } + .avatar { + margin: 10px; + } + .more-history { + display: none; + //.hover; + } + } + .chat { + height: 100%; + display: flex; + flex-flow: column; + .messages { + padding: 0 20px; + margin: 10px 0; + flex: 1; + overflow-x: auto; + .message { + & > div { + padding: 0 10px; + } + .content { + overflow: hidden; + word-wrap: break-word; + &> * { + margin: 0; + } + } + .date { + display: none; + font-style: italic; + } + .sender { + margin-top: 10px; + font-weight: bold; + background-color: rgba(0,0,0,0.1); + } + } + } + } + .input { + background-color: lighten(@bg-color, 15%); + height: auto; + min-height: 50px; + display: flex; + align-items: center; + justify-content: center; + padding: 0 75px; + textarea { + margin: 5px 0; + padding: 0 10px; + border: none; + height: 50px; + flex: 1; + background-color: darken(@bg-color, 10%); + color: @color; + resize: none; + line-height: 50px; + overflow-y: auto; + .placeholder(#bbb); + &[disabled=true] { + .placeholder(#999); + } + &:placeholder-shown { line-height: 50px; } + } + button { + height: 50px; + border-radius: 0; + border: none; + background-color: darken(@bg-color, 15%); + &:hover { + background-color: darken(@bg-color, 20%); + } + } + } +} + diff --git a/www/contacts2/messenger-ui.js b/www/contacts2/messenger-ui.js new file mode 100644 index 000000000..9f80f4ac6 --- /dev/null +++ b/www/contacts2/messenger-ui.js @@ -0,0 +1,324 @@ +define([ + 'jquery', + '/common/cryptpad-common.js', + '/common/hyperscript.js', + '/bower_components/marked/marked.min.js', +], function ($, Cryptpad, h, Marked) { + // TODO use our fancy markdown and support media-tags + Marked.setOptions({ sanitize: true, }); + + var UI = {}; + var Messages = Cryptpad.Messages; + + var stub = function (label) { + console.error('stub: ' + label); + }; + + var dataQuery = function (curvePublic) { + return '[data-key="' + curvePublic + '"]'; + }; + + UI.create = function (messenger, $userlist, $messages) { + var state = { + active: '', + }; + var avatars = state.avatars = {}; + var setActive = function (curvePublic) { + state.active = curvePublic; + }; + var isActive = function (curvePublic) { + return curvePublic === state.active; + }; + + var find = {}; + find.inList = function (curvePublic) { + return $userlist.find(dataQuery(curvePublic)); + }; + + var notify = function (curvePublic) { + find.inList(curvePublic).addClass('notify'); + }; + var unnotify = function (curvePublic) { + find.inList(curvePublic).removeClass('notify'); + }; + + var markup = {}; + markup.message = function (msg, name) { + return h('div.message', { + title: msg.time? new Date(msg.time).toLocaleString(): '?', + }, [ + name? h('div.sender', name): undefined, + h('div.content', msg.text), + ]); + }; + + markup.chatbox = function (curvePublic, data) { + var moreHistory = h('span.more-history', ['get more history']); // TODO translate + var displayName = data.displayName; + + $(moreHistory).click(function () { + stub('get older history'); + console.log('getting history'); + }); + + var removeHistory = h('span.remove-history.fa.fa-eraser', { + title: Messages.contacts_removeHistoryTitle + }); + + $(removeHistory).click(function () { + Cryptpad.confirm(Messages.contacts_confirmRemoveHistory, function (yes) { + if (!yes) { return; } + Cryptpad.clearOwnedChannel(data.channel, function (e) { + if (e) { + console.error(e); + Cryptpad.alert(Messages.contacts_removeHistoryServerError); + return; + } + }); + }); + }); + + var avatar = h('div.avatar'); + var header = h('div.header', [ + avatar, + moreHistory, + removeHistory, + ]); + var messages = h('div.messages'); + var input = h('textarea', { + placeholder: Messages.contacts_typeHere + }); + var sendButton = h('button.btn.btn-primary.fa.fa-paper-plane', { + title: Messages.contacts_send, + }); + + var rightCol = h('span.right-col', [ + h('span.name', displayName), + ]); + + var $avatar = $(avatar); + if (data.avatar && avatars[data.avatar]) { + $avatar.append(avatars[data.avatar]).append(rightCol); + } else { + Cryptpad.displayAvatar($avatar, data.avatar, data.displayName, function ($img) { + if (data.avatar && $img) { + avatars[data.avatar] = $img[0].outerHTML; + } + $avatar.append(rightCol); + }); + } + + var sending = false; + var send = function (content) { + if (sending) { return false; } + sending = true; + messenger.sendMessage(curvePublic, content, function (e) { + if (e) { + // failed to send + return void console.error('failed to send'); + } + input.value = ''; + sending = false; + console.log('sent successfully'); + }); + }; + + var onKeyDown = function (e) { + // ignore anything that isn't 'enter' + if (e.keyCode !== 13) { return; } + // send unless they're holding a ctrl-key or shift + if (!e.ctrlKey && !e.shiftKey) { + send(this.value); + return false; + } + + // insert a newline if they're holding either + var val = this.value; + var start = this.selectionState; + var end = this.selectionEnd; + + if (![start,end].some(function (x) { + return typeof(x) !== 'number'; + })) { + this.value = val.slice(0, start) + '\n' + val.slice(end); + this.selectionStart = this.selectionEnd = start + 1; + } else if (document.selection && document.selection.createRange) { + this.focus(); + var range = document.selection.createRange(); + range.text = '\r\n'; + range.collapse(false); + range.select(); + } + return false; + }; + $(input).on('keydown', onKeyDown); + $(sendButton).click(function () { send(input.value); }); + + return h('div.chat', { + 'data-key': curvePublic, + }, [ + header, + messages, + h('div.input', [ + input, + sendButton, + ]), + ]); + }; + + var hideInfo = function () { + $messages.find('.info').hide(); + }; + + var getChat = function (curvePublic) { + return $messages.find(dataQuery(curvePublic)); + }; + + var updateStatus = function (curvePublic) { + var $status = find.inList(curvePublic).find('.status'); + messenger.getStatus(curvePublic, function (e, online) { + if (e) { return void console.error(e); } + if (online) { + return void $status + .removeClass('offline').addClass('online'); + } + $status.removeClass('online').addClass('offline'); + }); + }; + + var display = function (curvePublic) { + setActive(curvePublic); + unnotify(curvePublic); + var $chat = getChat(curvePublic); + hideInfo(); + $messages.find('div.chat[data-key]').hide(); + if ($chat.length) { + return void $chat.show(); + } + messenger.getFriendInfo(curvePublic, function (e, info) { + if (e) { return void console.error(e); } // FIXME + $messages.append(markup.chatbox(curvePublic, info)); + }); + }; + + var removeFriend = function (curvePublic) { + messenger.removeFriend(curvePublic, function (e, removed) { + if (e) { return void console.error(e); } + console.log(removed); + }); + }; + + var friendExistsInUserList = function (curvePublic) { + return !!$userlist.find(dataQuery(curvePublic)).length; + }; + + markup.friend = function (data) { + var curvePublic = data.curvePublic; + var friend = h('div.friend.avatar', { + 'data-key': curvePublic, + }); + + var remove = h('span.remove.fa.fa-user-times', { + title: Messages.contacts_remove + }); + var status = h('span.status'); + var rightCol = h('span.right-col', [ + h('span.name', [data.displayName]), + remove, + ]); + + var $friend = $(friend) + .click(function () { + display(curvePublic); + }) + .dblclick(function () { + if (data.profile) { window.open('/profile/#' + data.profile); } + }); + + $(remove).click(function (e) { + e.stopPropagation(); + Cryptpad.confirm(Messages._getKey('contacts_confirmRemove', [ + Cryptpad.fixHTML(data.displayName) + ]), function (yes) { + if (!yes) { return; } + stub('remove friend: ' + curvePublic); + removeFriend(curvePublic); + }); + }); + + if (data.avatar && avatars[data.avatar]) { + $friend.append(avatars[data.avatar]); + $friend.append(rightCol); + } else { + Cryptpad.displayAvatar($friend, data.avatar, data.displayName, function ($img) { + if (data.avatar && $img) { + avatars[data.avatar] = $img[0].outerHTML; + } + $friend.append(rightCol); + }); + } + $friend.append(status); + return $friend; + }; + + var displayNames = {}; + + messenger.on('message', function (message) { + console.log(JSON.stringify(message)); + Cryptpad.notify(); + var curvePublic = message.curve; + + if (!isActive(curvePublic)) { notify(curvePublic); } + + var name = displayNames[curvePublic]; + var chat = getChat(curvePublic, name); + var el_message = markup.message(message, name); + + var $chat = $(chat); + console.log(chat, $chat, el_message.outerHTML); + $chat.find('.messages').append(el_message); + + // TODO notify if a message is newer than `lastKnownHash` + }); + + messenger.on('join', function (curvePublic, channel) { + console.log('join', curvePublic, channel); + updateStatus(curvePublic); + }); + messenger.on('leave', function (curvePublic, channel) { + console.log('leave', curvePublic, channel); + updateStatus(curvePublic); + }); + + // change in your friend list + messenger.on('update', function (info, curvePublic) { + curvePublic = curvePublic; + }); + + Cryptpad.onDisplayNameChanged(function () { + messenger.checkNewFriends(); + messenger.updateMyData(); + }); + + messenger.getFriendList(function (e, keys) { + keys.forEach(function (k) { + messenger.openFriendChannel(k, function (e) { + if (e) { return void console.error(e); } + // don't add friends that are already in your userlist + if (friendExistsInUserList(k)) { return; } + + messenger.getFriendInfo(k, function (e, info) { + if (e) { return console.error(e); } + var curvePublic = info.curvePublic; + var name = displayNames[curvePublic] = info.displayName; + var friend = markup.friend(info, name); + $userlist.append(friend); + updateStatus(curvePublic); + }); + }); + }); + }); + }; + + return UI; +}); From 443d8a8941c5b2bbb259b10319665b09b63275f1 Mon Sep 17 00:00:00 2001 From: ansuz Date: Thu, 24 Aug 2017 11:29:42 +0200 Subject: [PATCH 04/12] remove unnecessary files --- www/contacts2/inner.js | 13 --- www/contacts2/main.less | 244 ---------------------------------------- 2 files changed, 257 deletions(-) delete mode 100644 www/contacts2/inner.js delete mode 100644 www/contacts2/main.less diff --git a/www/contacts2/inner.js b/www/contacts2/inner.js deleted file mode 100644 index 556f37ee3..000000000 --- a/www/contacts2/inner.js +++ /dev/null @@ -1,13 +0,0 @@ -define([ - 'jquery', - 'css!/bower_components/components-font-awesome/css/font-awesome.min.css', - 'css!/bower_components/bootstrap/dist/css/bootstrap.min.css', - 'less!/contacts/main.less', - 'less!/customize/src/less/toolbar.less', -], function ($) { - $('.loading-hidden').removeClass('loading-hidden'); - // dirty hack to get rid the flash of the lock background - setTimeout(function () { - $('#app').addClass('ready'); - }, 100); -}); diff --git a/www/contacts2/main.less b/www/contacts2/main.less deleted file mode 100644 index 6805aa82d..000000000 --- a/www/contacts2/main.less +++ /dev/null @@ -1,244 +0,0 @@ -@import "/customize/src/less/variables.less"; -@import "/customize/src/less/mixins.less"; - -@button-border: 2px; -@bg-color: @toolbar-friends-bg; -@color: @toolbar-friends-color; - -html, body { - margin: 0px; - height: 100%; -} - -#toolbar { - display: flex; // We need this to remove a 3px border at the bottom of the toolbar -} - -body { - display: flex; - flex-flow: column; -} -#app { - flex: 1; - display: flex; - justify-content: center; - align-items: center; - min-height: 0; -} - -#app.ready { - //background: url('/customize/bg3.jpg') no-repeat center center; - background-size: cover; - background-position: center; -} -.cryptpad-toolbar { - padding: 0px; - display: inline-block; -} - - -@keyframes example { - 0% { - background: rgba(0,0,0,0.1); - } - 50% { - background: rgba(0,0,0,0.3); - } - 100% { - background: rgba(0,0,0,0.1); - } -} -#friendList { - width: 350px; - height: 100%; - background-color: lighten(@bg-color, 10%); - .friend { - background: rgba(0,0,0,0.1); - padding: 5px; - margin: 10px; - cursor: pointer; - &:hover { - background-color: rgba(0,0,0,0.3); - } - &.notify { - animation: example 2s ease-in-out infinite; - } - } -} - -#friendList .friend, #messaging .avatar { - .avatar(30px); - &.avatar { - display: flex; - } - cursor: pointer; - color: @color; - media-tag { - img { - color: #000; - } - } - media-tag, .default { - margin-right: 5px; - } - .status { - width: 5px; - display: inline-block; - position: absolute; - right: 0; - top: 0; - bottom: 0; - opacity: 0.7; - background-color: #777; - &.online { - background-color: green; - } - &.offline { - background-color: red; - } - } -} - -#friendList { - .friend { - position: relative; - } - .remove { - cursor: pointer; - width: 20px; - &:hover { - color: darken(@color, 20%); - } - } -} - -.placeholder (@color: #bbb) { - &::-webkit-input-placeholder { /* WebKit, Blink, Edge */ - color: @color; - } - &:-moz-placeholder { /* Mozilla Firefox 4 to 18 */ - color: @color; - opacity: 1; - } - &::-moz-placeholder { /* Mozilla Firefox 19+ */ - color: @color; - opacity: 1; - } - &:-ms-input-placeholder { /* Internet Explorer 10-11 */ - color: @color; - } - &::-ms-input-placeholder { /* Microsoft Edge */ - color: @color; - } -} - -#messaging { - flex: 1; - height: 100%; - background-color: lighten(@bg-color, 20%); - min-width: 0; - - .info { - padding: 20px; - } - .header { - background-color: lighten(@bg-color, 15%); - padding: 0; - display: flex; - justify-content: space-between; - align-items: center; - height: 50px; - - .hover () { - height: 100%; - line-height: 30px; - padding: 10px; - &:hover { - background-color: rgba(50,50,50,0.3); - } - } - - .avatar, - .right-col { - flex:1 1 auto; - } - .remove-history { - .hover; - } - .avatar { - margin: 10px; - } - .more-history { - display: none; - //.hover; - } - } - .chat { - height: 100%; - display: flex; - flex-flow: column; - .messages { - padding: 0 20px; - margin: 10px 0; - flex: 1; - overflow-x: auto; - .message { - & > div { - padding: 0 10px; - } - .content { - overflow: hidden; - word-wrap: break-word; - &> * { - margin: 0; - } - } - .date { - display: none; - font-style: italic; - } - .sender { - margin-top: 10px; - font-weight: bold; - background-color: rgba(0,0,0,0.1); - } - } - } - } - .input { - background-color: lighten(@bg-color, 15%); - height: auto; - min-height: 50px; - display: flex; - align-items: center; - justify-content: center; - padding: 0 75px; - textarea { - margin: 5px 0; - padding: 0 10px; - border: none; - height: 50px; - flex: 1; - background-color: darken(@bg-color, 10%); - color: @color; - resize: none; - line-height: 50px; - overflow-y: auto; - .placeholder(#bbb); - &[disabled=true] { - .placeholder(#999); - } - &:placeholder-shown { line-height: 50px; } - } - button { - height: 50px; - border-radius: 0; - border: none; - background-color: darken(@bg-color, 15%); - &:hover { - background-color: darken(@bg-color, 20%); - } - } - } -} - From b71f1860dba5eb4f832d3ce8f5595dacd4c54651 Mon Sep 17 00:00:00 2001 From: ansuz Date: Thu, 24 Aug 2017 11:31:20 +0200 Subject: [PATCH 05/12] make uid function reusable --- www/common/common-util.js | 5 +++++ www/common/cryptpad-common.js | 1 + www/common/rpc.js | 9 +++------ 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/www/common/common-util.js b/www/common/common-util.js index e09577553..8cbde420c 100644 --- a/www/common/common-util.js +++ b/www/common/common-util.js @@ -7,6 +7,11 @@ define([], function () { }, map)); }; + Util.uid = function () { + return Number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)) + .toString(32).replace(/\./g, ''); + }; + Util.fixHTML = function (str) { if (!str) { return ''; } return str.replace(/[<>&"']/g, function (x) { diff --git a/www/common/cryptpad-common.js b/www/common/cryptpad-common.js index 88ad0fde7..ab936914f 100644 --- a/www/common/cryptpad-common.js +++ b/www/common/cryptpad-common.js @@ -98,6 +98,7 @@ define([ common.createRandomInteger = Util.createRandomInteger; common.getAppType = Util.getAppType; common.notAgainForAnother = Util.notAgainForAnother; + common.uid = Util.uid; // import hash utilities for export var createRandomHash = common.createRandomHash = Hash.createRandomHash; diff --git a/www/common/rpc.js b/www/common/rpc.js index aee717a0a..f088ec0fd 100644 --- a/www/common/rpc.js +++ b/www/common/rpc.js @@ -1,13 +1,10 @@ define([ + '/common/common-util.js', '/bower_components/tweetnacl/nacl-fast.min.js', -], function () { +], function (Util) { var Nacl = window.nacl; - var uid = function () { - return Number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)) - .toString(32).replace(/\./g, ''); - }; - + var uid = Util.uid; var signMsg = function (data, signKey) { var buffer = Nacl.util.decodeUTF8(JSON.stringify(data)); return Nacl.util.encodeBase64(Nacl.sign.detached(buffer, signKey)); From 013b75ae6708f46f798d8379e7c93d272a83dae1 Mon Sep 17 00:00:00 2001 From: ansuz Date: Thu, 24 Aug 2017 11:33:33 +0200 Subject: [PATCH 06/12] implement history range requests --- www/common/common-messenger.js | 203 +++++++++++++++++++++++++++------ www/contacts/main.less | 4 +- www/contacts2/main.js | 6 - www/contacts2/messenger-ui.js | 162 ++++++++++++++++++++------ 4 files changed, 299 insertions(+), 76 deletions(-) diff --git a/www/common/common-messenger.js b/www/common/common-messenger.js index d087294aa..d73e73c6e 100644 --- a/www/common/common-messenger.js +++ b/www/common/common-messenger.js @@ -82,33 +82,6 @@ define([ }); }; - var getMoreHistory = function (network, chan, hash, count) { - var msg = [ 'GET_HISTORY_RANGE', chan.id, { - from: hash, - count: count, - } - ]; - - network.sendto(network.historyKeeper, JSON.stringify(msg)).then(function () { - }, function (err) { - throw new Error(err); - }); - }; - getMoreHistory = getMoreHistory; // FIXME - - var getChannelMessagesSince = function (network, proxy, chan, data, keys) { - var cfg = { - validateKey: keys.validateKey, - owners: [proxy.edPublic, data.edPublic], - lastKnownHash: data.lastKnownHash - }; - var msg = ['GET_HISTORY', chan.id, cfg]; - network.sendto(network.historyKeeper, JSON.stringify(msg)) - .then($.noop, function (err) { - throw new Error(err); - }); - }; - // Invitation // FIXME there are too many functions with this name var addToFriendList = Msg.addToFriendList = function (common, data, cb) { @@ -247,13 +220,20 @@ define([ }; Msg.messenger = function (common) { + 'use strict'; var messenger = { handlers: { message: [], join: [], leave: [], update: [], + new_friend: [], }, + range_requests: {}, + }; + + var eachHandler = function (type, g) { + messenger.handlers[type].forEach(g); }; messenger.on = function (type, f) { @@ -299,6 +279,38 @@ define([ return channels[chanId]; }; + var initRangeRequest = function (txid, curvePublic, sig, cb) { + messenger.range_requests[txid] = { + messages: [], + cb: cb, + curvePublic: curvePublic, + sig: sig, + }; + }; + + var getRangeRequest = function (txid) { + return messenger.range_requests[txid]; + }; + + messenger.getMoreHistory = function (curvePublic, hash, count, cb) { + if (typeof(cb) !== 'function') { return; } + var chan = getChannel(curvePublic); + var txid = common.uid(); + initRangeRequest(txid, curvePublic, hash, cb); + // FIXME hash is not necessarily defined. + var msg = [ 'GET_HISTORY_RANGE', chan.id, { + from: hash, + count: count, + txid: txid, + } + ]; + + network.sendto(network.historyKeeper, JSON.stringify(msg)).then(function () { + }, function (err) { + throw new Error(err); + }); + }; + var getCurveForChannel = function (id) { var channel = channels[id]; if (!channel) { return; } @@ -372,6 +384,27 @@ define([ network.sendto(sender, cryptMsg); }; + var orderMessages = function (curvePublic, new_messages, sig) { + var channel = getChannel(curvePublic); + var messages = channel.messages; + var idx; + messages.some(function (msg, i) { + if (msg.sig === sig) { idx = i; } + return true; + }); + + if (typeof(idx) !== 'undefined') { + console.error('found old message at %s', idx); + } else { + console.error("did not find desired message"); + } + + // TODO improve performance + new_messages.reverse().forEach(function (msg) { + messages.unshift(msg); + }); + }; + var pushMsg = function (channel, cryptMsg) { var msg = channel.encryptor.decrypt(cryptMsg); @@ -447,7 +480,8 @@ define([ var msgStr = JSON.stringify(msg); var cryptMsg = channel.encryptor.encrypt(msgStr); channel.wc.bcast(cryptMsg).then(function () { - channel.refresh(); + // TODO send event + //channel.refresh(); }, function (err) { console.error(err); }); @@ -468,6 +502,56 @@ define([ var onDirectMessage = function (common, msg, sender) { if (sender !== Msg.hk) { return void onIdMessage(msg, sender); } var parsed = JSON.parse(msg); + + if (/HISTORY_RANGE/.test(parsed[0])) { + //console.log(parsed); + var txid = parsed[1]; + var req = getRangeRequest(txid); + var type = parsed[0]; + if (!req) { + return void console.error("received response to unknown request"); + } + + if (type === 'HISTORY_RANGE') { + //console.log(parsed); + req.messages.push(parsed[2]); // TODO use pushMsg instead + } else if (type === 'HISTORY_RANGE_END') { + // process all the messages (decrypt) + var curvePublic = req.curvePublic; + var channel = getChannel(curvePublic); + + var decrypted = req.messages.map(function (msg) { + if (msg[2] !== 'MSG') { return; } + try { + return { + d: JSON.parse(channel.encryptor.decrypt(msg[4])), + sig: msg[4].slice(0, 64), + }; + } catch (e) { + console.log('failed to decrypt'); + return null; + } + }).filter(function (decrypted) { + return decrypted; + }).map(function (O) { + return { + type: O.d[0], + sig: O.sig, + channel: O.d[1], + time: O.d[2], + text: O.d[3], + curve: curvePublic, + }; + }); + + orderMessages(curvePublic, decrypted, req.sig); + return void req.cb(void 0, decrypted); + } else { + console.log(parsed); + } + return; + } + if ((parsed.validateKey || parsed.owners) && parsed.channel) { return; } @@ -510,12 +594,14 @@ define([ }); messenger.removeFriend = function (curvePublic, cb) { - // TODO throw if no callback + if (typeof(cb) !== 'function') { throw new Error('NO_CALLBACK'); } var data = getFriend(proxy, curvePublic); var channel = channels[data.channel]; var msg = [Types.unfriend, proxy.curvePublic, +new Date()]; var msgStr = JSON.stringify(msg); var cryptMsg = channel.encryptor.encrypt(msgStr); + + // TODO emit remove_friend event? channel.wc.bcast(cryptMsg).then(function () { delete friends[curvePublic]; Realtime.whenRealtimeSyncs(realtime, function () { @@ -527,8 +613,20 @@ define([ }); }; - // Open the channels - // TODO (curvePublic, cb) => (e) // READY + var getChannelMessagesSince = function (chan, data, keys) { + console.log('Fetching [%s] messages since [%s]', data.curvePublic, data.lastKnownHash || ''); + var cfg = { + validateKey: keys.validateKey, + owners: [proxy.edPublic, data.edPublic], + lastKnownHash: data.lastKnownHash + }; + var msg = ['GET_HISTORY', chan.id, cfg]; + network.sendto(network.historyKeeper, JSON.stringify(msg)) + .then($.noop, function (err) { + throw new Error(err); + }); + }; + var openFriendChannel = function (data, f) { var keys = Curve.deriveKeys(data.curvePublic, proxy.curvePrivate); var encryptor = Curve.createEncryptor(keys); @@ -570,6 +668,8 @@ define([ var onJoining = function (peer) { if (peer === Msg.hk) { return; } if (channel.userList.indexOf(peer) !== -1) { return; } + + // FIXME this doesn't seem to be mapping correctly channel.userList.push(peer); var msg = [Types.mapId, proxy.curvePublic, chan.myID]; var msgStr = JSON.stringify(msg); @@ -584,7 +684,7 @@ define([ chan.on('join', onJoining); chan.on('leave', function (peer) { var curvePublic = channel.mapId[peer]; - console.log(curvePublic); + console.log(curvePublic); // FIXME var i = channel.userList.indexOf(peer); while (i !== -1) { @@ -598,7 +698,8 @@ define([ }); }); - getChannelMessagesSince(network, proxy, chan, data, keys); + // FIXME don't subscribe to the channel implicitly + getChannelMessagesSince(chan, data, keys); }, function (err) { console.error(err); }); @@ -633,10 +734,10 @@ define([ })); }; +/* messenger.openFriendChannels = function () { eachFriend(friends, openFriendChannel); - }; - + };*/ messenger.openFriendChannel = function (curvePublic, cb) { if (typeof(curvePublic) !== 'string') { return void cb('INVALID_ID'); } @@ -694,9 +795,39 @@ define([ messenger.getFriendInfo = function (curvePublic, cb) { var friend = friends[curvePublic]; if (!friend) { return void cb('NO_SUCH_FRIEND'); } - cb(void 0, friend); + // this clone will be redundant when ui uses postmessage + cb(void 0, clone(friend)); + }; + + messenger.getMyInfo = function (cb) { + cb(void 0, { + curvePublic: proxy.curvePublic, + displayName: common.getDisplayName(), + }); }; + // TODO listen for changes to your friend list + // emit 'update' events for clients + + //var update = function (curvePublic + proxy.on('change', ['friends'], function (o, n, p) { + var curvePublic; + if (o === undefined) { + // new friend added + curvePublic = p.slice(-1)[0]; + eachHandler('new_friend', function (f) { + f(clone(n), curvePublic); + }); + return; + } + + console.error(o, n, p); + }).on('remove', ['friends'], function (o, p) { + console.error(o, p); + }); + + Object.freeze(messenger); + return messenger; }; diff --git a/www/contacts/main.less b/www/contacts/main.less index d8d50a41f..b291328c2 100644 --- a/www/contacts/main.less +++ b/www/contacts/main.less @@ -170,8 +170,8 @@ body { margin: 10px; } .more-history { - display: none; - //.hover; + //display: none; + .hover; } } .chat { diff --git a/www/contacts2/main.js b/www/contacts2/main.js index 9e318dac9..664ffc333 100644 --- a/www/contacts2/main.js +++ b/www/contacts2/main.js @@ -62,14 +62,8 @@ define([ $('
  • ').text(Messages.contacts_info3).appendTo($ul); //$('
  • ').text(Messages.contacts_info4).appendTo($ul); - - //var ui = APP.ui = Cryptpad.initMessagingUI(Cryptpad, $list, $messages); - //APP.messenger = Cryptpad.initMessaging(Cryptpad, ui); - var messenger = window.messenger = Messenger.messenger(Cryptpad); UI.create(messenger, $list, $messages); - - Cryptpad.removeLoadingScreen(); }; Cryptpad.ready(function () { diff --git a/www/contacts2/messenger-ui.js b/www/contacts2/messenger-ui.js index 9f80f4ac6..fed13f108 100644 --- a/www/contacts2/messenger-ui.js +++ b/www/contacts2/messenger-ui.js @@ -10,18 +10,33 @@ define([ var UI = {}; var Messages = Cryptpad.Messages; - var stub = function (label) { - console.error('stub: ' + label); + var m = function (md) { + var d = h('div.content'); + d.innerHTML = Marked(md || ''); + return d; }; var dataQuery = function (curvePublic) { return '[data-key="' + curvePublic + '"]'; }; + var initChannel = function (state, curvePublic, info) { + console.log('initializing channel for [%s]', curvePublic); + //console.log(info); + state.channels[curvePublic] = { + messages: [], + HEAD: info.lastKnownHash, + }; + }; + UI.create = function (messenger, $userlist, $messages) { - var state = { + var state = window.state = { active: '', }; + + state.channels = {}; + var displayNames = state.displayNames = {}; + var avatars = state.avatars = {}; var setActive = function (curvePublic) { state.active = curvePublic; @@ -48,17 +63,40 @@ define([ title: msg.time? new Date(msg.time).toLocaleString(): '?', }, [ name? h('div.sender', name): undefined, - h('div.content', msg.text), + m(msg.text), ]); }; + var getChat = function (curvePublic) { + return $messages.find(dataQuery(curvePublic)); + }; + markup.chatbox = function (curvePublic, data) { var moreHistory = h('span.more-history', ['get more history']); // TODO translate var displayName = data.displayName; + var fetching = false; $(moreHistory).click(function () { - stub('get older history'); + //stub('get older history'); console.log('getting history'); + + // get oldest known message... + var channel = state.channels[curvePublic]; + var sig = !(channel.messages && channel.messages.length)? + channel.HEAD: channel.messages[0].sig; + + fetching = true; + var $messages = $(getChat(curvePublic)).find('.messages'); + messenger.getMoreHistory(curvePublic, sig, 10, function (e, history) { + fetching = false; + if (e) { return void console.error(e); } + history.forEach(function (msg) { + channel.messages.unshift(msg); + var name = displayNames[msg.channel]; + var el_message = markup.message(msg, name); + $messages.prepend(el_message); + }); + }); }); var removeHistory = h('span.remove-history.fa.fa-eraser', { @@ -110,6 +148,7 @@ define([ var sending = false; var send = function (content) { + if (typeof(content) !== 'string' || !content.trim()) { return; } if (sending) { return false; } sending = true; messenger.sendMessage(curvePublic, content, function (e) { @@ -170,14 +209,11 @@ define([ $messages.find('.info').hide(); }; - var getChat = function (curvePublic) { - return $messages.find(dataQuery(curvePublic)); - }; - var updateStatus = function (curvePublic) { var $status = find.inList(curvePublic).find('.status'); + // FIXME this stopped working :( messenger.getStatus(curvePublic, function (e, online) { - if (e) { return void console.error(e); } + if (e) { return void console.error(curvePublic, e); } if (online) { return void $status .removeClass('offline').addClass('online'); @@ -187,17 +223,34 @@ define([ }; var display = function (curvePublic) { + var channel = state.channels[curvePublic]; + var lastMsg = channel.messages.slice(-1)[0]; + + if (lastMsg) { + channel.HEAD = lastMsg.sig; + messenger.setChannelHead(curvePublic, channel.HEAD, function (e) { + if (e) { console.error(e); } + }); + } + setActive(curvePublic); unnotify(curvePublic); var $chat = getChat(curvePublic); hideInfo(); $messages.find('div.chat[data-key]').hide(); if ($chat.length) { + var $chat_messages = $chat.find('div.message'); + if (!$chat_messages.length) { + var $more = $chat.find('.more-history'); + console.log($more); + $more.click(); + } return void $chat.show(); } messenger.getFriendInfo(curvePublic, function (e, info) { if (e) { return void console.error(e); } // FIXME - $messages.append(markup.chatbox(curvePublic, info)); + var chatbox = markup.chatbox(curvePublic, info); + $messages.append(chatbox); }); }; @@ -208,9 +261,9 @@ define([ }); }; - var friendExistsInUserList = function (curvePublic) { +/* var friendExistsInUserList = function (curvePublic) { return !!$userlist.find(dataQuery(curvePublic)).length; - }; + }; */ markup.friend = function (data) { var curvePublic = data.curvePublic; @@ -241,8 +294,10 @@ define([ Cryptpad.fixHTML(data.displayName) ]), function (yes) { if (!yes) { return; } - stub('remove friend: ' + curvePublic); removeFriend(curvePublic); + // TODO remove friend from userlist ui + // FIXME seems to trigger EJOINED from netflux-websocket (from server); + // (tried to join a channel in which you were already present) }); }); @@ -261,32 +316,53 @@ define([ return $friend; }; - var displayNames = {}; + var initializing = true; + + // TODO handle scrolling. messenger.on('message', function (message) { console.log(JSON.stringify(message)); - Cryptpad.notify(); + if (!initializing) { Cryptpad.notify(); } var curvePublic = message.curve; - if (!isActive(curvePublic)) { notify(curvePublic); } - var name = displayNames[curvePublic]; var chat = getChat(curvePublic, name); var el_message = markup.message(message, name); + state.channels[curvePublic].messages.push(message); + var $chat = $(chat); - console.log(chat, $chat, el_message.outerHTML); $chat.find('.messages').append(el_message); + var channel = state.channels[curvePublic]; + if (!channel) { + console.error('expected channel [%s] to be open', curvePublic); + return; + } + + if (isActive(curvePublic)) { + channel.HEAD = message.sig; + messenger.setChannelHead(curvePublic, message.sig, function (e) { + if (e) { return void console.error(e); } + }); + return; + } + var lastMsg = channel.messages.slice(-1)[0]; + if (lastMsg.sig !== channel.HEAD) { + return void notify(curvePublic); + } + unnotify(curvePublic); // TODO notify if a message is newer than `lastKnownHash` }); messenger.on('join', function (curvePublic, channel) { - console.log('join', curvePublic, channel); + //console.log('join', curvePublic, channel); + channel = channel; updateStatus(curvePublic); }); messenger.on('leave', function (curvePublic, channel) { - console.log('leave', curvePublic, channel); + //console.log('leave', curvePublic, channel); + channel = channel; updateStatus(curvePublic); }); @@ -300,20 +376,42 @@ define([ messenger.updateMyData(); }); + // FIXME dirty hack + messenger.getMyInfo(function (e, info) { + displayNames[info.curvePublic] = info.displayName; + }); + messenger.getFriendList(function (e, keys) { - keys.forEach(function (k) { - messenger.openFriendChannel(k, function (e) { + var count = keys.length + 1; + + var ready = function () { + count--; + if (count === 0) { + initializing = false; + Cryptpad.removeLoadingScreen(); + } + }; + + ready(); + keys.forEach(function (curvePublic) { + messenger.getFriendInfo(curvePublic, function (e, info) { if (e) { return void console.error(e); } - // don't add friends that are already in your userlist - if (friendExistsInUserList(k)) { return; } - - messenger.getFriendInfo(k, function (e, info) { - if (e) { return console.error(e); } - var curvePublic = info.curvePublic; - var name = displayNames[curvePublic] = info.displayName; - var friend = markup.friend(info, name); - $userlist.append(friend); + var name = displayNames[curvePublic] = info.displayName; + initChannel(state, curvePublic, info); + + var chatbox = markup.chatbox(curvePublic, info); + $(chatbox).hide(); + $messages.append(chatbox); + + var friend = markup.friend(info, name); + $userlist.append(friend); + messenger.openFriendChannel(curvePublic, function (e) { + if (e) { return void console.error(e); } + ready(info); + ready(); updateStatus(curvePublic); + // don't add friends that are already in your userlist + //if (friendExistsInUserList(k)) { return; } }); }); }); From 78404ce8b71020dbd008747c845f281c3c12faf7 Mon Sep 17 00:00:00 2001 From: ansuz Date: Thu, 24 Aug 2017 11:34:46 +0200 Subject: [PATCH 07/12] add npm sub-commands --- package.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/package.json b/package.json index 9821b6bdb..57acb12b1 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,8 @@ "less": "2.7.1" }, "scripts": { + "start": "node server.js", + "dev": "DEV=1 node server.js", "lint": "jshint --config .jshintrc --exclude-path .jshintignore .", "test": "node TestSelenium.js", "template": "cd customize.dist/src && for page in ../index.html ../privacy.html ../terms.html ../about.html ../contact.html ../what-is-cryptpad.html ../../www/login/index.html ../../www/register/index.html ../../www/settings/index.html ../../www/user/index.html;do echo $page; cp template.html $page; done;" From b75a951a98b5b8821730a6a8c9e0f4738ef1630a Mon Sep 17 00:00:00 2001 From: ansuz Date: Thu, 24 Aug 2017 17:14:03 +0200 Subject: [PATCH 08/12] encode messages with 'author' field instead of 'channel' --- www/common/common-messenger.js | 4 ++-- www/contacts2/messenger-ui.js | 38 ++++++++++++++++++++++++++-------- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/www/common/common-messenger.js b/www/common/common-messenger.js index d73e73c6e..804c26290 100644 --- a/www/common/common-messenger.js +++ b/www/common/common-messenger.js @@ -421,7 +421,7 @@ define([ var res = { type: parsedMsg[0], sig: sig, - channel: parsedMsg[1], + author: parsedMsg[1], time: parsedMsg[2], text: parsedMsg[3], // this makes debugging a whole lot easier @@ -537,7 +537,7 @@ define([ return { type: O.d[0], sig: O.sig, - channel: O.d[1], + author: O.d[1], time: O.d[2], text: O.d[3], curve: curvePublic, diff --git a/www/contacts2/messenger-ui.js b/www/contacts2/messenger-ui.js index fed13f108..4ce818d7f 100644 --- a/www/contacts2/messenger-ui.js +++ b/www/contacts2/messenger-ui.js @@ -58,9 +58,12 @@ define([ }; var markup = {}; - markup.message = function (msg, name) { + markup.message = function (msg) { + var curvePublic = msg.author; + var name = displayNames[msg.author]; return h('div.message', { title: msg.time? new Date(msg.time).toLocaleString(): '?', + 'data-key': curvePublic, }, [ name? h('div.sender', name): undefined, m(msg.text), @@ -71,13 +74,25 @@ define([ return $messages.find(dataQuery(curvePublic)); }; + var normalizeLabels = function ($messagebox) { + $messagebox.find('div.message').toArray().reduce(function (a, b) { + var $b = $(b); + if ($(a).data('key') === $b.data('key')) { + $b.find('.sender').hide(); + return a; + } + return b; + }); + }; + markup.chatbox = function (curvePublic, data) { - var moreHistory = h('span.more-history', ['get more history']); // TODO translate + var moreHistory = h('span.more-history.fa.fa-history', { + title: Messages.contacts_fetchHistory, + }); var displayName = data.displayName; var fetching = false; $(moreHistory).click(function () { - //stub('get older history'); console.log('getting history'); // get oldest known message... @@ -86,16 +101,16 @@ define([ channel.HEAD: channel.messages[0].sig; fetching = true; - var $messages = $(getChat(curvePublic)).find('.messages'); + var $messagebox = $(getChat(curvePublic)).find('.messages'); messenger.getMoreHistory(curvePublic, sig, 10, function (e, history) { fetching = false; if (e) { return void console.error(e); } history.forEach(function (msg) { channel.messages.unshift(msg); - var name = displayNames[msg.channel]; - var el_message = markup.message(msg, name); - $messages.prepend(el_message); + var el_message = markup.message(msg); + $messagebox.prepend(el_message); }); + normalizeLabels($messagebox); }); }); @@ -159,6 +174,10 @@ define([ input.value = ''; sending = false; console.log('sent successfully'); + var $messagebox = $(messages); + + var height = $messagebox[0].scrollHeight; + $messagebox.scrollTop(height); }); }; @@ -327,12 +346,13 @@ define([ var name = displayNames[curvePublic]; var chat = getChat(curvePublic, name); - var el_message = markup.message(message, name); + var el_message = markup.message(message); state.channels[curvePublic].messages.push(message); var $chat = $(chat); - $chat.find('.messages').append(el_message); + var $messagebox = $chat.find('.messages').append(el_message); + normalizeLabels($messagebox); var channel = state.channels[curvePublic]; if (!channel) { From ea5f47f0f92318ebf983ebcd610ca40529bfbfe5 Mon Sep 17 00:00:00 2001 From: ansuz Date: Thu, 24 Aug 2017 17:18:59 +0200 Subject: [PATCH 09/12] remove some TODOs and solve some wee bugs --- www/contacts2/messenger-ui.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/www/contacts2/messenger-ui.js b/www/contacts2/messenger-ui.js index 4ce818d7f..759db183c 100644 --- a/www/contacts2/messenger-ui.js +++ b/www/contacts2/messenger-ui.js @@ -4,6 +4,7 @@ define([ '/common/hyperscript.js', '/bower_components/marked/marked.min.js', ], function ($, Cryptpad, h, Marked) { + 'use strict'; // TODO use our fancy markdown and support media-tags Marked.setOptions({ sanitize: true, }); @@ -22,7 +23,6 @@ define([ var initChannel = function (state, curvePublic, info) { console.log('initializing channel for [%s]', curvePublic); - //console.log(info); state.channels[curvePublic] = { messages: [], HEAD: info.lastKnownHash, @@ -317,7 +317,7 @@ define([ // TODO remove friend from userlist ui // FIXME seems to trigger EJOINED from netflux-websocket (from server); // (tried to join a channel in which you were already present) - }); + }, undefined, true); }); if (data.avatar && avatars[data.avatar]) { @@ -338,7 +338,6 @@ define([ var initializing = true; - // TODO handle scrolling. messenger.on('message', function (message) { console.log(JSON.stringify(message)); if (!initializing) { Cryptpad.notify(); } @@ -372,7 +371,6 @@ define([ return void notify(curvePublic); } unnotify(curvePublic); - // TODO notify if a message is newer than `lastKnownHash` }); messenger.on('join', function (curvePublic, channel) { From f58d4c941fe3ccb665029a8d45b339aabc4b45e4 Mon Sep 17 00:00:00 2001 From: ansuz Date: Thu, 24 Aug 2017 17:19:57 +0200 Subject: [PATCH 10/12] clean up a bit --- www/common/common-messenger.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/www/common/common-messenger.js b/www/common/common-messenger.js index 804c26290..3117c60c1 100644 --- a/www/common/common-messenger.js +++ b/www/common/common-messenger.js @@ -228,6 +228,7 @@ define([ leave: [], update: [], new_friend: [], + unfriend: [], }, range_requests: {}, }; @@ -371,8 +372,8 @@ define([ // check that the responding peer's encrypted netflux id matches // the sender field. This is to prevent replay attacks. if (parsed[2] !== sender || !parsed[1]) { return; } - channel.mapId[sender] = parsed[1]; // HERE - messenger.handlers.join.forEach(function (f) { + channel.mapId[sender] = parsed[1]; + eachHandler('join', function (f) { f(parsed[1], channel.id); }); @@ -431,7 +432,7 @@ define([ // TODO emit message event channel.messages.push(res); - messenger.handlers.message.forEach(function (f) { + eachHandler('message', function (f) { f(res); }); @@ -693,7 +694,7 @@ define([ } // update status if (!curvePublic) { return; } - messenger.handlers.leave.forEach(function (f) { + eachHandler('leave', function (f) { f(curvePublic, channel.id); }); }); @@ -823,6 +824,7 @@ define([ console.error(o, n, p); }).on('remove', ['friends'], function (o, p) { + // TODO eachHandler('unfriend', function (f) { f(); }); console.error(o, p); }); From f9cdbe66a0271ff6d41e569b7d6c0496b02e62e3 Mon Sep 17 00:00:00 2001 From: ansuz Date: Thu, 24 Aug 2017 17:20:59 +0200 Subject: [PATCH 11/12] add forgotten translation string --- customize.dist/translations/messages.js | 1 + 1 file changed, 1 insertion(+) diff --git a/customize.dist/translations/messages.js b/customize.dist/translations/messages.js index acab6951d..d5aa373df 100644 --- a/customize.dist/translations/messages.js +++ b/customize.dist/translations/messages.js @@ -293,6 +293,7 @@ define(function () { out.contacts_removeHistoryTitle = 'Clean the chat history'; out.contacts_confirmRemoveHistory = 'Are you sure you want to permanently remove your chat history? Data cannot be restored'; out.contacts_removeHistoryServerError = 'There was an error while removing your chat history. Try again later'; + out.contacts_fetchHistory = "Retrieve older history"; // File manager From 22d754d514354dde0fdb8ee8032d0b850462b936 Mon Sep 17 00:00:00 2001 From: ansuz Date: Fri, 25 Aug 2017 14:42:05 +0200 Subject: [PATCH 12/12] handle user renames --- www/common/common-messenger.js | 18 +++++++++++++----- www/contacts2/messenger-ui.js | 24 +++++++++++++++++++++--- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/www/common/common-messenger.js b/www/common/common-messenger.js index 3117c60c1..129c27935 100644 --- a/www/common/common-messenger.js +++ b/www/common/common-messenger.js @@ -395,9 +395,9 @@ define([ }); if (typeof(idx) !== 'undefined') { - console.error('found old message at %s', idx); + //console.error('found old message at %s', idx); } else { - console.error("did not find desired message"); + //console.error("did not find desired message"); } // TODO improve performance @@ -439,9 +439,8 @@ define([ return true; } if (parsedMsg[0] === Types.update) { - // TODO emit update event - if (parsedMsg[1] === proxy.curvePublic) { return; } + var curvePublic = parsedMsg[1]; var newdata = parsedMsg[3]; var data = getFriend(proxy, parsedMsg[1]); var types = []; @@ -451,13 +450,19 @@ define([ data[k] = newdata[k]; } }); - //channel.updateUI(types); + + eachHandler('update', function (f) { + f(clone(newdata), curvePublic); + }); return; } if (parsedMsg[0] === Types.unfriend) { + console.log('UNFRIEND'); removeFromFriendList(proxy, realtime, channel.friendEd, function () { channel.wc.leave(Types.unfriend); //channel.removeUI(); + + }); return; } @@ -483,6 +488,9 @@ define([ channel.wc.bcast(cryptMsg).then(function () { // TODO send event //channel.refresh(); + eachHandler('update', function (f) { + f(myData, myData.curvePublic); + }); }, function (err) { console.error(err); }); diff --git a/www/contacts2/messenger-ui.js b/www/contacts2/messenger-ui.js index 759db183c..573ac2110 100644 --- a/www/contacts2/messenger-ui.js +++ b/www/contacts2/messenger-ui.js @@ -13,7 +13,12 @@ define([ var m = function (md) { var d = h('div.content'); - d.innerHTML = Marked(md || ''); + try { + d.innerHTML = Marked(md || ''); + } catch (e) { + console.error(md); + console.error(e); + } return d; }; @@ -82,7 +87,7 @@ define([ return a; } return b; - }); + }, []); }; markup.chatbox = function (curvePublic, data) { @@ -106,6 +111,11 @@ define([ fetching = false; if (e) { return void console.error(e); } history.forEach(function (msg) { + if (msg.type !== 'MSG') { + // handle other types of messages? + return; + } + channel.messages.unshift(msg); var el_message = markup.message(msg); $messagebox.prepend(el_message); @@ -386,7 +396,15 @@ define([ // change in your friend list messenger.on('update', function (info, curvePublic) { - curvePublic = curvePublic; + console.log(info, curvePublic); + var name = displayNames[curvePublic] = info.displayName; + + // update label in friend list + find.inList(curvePublic).find('.name').text(name); + + // update title bar and messages + $messages.find(dataQuery(curvePublic) + ' .header .name, div.message'+ + dataQuery(curvePublic) + ' div.sender').text(name).text(name); }); Cryptpad.onDisplayNameChanged(function () {