Merge branch 'new-messaging' into staging

pull/1/head
ansuz 7 years ago
commit 57d0c6c973

@ -657,6 +657,10 @@ define([
return loadingScreen();
};
Pages['/contacts2/'] = Pages['/contacts2/index.html'] = function () {
return loadingScreen();
};
Pages['/pad/'] = Pages['/pad/index.html'] = function () {
return loadingScreen();
};

@ -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);

@ -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

@ -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;"

@ -0,0 +1,845 @@
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'
};
var clone = function (o) {
return JSON.parse(JSON.stringify(o));
};
// TODO
// - mute a channel (hide notifications or don't open it?)
var pending = {};
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
};
};
// TODO make this async
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;
};
// TODO make this async
var removeFromFriendList = function (proxy, realtime, curvePublic, cb) {
if (!proxy.friends) { return; }
var friends = proxy.friends;
delete friends[curvePublic];
Realtime.whenRealtimeSyncs(realtime, cb);
};
// TODO make this async
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;
});
};
// 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) {
'use strict';
var messenger = {
handlers: {
message: [],
join: [],
leave: [],
update: [],
new_friend: [],
unfriend: [],
},
range_requests: {},
};
var eachHandler = function (type, g) {
messenger.handlers[type].forEach(g);
};
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();
var realtime = common.getRealtime();
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 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; }
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;
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];
eachHandler('join', 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
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 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);
// 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,
author: 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);
eachHandler('message', function (f) {
f(res);
});
return true;
}
if (parsedMsg[0] === Types.update) {
if (parsedMsg[1] === proxy.curvePublic) { return; }
var curvePublic = parsedMsg[1];
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];
}
});
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;
}
};
/* Broadcast a display name, profile, or avatar change to all contacts
*/
// TODO send event...
messenger.updateMyData = function () {
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 () {
// TODO send event
//channel.refresh();
eachHandler('update', function (f) {
f(myData, myData.curvePublic);
});
}, function (err) {
console.error(err);
});
});
friends.me = myData;
}
};
var onChannelReady = function (chanId) {
var cb = joining[chanId];
if (typeof(cb) !== 'function') {
return void console.log('channel ready without callback');
}
delete joining[chanId];
return cb();
};
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,
author: 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;
}
if (parsed.state && parsed.state === 1 && parsed.channel) {
if (channels[parsed.channel]) {
// parsed.channel is Ready
// channel[parsed.channel].ready();
channels[parsed.channel].ready = true;
onChannelReady(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]);
};
var onMessage = function (common, 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();
// TODO emit message event
}
};
// listen for messages...
network.on('message', function(msg, sender) {
onDirectMessage(common, msg, sender);
});
messenger.removeFriend = function (curvePublic, cb) {
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 () {
cb();
});
}, function (err) {
console.error(err);
cb(err);
});
};
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);
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: [],
wc: chan,
userList: [],
mapId: {},
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; }
// 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);
var cryptMsg = channel.encryptor.encrypt(msgStr);
network.sendto(peer, cryptMsg);
};
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 curvePublic = channel.mapId[peer];
console.log(curvePublic); // FIXME
var i = channel.userList.indexOf(peer);
while (i !== -1) {
channel.userList.splice(i, 1);
i = channel.userList.indexOf(peer);
}
// update status
if (!curvePublic) { return; }
eachHandler('leave', function (f) {
f(curvePublic, channel.id);
});
});
// FIXME don't subscribe to the channel implicitly
getChannelMessagesSince(chan, data, keys);
}, function (err) {
console.error(err);
});
};
// 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();
});
};*/
// 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';
}));
};
/*
messenger.openFriendChannels = function () {
eachFriend(friends, openFriendChannel);
};*/
messenger.openFriendChannel = function (curvePublic, cb) {
if (typeof(curvePublic) !== 'string') { return void cb('INVALID_ID'); }
if (typeof(cb) !== 'function') { throw new Error('expected callback'); }
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);
};
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');
}
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);
});
};
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);
};
// TODO emit friend-list-changed event
messenger.checkNewFriends = function () {
eachFriend(friends, function (friend, id) {
if (!channels[id]) {
openFriendChannel(friend, id);
}
});
};
messenger.getFriendInfo = function (curvePublic, cb) {
var friend = friends[curvePublic];
if (!friend) { return void cb('NO_SUCH_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) {
// TODO eachHandler('unfriend', function (f) { f(); });
console.error(o, p);
});
Object.freeze(messenger);
return messenger;
};
return Msg;
});

@ -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) {

@ -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;

@ -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));

