define([ '/bower_components/chainpad-crypto/crypto.js', '/common/curve.js', '/common/common-hash.js', '/common/common-util.js', '/common/common-realtime.js', '/common/common-constants.js', '/customize/messages.js', '/bower_components/nthen/index.js', ], function (Crypto, Curve, Hash, Util, Realtime, Constants, Messages, nThen) { 'use strict'; var Msg = { inputs: [], }; var Types = { message: 'MSG', update: 'UPDATE', unfriend: 'UNFRIEND', mapId: 'MAP_ID', mapIdAck: 'MAP_ID_ACK' }; var clone = function (o) { return JSON.parse(JSON.stringify(o)); }; var convertToUint8 = function (obj) { var l = Object.keys(obj).length; var u = new Uint8Array(l); for (var i = 0; i we asked for an invalid last known hash if (parsed.error && parsed.error === "EINVAL") { setChannelHead(parsed.channel, '', function () { getChannelMessagesSince(getChannel(parsed.channel), {}, {}); }); return; } // End of initial history if (parsed.state && parsed.state === 1 && parsed.channel) { // parsed.channel is Ready // channel[parsed.channel].ready(); channels[parsed.channel].ready = true; onChannelReady(parsed.channel); return; } } // Initial history message var chan = parsed[3]; if (!chan || !channels[chan]) { return; } pushMsg(channels[chan], parsed[4]); }; var onMessage = function (msg, sender, chan) { if (!channels[chan.id]) { return; } var isMessage = pushMsg(channels[chan.id], msg); if (isMessage) { if (channels[chan.id].wc.myID !== sender) { // Don't notify for your own messages //channels[chan.id].notify(); } //channels[chan.id].refresh(); } }; // listen for messages... network.on('message', function(msg, sender) { onDirectMessage(msg, sender); }); var removeFriend = function (curvePublic, _cb) { var cb = Util.once(_cb); if (typeof(cb) !== 'function') { throw new Error('NO_CALLBACK'); } var data = getFriend(proxy, curvePublic); if (!data) { // friend is not valid console.error('friend is not valid'); return void cb({error: 'INVALID_FRIEND'}); } var channel = channels[data.channel]; if (!channel) { return void cb({error: "NO_SUCH_CHANNEL"}); } if (!network.webChannels.some(function (wc) { return wc.id === channel.id; })) { console.error('bad channel: ', curvePublic); } var msg = [Types.unfriend, proxy.curvePublic, +new Date()]; var msgStr = JSON.stringify(msg); var cryptMsg = channel.encrypt(msgStr); try { if (store.mailbox && data.curvePublic && data.notifications) { store.mailbox.sendTo('UNFRIEND', { curvePublic: proxy.curvePublic }, { channel: data.notifications, curvePublic: data.curvePublic }, function (obj) { console.log(obj); if (obj && obj.error) { return void cb(obj); } removeFromFriendList(curvePublic, function () { delete channels[channel.id]; emit('UNFRIEND', { curvePublic: curvePublic, fromMe: true }); cb(); }); }); } else { removeFromFriendList(curvePublic, function () { delete channels[channel.id]; emit('UNFRIEND', { curvePublic: curvePublic, fromMe: true }); cb(); }); } channel.wc.bcast(cryptMsg).then(function () {}, function (err) { console.error(err); }); } catch (e) { cb({error: e}); } }; var openChannel = function (data) { var keys = data.keys; var encryptor = data.encryptor || Curve.createEncryptor(keys); var channel = { id: data.channel, isFriendChat: data.isFriendChat, isPadChat: data.isPadChat, padChan: data.padChan, readOnly: data.readOnly, sending: false, messages: [], userList: [], mapId: {}, }; channel.encrypt = function (msg) { if (channel.readOnly) { return; } return encryptor.encrypt(msg); }; channel.decrypt = data.decrypt || function (msg) { return encryptor.decrypt(msg); }; var onJoining = function (peer) { if (peer === Msg.hk) { return; } if (channel.userList.indexOf(peer) !== -1) { return; } channel.userList.push(peer); if (channel.readOnly) { return; } // Join event will be sent once we are able to ID this peer var myData = createData(proxy); delete myData.channel; var msg = [Types.mapId, myData, channel.wc.myID]; var msgStr = JSON.stringify(msg); var cryptMsg = channel.encrypt(msgStr); var data = { channel: channel.id, msg: cryptMsg }; network.sendto(peer, JSON.stringify(data)); }; var onLeaving = function (peer) { var i = channel.userList.indexOf(peer); while (i !== -1) { channel.userList.splice(i, 1); i = channel.userList.indexOf(peer); } // update status var otherData = channel.mapId[peer]; if (!otherData) { return; } // Make sure the leaving user is not connected with another netflux id if (channel.userList.some(function (nId) { return channel.mapId[nId] && channel.mapId[nId].curvePublic === otherData.curvePublic; })) { return; } // Send the notification emit('LEAVE', { info: otherData, id: channel.id }); }; var onOpen = function (chan) { channel.wc = chan; channels[data.channel] = channel; chan.on('message', function (msg, sender) { onMessage(msg, sender, chan); }); 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', onLeaving); // FIXME don't subscribe to the channel implicitly getChannelMessagesSince(channel, data, keys); }; network.join(data.channel).then(onOpen, function (err) { console.error(err); }); network.on('reconnect', function () { if (channel && channel.stopped) { return; } if (!channels[data.channel]) { return; } network.join(data.channel).then(onOpen, function (err) { console.error(err); }); }); }; 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 sendMessage = function (id, payload, cb) { var channel = getChannel(id); if (!channel) { return void cb({error: 'NO_CHANNEL'}); } if (channel.readOnly) { return void cb({error: 'FORBIDDEN'}); } if (!network.webChannels.some(function (wc) { if (wc.id === channel.wc.id) { return true; } })) { return void cb({error: 'NO_SUCH_CHANNEL'}); } var msg = [Types.message, proxy.curvePublic, +new Date(), payload]; if (!channel.isFriendChat) { var name = proxy[Constants.displayNameKey] || Messages.anonymous + '#' + proxy.uid.slice(0,5); msg.push(name); } var msgStr = JSON.stringify(msg); var cryptMsg = channel.encrypt(msgStr); channel.wc.bcast(cryptMsg).then(function () { pushMsg(channel, cryptMsg); cb(); }, function (err) { cb({error: err}); }); }; var getStatus = function (chanId, cb) { // Display green status if one member is not me var channel = getChannel(chanId); if (!channel) { return void cb('NO_SUCH_CHANNEL'); } var online = channel.userList.some(function (nId) { var data = channel.mapId[nId] || undefined; if (!data) { return false; } return data.curvePublic !== proxy.curvePublic; }); cb(online); }; var getMyInfo = function (cb) { cb({ curvePublic: proxy.curvePublic, displayName: proxy[Constants.displayNameKey] }); }; var loadFriend = function (friend, cb) { var channel = friend.channel; if (getChannel(channel)) { return void cb(); } joining[channel] = cb; var keys = Curve.deriveKeys(friend.curvePublic, proxy.curvePrivate); var data = { keys: keys, channel: friend.channel, lastKnownHash: friend.lastKnownHash, owners: [proxy.edPublic, friend.edPublic], isFriendChat: true }; openChannel(data); }; // Friend added in our contacts in the current worker messenger.onFriendAdded = function (friendData) { if (!allowFriendsChannels) { return; } var friend = friends[friendData.curvePublic]; if (typeof(friend) !== 'object') { return; } var channel = friend.channel; if (!channel) { return; } loadFriend(friend, function () { emit('FRIEND', { curvePublic: friend.curvePublic, }); }); }; messenger.onFriendRemoved = function (curvePublic, chanId) { var channel = channels[chanId]; if (!channel) { return; } if (channel.wc) { channel.wc.leave(Types.unfriend); } delete channels[channel.id]; emit('UNFRIEND', { curvePublic: curvePublic, fromMe: true }); }; var ready = false; var initialized = false; var init = function () { allowFriendsChannels = true; if (initialized) { return; } initialized = true; var friends = getFriendList(proxy); nThen(function (waitFor) { Object.keys(friends).forEach(function (key) { if (key === 'me') { return; } var friend = clone(friends[key]); if (typeof(friend) !== 'object') { return; } var channel = friend.channel; if (!channel) { return; } loadFriend(friend, waitFor()); }); // TODO load rooms }).nThen(function () { ready = true; emit('READY'); }); }; //init(); var getRooms = function (data, cb) { if (data && data.curvePublic) { var curvePublic = data.curvePublic; // We need to get data about a new friend's room var friend = getFriend(proxy, curvePublic); if (!friend) { return void cb({error: 'NO_SUCH_FRIEND'}); } var channel = getChannel(friend.channel); if (!channel) { return void cb({error: 'NO_SUCH_CHANNEL'}); } return void cb([{ id: channel.id, isFriendChat: true, name: friend.displayName, lastKnownHash: friend.lastKnownHash, curvePublic: friend.curvePublic, messages: channel.messages }]); } if (data && data.padChat) { var pCChannel = getChannel(data.padChat); if (!pCChannel) { return void cb({error: 'NO_SUCH_CHANNEL'}); } return void cb([{ id: pCChannel.id, isPadChat: true, messages: pCChannel.messages }]); } var rooms = Object.keys(channels).map(function (id) { var r = getChannel(id); var name, lastKnownHash, curvePublic; if (r.isFriendChat) { var friend = getFriendFromChannel(id); if (!friend) { return null; } name = friend.displayName; lastKnownHash = friend.lastKnownHash; curvePublic = friend.curvePublic; } else if (r.isPadChat) { return; } else { // TODO room get metadata (name) && lastKnownHash } return { id: r.id, isFriendChat: r.isFriendChat, name: name, lastKnownHash: lastKnownHash, curvePublic: curvePublic, messages: r.messages }; }).filter(function (x) { return x; }); cb(rooms); }; var getUserList = function (data, cb) { var room = getChannel(data.id); if (!room) { return void cb({error: 'NO_SUCH_CHANNEL'}); } if (room.isFriendChat) { var friend = getFriendFromChannel(data.id); if (!friend) { return void cb({error: 'NO_SUCH_FRIEND'}); } cb([friend]); } else { // TODO room userlist in rooms... // (this is the static userlist, not the netflux one) cb([]); } }; var validateKeys = {}; messenger.storeValidateKey = function (chan, key) { validateKeys[chan] = key; }; var openPadChat = function (data, cb) { var channel = data.channel; if (getChannel(channel)) { emit('PADCHAT_READY', channel); return void cb(); } var secret = data.secret; if (secret.keys.cryptKey) { secret.keys.cryptKey = convertToUint8(secret.keys.cryptKey); } var encryptor = Crypto.createEncryptor(secret.keys); var vKey = (secret.keys && secret.keys.validateKey) || validateKeys[secret.channel]; var chanData = { padChan: data.secret && data.secret.channel, readOnly: typeof(secret.keys) === "object" && !secret.keys.validateKey, encryptor: encryptor, channel: data.channel, isPadChat: true, decrypt: function (msg) { return encryptor.decrypt(msg, vKey); }, //lastKnownHash: friend.lastKnownHash, //owners: [proxy.edPublic, friend.edPublic], //isFriendChat: true }; openChannel(chanData); joining[channel] = function () { emit('PADCHAT_READY', channel); }; cb(); }; var clearOwnedChannel = function (id, cb) { var channel = getChannel(id); if (!channel) { return void cb({error: 'NO_CHANNEL'}); } if (!store.rpc) { return void cb({error: 'RPC_NOT_READY'}); } store.rpc.clearOwnedChannel(id, function (err) { cb({error:err}); }); channel.messages = []; }; network.on('disconnect', function () { emit('DISCONNECT'); }); network.on('reconnect', function () { emit('RECONNECT'); }); messenger.leavePad = function (padChan) { // Leave chat and prevent reconnect when we leave a pad delete validateKeys[padChan]; Object.keys(channels).some(function (chatChan) { var channel = channels[chatChan]; if (channel.padChan !== padChan) { return; } if (channel.wc) { channel.wc.leave(); } channel.stopped = true; delete channels[chatChan]; return true; }); }; messenger.execCommand = function (obj, cb) { var cmd = obj.cmd; var data = obj.data; if (cmd === 'INIT_FRIENDS') { init(); return void cb(); } if (cmd === 'IS_READY') { return void cb(ready); } if (cmd === 'GET_ROOMS') { return void getRooms(data, cb); } if (cmd === 'GET_USERLIST') { return void getUserList(data, cb); } if (cmd === 'OPEN_PAD_CHAT') { return void openPadChat(data, cb); } if (cmd === 'GET_MY_INFO') { return void getMyInfo(cb); } if (cmd === 'REMOVE_FRIEND') { return void removeFriend(data, cb); } if (cmd === 'GET_STATUS') { return void getStatus(data, cb); } if (cmd === 'GET_MORE_HISTORY') { return void getMoreHistory(data.id, data.sig, data.count, cb); } if (cmd === 'SEND_MESSAGE') { return void sendMessage(data.id, data.content, cb); } if (cmd === 'SET_CHANNEL_HEAD') { return void setChannelHead(data.id, data.sig, cb); } if (cmd === 'CLEAR_OWNED_CHANNEL') { return void clearOwnedChannel(data, cb); } }; Object.freeze(messenger); return messenger; }; return Msg; });