Merge branch 'staging' of github.com:xwiki-labs/cryptpad into staging

pull/1/head
Caleb James DeLisle 7 years ago
commit e4a356d873

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

@ -15,3 +15,63 @@
} }
} }
} }
.cp-modal-container {
display: none;
z-index: 100000;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: @colortheme_modal-dim;
.cp-modal {
background-color: @colortheme_modal-bg;
color: @colortheme_modal-fg;
box-shadow: @colortheme_modal-shadow;
padding: @colortheme_modal-padding;
position: absolute;
top: 15vh; bottom: 15vh;
left: 10vw; right: 10vw;
overflow: auto;
font-family: @colortheme_font;
text-align: center;
& > p {
margin-bottom: 1em;
}
.cp-modal-form {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
input {
background-color: @colortheme_modal-input;
color: @colortheme_modal-fg;
border: 0;
padding: 8px 12px;
margin: 1em;
width: 300px;
}
.cp-modal-close {
text-shadow: none;
color: inherit;
position: absolute;
top: 0;
right: 0;
margin: @colortheme_modal-padding;
cursor: pointer;
}
}
}

@ -9,7 +9,7 @@ define([
$(function () { $(function () {
var $body = $('body'); var $body = $('body');
var isMainApp = function () { var isMainApp = function () {
return /^\/(pad|code|slide|poll|whiteboard|file|media|contacts|contacts2|drive|settings|profile|todo)\/$/.test(location.pathname); return /^\/(pad|code|slide|poll|whiteboard|file|media|contacts|drive|settings|profile|todo)\/$/.test(location.pathname);
}; };
var infoPage = function () { var infoPage = function () {
@ -55,9 +55,6 @@ $(function () {
} else if (/^\/contacts\/$/.test(pathname)) { } else if (/^\/contacts\/$/.test(pathname)) {
$('body').append(h('body', Pages[pathname]()).innerHTML); $('body').append(h('body', Pages[pathname]()).innerHTML);
require([ '/contacts/main.js' ], ready); 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)) { } else if (/pad/.test(pathname)) {
$('body').append(h('body', Pages[pathname]()).innerHTML); $('body').append(h('body', Pages[pathname]()).innerHTML);
require([ '/pad/main.js' ], ready); require([ '/pad/main.js' ], ready);

@ -301,6 +301,7 @@ define(function () {
out.fm_filesDataName = "Tous les fichiers"; out.fm_filesDataName = "Tous les fichiers";
out.fm_templateName = "Modèles"; out.fm_templateName = "Modèles";
out.fm_searchName = "Recherche"; out.fm_searchName = "Recherche";
out.fm_recentPadsName = "Pads récents";
out.fm_searchPlaceholder = "Rechercher..."; out.fm_searchPlaceholder = "Rechercher...";
out.fm_newButton = "Nouveau"; out.fm_newButton = "Nouveau";
out.fm_newButtonTitle = "Créer un nouveau pad ou un dossier, importer un fichier dans le dossier courant"; out.fm_newButtonTitle = "Créer un nouveau pad ou un dossier, importer un fichier dans le dossier courant";
@ -332,6 +333,7 @@ define(function () {
out.fm_info_root = "Créez ici autant de dossiers que vous le souhaitez pour trier vos fichiers."; out.fm_info_root = "Créez ici autant de dossiers que vous le souhaitez pour trier vos fichiers.";
out.fm_info_unsorted = 'Contient tous les pads que vous avez ouvert et qui ne sont pas triés dans "Documents" ou déplacés vers la "Corbeille".'; // "My Documents" should match with the "out.fm_rootName" key, and "Trash" with "out.fm_trashName" out.fm_info_unsorted = 'Contient tous les pads que vous avez ouvert et qui ne sont pas triés dans "Documents" ou déplacés vers la "Corbeille".'; // "My Documents" should match with the "out.fm_rootName" key, and "Trash" with "out.fm_trashName"
out.fm_info_template = "Contient tous les fichiers que vous avez sauvés en tant que modèle afin de les réutiliser lors de la création d'un nouveau pad."; out.fm_info_template = "Contient tous les fichiers que vous avez sauvés en tant que modèle afin de les réutiliser lors de la création d'un nouveau pad.";
out.fm_info_recent = "Liste les derniers pads que vous avez modifiés ou ouverts.";
out.updated_0_fm_info_trash = "Vider la corbeille permet de libérer de l'espace dans votre CryptDrive"; out.updated_0_fm_info_trash = "Vider la corbeille permet de libérer de l'espace dans votre CryptDrive";
out.fm_info_trash = out.updated_0_fm_info_trash; out.fm_info_trash = out.updated_0_fm_info_trash;
out.fm_info_allFiles = 'Contient tous les fichiers de "Documents", "Fichiers non triés" et "Corbeille". Vous ne pouvez pas supprimer ou déplacer des fichiers depuis cet endroit.'; // Same here out.fm_info_allFiles = 'Contient tous les fichiers de "Documents", "Fichiers non triés" et "Corbeille". Vous ne pouvez pas supprimer ou déplacer des fichiers depuis cet endroit.'; // Same here

@ -303,6 +303,7 @@ define(function () {
out.fm_filesDataName = "All files"; out.fm_filesDataName = "All files";
out.fm_templateName = "Templates"; out.fm_templateName = "Templates";
out.fm_searchName = "Search"; out.fm_searchName = "Search";
out.fm_recentPadsName = "Recent pads";
out.fm_searchPlaceholder = "Search..."; out.fm_searchPlaceholder = "Search...";
out.fm_newButton = "New"; out.fm_newButton = "New";
out.fm_newButtonTitle = "Create a new pad or folder, import a file in the current folder"; out.fm_newButtonTitle = "Create a new pad or folder, import a file in the current folder";
@ -334,6 +335,7 @@ define(function () {
out.fm_info_root = "Create as many nested folders here as you want to sort your files."; out.fm_info_root = "Create as many nested folders here as you want to sort your files.";
out.fm_info_unsorted = 'Contains all the files you\'ve visited that are not yet sorted in "Documents" or moved to the "Trash".'; // "My Documents" should match with the "out.fm_rootName" key, and "Trash" with "out.fm_trashName" out.fm_info_unsorted = 'Contains all the files you\'ve visited that are not yet sorted in "Documents" or moved to the "Trash".'; // "My Documents" should match with the "out.fm_rootName" key, and "Trash" with "out.fm_trashName"
out.fm_info_template = 'Contains all the pads stored as templates and that you can re-use when you create a new pad.'; out.fm_info_template = 'Contains all the pads stored as templates and that you can re-use when you create a new pad.';
out.fm_info_recent = "List the recently modified or opened pads.";
out.updated_0_fm_info_trash = 'Empty your trash to free space in your CryptDrive.'; out.updated_0_fm_info_trash = 'Empty your trash to free space in your CryptDrive.';
out.fm_info_trash = out.updated_0_fm_info_trash; out.fm_info_trash = out.updated_0_fm_info_trash;
out.fm_info_allFiles = 'Contains all the files from "Documents", "Unsorted" and "Trash". You can\'t move or remove files from here.'; // Same here out.fm_info_allFiles = 'Contains all the files from "Documents", "Unsorted" and "Trash". You can\'t move or remove files from here.'; // Same here

@ -6,62 +6,16 @@ define([
'/bower_components/marked/marked.min.js', '/bower_components/marked/marked.min.js',
'/common/common-realtime.js', '/common/common-realtime.js',
// displayAvatar
// whenRealtimeSyncs
// getRealtime -> removeFromFriendList
/* UI
Messages
confirm
fixHTML
displayAvatar
clearOwnedChannel
alert
pushMsg
removeFromFriendList
onDirectMessage
getNetwork
getProxy
pushMsg
Init
getNetwork
getProxy
onDirectMessage
removeFromFriendList
notify
onMessage
*/
], function ($, Crypto, Curve, Hash, Marked, Realtime) { ], function ($, Crypto, Curve, Hash, Marked, Realtime) {
var Msg = { var Msg = {
inputs: [], inputs: [],
}; };
var Types = {
message: 'MSG',
update: 'UPDATE',
unfriend: 'UNFRIEND',
mapId: 'MAP_ID',
mapIdAck: 'MAP_ID_ACK'
};
// TODO // TODO
// - mute a channel (hide notifications or don't open it?) // - mute a channel (hide notifications or don't open it?)
var ready = [];
var pending = {}; var pending = {};
var pendingRequests = []; var pendingRequests = [];
var parseMessage = function (content) {
return Marked(content);
};
var createData = Msg.createData = function (proxy, hash) { var createData = Msg.createData = function (proxy, hash) {
return { return {
channel: hash || Hash.createChannelId(), channel: hash || Hash.createChannelId(),
@ -82,13 +36,6 @@ define([
return proxy.friends ? proxy.friends[pubkey] : undefined; 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) { var getFriendList = Msg.getFriendList = function (proxy) {
if (!proxy.friends) { proxy.friends = {}; } if (!proxy.friends) { proxy.friends = {}; }
return proxy.friends; return proxy.friends;
@ -101,7 +48,6 @@ define([
}); });
}; };
Msg.getFriendChannelsList = function (proxy) { Msg.getFriendChannelsList = function (proxy) {
var list = []; var list = [];
eachFriend(proxy, function (friend) { eachFriend(proxy, function (friend) {
@ -110,500 +56,9 @@ define([
return list; return list;
}; };
// Messaging tools
var avatars = {};
// TODO make this internal to the messenger // TODO make this internal to the messenger
var channels = Msg.channels = window.channels = {}; var channels = Msg.channels = window.channels = {};
var UI = Msg.UI = {};
UI.init = function (common, $listContainer, $msgContainer) {
var ui = {
containers: {
friendList: $listContainer,
messages: $msgContainer,
},
};
ui.addToFriendList = function (data, display, remove) {
var $block = ui.containers.friendBlock;
var $friend = $('<div>', {'class': 'friend avatar'}).appendTo($block);
$friend.data('key', data.curvePublic);
var $rightCol = $('<span>', {'class': 'right-col'});
$('<span>', {'class': 'name'}).text(data.displayName).appendTo($rightCol);
var $remove = $('<span>', {'class': 'remove fa fa-user-times'}).appendTo($rightCol);
$remove.attr('title', common.Messages.contacts_remove);
$friend.dblclick(function () {
if (data.profile) {
window.open('/profile/#' + data.profile);
}
});
$friend.click(function () {
display(data.curvePublic);
});
$remove.click(function (e) {
e.stopPropagation();
common.confirm(common.Messages._getKey('contacts_confirmRemove', [
common.fixHTML(data.displayName)
]), function (yes) {
if (!yes) { return; }
remove(data.curvePublic);
}, null, true);
});
if (data.avatar && avatars[data.avatar]) {
$friend.append(avatars[data.avatar]);
$friend.append($rightCol);
} else {
common.displayAvatar($friend, data.avatar, data.displayName, function ($img) {
if (data.avatar && $img) {
avatars[data.avatar] = $img[0].outerHTML;
}
$friend.append($rightCol);
});
}
$('<span>', {'class': 'status'}).appendTo($friend);
};
ui.createFriendList = function (friends, display, remove) {
var $block = ui.containers.friendBlock = $('<div>');
eachFriend(friends, function (friend) {
ui.addToFriendList(friend, display, remove);
});
$block.appendTo($listContainer);
};
ui.notify = function (curvePublic) {
var $friend = $listContainer.find('.friend').filter(function (idx, el) {
return $(el).data('key') === curvePublic;
});
$friend.addClass('notify');
};
ui.unnotify = function (curvePublic) {
var $friend = $listContainer.find('.friend').filter(function (idx, el) {
return $(el).data('key') === curvePublic;
});
$friend.removeClass('notify');
};
ui.update = function (curvePublic, types) {
var proxy = common.getProxy();
var data = getFriend(proxy, 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;
}
});
}
}
};
ui.updateStatus = function (curvePublic, online) {
ui.getFriend(curvePublic).find('.status')
.attr('class', 'status ' + (online? 'online' : 'offline'));
};
ui.getChannel = function (curvePublic) {
var $chat = $msgContainer.find('.chat').filter(function (idx, el) {
return $(el).data('key') === curvePublic;
});
return $chat.length? $chat: null;
};
ui.hideInfo = function () {
$msgContainer.find('.info').hide();
};
ui.showInfo = function () {
$msgContainer.find('.info').show();
};
ui.createChat = function (curvePublic) {
return $('<div>', {'class':'chat'})
.data('key', curvePublic).appendTo($msgContainer);
};
ui.hideChat = function () {
$msgContainer.find('.chat').hide();
};
ui.getFriend = function (curvePublic) {
return $listContainer.find('.friend').filter(function (idx, el) {
return $(el).data('key') === curvePublic;
});
};
ui.remove = function (curvePublic) {
var $friend = ui.getFriend(curvePublic);
var $chat = ui.getChannel(curvePublic);
$friend.remove();
if ($chat) { $chat.remove(); }
ui.showInfo();
};
ui.createMessage = function (msg, name) {
var $msg = $('<div>', {'class': 'message'})
.attr('title', msg.time ? new Date(msg.time).toLocaleString(): '?');
if (name) {
$('<div>', {'class':'sender'}).text(name).appendTo($msg);
}
$('<div>', {'class':'content'}).html(parseMessage(msg.text)).appendTo($msg);
return $msg;
};
ui.setEditable = function (bool) {
bool = !bool;
var input = ui.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);
}
};
ui.createChatBox = function (proxy, $container, curvePublic) {
var data = getFriend(proxy, curvePublic);
// Input
var channel = channels[data.channel];
var $header = $('<div>', {
'class': 'header',
}).appendTo($container);
var $avatar = $('<div>', {'class': 'avatar'}).appendTo($header);
// more history...
$('<span>', {
'class': 'more-history',
})
.text('get more history')
.click(function () {
console.log("GETTING HISTORY");
channel.getPreviousMessages();
})
.appendTo($header);
var $removeHistory = $('<span>', {
'class': 'remove-history fa fa-eraser',
title: common.Messages.contacts_removeHistoryTitle
})
.click(function () {
common.confirm(common.Messages.contacts_confirmRemoveHistory, function (yes) {
if (!yes) { return; }
common.clearOwnedChannel(data.channel, function (e) {
if (e) {
console.error(e);
common.alert(common.Messages.contacts_removeHistoryServerError);
return;
}
});
});
});
$removeHistory.appendTo($header);
$('<div>', {'class': 'messages'}).appendTo($container);
var $inputBlock = $('<div>', {'class': 'input'}).appendTo($container);
var $input = $('<textarea>').appendTo($inputBlock);
$input.attr('placeholder', common.Messages.contacts_typeHere);
ui.input = $input[0];
var send = function () {
// TODO implement sending queue
// TODO separate message logic from UI
var channel = channels[data.channel];
if (channel.sending) {
console.error("still sending");
return;
}
if (!$input.val()) {
console.error("nothing to send");
return;
}
if ($input.attr('disabled')) {
console.error("input is disabled");
return;
}
var payload = $input.val();
// Send the message
channel.sending = true;
channel.send(payload, function (e) {
if (e) {
channel.sending = false;
console.error(e);
return;
}
$input.val('');
channel.refresh();
channel.sending = false;
});
};
$('<button>', {
'class': 'btn btn-primary fa fa-paper-plane',
title: common.Messages.contacts_send,
}).appendTo($inputBlock).click(send);
var onKeyDown = function (e) {
if (e.keyCode === 13) {
if (e.ctrlKey || e.shiftKey) {
var val = this.value;
if (typeof this.selectionStart === "number" && typeof this.selectionEnd === "number") {
var start = this.selectionStart;
this.value = val.slice(0, start) + "\n" + val.slice(this.selectionEnd);
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;
}
send();
return false;
}
};
$input.on('keydown', onKeyDown);
// Header
var $rightCol = $('<span>', {'class': 'right-col'});
$('<span>', {'class': 'name'}).text(data.displayName).appendTo($rightCol);
if (data.avatar && avatars[data.avatar]) {
$avatar.append(avatars[data.avatar]);
$avatar.append($rightCol);
} else {
common.displayAvatar($avatar, data.avatar, data.displayName, function ($img) {
if (data.avatar && $img) {
avatars[data.avatar] = $img[0].outerHTML;
}
$avatar.append($rightCol);
});
}
};
return ui;
};
var msgAlreadyKnown = function (channel, sig) {
return channel.messages.some(function (message) {
return message[0] === sig;
});
};
// TODO remove dependency on common
var pushMsg = function (realtime, proxy, common, channel, cryptMsg) {
var msg = channel.encryptor.decrypt(cryptMsg);
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;
};
// Id message allows us to map a netfluxId with a public curve key
var onIdMessage = function (proxy, network, 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);
};
// HERE
var onDirectMessage = function (common, msg, sender) {
var proxy = common.getProxy();
var network = common.getNetwork();
var realtime = common.getRealtime();
if (sender !== Msg.hk) { return void onIdMessage(proxy, network, 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(realtime, proxy, common, 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(realtime, proxy, common, 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();
}
};
Msg.getLatestMessages = function () { Msg.getLatestMessages = function () {
Object.keys(channels).forEach(function (id) { Object.keys(channels).forEach(function (id) {
if (id === 'me') { return; } if (id === 'me') { return; }
@ -613,280 +68,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);
});
};
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);
});
};
/* TODO remove dependency on common
*/
Msg.init = function (common, ui) {
// declare common variables
var network = common.getNetwork();
var proxy = common.getProxy();
var realtime = common.getRealtime();
Msg.hk = network.historyKeeper;
var friends = getFriendList(proxy);
// listen for messages...
network.on('message', function(msg, sender) {
onDirectMessage(common, msg, sender);
});
// declare messenger and common methods
var messenger = {
ui: ui,
};
messenger.setActive = function (id) {
// TODO validate id
messenger.active = id;
};
// Refresh the active channel
// TODO extract into UI method
var refresh = function (curvePublic) {
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<messages.length; i++) {
msg = messages[i];
name = (msg.channel !== channel.lastSender)?
getFriend(proxy, msg.channel).displayName: undefined;
ui.createMessage(msg, name).appendTo($messages);
channel.lastSender = msg.channel;
}
$messages.scrollTop($messages[0].scrollHeight);
channel.lastDisplayed = i-1;
channel.unnotify();
// return void channel.notify();
if (messages.length > 10) {
var lastKnownMsg = messages[messages.length - 11];
channel.setLastMessageRead(lastKnownMsg.sig);
}
};
// Display a new channel
// TODO extract into UI method
var display = function (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);
});
};
// Display friend list
ui.createFriendList(friends, display, remove);
// Open the channels
// TODO extract this into an external function
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: [],
refresh: function () { refresh(data.curvePublic); },
notify: function () {
ui.notify(data.curvePublic);
common.notify(); // HERE
},
unnotify: function () { ui.unnotify(data.curvePublic); },
removeUI: function () { ui.remove(data.curvePublic); },
updateUI: function (types) { ui.update(data.curvePublic, types); },
updateStatus: function () {
ui.updateStatus(data.curvePublic,
channel.getStatus(data.curvePublic));
},
setLastMessageRead: function (hash) {
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(realtime, proxy, common, 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.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) {
var $friend = ui.getFriend(id);
if (!$friend.length) {
openFriendChannel(friend, id);
ui.addToFriendList(friend, display, remove);
}
});
};
common.onDisplayNameChanged(function () {
checkNewFriends();
updateMyData(proxy);
});
return messenger;
};
// Invitation // Invitation
// FIXME there are too many functions with this name // FIXME there are too many functions with this name
var addToFriendList = Msg.addToFriendList = function (common, data, cb) { var addToFriendList = Msg.addToFriendList = function (common, data, cb) {
@ -898,9 +79,11 @@ define([
friends[pubKey] = data; friends[pubKey] = data;
Realtime.whenRealtimeSyncs(common.getRealtime(), function () { Realtime.whenRealtimeSyncs(common, common.getRealtime(), function () {
cb(); cb();
common.pinPads([data.channel]); common.pinPads([data.channel], function (e) {
if (e) { console.error(e); }
});
}); });
common.changeDisplayName(proxy[common.displayNameKey]); common.changeDisplayName(proxy[common.displayNameKey]);
}; };

@ -4,8 +4,8 @@ define([
'/common/curve.js', '/common/curve.js',
'/common/common-hash.js', '/common/common-hash.js',
'/common/common-realtime.js' '/common/common-realtime.js'
// '/bower_components/marked/marked.min.js'
], function ($, Crypto, Curve, Hash, Realtime) { ], function ($, Crypto, Curve, Hash, Realtime) {
'use strict';
var Msg = { var Msg = {
inputs: [], inputs: [],
}; };
@ -37,7 +37,6 @@ define([
}; };
}; };
// TODO make this async
var getFriend = function (proxy, pubkey) { var getFriend = function (proxy, pubkey) {
if (pubkey === proxy.curvePublic) { if (pubkey === proxy.curvePublic) {
var data = createData(proxy); var data = createData(proxy);
@ -47,15 +46,6 @@ define([
return proxy.friends ? proxy.friends[pubkey] : undefined; 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) { var getFriendList = Msg.getFriendList = function (proxy) {
if (!proxy.friends) { proxy.friends = {}; } if (!proxy.friends) { proxy.friends = {}; }
return proxy.friends; return proxy.friends;
@ -93,9 +83,11 @@ define([
friends[pubKey] = data; friends[pubKey] = data;
Realtime.whenRealtimeSyncs(common.getRealtime(), function () { Realtime.whenRealtimeSyncs(common, common.getRealtime(), function () {
cb(); cb();
common.pinPads([data.channel]); common.pinPads([data.channel], function (e) {
if (e) { console.error(e); }
});
}); });
common.changeDisplayName(proxy[common.displayNameKey]); common.changeDisplayName(proxy[common.displayNameKey]);
}; };
@ -103,8 +95,7 @@ define([
var pendingRequests = []; var pendingRequests = [];
/* Used to accept friend requests within apps other than /contacts/ */ /* Used to accept friend requests within apps other than /contacts/ */
// TODO move this into MSG.messenger // TODO rename as _openGroupChannel_
// as _openGroupChannel_
Msg.addDirectMessageHandler = function (common) { Msg.addDirectMessageHandler = function (common) {
var network = common.getNetwork(); var network = common.getNetwork();
var proxy = common.getProxy(); var proxy = common.getProxy();
@ -213,14 +204,12 @@ define([
pendingRequests.push(netfluxId); pendingRequests.push(netfluxId);
var proxy = common.getProxy(); var proxy = common.getProxy();
// this redraws the userlist after a change has occurred // this redraws the userlist after a change has occurred
// TODO rename this function to reflect its purpose
common.changeDisplayName(proxy[common.displayNameKey]); common.changeDisplayName(proxy[common.displayNameKey]);
} }
network.sendto(netfluxId, msgStr); network.sendto(netfluxId, msgStr);
}; };
Msg.messenger = function (common) { Msg.messenger = function (common) {
'use strict';
var messenger = { var messenger = {
handlers: { handlers: {
message: [], message: [],
@ -248,18 +237,10 @@ define([
stack.push(f); stack.push(f);
}; };
// TODO openGroupChannel /* messenger.openGroupChannel = function (hash, cb) {
messenger.openGroupChannel = function (hash, cb) { // TODO set up infrastructure for a many to many channel
// sets up infrastructure for a one to one channel using curve cryptography
cb = cb; cb = cb;
}; }; */
//var ready = messenger.ready = [];
var DEBUG = function (label) {
console.log('event:' + label);
};
DEBUG = DEBUG; // FIXME
var channels = messenger.channels = {}; var channels = messenger.channels = {};
@ -295,10 +276,22 @@ define([
messenger.getMoreHistory = function (curvePublic, hash, count, cb) { messenger.getMoreHistory = function (curvePublic, hash, count, cb) {
if (typeof(cb) !== 'function') { return; } if (typeof(cb) !== 'function') { return; }
if (typeof(hash) !== 'string') {
// FIXME hash is not necessarily defined.
// What does this mean?
console.error("not sure what to do here");
return;
}
var chan = getChannel(curvePublic); var chan = getChannel(curvePublic);
if (typeof(chan) === 'undefined') {
console.error("chan is undefined. we're going to have a problem here");
return;
}
var txid = common.uid(); var txid = common.uid();
initRangeRequest(txid, curvePublic, hash, cb); initRangeRequest(txid, curvePublic, hash, cb);
// FIXME hash is not necessarily defined.
var msg = [ 'GET_HISTORY_RANGE', chan.id, { var msg = [ 'GET_HISTORY_RANGE', chan.id, {
from: hash, from: hash,
count: count, count: count,
@ -346,13 +339,7 @@ define([
var decryptedMsg = channel.encryptor.decrypt(msg); var decryptedMsg = channel.encryptor.decrypt(msg);
if (decryptedMsg === null) { if (decryptedMsg === null) {
// console.error('unable to decrypt message'); return void console.error("Failed 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) { if (!decryptedMsg) {
@ -388,35 +375,27 @@ define([
var orderMessages = function (curvePublic, new_messages, sig) { var orderMessages = function (curvePublic, new_messages, sig) {
var channel = getChannel(curvePublic); var channel = getChannel(curvePublic);
var messages = channel.messages; var messages = channel.messages;
var idx;
messages.some(function (msg, i) {
if (msg.sig === sig) { idx = i; }
return true;
});
if (typeof(idx) !== 'undefined') { // TODO improve performance, guarantee correct ordering
//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) { new_messages.reverse().forEach(function (msg) {
messages.unshift(msg); messages.unshift(msg);
}); });
}; };
var removeFromFriendList = function (curvePublic, cb) {
if (!proxy.friends) { return; }
var friends = proxy.friends;
delete friends[curvePublic];
Realtime.whenRealtimeSyncs(common, realtime, cb);
};
var pushMsg = function (channel, cryptMsg) { var pushMsg = function (channel, cryptMsg) {
var msg = channel.encryptor.decrypt(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); var sig = cryptMsg.slice(0, 64);
if (msgAlreadyKnown(channel, sig)) { return; } if (msgAlreadyKnown(channel, sig)) { return; }
var parsedMsg = JSON.parse(msg); var parsedMsg = JSON.parse(msg);
var curvePublic;
if (parsedMsg[0] === Types.message) { if (parsedMsg[0] === Types.message) {
// TODO validate messages here // TODO validate messages here
var res = { var res = {
@ -429,9 +408,7 @@ define([
curve: getCurveForChannel(channel.id), curve: getCurveForChannel(channel.id),
}; };
// TODO emit message event
channel.messages.push(res); channel.messages.push(res);
eachHandler('message', function (f) { eachHandler('message', function (f) {
f(res); f(res);
}); });
@ -440,7 +417,7 @@ define([
} }
if (parsedMsg[0] === Types.update) { if (parsedMsg[0] === Types.update) {
if (parsedMsg[1] === proxy.curvePublic) { return; } if (parsedMsg[1] === proxy.curvePublic) { return; }
var curvePublic = parsedMsg[1]; curvePublic = parsedMsg[1];
var newdata = parsedMsg[3]; var newdata = parsedMsg[3];
var data = getFriend(proxy, parsedMsg[1]); var data = getFriend(proxy, parsedMsg[1]);
var types = []; var types = [];
@ -457,12 +434,16 @@ define([
return; return;
} }
if (parsedMsg[0] === Types.unfriend) { if (parsedMsg[0] === Types.unfriend) {
console.log('UNFRIEND'); curvePublic = parsedMsg[1];
removeFromFriendList(proxy, realtime, channel.friendEd, function () { delete friends[curvePublic];
channel.wc.leave(Types.unfriend);
//channel.removeUI();
removeFromFriendList(parsedMsg[1], function () {
channel.wc.leave(Types.unfriend);
eachHandler('unfriend', function (f) {
f=f; // FIXME
// TODO
console.log('unfriend');
});
}); });
return; return;
} }
@ -488,13 +469,13 @@ define([
channel.wc.bcast(cryptMsg).then(function () { channel.wc.bcast(cryptMsg).then(function () {
// TODO send event // TODO send event
//channel.refresh(); //channel.refresh();
eachHandler('update', function (f) {
f(myData, myData.curvePublic);
});
}, function (err) { }, function (err) {
console.error(err); console.error(err);
}); });
}); });
eachHandler('update', function (f) {
f(myData, myData.curvePublic);
});
friends.me = myData; friends.me = myData;
} }
}; };
@ -605,21 +586,43 @@ define([
messenger.removeFriend = function (curvePublic, cb) { messenger.removeFriend = function (curvePublic, cb) {
if (typeof(cb) !== 'function') { throw new Error('NO_CALLBACK'); } if (typeof(cb) !== 'function') { throw new Error('NO_CALLBACK'); }
var data = getFriend(proxy, curvePublic); var data = getFriend(proxy, curvePublic);
if (!data) {
// friend is not valid
console.error('friend is not valid');
return;
}
var channel = channels[data.channel]; var channel = channels[data.channel];
if (!channel) {
return void cb("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 msg = [Types.unfriend, proxy.curvePublic, +new Date()];
var msgStr = JSON.stringify(msg); var msgStr = JSON.stringify(msg);
var cryptMsg = channel.encryptor.encrypt(msgStr); var cryptMsg = channel.encryptor.encrypt(msgStr);
// TODO emit remove_friend event? // TODO emit remove_friend event?
channel.wc.bcast(cryptMsg).then(function () { try {
delete friends[curvePublic]; channel.wc.bcast(cryptMsg).then(function () {
Realtime.whenRealtimeSyncs(realtime, function () { delete friends[curvePublic];
cb(); delete channels[curvePublic];
Realtime.whenRealtimeSyncs(common, realtime, function () {
cb();
});
}, function (err) {
console.error(err);
cb(err);
}); });
}, function (err) { } catch (e) {
console.error(err); cb(e);
cb(err); }
});
}; };
var getChannelMessagesSince = function (chan, data, keys) { var getChannelMessagesSince = function (chan, data, keys) {
@ -832,8 +835,9 @@ define([
console.error(o, n, p); console.error(o, n, p);
}).on('remove', ['friends'], function (o, p) { }).on('remove', ['friends'], function (o, p) {
// TODO eachHandler('unfriend', function (f) { f(); }); eachHandler('unfriend', function (f) {
console.error(o, p); f(p[1]); // TODO
});
}); });
Object.freeze(messenger); Object.freeze(messenger);

@ -16,6 +16,10 @@ define([
TODO make this not blow up when disconnected or lagging... TODO make this not blow up when disconnected or lagging...
*/ */
common.whenRealtimeSyncs = function (Cryptpad, realtime, cb) { common.whenRealtimeSyncs = function (Cryptpad, realtime, cb) {
if (typeof(realtime.getAuthDoc) !== 'function') {
return void console.error('improper use of this function');
}
window.setTimeout(function () { window.setTimeout(function () {
if (realtime.getAuthDoc() === realtime.getUserDoc()) { if (realtime.getAuthDoc() === realtime.getUserDoc()) {
return void cb(); return void cb();

@ -122,7 +122,6 @@ define([
common.createInviteUrl = Hash.createInviteUrl; common.createInviteUrl = Hash.createInviteUrl;
// Messaging // Messaging
common.initMessaging = Messaging.init;
common.addDirectMessageHandler = Messaging.addDirectMessageHandler; common.addDirectMessageHandler = Messaging.addDirectMessageHandler;
common.inviteFromUserlist = Messaging.inviteFromUserlist; common.inviteFromUserlist = Messaging.inviteFromUserlist;
common.getFriendList = Messaging.getFriendList; common.getFriendList = Messaging.getFriendList;
@ -130,7 +129,6 @@ define([
common.createData = Messaging.createData; common.createData = Messaging.createData;
common.getPendingInvites = Messaging.getPending; common.getPendingInvites = Messaging.getPending;
common.getLatestMessages = Messaging.getLatestMessages; common.getLatestMessages = Messaging.getLatestMessages;
common.initMessagingUI = Messaging.UI.init;
// Realtime // Realtime
var whenRealtimeSyncs = common.whenRealtimeSyncs = function (realtime, cb) { var whenRealtimeSyncs = common.whenRealtimeSyncs = function (realtime, cb) {
@ -813,6 +811,9 @@ define([
common.pinPads = function (pads, cb) { common.pinPads = function (pads, cb) {
if (!pinsReady()) { return void cb ('RPC_NOT_READY'); } if (!pinsReady()) { return void cb ('RPC_NOT_READY'); }
if (typeof(cb) !== 'function') {
console.error('expected a callback');
}
rpc.pin(pads, function (e, hash) { rpc.pin(pads, function (e, hash) {
if (e) { return void cb(e); } if (e) { return void cb(e); }
@ -1427,23 +1428,37 @@ define([
return $icon; return $icon;
}; };
common.createFileDialog = function (cfg) { common.createModal = function (cfg) {
var $body = cfg.$body || $('body'); var $body = cfg.$body || $('body');
var $blockContainer = $body.find('#fileDialog'); var $blockContainer = $body.find('#'+cfg.id);
if (!$blockContainer.length) { if (!$blockContainer.length) {
$blockContainer = $('<div>', {id: "fileDialog"}).appendTo($body); $blockContainer = $('<div>', {
'class': 'cp-modal-container',
'id': cfg.id
});
} }
$blockContainer.html(''); $blockContainer.html('').appendTo($body);
var $block = $('<div>', {'class': 'cp-modal'}).appendTo($blockContainer); var $block = $('<div>', {'class': 'cp-modal'}).appendTo($blockContainer);
$('<span>', { $('<span>', {
'class': 'close fa fa-times', 'class': 'cp-modal-close fa fa-times',
'title': Messages.filePicker_close 'title': Messages.filePicker_close
}).click(function () { }).click(function () {
$blockContainer.hide(); $blockContainer.hide();
}).appendTo($block); }).appendTo($block);
$body.keydown(function (e) {
if (e.which === 27) { $blockContainer.hide(); }
});
return $blockContainer;
};
common.createFileDialog = function (cfg) {
var $blockContainer = common.createModal({
id: 'fileDialog',
$body: cfg.$body
});
var $block = $blockContainer.find('.cp-modal');
var $description = $('<p>').text(Messages.filePicker_description); var $description = $('<p>').text(Messages.filePicker_description);
$block.append($description); $block.append($description);
var $filter = $('<p>', {'class': 'cp-form'}).appendTo($block); var $filter = $('<p>', {'class': 'cp-modal-form'}).appendTo($block);
var $container = $('<span>', {'class': 'fileContainer'}).appendTo($block); var $container = $('<span>', {'class': 'fileContainer'}).appendTo($block);
var updateContainer = function () { var updateContainer = function () {
$container.html(''); $container.html('');
@ -1483,9 +1498,6 @@ define([
$blockContainer.hide(); $blockContainer.hide();
})); }));
updateContainer(); updateContainer();
$body.keydown(function (e) {
if (e.which === 27) { $blockContainer.hide(); }
});
$blockContainer.show(); $blockContainer.show();
}; };

@ -1,63 +1,8 @@
@import (once) '../customize/src/less2/include/colortheme.less'; @import (once) '../customize/src/less2/include/colortheme.less';
@import '../customize/src/less2/include/modal.less';
#fileDialog { #fileDialog {
display: none;
z-index: 100000;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: @colortheme_modal-dim;
.cp-modal { .cp-modal {
background-color: @colortheme_modal-bg;
color: @colortheme_modal-fg;
box-shadow: @colortheme_modal-shadow;
padding: @colortheme_modal-padding;
position: absolute;
top: 15vh; bottom: 15vh;
left: 10vw; right: 10vw;
overflow: auto;
font-family: @colortheme_font;
text-align: center;
& > p {
margin-bottom: 1em;
}
.cp-form {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
input {
background-color: @colortheme_modal-input;
color: @colortheme_modal-fg;
border: 0;
padding: 8px 12px;
margin: 1em;
width: 300px;
}
.close {
text-shadow: none;
color: inherit;
position: absolute;
top: 0;
right: 0;
margin: @colortheme_modal-padding;
cursor: pointer;
}
.fileContainer { .fileContainer {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;

@ -24,6 +24,10 @@ types of messages:
var hkn = network.historyKeeper; var hkn = network.historyKeeper;
var txid = uid(); var txid = uid();
if (typeof(cb) !== 'function') {
return console.error('expected callback');
}
var pending = ctx.pending[txid] = function (err, response) { var pending = ctx.pending[txid] = function (err, response) {
cb(err, response); cb(err, response);
}; };

@ -4,9 +4,12 @@ define([
'/common/toolbar2.js', '/common/toolbar2.js',
'/common/cryptpad-common.js', '/common/cryptpad-common.js',
'/common/common-messenger.js',
'/contacts/messenger-ui.js',
'css!/bower_components/components-font-awesome/css/font-awesome.min.css', 'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
'less!/customize/src/less/cryptpad.less', 'less!/customize/src/less/cryptpad.less',
], function ($, Crypto, Toolbar, Cryptpad) { ], function ($, Crypto, Toolbar, Cryptpad, Messenger, UI) {
var Messages = Cryptpad.Messages; var Messages = Cryptpad.Messages;
var APP = window.APP = { var APP = window.APP = {
@ -20,7 +23,6 @@ define([
var ifrw = $('#pad-iframe')[0].contentWindow; var ifrw = $('#pad-iframe')[0].contentWindow;
var $iframe = $('#pad-iframe').contents(); var $iframe = $('#pad-iframe').contents();
//var $appContainer = $iframe.find('#app');
var $list = $iframe.find('#friendList'); var $list = $iframe.find('#friendList');
var $messages = $iframe.find('#messaging'); var $messages = $iframe.find('#messaging');
var $bar = $iframe.find('.toolbar-container'); var $bar = $iframe.find('.toolbar-container');
@ -40,28 +42,20 @@ define([
Cryptpad.getProxy().on('disconnect', function () { Cryptpad.getProxy().on('disconnect', function () {
Cryptpad.alert(Messages.common_connectionLost, undefined, true); Cryptpad.alert(Messages.common_connectionLost, undefined, true);
Cryptpad.enableMessaging(false);
}); });
Cryptpad.getProxy().on('reconnect', function (uid) { Cryptpad.getProxy().on('reconnect', function (uid) {
console.error('reconnecting: ', uid); console.error('reconnecting: ', uid);
Cryptpad.findOKButton().click(); Cryptpad.findOKButton().click();
APP.messenger.cleanFriendChannels();
APP.messenger.openFriendChannels();
APP.messenger.setEditable(true);
}); });
var ui = APP.ui = Cryptpad.initMessagingUI(Cryptpad, $list, $messages);
APP.messenger = Cryptpad.initMessaging(Cryptpad, ui);
var $infoBlock = $('<div>', {'class': 'info'}).appendTo($messages); var $infoBlock = $('<div>', {'class': 'info'}).appendTo($messages);
$('<h2>').text(Messages.contacts_info1).appendTo($infoBlock); $('<h2>').text(Messages.contacts_info1).appendTo($infoBlock);
var $ul = $('<ul>').appendTo($infoBlock); var $ul = $('<ul>').appendTo($infoBlock);
$('<li>').text(Messages.contacts_info2).appendTo($ul); $('<li>').text(Messages.contacts_info2).appendTo($ul);
$('<li>').text(Messages.contacts_info3).appendTo($ul); $('<li>').text(Messages.contacts_info3).appendTo($ul);
//$('<li>').text(Messages.contacts_info4).appendTo($ul);
Cryptpad.removeLoadingScreen(); var messenger = window.messenger = Messenger.messenger(Cryptpad);
UI.create(messenger, $list, $messages);
}; };
Cryptpad.ready(function () { Cryptpad.ready(function () {

@ -242,7 +242,13 @@ define([
var $status = find.inList(curvePublic).find('.status'); var $status = find.inList(curvePublic).find('.status');
// FIXME this stopped working :( // FIXME this stopped working :(
messenger.getStatus(curvePublic, function (e, online) { messenger.getStatus(curvePublic, function (e, online) {
if (e) { return void console.error(curvePublic, e); } // if error maybe you shouldn't display this friend...
if (e) {
find.inList(curvePublic).hide();
getChat(curvePublic).hide();
return void console.error(curvePublic, e);
}
if (online) { if (online) {
return void $status return void $status
.removeClass('offline').addClass('online'); .removeClass('offline').addClass('online');
@ -286,14 +292,11 @@ define([
var removeFriend = function (curvePublic) { var removeFriend = function (curvePublic) {
messenger.removeFriend(curvePublic, function (e, removed) { messenger.removeFriend(curvePublic, function (e, removed) {
if (e) { return void console.error(e); } if (e) { return void console.error(e); }
find.inList(curvePublic).remove();
console.log(removed); console.log(removed);
}); });
}; };
/* var friendExistsInUserList = function (curvePublic) {
return !!$userlist.find(dataQuery(curvePublic)).length;
}; */
markup.friend = function (data) { markup.friend = function (data) {
var curvePublic = data.curvePublic; var curvePublic = data.curvePublic;
var friend = h('div.friend.avatar', { var friend = h('div.friend.avatar', {
@ -323,7 +326,9 @@ define([
Cryptpad.fixHTML(data.displayName) Cryptpad.fixHTML(data.displayName)
]), function (yes) { ]), function (yes) {
if (!yes) { return; } if (!yes) { return; }
removeFriend(curvePublic); removeFriend(curvePublic, function (e) {
if (e) { return void console.error(e); }
});
// TODO remove friend from userlist ui // TODO remove friend from userlist ui
// FIXME seems to trigger EJOINED from netflux-websocket (from server); // FIXME seems to trigger EJOINED from netflux-websocket (from server);
// (tried to join a channel in which you were already present) // (tried to join a channel in which you were already present)
@ -384,19 +389,16 @@ define([
}); });
messenger.on('join', function (curvePublic, channel) { messenger.on('join', function (curvePublic, channel) {
//console.log('join', curvePublic, channel);
channel = channel; channel = channel;
updateStatus(curvePublic); updateStatus(curvePublic);
}); });
messenger.on('leave', function (curvePublic, channel) { messenger.on('leave', function (curvePublic, channel) {
//console.log('leave', curvePublic, channel);
channel = channel; channel = channel;
updateStatus(curvePublic); updateStatus(curvePublic);
}); });
// change in your friend list // change in your friend list
messenger.on('update', function (info, curvePublic) { messenger.on('update', function (info, curvePublic) {
console.log(info, curvePublic);
var name = displayNames[curvePublic] = info.displayName; var name = displayNames[curvePublic] = info.displayName;
// update label in friend list // update label in friend list
@ -407,6 +409,10 @@ define([
dataQuery(curvePublic) + ' div.sender').text(name).text(name); dataQuery(curvePublic) + ' div.sender').text(name).text(name);
}); });
messenger.on('unfriend', function (curvePublic) {
console.log(curvePublic);
});
Cryptpad.onDisplayNameChanged(function () { Cryptpad.onDisplayNameChanged(function () {
messenger.checkNewFriends(); messenger.checkNewFriends();
messenger.updateMyData(); messenger.updateMyData();

@ -1,30 +0,0 @@
<!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>

@ -1,17 +0,0 @@
<!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>

@ -1,75 +0,0 @@
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();
});
});
});

@ -506,9 +506,9 @@ span {
} }
.fa { .fa {
cursor: pointer; cursor: pointer;
font-size: 100px; font-size: 90px;
line-height: 140px; margin-top: 5px;
margin: 0; margin-bottom: 0;
} }
} }
} }
@ -597,6 +597,34 @@ span {
flex: 1; flex: 1;
} }
#addPadDialog.cp-modal-container {
.fileIcon;
li:not(.selected):hover {
border: 1px solid white;
}
.cp-modal {
display: flex;
flex-flow: column;
li, li .fa {
cursor: pointer;
}
&> p {
margin: 50px;
}
&> div {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-content: center;
.uploadFile {
break-after: always;
page-break-after: always;
}
}
}
}
/* Toolbar */ /* Toolbar */

@ -52,7 +52,7 @@ define([
var TRASH = "trash"; var TRASH = "trash";
var TRASH_NAME = Messages.fm_trashName; var TRASH_NAME = Messages.fm_trashName;
var RECENT = "recent"; var RECENT = "recent";
var RECENT_NAME = "Recent pads"; var RECENT_NAME = Messages.fm_recentPadsName;
var LOCALSTORAGE_LAST = "cryptpad-file-lastOpened"; var LOCALSTORAGE_LAST = "cryptpad-file-lastOpened";
var LOCALSTORAGE_OPENED = "cryptpad-file-openedFolders"; var LOCALSTORAGE_OPENED = "cryptpad-file-openedFolders";
@ -163,6 +163,7 @@ define([
//var $upIcon = $('<span>', {"class": "fa fa-arrow-circle-up"}); //var $upIcon = $('<span>', {"class": "fa fa-arrow-circle-up"});
var $unsortedIcon = $('<span>', {"class": "fa fa-files-o"}); var $unsortedIcon = $('<span>', {"class": "fa fa-files-o"});
var $templateIcon = $('<span>', {"class": "fa fa-cubes"}); var $templateIcon = $('<span>', {"class": "fa fa-cubes"});
var $recentIcon = $('<span>', {"class": "fa fa-clock-o"});
var $trashIcon = $('<span>', {"class": "fa fa-trash-o"}); var $trashIcon = $('<span>', {"class": "fa fa-trash-o"});
var $trashEmptyIcon = $('<span>', {"class": "fa fa-trash-o"}); var $trashEmptyIcon = $('<span>', {"class": "fa fa-trash-o"});
//var $collapseIcon = $('<span>', {"class": "fa fa-minus-square-o expcol"}); //var $collapseIcon = $('<span>', {"class": "fa fa-minus-square-o expcol"});
@ -1324,7 +1325,7 @@ define([
msg = Messages.fm_info_allFiles; msg = Messages.fm_info_allFiles;
break; break;
case RECENT: case RECENT:
msg = Messages.fm_info_recent || 'TODO'; msg = Messages.fm_info_recent;
break; break;
default: default:
msg = undefined; msg = undefined;
@ -1388,10 +1389,63 @@ define([
$container.append($listButton).append($gridButton); $container.append($listButton).append($gridButton);
}; };
var getNewPadTypes = function () {
var arr = [];
AppConfig.availablePadTypes.forEach(function (type) {
if (type === 'drive') { return; }
if (type === 'contacts') { return; }
if (type === 'todo') { return; }
if (type === 'file') { return; }
if (!Cryptpad.isLoggedIn() && AppConfig.registeredOnlyTypes &&
AppConfig.registeredOnlyTypes.indexOf(type) !== -1) {
return;
}
arr.push(type);
});
return arr;
};
var addNewPadHandlers = function ($block, isInRoot) {
// Handlers
if (isInRoot) {
var onCreated = function (err, info) {
if (err) {
if (err === E_OVER_LIMIT) {
return void Cryptpad.alert(Messages.pinLimitDrive, null, true);
}
return void Cryptpad.alert(Messages.fm_error_cantPin);
}
module.newFolder = info.newPath;
refresh();
};
$block.find('a.newFolder, li.newFolder').click(function () {
filesOp.addFolder(currentPath, null, onCreated);
});
$block.find('a.uploadFile, li.uploadFile').click(function () {
var $input = $('<input>', {
'type': 'file',
'style': 'display: none;'
}).on('change', function (e) {
var file = e.target.files[0];
var ev = {
target: $content[0]
};
APP.FM.handleFile(file, ev);
});
$input.click();
});
}
$block.find('a.newdoc, li.newdoc').click(function () {
var type = $(this).attr('data-type') || 'pad';
sessionStorage[Cryptpad.newPadPathKey] = filesOp.isPathIn(currentPath, [TRASH]) ? '' : currentPath;
window.open('/' + type + '/');
});
};
var createNewButton = function (isInRoot, $container) { var createNewButton = function (isInRoot, $container) {
if (!APP.editable) { return; } if (!APP.editable) { return; }
if (!APP.loggedIn) { return; } // Anonymous users can use the + menu in the toolbar if (!APP.loggedIn) { return; } // Anonymous users can use the + menu in the toolbar
if (!filesOp.isPathIn(currentPath, [ROOT, 'hrefArray'])) { return; }
// Create dropdown // Create dropdown
var options = []; var options = [];
if (isInRoot) { if (isInRoot) {
@ -1408,13 +1462,7 @@ define([
}); });
options.push({tag: 'hr'}); options.push({tag: 'hr'});
} }
AppConfig.availablePadTypes.forEach(function (type) { getNewPadTypes().forEach(function (type) {
if (type === 'drive') { return; }
if (type === 'contacts') { return; }
if (!Cryptpad.isLoggedIn() && AppConfig.registeredOnlyTypes &&
AppConfig.registeredOnlyTypes.indexOf(type) !== -1) {
return;
}
var attributes = { var attributes = {
'class': 'newdoc', 'class': 'newdoc',
'data-type': type, 'data-type': type,
@ -1440,40 +1488,7 @@ define([
$block.find('button').addClass('new'); $block.find('button').addClass('new');
$block.find('button').attr('title', Messages.fm_newButtonTitle); $block.find('button').attr('title', Messages.fm_newButtonTitle);
// Handlers addNewPadHandlers($block, isInRoot);
if (isInRoot) {
var onCreated = function (err, info) {
if (err) {
if (err === E_OVER_LIMIT) {
return void Cryptpad.alert(Messages.pinLimitDrive, null, true);
}
return void Cryptpad.alert(Messages.fm_error_cantPin);
}
module.newFolder = info.newPath;
refresh();
};
$block.find('a.newFolder').click(function () {
filesOp.addFolder(currentPath, null, onCreated);
});
$block.find('a.uploadFile').click(function () {
var $input = $('<input>', {
'type': 'file',
'style': 'display: none;'
}).on('change', function (e) {
var file = e.target.files[0];
var ev = {
target: $content[0]
};
APP.FM.handleFile(file, ev);
});
$input.click();
});
}
$block.find('a.newdoc').click(function () {
var type = $(this).attr('data-type') || 'pad';
sessionStorage[Cryptpad.newPadPathKey] = filesOp.isPathIn(currentPath, [TRASH]) ? '' : currentPath;
window.open('/' + type + '/');
});
$container.append($block); $container.append($block);
}; };
@ -1646,6 +1661,58 @@ define([
return keys; return keys;
}; };
// Create the ghost icon to add pads/folders
var createNewPadIcons = function ($block, isInRoot) {
var $container = $('<div>');
if (isInRoot) {
// Folder
var $element1 = $('<li>', {
'class': 'newFolder element-row grid-element'
}).prepend($folderIcon.clone()).appendTo($container);
$element1.append($('<span>', {'class': 'name'}).text(Messages.fm_folder));
// File
var $element2 = $('<li>', {
'class': 'uploadFile element-row grid-element'
}).prepend(getIcon('file')).appendTo($container);
$element2.append($('<span>', {'class': 'name'}).text(Messages.uploadButton));
}
// Pads
getNewPadTypes().forEach(function (type) {
var $element = $('<li>', {
'class': 'newdoc element-row grid-element'
}).prepend(getIcon(type)).appendTo($container);
$element.append($('<span>', {'class': 'name'}).text(Messages.type[type]));
$element.attr('data-type', type);
});
$container.find('.element-row').click(function () {
$block.hide();
});
return $container;
};
var createGhostIcon = function ($list) {
var isInRoot = currentPath[0] === ROOT;
var $element = $('<li>', {
'class': 'element-row grid-element addpad'
}).prepend($addIcon.clone()).appendTo($list);
$element.append($('<span>', {'class': 'name'}).text(Messages.fm_newFile));
$element.attr('title', Messages.fm_newFile);
$element.click(function () {
var $modal = Cryptpad.createModal({
id: 'addPadDialog',
$body: $iframe.find('body')
});
var $title = $('<h3>').text(Messages.fm_newFile);
var $description = $('<p>').text(Messages.fm_newButtonTitle);
$modal.find('.cp-modal').append($title);
$modal.find('.cp-modal').append($description);
var $content = createNewPadIcons($modal, isInRoot);
$modal.find('.cp-modal').append($content);
$modal.show();
addNewPadHandlers($modal, isInRoot);
});
};
// Drive content toolbar // Drive content toolbar
var createToolbar = function () { var createToolbar = function () {
var $toolbar = $driveToolbar; var $toolbar = $driveToolbar;
@ -1704,6 +1771,7 @@ define([
} }
$container.append($element); $container.append($element);
}); });
createGhostIcon($container);
}; };
var displayAllFiles = function ($container) { var displayAllFiles = function ($container) {
@ -1997,22 +2065,8 @@ define([
$element.appendTo($list); $element.appendTo($list);
}); });
var $element = $('<li>', { createGhostIcon($list);
'class': 'element-row grid-element addpad'
}).prepend($addIcon.clone()).appendTo($list);
$element.attr('title', "TODO: Add a pad");
$element.click(function () {
window.setTimeout(function () {
$driveToolbar.find('.leftside .dropdown-bar-content').show();
});
/*var $content = $driveToolbar.find('.leftside .dropdown-bar-content').html();
var $container = $('<div>').append($('<div>', {id:'cryptpad-add-pad'}));
Cryptpad.alert($container.html(),null,true);
var $c = $('body > .alertify').last().find('#cryptpad-add-pad');
$c.append($content);*/
});
} }
//$content.append($toolbar).append($title).append($info).append($dirContent);
$content.append($info).append($dirContent); $content.append($info).append($dirContent);
var $truncated = $('<span>', {'class': 'truncated'}).text('...'); var $truncated = $('<span>', {'class': 'truncated'}).text('...');
@ -2168,7 +2222,7 @@ define([
}; };
var createRecent = function ($container, path) { var createRecent = function ($container, path) {
var $icon = $templateIcon.clone(); //TODO var $icon = $recentIcon.clone();
var isOpened = filesOp.comparePath(path, currentPath); var isOpened = filesOp.comparePath(path, currentPath);
var $element = createTreeElement(RECENT_NAME, $icon, [RECENT], false, false, false, isOpened); var $element = createTreeElement(RECENT_NAME, $icon, [RECENT], false, false, false, isOpened);
$element.addClass('root'); $element.addClass('root');

Loading…
Cancel
Save