@ -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;
@ -169,8 +170,8 @@ body {
margin: 10px;
}
.more-history {
display: none;
//.hover;
//display: none;
.hover;
}
}
.chat {

@ -0,0 +1,30 @@
<!DOCTYPE html>
<html class="cp pad">
<head>
<title>CryptPad</title>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script async data-bootload="/customize/template.js" data-main="/common/boot.js?ver=1.0" src="/bower_components/requirejs/require.js?ver=2.1.15"></script>
<style>
html, body {
margin: 0px;
padding: 0px;
}
#pad-iframe {
position:fixed;
top:0px;
left:0px;
bottom:0px;
right:0px;
width:100%;
height:100%;
border:none;
margin:0;
padding:0;
overflow:hidden;
}
</style>
</head>
<body>
<iframe id="pad-iframe"></iframe><script src="/common/noscriptfix.js"></script>

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<script async data-bootload="/contacts/inner.js" data-main="/common/boot.js?ver=1.0" src="/bower_components/requirejs/require.js?ver=2.1.15"></script>
<style>.loading-hidden, .loading-hidden * {display: none !important;}</style>
</head>
<body class="loading-hidden">
<div id="toolbar" class="toolbar-container"></div>
<div id="app">
<div id="friendList"></div>
<div id="messaging"></div>
</div>
</body>
</html>

@ -0,0 +1,75 @@
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 = $('<div>', {'class': 'info'}).appendTo($messages);
$('<h2>').text(Messages.contacts_info1).appendTo($infoBlock);
var $ul = $('<ul>').appendTo($infoBlock);
$('<li>').text(Messages.contacts_info2).appendTo($ul);
$('<li>').text(Messages.contacts_info3).appendTo($ul);
//$('<li>').text(Messages.contacts_info4).appendTo($ul);
var messenger = window.messenger = Messenger.messenger(Cryptpad);
UI.create(messenger, $list, $messages);
};
Cryptpad.ready(function () {
andThen();
Cryptpad.reportAppUsage();
});
});
});

@ -0,0 +1,458 @@
define([
'jquery',
'/common/cryptpad-common.js',
'/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, });
var UI = {};
var Messages = Cryptpad.Messages;
var m = function (md) {
var d = h('div.content');
try {
d.innerHTML = Marked(md || '');
} catch (e) {
console.error(md);
console.error(e);
}
return d;
};
var dataQuery = function (curvePublic) {
return '[data-key="' + curvePublic + '"]';
};
var initChannel = function (state, curvePublic, info) {
console.log('initializing channel for [%s]', curvePublic);
state.channels[curvePublic] = {
messages: [],
HEAD: info.lastKnownHash,
};
};
UI.create = function (messenger, $userlist, $messages) {
var state = window.state = {
active: '',
};
state.channels = {};
var displayNames = state.displayNames = {};
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) {
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),
]);
};
var getChat = function (curvePublic) {
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.fa.fa-history', {
title: Messages.contacts_fetchHistory,
});
var displayName = data.displayName;
var fetching = false;
$(moreHistory).click(function () {
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 $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) {
if (msg.type !== 'MSG') {
// handle other types of messages?
return;
}
channel.messages.unshift(msg);
var el_message = markup.message(msg);
$messagebox.prepend(el_message);
});
normalizeLabels($messagebox);
});
});
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 (typeof(content) !== 'string' || !content.trim()) { return; }
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 $messagebox = $(messages);
var height = $messagebox[0].scrollHeight;
$messagebox.scrollTop(height);
});
};
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 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(curvePublic, e); }
if (online) {
return void $status
.removeClass('offline').addClass('online');
}
$status.removeClass('online').addClass('offline');
});
};
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
var chatbox = markup.chatbox(curvePublic, info);
$messages.append(chatbox);
});
};
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; }
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)
}, undefined, true);
});
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 initializing = true;
messenger.on('message', function (message) {
console.log(JSON.stringify(message));
if (!initializing) { Cryptpad.notify(); }
var curvePublic = message.curve;
var name = displayNames[curvePublic];
var chat = getChat(curvePublic, name);
var el_message = markup.message(message);
state.channels[curvePublic].messages.push(message);
var $chat = $(chat);
var $messagebox = $chat.find('.messages').append(el_message);
normalizeLabels($messagebox);
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);
});
messenger.on('join', function (curvePublic, channel) {
//console.log('join', curvePublic, channel);
channel = channel;
updateStatus(curvePublic);
});
messenger.on('leave', function (curvePublic, channel) {
//console.log('leave', curvePublic, channel);
channel = channel;
updateStatus(curvePublic);
});
// change in your friend list
messenger.on('update', function (info, 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 () {
messenger.checkNewFriends();
messenger.updateMyData();
});
// FIXME dirty hack
messenger.getMyInfo(function (e, info) {
displayNames[info.curvePublic] = info.displayName;
});
messenger.getFriendList(function (e, keys) {
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); }
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; }
});
});
});
});
};
return UI;
});
Loading…
Cancel
Save