', {'class':'sender'}).text(name).appendTo($msg);
}
channel.lastSender = msg.channel;
$('
', {'class':'content'}).html(parseMessage(msg.text)).appendTo($msg);
}
$messages.scrollTop($messages[0].scrollHeight);
channel.lastDisplayed = i-1;
channel.unnotify();
if (messages.length > 10) {
var lastKnownMsg = messages[messages.length - 11];
channel.setLastMessageRead(lastKnownMsg.sig);
}
};
// Display a new channel
var display = function (curvePublic) {
$msgContainer.find('.info').hide();
var isNew = false;
var $chat = $msgContainer.find('.chat').filter(function (idx, el) {
return $(el).data('key') === curvePublic;
});
if (!$chat.length) {
$chat = $('
', {'class':'chat'})
.data('key', curvePublic).appendTo($msgContainer);
createChatBox(common, $chat, curvePublic, messenger);
isNew = true;
}
// Show the correct div
$msgContainer.find('.chat').hide();
$chat.show();
Msg.active = curvePublic;
// TODO don't mark messages as read unless you have displayed them
refresh(curvePublic);
};
var remove = function (curvePublic) {
var data = getFriend(common, curvePublic);
var channel = channels[data.channel];
//var newdata = createData(common, 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);
});
};
// Display friend list
common.getFriendListUI(common, display, remove).appendTo($listContainer);
// Notify on new messages
var notify = function (curvePublic) {
//if (Msg.active === curvePublic) { return; }
var $friend = $listContainer.find('.friend').filter(function (idx, el) {
return $(el).data('key') === curvePublic;
});
$friend.addClass('notify');
common.notify();
};
var unnotify = function (curvePublic) {
var $friend = $listContainer.find('.friend').filter(function (idx, el) {
return $(el).data('key') === curvePublic;
});
$friend.removeClass('notify');
};
var removeUI = function (curvePublic) {
var $friend = $listContainer.find('.friend').filter(function (idx, el) {
return $(el).data('key') === curvePublic;
});
var $chat = $msgContainer.find('.chat').filter(function (idx, el) {
return $(el).data('key') === curvePublic;
});
$friend.remove();
$chat.remove();
$msgContainer.find('.info').show();
};
var updateUI = function (curvePublic, types) {
var data = getFriend(common, curvePublic);
var chan = channels[data.channel];
if (!chan.ready) {
chan.updateOnReady = (chan.updateOnReady || []).concat(types);
return;
}
var $friend = $listContainer.find('.friend').filter(function (idx, el) {
return $(el).data('key') === curvePublic;
});
if (types.indexOf('displayName') >= 0) {
$friend.find('.name').text(data.displayName);
}
if (types.indexOf('avatar') >= 0) {
$friend.find('.default').remove();
$friend.find('media-tag').remove();
if (data.avatar && avatars[data.avatar]) {
$friend.prepend(avatars[data.avatar]);
} else {
common.displayAvatar($friend, data.avatar, data.displayName, function ($img) {
if (data.avatar && $img) {
avatars[data.avatar] = $img[0].outerHTML;
}
});
}
}
};
var updateStatus = function (curvePublic) {
var data = getFriend(common, curvePublic);
var chan = channels[data.channel];
var $friend = $listContainer.find('.friend').filter(function (idx, el) {
return $(el).data('key') === curvePublic;
});
var status = chan.userList.some(function (nId) {
return chan.mapId[nId] === curvePublic;
});
var statusText = status ? 'online' : 'offline';
$friend.find('.status').attr('class', 'status '+statusText);
};
var getMoreHistory = function (network, chan, hash, count) {
var msg = [
'GET_HISTORY_RANGE',
chan.id,
{
from: hash,
count: count,
}
];
console.log(msg);
network.sendto(network.historyKeeper, JSON.stringify(msg)).then(function (a, b, c) {
console.log(a, b, c);
}, function (err) {
throw new Error(err);
});
};
var getChannelMessagesSince = function (network, 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);
});
};
// Open the channels
var openFriendChannel = function (f) {
if (f === "me") { return; }
var data = friends[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: [],
refresh: function () { refresh(data.curvePublic); },
notify: function () { notify(data.curvePublic); },
unnotify: function () { unnotify(data.curvePublic); },
removeUI: function () { removeUI(data.curvePublic); },
updateUI: function (types) { updateUI(data.curvePublic, types); },
updateStatus: function () { updateStatus(data.curvePublic); },
setLastMessageRead: function (hash) {
data.lastKnownHash = hash;
},
getMessagesSinceDisconnect: function () {
getChannelMessagesSince(network, chan, data, keys);
},
wc: chan,
userList: [],
mapId: {},
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);
},
};
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, chan, data, keys);
}, function (err) {
console.error(err);
});
};
messenger.cleanFriendChannels = function () {
Object.keys(channels).forEach(function (id) {
delete channels[id];
});
};
var openFriendChannels = messenger.openFriendChannels = function () {
Object.keys(friends).forEach(openFriendChannel);
};
messenger.setEditable = function (bool) {
bool = !bool;
var input = messenger.input;
if (!input) { return; }
if (bool) {
input.setAttribute('disabled', bool);
} else {
input.removeAttribute('disabled');
}
if (common.Messages) {
// set placeholder
var placeholder = bool?
common.Messages.disconnected:
common.Messages.contacts_typeHere;
input.setAttribute('placeholder', placeholder);
}
};
openFriendChannels();
var checkNewFriends = function () {
Object.keys(friends).forEach(function (f) {
var $friend = $listContainer.find('.friend').filter(function (idx, el) {
return $(el).data('key') === f;
});
if (!$friend.length) {
openFriendChannel(f);
addToFriendListUI(common, $listContainer.find('> div'), display, remove, f);
}
});
};
common.onDisplayNameChanged(function () {
checkNewFriends();
updateMyData(common);
});
return messenger;
};
// Invitation
var addToFriendList = Msg.addToFriendList = function (common, data, cb) {
var proxy = common.getProxy();
if (!proxy.friends) {
proxy.friends = {};
}
var friends = proxy.friends;
var pubKey = data.curvePublic;
if (pubKey === proxy.curvePublic) { return void cb("E_MYKEY"); }
friends[pubKey] = data;
common.whenRealtimeSyncs(common.getRealtime(), function () {
cb();
common.pinPads([data.channel]);
});
common.changeDisplayName(proxy[common.displayNameKey]);
};
Msg.addDirectMessageHandler = function (common) {
var network = common.getNetwork();
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(common, 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); }
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);
var proxy = common.getProxy();
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();
common.changeDisplayName(proxy[common.displayNameKey]);
}
network.sendto(netfluxId, msgStr);
};
return Msg;
});