Refactor contacts/messenger so that it is usable directly in the apps

pull/1/head
yflory 6 years ago
parent 2f3576f90e
commit e6743887fc

@ -12,6 +12,7 @@
@import (reference) './font.less'; @import (reference) './font.less';
@import (reference) "./app-print.less"; @import (reference) "./app-print.less";
@import (reference) "./app-noscroll.less"; @import (reference) "./app-noscroll.less";
@import (reference) "./messenger.less";
.framework_main(@bg-color, @warn-color, @color) { .framework_main(@bg-color, @warn-color, @color) {
--LessLoader_require: LessLoader_currentFile(); --LessLoader_require: LessLoader_currentFile();
@ -36,6 +37,7 @@
.tippy_main(); .tippy_main();
.checkmark_main(20px); .checkmark_main(20px);
.password_main(); .password_main();
.messenger_main();
.creation_main( .creation_main(
@bg-color: @bg-color, @bg-color: @bg-color,
@color: @color @color: @color

@ -0,0 +1,252 @@
@import (reference) './avatar.less';
@import (reference) "./colortheme-all.less";
.messenger_main() {
--LessLoader_require: LessLoader_currentFile();
};
& {
@keyframes example {
0% {
background: rgba(0,0,0,0.1);
}
50% {
background: rgba(0,0,0,0.3);
}
100% {
background: rgba(0,0,0,0.1);
}
}
@button-border: 2px;
@bg-color: @colortheme_friends-bg;
@color: @colortheme_friends-color;
#cp-app-contacts-container {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
min-height: 0;
&.ready {
background-size: cover;
background-position: center;
}
}
.cp-app-contacts-spinner {
display: none;
}
.cp-app-contacts-initializing {
.cp-app-contacts-spinner {
color: white;
display: block;
}
.cp-app-contacts-info {
display: none;
}
#cp-app-contacts-friendlist,
#cp-app-contacts-messaging {
display: flex;
justify-content: center;
align-items: center;
}
}
#cp-app-contacts-friendlist {
width: 350px;
max-width: 30%;
height: 100%;
background-color: lighten(@bg-color, 10%);
overflow-y: auto;
.cp-app-contacts-friend {
background: rgba(0,0,0,0.1);
padding: 5px;
margin: 10px;
cursor: pointer;
position: relative;
.cp-app-contacts-right-col {
margin-left: 5px;
display: flex;
flex-flow: column;
}
&:hover {
background-color: rgba(0,0,0,0.3);
}
&.cp-app-contacts-notify {
animation: example 2s ease-in-out infinite;
}
}
.cp-app-contacts-remove {
cursor: pointer;
width: 20px;
&:hover {
color: darken(@color, 20%);
}
}
}
#cp-app-contacts-friendlist .cp-app-contacts-friend, #cp-app-contacts-messaging .cp-avatar {
.avatar_main(30px);
&.cp-avatar {
display: flex;
}
cursor: pointer;
color: @color;
media-tag {
img {
color: #000;
}
}
media-tag, .cp-avatar-default {
margin-right: 5px;
}
.cp-app-contacts-status {
width: 5px;
display: inline-block;
position: absolute;
right: 0;
top: 0;
bottom: 0;
opacity: 0.7;
background-color: #777;
&.cp-app-contacts-online {
background-color: green;
}
&.cp-app-contacts-offline {
background-color: red;
}
}
}
.placeholder (@color: #bbb) {
&::-webkit-input-placeholder { /* WebKit, Blink, Edge */
color: @color;
}
&:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
color: @color;
opacity: 1;
}
&::-moz-placeholder { /* Mozilla Firefox 19+ */
color: @color;
opacity: 1;
}
&:-ms-input-placeholder { /* Internet Explorer 10-11 */
color: @color;
}
&::-ms-input-placeholder { /* Microsoft Edge */
color: @color;
}
}
#cp-app-contacts-messaging {
flex: 1;
height: 100%;
background-color: lighten(@bg-color, 20%);
min-width: 0;
.cp-app-contacts-info {
padding: 20px;
}
.cp-app-contacts-header {
background-color: lighten(@bg-color, 15%);
padding: 0;
display: flex;
justify-content: space-between;
align-items: center;
height: 50px;
.hover () {
height: 100%;
line-height: 30px;
padding: 10px;
&:hover {
background-color: rgba(50,50,50,0.3);
}
}
.cp-avatar,
.cp-app-contacts-right-col {
flex:1 1 auto;
}
.cp-app-contacts-remove-history {
.hover;
}
.cp-avatar {
margin: 10px;
}
.cp-app-contacts-more-history {
//display: none;
.hover;
&.cp-app-contacts-faded {
color: darken(@bg-color, 5%);
}
}
}
.cp-app-contacts-chat {
height: 100%;
display: flex;
flex-flow: column;
.cp-app-contacts-messages {
padding: 0 20px;
margin: 10px 0;
flex: 1;
overflow-x: auto;
.cp-app-contacts-message {
& > div {
padding: 0 10px;
}
.cp-app-contacts-content {
overflow: hidden;
word-wrap: break-word;
&> * {
margin: 0;
}
}
.cp-app-contacts-date {
display: none;
font-style: italic;
}
.cp-app-contacts-sender {
margin-top: 10px;
font-weight: bold;
background-color: rgba(0,0,0,0.1);
}
}
}
}
.cp-app-contacts-input {
background-color: lighten(@bg-color, 15%);
height: auto;
min-height: 50px;
display: flex;
align-items: center;
justify-content: center;
padding: 0 5%;
textarea {
margin: 5px 0;
padding: 5px 10px;
border: none;
height: 50px;
flex: 1;
background-color: darken(@bg-color, 10%);
color: @color;
resize: none;
overflow-y: auto;
.placeholder(#bbb);
&[disabled=true] {
.placeholder(#999);
}
}
button {
height: 50px;
border-radius: 0;
border: none;
background-color: darken(@bg-color, 15%);
&:hover {
background-color: darken(@bg-color, 20%);
}
}
}
}
}

@ -134,9 +134,37 @@
} }
} }
.cp-toolbar-userlist-drawer { .cp-toolbar-chat-drawer {
background-color: @toolbar-bg-color; background-color: @toolbar-bg-color;
background-color: var(--toolbar-bg-color); background-color: var(--toolbar-bg-color);
font: @colortheme_app-font-size @colortheme_font;
width: 400px;
display: block;
overflow-y: auto;
overflow-x: hidden;
padding: 0;
box-sizing: border-box;
position: relative;
order: -2;
#cp-app-contacts-container {
height: 100%;
}
.cp-toolbar-chat-drawer-close {
color: @toolbar-color;
color: var(--toolbar-color);
position: absolute;
top: 0;
right: 1px;
font-size: 15px;
opacity: 0.5;
cursor: pointer;
text-shadow: unset;
&:hover {
opacity: 1;
}
}
}
.cp-toolbar-userlist-drawer {
font: @colortheme_app-font-size @colortheme_font; font: @colortheme_app-font-size @colortheme_font;
min-width: 175px; min-width: 175px;
width: 175px; width: 175px;
@ -145,6 +173,7 @@
overflow-x: hidden; overflow-x: hidden;
padding: 10px; padding: 10px;
box-sizing: border-box; box-sizing: border-box;
order: -1;
.cp-toolbar-userlist-drawer-close { .cp-toolbar-userlist-drawer-close {
position: absolute; position: absolute;
margin-top: -10px; margin-top: -10px;

@ -150,7 +150,8 @@ define([
} }
cfg.friendComplete({ cfg.friendComplete({
logText: Messages.contacts_added, logText: Messages.contacts_added,
netfluxId: sender netfluxId: sender,
friend: msgData
}); });
var msg = ["FRIEND_REQ_ACK", chan]; var msg = ["FRIEND_REQ_ACK", chan];
var msgStr = Crypto.encrypt(JSON.stringify(msg), key); var msgStr = Crypto.encrypt(JSON.stringify(msg), key);
@ -163,7 +164,7 @@ define([
if (i !== -1) { pendingRequests.splice(i, 1); } if (i !== -1) { pendingRequests.splice(i, 1); }
cfg.friendComplete({ cfg.friendComplete({
logText: Messages.contacts_rejected, logText: Messages.contacts_rejected,
netfluxId: sender netfluxId: sender,
}); });
cfg.updateMetadata(); cfg.updateMetadata();
return; return;
@ -180,7 +181,8 @@ define([
} }
cfg.friendComplete({ cfg.friendComplete({
logText: Messages.contacts_added, logText: Messages.contacts_added,
netfluxId: sender netfluxId: sender,
friend: data
}); });
}); });
return; return;

@ -5,7 +5,9 @@ define([
'/common/common-util.js', '/common/common-util.js',
'/common/common-realtime.js', '/common/common-realtime.js',
'/common/common-constants.js', '/common/common-constants.js',
], function (Crypto, Curve, Hash, Util, Realtime, Constants) {
'/bower_components/nthen/index.js',
], function (Crypto, Curve, Hash, Util, Realtime, Constants, nThen) {
'use strict'; 'use strict';
var Msg = { var Msg = {
inputs: [], inputs: [],
@ -65,6 +67,7 @@ define([
update: [], update: [],
friend: [], friend: [],
unfriend: [], unfriend: [],
ready: []
}, },
range_requests: {}, range_requests: {},
}; };
@ -95,19 +98,26 @@ define([
Msg.hk = network.historyKeeper; Msg.hk = network.historyKeeper;
var friends = getFriendList(proxy); var friends = getFriendList(proxy);
var getChannel = function (curvePublic) { var getChannel = function (chanId) {
var friend = friends[curvePublic];
if (!friend) { return; }
var chanId = friend.channel;
if (!chanId) { return; }
return channels[chanId]; return channels[chanId];
}; };
var initRangeRequest = function (txid, curvePublic, sig, cb) { var getFriendFromChannel = function (id) {
var friend;
for (var k in friends) {
if (friends[k].channel === id) {
friend = friends[k];
break;
}
}
return friend;
};
var initRangeRequest = function (txid, chanId, sig, cb) {
messenger.range_requests[txid] = { messenger.range_requests[txid] = {
messages: [], messages: [],
cb: cb, cb: cb,
curvePublic: curvePublic, chanId: chanId,
sig: sig, sig: sig,
}; };
}; };
@ -120,24 +130,22 @@ define([
delete messenger.range_requests[txid]; delete messenger.range_requests[txid];
}; };
messenger.getMoreHistory = function (curvePublic, hash, count, cb) { messenger.getMoreHistory = function (chanId, hash, count, cb) {
if (typeof(cb) !== 'function') { return; } if (typeof(cb) !== 'function') { return; }
if (typeof(hash) !== 'string') { if (typeof(hash) !== 'string') {
// FIXME hash is not necessarily defined. // Channel is empty!
// What does this mean? return void cb(void 0, []);
console.error("not sure what to do here");
return;
} }
var chan = getChannel(curvePublic); var chan = getChannel(chanId);
if (typeof(chan) === 'undefined') { if (typeof(chan) === 'undefined') {
console.error("chan is undefined. we're going to have a problem here"); console.error("chan is undefined. we're going to have a problem here");
return; return;
} }
var txid = Util.uid(); var txid = Util.uid();
initRangeRequest(txid, curvePublic, hash, cb); initRangeRequest(txid, chanId, hash, cb);
var msg = [ 'GET_HISTORY_RANGE', chan.id, { var msg = [ 'GET_HISTORY_RANGE', chan.id, {
from: hash, from: hash,
count: count, count: count,
@ -151,23 +159,58 @@ define([
}); });
}; };
var getCurveForChannel = function (id) { /*var getCurveForChannel = function (id) {
var channel = channels[id]; var channel = channels[id];
if (!channel) { return; } if (!channel) { return; }
return channel.curve; return channel.curve;
}; };*/
/*messenger.getChannelHead = function (id, cb) {
var channel = getChannel(id);
if (channel.isFriendChat) {
var friend;
for (var k in friends) {
if (friends[k].channel === id) {
friend = friends[k];
break;
}
}
if (!friend) { return void cb('NO_SUCH_FRIEND'); }
cb(void 0, friend.lastKnownHash);
} else {
// TODO room
cb('NOT_IMPLEMENTED');
}
};*/
messenger.getChannelHead = function (curvePublic, cb) { messenger.setChannelHead = function (id, hash, cb) {
var friend = friends[curvePublic]; var channel = getChannel(id);
if (!friend) { return void cb('NO_SUCH_FRIEND'); } if (channel.isFriendChat) {
cb(void 0, friend.lastKnownHash); var friend = getFriendFromChannel(id);
if (!friend) { return void cb('NO_SUCH_FRIEND'); }
friend.lastKnownHash = hash;
} else {
// TODO room
return void cb('NOT_IMPLEMENTED');
}
cb();
}; };
messenger.setChannelHead = function (curvePublic, hash, cb) { // Make sure the data we have about our friends are up-to-date when we see them online
var friend = friends[curvePublic]; var checkFriendData = function (curve, data) {
if (!friend) { return void cb('NO_SUCH_FRIEND'); } if (curve === proxy.curvePublic) { return; }
friend.lastKnownHash = hash; var friend = getFriend(proxy, curve);
cb(); var types = [];
Object.keys(data).forEach(function (k) {
if (friend[k] !== data[k]) {
types.push(k);
friend[k] = data[k];
}
});
eachHandler('update', function (f) {
f(clone(data), types);
});
}; };
// Id message allows us to map a netfluxId with a public curve key // Id message allows us to map a netfluxId with a public curve key
@ -206,20 +249,22 @@ define([
// the sender field. This is to prevent replay attacks. // the sender field. This is to prevent replay attacks.
if (parsed[2] !== sender || !parsed[1]) { return; } if (parsed[2] !== sender || !parsed[1]) { return; }
channel.mapId[sender] = parsed[1]; channel.mapId[sender] = parsed[1];
checkFriendData(parsed[1].curvePublic, parsed[1]);
eachHandler('join', function (f) { eachHandler('join', function (f) {
f(parsed[1], channel.id); f(parsed[1], channel.id);
}); });
if (parsed[0] !== Types.mapId) { return; } // Don't send your key if it's already an ACK if (parsed[0] !== Types.mapId) { return; } // Don't send your key if it's already an ACK
// Answer with your own key // Answer with your own key
var rMsg = [Types.mapIdAck, proxy.curvePublic, channel.wc.myID]; var myData = createData(proxy);
delete myData.channel;
var rMsg = [Types.mapIdAck, myData, channel.wc.myID];
var rMsgStr = JSON.stringify(rMsg); var rMsgStr = JSON.stringify(rMsg);
var cryptMsg = channel.encryptor.encrypt(rMsgStr); var cryptMsg = channel.encryptor.encrypt(rMsgStr);
network.sendto(sender, cryptMsg); network.sendto(sender, cryptMsg);
}; };
var orderMessages = function (curvePublic, new_messages /*, sig */) { var orderMessages = function (channel, new_messages /*, sig */) {
var channel = getChannel(curvePublic);
var messages = channel.messages; var messages = channel.messages;
// TODO improve performance, guarantee correct ordering // TODO improve performance, guarantee correct ordering
@ -250,8 +295,9 @@ define([
author: parsedMsg[1], author: parsedMsg[1],
time: parsedMsg[2], time: parsedMsg[2],
text: parsedMsg[3], text: parsedMsg[3],
channel: channel.id
// this makes debugging a whole lot easier // this makes debugging a whole lot easier
curve: getCurveForChannel(channel.id), //curve: getCurveForChannel(channel.id),
}; };
channel.messages.push(res); channel.messages.push(res);
@ -262,31 +308,21 @@ define([
return true; return true;
} }
if (parsedMsg[0] === Types.update) { if (parsedMsg[0] === Types.update) {
if (parsedMsg[1] === proxy.curvePublic) { return; } checkFriendData(parsedMsg[1], parsedMsg[3]);
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; return;
} }
if (parsedMsg[0] === Types.unfriend) { if (parsedMsg[0] === Types.unfriend) {
curvePublic = parsedMsg[1]; curvePublic = parsedMsg[1];
delete friends[curvePublic];
removeFromFriendList(parsedMsg[1], function () { // If this a removal from our part by in another tab, do nothing.
// The channel is already closed in the proxy.on('remove') part
if (curvePublic === proxy.curvePublic) { return; }
removeFromFriendList(curvePublic, function () {
channel.wc.leave(Types.unfriend); channel.wc.leave(Types.unfriend);
delete channels[channel.id];
eachHandler('unfriend', function (f) { eachHandler('unfriend', function (f) {
f(curvePublic); f(curvePublic, false);
}); });
}); });
return; return;
@ -324,7 +360,7 @@ define([
}); });
}); });
eachHandler('update', function (f) { eachHandler('update', function (f) {
f(myData, myData.curvePublic); f(myData, ['displayName', 'profile', 'avatar']);
}); });
friends.me = myData; friends.me = myData;
} }
@ -356,8 +392,7 @@ define([
req.messages.push(parsed[2]); req.messages.push(parsed[2]);
} else if (type === 'HISTORY_RANGE_END') { } else if (type === 'HISTORY_RANGE_END') {
// process all the messages (decrypt) // process all the messages (decrypt)
var curvePublic = req.curvePublic; var channel = getChannel(req.chanId);
var channel = getChannel(curvePublic);
var decrypted = req.messages.map(function (msg) { var decrypted = req.messages.map(function (msg) {
if (msg[2] !== 'MSG') { return; } if (msg[2] !== 'MSG') { return; }
@ -379,11 +414,11 @@ define([
author: O.d[1], author: O.d[1],
time: O.d[2], time: O.d[2],
text: O.d[3], text: O.d[3],
curve: curvePublic, channel: req.chanId
}; };
}); });
orderMessages(curvePublic, decrypted, req.sig); orderMessages(channel, decrypted, req.sig);
req.cb(void 0, decrypted); req.cb(void 0, decrypted);
return deleteRangeRequest(txid); return deleteRangeRequest(txid);
} else { } else {
@ -395,6 +430,7 @@ define([
if ((parsed.validateKey || parsed.owners) && parsed.channel) { if ((parsed.validateKey || parsed.owners) && parsed.channel) {
return; return;
} }
// End of initial history
if (parsed.state && parsed.state === 1 && parsed.channel) { if (parsed.state && parsed.state === 1 && parsed.channel) {
if (channels[parsed.channel]) { if (channels[parsed.channel]) {
// parsed.channel is Ready // parsed.channel is Ready
@ -409,6 +445,7 @@ define([
} }
return; return;
} }
// Initial history message
var chan = parsed[3]; var chan = parsed[3];
if (!chan || !channels[chan]) { return; } if (!chan || !channels[chan]) { return; }
pushMsg(channels[chan], parsed[4]); pushMsg(channels[chan], parsed[4]);
@ -440,7 +477,7 @@ define([
if (!data) { if (!data) {
// friend is not valid // friend is not valid
console.error('friend is not valid'); console.error('friend is not valid');
return; return void cb('INVALID_FRIEND');
} }
var channel = channels[data.channel]; var channel = channels[data.channel];
@ -458,12 +495,13 @@ define([
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?
try { try {
channel.wc.bcast(cryptMsg).then(function () { channel.wc.bcast(cryptMsg).then(function () {
delete friends[curvePublic]; removeFromFriendList(curvePublic, function () {
delete channels[curvePublic]; delete channels[channel.id];
Realtime.whenRealtimeSyncs(realtime, function () { eachHandler('unfriend', function (f) {
f(curvePublic, true);
});
cb(); cb();
}); });
}, function (err) { }, function (err) {
@ -476,7 +514,7 @@ define([
}; };
var getChannelMessagesSince = function (chan, data, keys) { var getChannelMessagesSince = function (chan, data, keys) {
console.log('Fetching [%s] messages since [%s]', data.curvePublic, data.lastKnownHash || ''); console.log('Fetching [%s] messages since [%s]', chan.id, data.lastKnownHash || '');
var cfg = { var cfg = {
validateKey: keys.validateKey, validateKey: keys.validateKey,
owners: [proxy.edPublic, data.edPublic], owners: [proxy.edPublic, data.edPublic],
@ -489,39 +527,19 @@ define([
}); });
}; };
var openFriendChannel = function (data, f) { var openChannel = function (data) {
var keys = Curve.deriveKeys(data.curvePublic, proxy.curvePrivate); var keys = data.keys;
var encryptor = Curve.createEncryptor(keys); var encryptor = Curve.createEncryptor(keys);
network.join(data.channel).then(function (chan) { network.join(data.channel).then(function (chan) {
var channel = channels[data.channel] = { var channel = channels[data.channel] = {
id: data.channel, id: data.channel,
isFriendChat: data.isFriendChat,
sending: false, sending: false,
friendEd: f,
keys: keys,
curve: data.curvePublic,
encryptor: encryptor, encryptor: encryptor,
messages: [], messages: [],
wc: chan, wc: chan,
userList: [], userList: [],
mapId: {}, 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) { chan.on('message', function (msg, sender) {
onMessage(msg, sender, chan); onMessage(msg, sender, chan);
@ -530,9 +548,12 @@ define([
var onJoining = function (peer) { var onJoining = function (peer) {
if (peer === Msg.hk) { return; } if (peer === Msg.hk) { return; }
if (channel.userList.indexOf(peer) !== -1) { return; } if (channel.userList.indexOf(peer) !== -1) { return; }
channel.userList.push(peer); channel.userList.push(peer);
var msg = [Types.mapId, proxy.curvePublic, chan.myID];
// Join event will be sent once we are able to ID this peer
var myData = createData(proxy);
delete myData.channel;
var msg = [Types.mapId, myData, chan.myID];
var msgStr = JSON.stringify(msg); var msgStr = JSON.stringify(msg);
var cryptMsg = channel.encryptor.encrypt(msgStr); var cryptMsg = channel.encryptor.encrypt(msgStr);
network.sendto(peer, cryptMsg); network.sendto(peer, cryptMsg);
@ -544,16 +565,24 @@ define([
}); });
chan.on('join', onJoining); chan.on('join', onJoining);
chan.on('leave', function (peer) { chan.on('leave', function (peer) {
var curvePublic = channel.mapId[peer];
var i = channel.userList.indexOf(peer); var i = channel.userList.indexOf(peer);
while (i !== -1) { while (i !== -1) {
channel.userList.splice(i, 1); channel.userList.splice(i, 1);
i = channel.userList.indexOf(peer); i = channel.userList.indexOf(peer);
} }
// update status // update status
if (!curvePublic) { return; } var otherData = channel.mapId[peer];
if (!otherData) { return; }
// Make sure the leaving user is not connected with another netflux id
if (channel.userList.some(function (nId) {
return channel.mapId[nId]
&& channel.mapId[nId].curvePublic === otherData.curvePublic;
})) { return; }
// Send the notification
eachHandler('leave', function (f) { eachHandler('leave', function (f) {
f(curvePublic, channel.id); f(otherData, channel.id);
}); });
}); });
@ -573,7 +602,7 @@ define([
})); }));
}; };
messenger.openFriendChannel = function (curvePublic, cb) { /*messenger.openFriendChannel = function (curvePublic, cb) {
if (typeof(curvePublic) !== 'string') { return void cb('INVALID_ID'); } if (typeof(curvePublic) !== 'string') { return void cb('INVALID_ID'); }
if (typeof(cb) !== 'function') { throw new Error('expected callback'); } if (typeof(cb) !== 'function') { throw new Error('expected callback'); }
@ -585,10 +614,10 @@ define([
if (!channel) { return void cb('E_NO_CHANNEL'); } if (!channel) { return void cb('E_NO_CHANNEL'); }
joining[channel] = cb; joining[channel] = cb;
openFriendChannel(friend, curvePublic); openFriendChannel(friend, curvePublic);
}; };*/
messenger.sendMessage = function (curvePublic, payload, cb) { messenger.sendMessage = function (id, payload, cb) {
var channel = getChannel(curvePublic); var channel = getChannel(id);
if (!channel) { return void cb('NO_CHANNEL'); } if (!channel) { return void cb('NO_CHANNEL'); }
if (!network.webChannels.some(function (wc) { if (!network.webChannels.some(function (wc) {
if (wc.id === channel.wc.id) { return true; } if (wc.id === channel.wc.id) { return true; }
@ -597,6 +626,9 @@ define([
} }
var msg = [Types.message, proxy.curvePublic, +new Date(), payload]; var msg = [Types.message, proxy.curvePublic, +new Date(), payload];
if (!channel.isFriendChat) {
msg.push(proxy[Constants.displayNameKey]);
}
var msgStr = JSON.stringify(msg); var msgStr = JSON.stringify(msg);
var cryptMsg = channel.encryptor.encrypt(msgStr); var cryptMsg = channel.encryptor.encrypt(msgStr);
@ -608,18 +640,27 @@ define([
}); });
}; };
messenger.getStatus = function (curvePublic, cb) { messenger.getStatus = function (chanId, cb) {
var channel = getChannel(curvePublic); // Display green status if one member is not me
var channel = getChannel(chanId);
if (!channel) { return void cb('NO_SUCH_CHANNEL'); } if (!channel) { return void cb('NO_SUCH_CHANNEL'); }
var online = channel.userList.some(function (nId) { var online = channel.userList.some(function (nId) {
return channel.mapId[nId] === curvePublic; var data = channel.mapId[nId] || undefined;
if (!data) { return false; }
return data.curvePublic !== proxy.curvePublic;
}); });
cb(void 0, online); cb(void 0, online);
}; };
messenger.getFriendInfo = function (curvePublic, cb) { messenger.getFriendInfo = function (channel, cb) {
setTimeout(function () { setTimeout(function () {
var friend = friends[curvePublic]; var friend;
for (var k in friends) {
if (friends[k].channel === channel) {
friend = friends[k];
break;
}
}
if (!friend) { return void cb('NO_SUCH_FRIEND'); } if (!friend) { return void cb('NO_SUCH_FRIEND'); }
// this clone will be redundant when ui uses postmessage // this clone will be redundant when ui uses postmessage
cb(void 0, clone(friend)); cb(void 0, clone(friend));
@ -633,28 +674,163 @@ define([
}); });
}; };
// TODO listen for changes to your friend list var loadFriend = function (friend, cb) {
// emit 'update' events for clients var channel = friend.channel;
if (getChannel(channel)) { return void cb(); }
//var update = function (curvePublic joining[channel] = cb;
var keys = Curve.deriveKeys(friend.curvePublic, proxy.curvePrivate);
var data = {
keys: keys,
channel: friend.channel,
lastKnownHash: friend.lastKnownHash,
owners: [proxy.edPublic, friend.edPublic],
isFriendChat: true
};
openChannel(data);
};
// Detect friends changes made in another worker
proxy.on('change', ['friends'], function (o, n, p) { proxy.on('change', ['friends'], function (o, n, p) {
var curvePublic; var curvePublic;
if (o === undefined) { if (o === undefined) {
// new friend added // new friend added
curvePublic = p.slice(-1)[0]; curvePublic = p.slice(-1)[0];
eachHandler('friend', function (f) {
f(curvePublic, clone(n)); // Load channel
var friend = friends[curvePublic];
if (typeof(friend) !== 'object') { return; }
var channel = friend.channel;
if (!channel) { return; }
loadFriend(friend, function () {
eachHandler('friend', function (f) {
f(curvePublic);
});
}); });
return; return;
} }
if (typeof(n) === 'undefined') {
// Handled by .on('remove')
return;
}
console.error(o, n, p); console.error(o, n, p);
}).on('remove', ['friends'], function (o, p) { }).on('remove', ['friends'], function (o, p) {
var curvePublic = p[1];
if (!curvePublic) { return; }
if (p[2] !== 'channel') { return; }
var channel = channels[o];
channel.wc.leave(Types.unfriend);
delete channels[channel.id];
eachHandler('unfriend', function (f) { eachHandler('unfriend', function (f) {
f(p[1]); // TODO f(curvePublic, true);
}); });
}); });
// Friend added in our contacts in the current worker
messenger.onFriendAdded = function (friendData) {
var friend = friends[friendData.curvePublic];
if (typeof(friend) !== 'object') { return; }
var channel = friend.channel;
if (!channel) { return; }
loadFriend(friend, function () {
eachHandler('friend', function (f) {
f(friend.curvePublic);
});
});
};
var ready = false;
var init = function () {
var friends = getFriendList(proxy);
nThen(function (waitFor) {
Object.keys(friends).forEach(function (key) {
if (key === 'me') { return; }
var friend = clone(friends[key]);
if (typeof(friend) !== 'object') { return; }
var channel = friend.channel;
if (!channel) { return; }
loadFriend(friend, waitFor());
});
// TODO load rooms
}).nThen(function () {
// TODO send event chat ready
// Remove spinner in chatbox
ready = true;
eachHandler('ready', function (f) {
f();
});
});
};
init();
var getRooms = function (curvePublic, cb) {
if (curvePublic) {
// We need to get data about a new friend's room
var friend = getFriend(proxy, curvePublic);
if (!friend) { return void cb({error: 'NO_SUCH_FRIEND'}); }
var channel = getChannel(friend.channel);
if (!channel) { return void cb({error: 'NO_SUCH_CHANNEL'}); }
return void cb([{
id: channel.id,
isFriendChat: true,
name: friend.displayName,
lastKnownHash: friend.lastKnownHash,
curvePublic: friend.curvePublic
}]);
}
var rooms = Object.keys(channels).map(function (id) {
var r = getChannel(id);
var name, lastKnownHash, curvePublic;
if (r.isFriendChat) {
var friend = getFriendFromChannel(id);
if (!friend) { return null; }
name = friend.displayName;
lastKnownHash = friend.lastKnownHash;
curvePublic = friend.curvePublic;
} else {
// TODO room get metadata (name) && lastKnownHash
}
return {
id: r.id,
isFriendChat: r.isFriendChat,
name: name,
lastKnownHash: lastKnownHash,
curvePublic: curvePublic
};
}).filter(function (x) { return x; });
cb(rooms);
};
var getUserList = function (data, cb) {
var room = getChannel(data.id);
if (!room) { return void cb({error: 'NO_SUCH_CHANNEL'}); }
if (room.isFriendChat) {
var friend = getFriendFromChannel(data.id);
if (!friend) { return void cb({error: 'NO_SUCH_FRIEND'}); }
cb([friend]);
} else {
// TODO room userlist in rooms...
// (this is the static userlist, not the netflux one)
}
};
messenger.execCommand = function (obj, cb) {
var cmd = obj.cmd;
var data = obj.data;
if (cmd === 'IS_READY') {
return void cb(ready);
}
if (cmd === 'GET_ROOMS') {
return void getRooms(data, cb);
}
if (cmd === 'GET_USERLIST') {
return void getUserList(data, cb);
}
};
Object.freeze(messenger); Object.freeze(messenger);
return messenger; return messenger;

@ -622,6 +622,12 @@ define([
messenger.setChannelHead = function (data, cb) { messenger.setChannelHead = function (data, cb) {
postMessage("CONTACTS_SET_CHANNEL_HEAD", data, cb); postMessage("CONTACTS_SET_CHANNEL_HEAD", data, cb);
}; };
messenger.execCommand = function (data, cb) {
postMessage("CHAT_COMMAND", data, cb);
};
messenger.onEvent = Util.mkEvent();
messenger.onMessageEvent = Util.mkEvent(); messenger.onMessageEvent = Util.mkEvent();
messenger.onJoinEvent = Util.mkEvent(); messenger.onJoinEvent = Util.mkEvent();
messenger.onLeaveEvent = Util.mkEvent(); messenger.onLeaveEvent = Util.mkEvent();
@ -1059,6 +1065,8 @@ define([
CONTACTS_UPDATE: common.messenger.onUpdateEvent.fire, CONTACTS_UPDATE: common.messenger.onUpdateEvent.fire,
CONTACTS_FRIEND: common.messenger.onFriendEvent.fire, CONTACTS_FRIEND: common.messenger.onFriendEvent.fire,
CONTACTS_UNFRIEND: common.messenger.onUnfriendEvent.fire, CONTACTS_UNFRIEND: common.messenger.onUnfriendEvent.fire,
// Chat
CHAT_EVENT: common.messenger.onEvent.fire,
// Pad // Pad
PAD_READY: common.padRpc.onReadyEvent.fire, PAD_READY: common.padRpc.onReadyEvent.fire,
PAD_MESSAGE: common.padRpc.onMessageEvent.fire, PAD_MESSAGE: common.padRpc.onMessageEvent.fire,

@ -59,6 +59,9 @@ define([
obj[key] = data.value; obj[key] = data.value;
} }
broadcast([clientId], "UPDATE_METADATA"); broadcast([clientId], "UPDATE_METADATA");
if (Array.isArray(path) && path[0] === 'profile' && store.messenger) {
store.messenger.updateMyData();
}
onSync(cb); onSync(cb);
}; };
@ -597,6 +600,7 @@ define([
Store.setDisplayName = function (clientId, value, cb) { Store.setDisplayName = function (clientId, value, cb) {
store.proxy[Constants.displayNameKey] = value; store.proxy[Constants.displayNameKey] = value;
broadcast([clientId], "UPDATE_METADATA"); broadcast([clientId], "UPDATE_METADATA");
if (store.messenger) { store.messenger.updateMyData(); }
onSync(cb); onSync(cb);
}; };
@ -859,6 +863,9 @@ define([
}, },
pinPads: function (data, cb) { Store.pinPads(null, data, cb); }, pinPads: function (data, cb) { Store.pinPads(null, data, cb); },
friendComplete: function (data) { friendComplete: function (data) {
if (data.friend && store.messenger && store.messenger.onFriendAdded) {
store.messenger.onFriendAdded(data.friend);
}
postMessage(clientId, "EV_FRIEND_COMPLETE", data); postMessage(clientId, "EV_FRIEND_COMPLETE", data);
}, },
friendRequest: function (data, cb) { friendRequest: function (data, cb) {
@ -957,6 +964,10 @@ define([
error: e error: e
}); });
}); });
},
execCommand: function (clientId, data, cb) {
store.messenger.execCommand(data, cb);
} }
}; };
@ -1317,7 +1328,6 @@ define([
} }
}; };
var messengerEventInit = false;
var sendMessengerEvent = function (q, data) { var sendMessengerEvent = function (q, data) {
messengerEventClients.forEach(function (cId) { messengerEventClients.forEach(function (cId) {
postMessage(cId, q, data); postMessage(cId, q, data);
@ -1327,41 +1337,47 @@ define([
if (messengerEventClients.indexOf(clientId) === -1) { if (messengerEventClients.indexOf(clientId) === -1) {
messengerEventClients.push(clientId); messengerEventClients.push(clientId);
} }
if (!messengerEventInit) { };
var messenger = store.messenger = Messenger.messenger(store); var loadMessenger = function () {
messenger.on('message', function (message) { var messenger = store.messenger = Messenger.messenger(store);
sendMessengerEvent('CONTACTS_MESSAGE', message); messenger.on('message', function (message) {
sendMessengerEvent('CONTACTS_MESSAGE', message);
});
messenger.on('join', function (curvePublic, channel) {
sendMessengerEvent('CONTACTS_JOIN', {
curvePublic: curvePublic,
channel: channel,
}); });
messenger.on('join', function (curvePublic, channel) { });
sendMessengerEvent('CONTACTS_JOIN', { messenger.on('leave', function (curvePublic, channel) {
curvePublic: curvePublic, sendMessengerEvent('CONTACTS_LEAVE', {
channel: channel, curvePublic: curvePublic,
}); channel: channel,
}); });
messenger.on('leave', function (curvePublic, channel) { });
sendMessengerEvent('CONTACTS_LEAVE', { messenger.on('update', function (info, types) {
curvePublic: curvePublic, sendMessengerEvent('CONTACTS_UPDATE', {
channel: channel, types: types,
}); info: info,
}); });
messenger.on('update', function (info, curvePublic) { });
sendMessengerEvent('CONTACTS_UPDATE', { messenger.on('friend', function (curvePublic) {
curvePublic: curvePublic, sendMessengerEvent('CONTACTS_FRIEND', {
info: info, curvePublic: curvePublic,
});
}); });
messenger.on('friend', function (curvePublic) { });
sendMessengerEvent('CONTACTS_FRIEND', { messenger.on('unfriend', function (curvePublic, removedByMe) {
curvePublic: curvePublic, sendMessengerEvent('CONTACTS_UNFRIEND', {
}); curvePublic: curvePublic,
removedByMe: removedByMe
}); });
messenger.on('unfriend', function (curvePublic) { });
sendMessengerEvent('CONTACTS_UNFRIEND', { messenger.on('ready', function () {
curvePublic: curvePublic, console.log('here');
}); sendMessengerEvent('CHAT_EVENT', {
ev: 'READY'
}); });
messengerEventInit = true; });
}
}; };
@ -1450,6 +1466,7 @@ define([
}); });
userObject.fixFiles(); userObject.fixFiles();
loadSharedFolders(waitFor); loadSharedFolders(waitFor);
loadMessenger();
}).nThen(function () { }).nThen(function () {
var requestLogin = function () { var requestLogin = function () {
broadcast([], "REQUEST_LOGIN"); broadcast([], "REQUEST_LOGIN");

@ -69,6 +69,8 @@ define([
CONTACTS_GET_MORE_HISTORY: Store.messenger.getMoreHistory, CONTACTS_GET_MORE_HISTORY: Store.messenger.getMoreHistory,
CONTACTS_SEND_MESSAGE: Store.messenger.sendMessage, CONTACTS_SEND_MESSAGE: Store.messenger.sendMessage,
CONTACTS_SET_CHANNEL_HEAD: Store.messenger.setChannelHead, CONTACTS_SET_CHANNEL_HEAD: Store.messenger.setChannelHead,
// Chat
CHAT_COMMAND: Store.messenger.execCommand,
// Pad // Pad
SEND_PAD_MSG: Store.sendPadMsg, SEND_PAD_MSG: Store.sendPadMsg,
JOIN_PAD: Store.joinPad, JOIN_PAD: Store.joinPad,

@ -559,6 +559,7 @@ define([
}, onLocal); }, onLocal);
var configTb = { var configTb = {
displayed: [ displayed: [
'chat',
'userlist', 'userlist',
'title', 'title',
'useradmin', 'useradmin',

@ -36,7 +36,8 @@ define([
window.addEventListener('message', onMsg); window.addEventListener('message', onMsg);
}).nThen(function (/*waitFor*/) { }).nThen(function (/*waitFor*/) {
SFCommonO.start({ SFCommonO.start({
useCreationScreen: true useCreationScreen: true,
messaging: true
}); });
}); });
}); });

@ -776,6 +776,14 @@ define([
Cryptpad.messenger.setChannelHead(opt, cb); Cryptpad.messenger.setChannelHead(opt, cb);
}); });
sframeChan.on('Q_CHAT_COMMAND', function (data, cb) {
Cryptpad.messenger.execCommand(data, cb);
});
Cryptpad.messenger.onEvent.reg(function (data) {
console.log(data);
sframeChan.event('EV_CHAT_EVENT', data);
});
Cryptpad.messenger.onMessageEvent.reg(function (data) { Cryptpad.messenger.onMessageEvent.reg(function (data) {
sframeChan.event('EV_CONTACTS_MESSAGE', data); sframeChan.event('EV_CONTACTS_MESSAGE', data);
}); });

@ -35,7 +35,7 @@ define([], function () {
}); });
sFrameChan.on('EV_CONTACTS_UPDATE', function (data) { sFrameChan.on('EV_CONTACTS_UPDATE', function (data) {
_handlers.update.forEach(function (f) { _handlers.update.forEach(function (f) {
f(data.info, data.curvePublic); f(data.info, data.types);
}); });
}); });
sFrameChan.on('EV_CONTACTS_FRIEND', function (data) { sFrameChan.on('EV_CONTACTS_FRIEND', function (data) {
@ -45,7 +45,7 @@ define([], function () {
}); });
sFrameChan.on('EV_CONTACTS_UNFRIEND', function (data) { sFrameChan.on('EV_CONTACTS_UNFRIEND', function (data) {
_handlers.unfriend.forEach(function (f) { _handlers.unfriend.forEach(function (f) {
f(data.curvePublic); f(data.curvePublic, data.removedByMe);
}); });
}); });

@ -171,6 +171,10 @@ define({
'Q_CONTACTS_SET_CHANNEL_HEAD': true, 'Q_CONTACTS_SET_CHANNEL_HEAD': true,
'Q_CONTACTS_CLEAR_OWNED_CHANNEL': true, 'Q_CONTACTS_CLEAR_OWNED_CHANNEL': true,
// Chat
'EV_CHAT_EVENT': true,
'Q_CHAT_COMMAND': true,
// Put one or more entries to the localStore which will go in localStorage. // Put one or more entries to the localStore which will go in localStorage.
'EV_LOCALSTORE_PUT': true, 'EV_LOCALSTORE_PUT': true,
// Put one entry in the parent sessionStorage // Put one entry in the parent sessionStorage

@ -6,8 +6,11 @@ define([
'/common/common-interface.js', '/common/common-interface.js',
'/common/common-hash.js', '/common/common-hash.js',
'/common/common-feedback.js', '/common/common-feedback.js',
'/common/sframe-messenger-inner.js',
'/contacts/messenger-ui.js',
'/customize/messages.js', '/customize/messages.js',
], function ($, Config, ApiConfig, UIElements, UI, Hash, Feedback, Messages) { ], function ($, Config, ApiConfig, UIElements, UI, Hash, Feedback,
Messenger, MessengerUI, Messages) {
var Common; var Common;
var Bar = { var Bar = {
@ -410,6 +413,72 @@ define([
return $container; return $container;
}; };
var initChat = function (toolbar, config) {
var $container = $('<div>', {id: 'cp-app-contacts-container'})
.prependTo(toolbar.chatContent);
var sframeChan = Common.getSframeChannel();
var messenger = Messenger.create(sframeChan);
MessengerUI.create(messenger, $container, Common);
};
var createChat = function (toolbar, config) {
if (!config.metadataMgr) {
throw new Error("You must provide a `metadataMgr` to display the chat");
}
var $content = $('<div>', {'class': 'cp-toolbar-chat-drawer'});
$content.on('drop dragover', function (e) {
e.preventDefault();
e.stopPropagation();
});
var $closeIcon = $('<span>', {"class": "fa fa-window-close cp-toolbar-chat-drawer-close"}).appendTo($content);
//$('<h2>').text(Messages.users).appendTo($content);
//$('<p>', {'class': USERLIST_CLS}).appendTo($content);
toolbar.chatContent = $content;
var $container = $('<span>', {id: 'cp-toolbar-chat-drawer-open', title: Messages.chatButton || 'CHAT'}); //XXX
var $button = $('<button>').text('Chat').appendTo($container); //XXX
$('<span>',{'class': 'cp-dropdown-button-title'}).appendTo($button);
toolbar.$leftside.prepend($container);
if (config.$contentContainer) {
config.$contentContainer.prepend($content);
}
var hide = function () {
$content.hide();
$button.removeClass('cp-toolbar-button-active');
};
var show = function () {
if (Bar.isEmbed) { $content.hide(); return; }
$content.show();
$button.addClass('cp-toolbar-button-active');
};
$closeIcon.click(function () {
Common.setAttribute(['toolbar', 'chat-drawer'], false);
hide();
});
$button.click(function () {
var visible = $content.is(':visible');
if (visible) { hide(); }
else { show(); }
visible = !visible;
Common.setAttribute(['toolbar', 'chat-drawer'], visible);
//Feedback.send(visible?'USERLIST_SHOW': 'USERLIST_HIDE'); // XXX
});
show();
Common.getAttribute(['toolbar', 'chat-drawer'], function (err, val) {
if (val === false || ($(window).height() < 800 && $(window).width() < 800)) {
return void hide();
}
show();
});
initChat(toolbar, config);
return $container;
};
var createShare = function (toolbar, config) { var createShare = function (toolbar, config) {
if (!config.metadataMgr) { if (!config.metadataMgr) {
throw new Error("You must provide a `metadataMgr` to display the userlist"); throw new Error("You must provide a `metadataMgr` to display the userlist");
@ -997,6 +1066,7 @@ define([
// Create the subelements // Create the subelements
var tb = {}; var tb = {};
tb['userlist'] = createUserList; tb['userlist'] = createUserList;
tb['chat'] = createChat;
tb['share'] = createShare; tb['share'] = createShare;
tb['fileshare'] = createFileShare; tb['fileshare'] = createFileShare;
tb['title'] = createTitle; tb['title'] = createTitle;

@ -1,5 +1,5 @@
@import (reference) '../../customize/src/less2/include/avatar.less';
@import (reference) '../../customize/src/less2/include/framework.less'; @import (reference) '../../customize/src/less2/include/framework.less';
@import (reference) '../../customize/src/less2/include/messenger.less';
// body // body
&.cp-app-contacts { &.cp-app-contacts {
@ -9,238 +9,14 @@
@color: @colortheme_friends-color @color: @colortheme_friends-color
); );
@keyframes example {
0% {
background: rgba(0,0,0,0.1);
}
50% {
background: rgba(0,0,0,0.3);
}
100% {
background: rgba(0,0,0,0.1);
}
}
display: flex; display: flex;
flex-flow: column; flex-flow: column;
background-color: red !important;
@button-border: 2px;
@bg-color: @colortheme_friends-bg;
@color: @colortheme_friends-color;
#cp-app-contacts-container {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
min-height: 0;
&.ready {
background-size: cover;
background-position: center;
}
}
#cp-toolbar { #cp-toolbar {
display: flex; // We need this to remove a 3px border at the bottom of the toolbar display: flex; // We need this to remove a 3px border at the bottom of the toolbar
} }
#cp-app-contacts-friendlist { .messenger_main();
width: 350px;
height: 100%;
background-color: lighten(@bg-color, 10%);
overflow-y: auto;
.cp-app-contacts-friend {
background: rgba(0,0,0,0.1);
padding: 5px;
margin: 10px;
cursor: pointer;
position: relative;
.cp-app-contacts-right-col {
margin-left: 5px;
display: flex;
flex-flow: column;
}
&:hover {
background-color: rgba(0,0,0,0.3);
}
&.cp-app-contacts-notify {
animation: example 2s ease-in-out infinite;
}
}
.cp-app-contacts-remove {
cursor: pointer;
width: 20px;
&:hover {
color: darken(@color, 20%);
}
}
}
#cp-app-contacts-friendlist .cp-app-contacts-friend, #cp-app-contacts-messaging .cp-avatar {
.avatar_main(30px);
&.cp-avatar {
display: flex;
}
cursor: pointer;
color: @color;
media-tag {
img {
color: #000;
}
}
media-tag, .cp-avatar-default {
margin-right: 5px;
}
.cp-app-contacts-status {
width: 5px;
display: inline-block;
position: absolute;
right: 0;
top: 0;
bottom: 0;
opacity: 0.7;
background-color: #777;
&.cp-app-contacts-online {
background-color: green;
}
&.cp-app-contacts-offline {
background-color: red;
}
}
}
.placeholder (@color: #bbb) {
&::-webkit-input-placeholder { /* WebKit, Blink, Edge */
color: @color;
}
&:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
color: @color;
opacity: 1;
}
&::-moz-placeholder { /* Mozilla Firefox 19+ */
color: @color;
opacity: 1;
}
&:-ms-input-placeholder { /* Internet Explorer 10-11 */
color: @color;
}
&::-ms-input-placeholder { /* Microsoft Edge */
color: @color;
}
}
#cp-app-contacts-messaging {
flex: 1;
height: 100%;
background-color: lighten(@bg-color, 20%);
min-width: 0;
.cp-app-contacts-info {
padding: 20px;
}
.cp-app-contacts-header {
background-color: lighten(@bg-color, 15%);
padding: 0;
display: flex;
justify-content: space-between;
align-items: center;
height: 50px;
.hover () {
height: 100%;
line-height: 30px;
padding: 10px;
&:hover {
background-color: rgba(50,50,50,0.3);
}
}
.cp-avatar,
.cp-app-contacts-right-col {
flex:1 1 auto;
}
.cp-app-contacts-remove-history {
.hover;
}
.cp-avatar {
margin: 10px;
}
.cp-app-contacts-more-history {
//display: none;
.hover;
&.cp-app-contacts-faded {
color: darken(@bg-color, 5%);
}
}
}
.cp-app-contacts-chat {
height: 100%;
display: flex;
flex-flow: column;
.cp-app-contacts-messages {
padding: 0 20px;
margin: 10px 0;
flex: 1;
overflow-x: auto;
.cp-app-contacts-message {
& > div {
padding: 0 10px;
}
.cp-app-contacts-content {
overflow: hidden;
word-wrap: break-word;
&> * {
margin: 0;
}
}
.cp-app-contacts-date {
display: none;
font-style: italic;
}
.cp-app-contacts-sender {
margin-top: 10px;
font-weight: bold;
background-color: rgba(0,0,0,0.1);
}
}
}
}
.cp-app-contacts-input {
background-color: lighten(@bg-color, 15%);
height: auto;
min-height: 50px;
display: flex;
align-items: center;
justify-content: center;
padding: 0 75px;
textarea {
margin: 5px 0;
padding: 0 10px;
border: none;
height: 50px;
flex: 1;
background-color: darken(@bg-color, 10%);
color: @color;
resize: none;
line-height: 50px;
overflow-y: auto;
.placeholder(#bbb);
&[disabled=true] {
.placeholder(#999);
}
&:placeholder-shown { line-height: 50px; }
}
button {
height: 50px;
border-radius: 0;
border: none;
background-color: darken(@bg-color, 15%);
&:hover {
background-color: darken(@bg-color, 20%);
}
}
}
}
} }

@ -41,22 +41,7 @@ define([
document.body.appendChild(toolbarElement); document.body.appendChild(toolbarElement);
var messaging = h('div#cp-app-contacts-messaging', [ var appElement = h('div#cp-app-contacts-container');
h('div.cp-app-contacts-info', [
h('h2', Messages.contacts_info1),
h('ul', [
h('li', Messages.contacts_info2),
h('li', Messages.contacts_info3),
])
])
]);
var friendList = h('div#cp-app-contacts-friendlist');
var appElement = h('div#cp-app-contacts-container', [
friendList,
messaging,
]);
document.body.appendChild(appElement); document.body.appendChild(appElement);
@ -73,7 +58,7 @@ define([
var messenger = Messenger.create(sFrameChan); var messenger = Messenger.create(sFrameChan);
MessengerUI.create(messenger, $(friendList), $(messaging), common); MessengerUI.create(messenger, $(appElement), common);
UI.removeLoadingScreen(); UI.removeLoadingScreen();

@ -10,49 +10,81 @@ define([
], function ($, Messages, Util, UI, Notifier, h, Marked, MediaTag) { ], function ($, Messages, Util, UI, Notifier, h, Marked, MediaTag) {
'use strict'; 'use strict';
var debug = console.log;
debug = function () {};
var MessengerUI = {}; var MessengerUI = {};
var dataQuery = function (curvePublic) { var dataQuery = function (id) {
return '[data-key="' + curvePublic + '"]'; return '[data-key="' + id + '"]';
};
var userQuery = function (curve) {
return '[data-user="' + curve + '"]';
}; };
var initChannel = function (state, curvePublic, info) { var initChannel = function (state, info) {
console.log('initializing channel for [%s]', curvePublic); console.log('initializing channel for [%s]', info.id);
state.channels[curvePublic] = { state.channels[info.id] = {
messages: [], messages: [],
name: info.name,
isFriendChat: info.isFriendChat,
curvePublic: info.curvePublic,
HEAD: info.lastKnownHash, HEAD: info.lastKnownHash,
TAIL: null, TAIL: null,
}; };
}; };
MessengerUI.create = function (messenger, $userlist, $messages, common) { MessengerUI.create = function (messenger, $container, common) {
var origin = common.getMetadataMgr().getPrivateData().origin; var sframeChan = common.getSframeChannel();
var metadataMgr = common.getMetadataMgr();
var origin = metadataMgr.getPrivateData().origin;
$container.addClass('cp-app-contacts-initializing');
var spinner = '<span class="fa fa-spinner fa-pulse fa-4x fa-fw"></span>';
var messaging = h('div#cp-app-contacts-messaging', [
h('span.fa.fa-spinner.fa-pulse.fa-4x.fa-fw.cp-app-contacts-spinner'),
h('div.cp-app-contacts-info', [
h('h2', Messages.contacts_info1),
h('ul', [
h('li', Messages.contacts_info2),
h('li', Messages.contacts_info3),
])
])
]);
var friendList = h('div#cp-app-contacts-friendlist', [
h('span.fa.fa-spinner.fa-pulse.fa-4x.fa-fw.cp-app-contacts-spinner'),
]);
var $userlist = $(friendList).appendTo($container);
var $messages = $(messaging).appendTo($container);
var state = window.state = { var state = window.state = {
active: '', active: '',
channels: {}
}; };
state.channels = {}; var contactsData = state.contactsData = {};
var displayNames = state.displayNames = {};
var avatars = state.avatars = {}; var avatars = state.avatars = {};
var setActive = function (curvePublic) { var setActive = function (id) {
state.active = curvePublic; state.active = id;
}; };
var isActive = function (curvePublic) { var isActive = function (id) {
return curvePublic === state.active; return id === state.active;
}; };
var find = {}; var find = {};
find.inList = function (curvePublic) { find.inList = function (id) {
return $userlist.find(dataQuery(curvePublic)); return $userlist.find(dataQuery(id));
}; };
var notify = function (curvePublic) { var notify = function (id) {
find.inList(curvePublic).addClass('cp-app-contacts-notify'); find.inList(id).addClass('cp-app-contacts-notify');
}; };
var unnotify = function (curvePublic) { var unnotify = function (id) {
find.inList(curvePublic).removeClass('cp-app-contacts-notify'); find.inList(id).removeClass('cp-app-contacts-notify');
}; };
var m = function (md) { var m = function (md) {
@ -83,24 +115,24 @@ define([
var markup = {}; var markup = {};
markup.message = function (msg) { markup.message = function (msg) {
var curvePublic = msg.author; var curvePublic = msg.author;
var name = displayNames[msg.author]; var name = contactsData[msg.author].displayName;
return h('div.cp-app-contacts-message', { return h('div.cp-app-contacts-message', {
title: msg.time? new Date(msg.time).toLocaleString(): '?', title: msg.time? new Date(msg.time).toLocaleString(): '?',
'data-key': curvePublic, 'data-user': curvePublic,
}, [ }, [
name? h('div.cp-app-contacts-sender', name): undefined, name? h('div.cp-app-contacts-sender', name): undefined,
m(msg.text), m(msg.text),
]); ]);
}; };
var getChat = function (curvePublic) { var getChat = function (id) {
return $messages.find(dataQuery(curvePublic)); return $messages.find(dataQuery(id));
}; };
var normalizeLabels = function ($messagebox) { var normalizeLabels = function ($messagebox) {
$messagebox.find('div.cp-app-contacts-message').toArray().reduce(function (a, b) { $messagebox.find('div.cp-app-contacts-message').toArray().reduce(function (a, b) {
var $b = $(b); var $b = $(b);
if ($(a).data('key') === $b.data('key')) { if ($(a).data('user') === $b.data('user')) {
$b.find('.cp-app-contacts-sender').hide(); $b.find('.cp-app-contacts-sender').hide();
return a; return a;
} }
@ -108,29 +140,31 @@ define([
}, []); }, []);
}; };
markup.chatbox = function (curvePublic, data) { markup.chatbox = function (id, data, curvePublic) {
var moreHistory = h('span.cp-app-contacts-more-history.fa.fa-history', { var moreHistory = h('span.cp-app-contacts-more-history.fa.fa-history', {
title: Messages.contacts_fetchHistory, title: Messages.contacts_fetchHistory,
}); });
var displayName = data.displayName;
var chan = state.channels[id];
var displayName = chan.name;
var fetching = false; var fetching = false;
var $moreHistory = $(moreHistory).click(function () { var $moreHistory = $(moreHistory).click(function () {
if (fetching) { return; } if (fetching) { return; }
// get oldest known message... // get oldest known message...
var channel = state.channels[curvePublic]; var channel = state.channels[id];
if (channel.exhausted) { if (channel.exhausted) {
return void $moreHistory.addClass('cp-app-contacts-faded'); return void $moreHistory.addClass('cp-app-contacts-faded');
} }
console.log('getting history'); debug('getting history');
var sig = channel.TAIL || channel.HEAD; var sig = channel.TAIL || channel.HEAD;
fetching = true; fetching = true;
var $messagebox = $(getChat(curvePublic)).find('.cp-app-contacts-messages'); var $messagebox = $(getChat(id)).find('.cp-app-contacts-messages');
messenger.getMoreHistory(curvePublic, sig, 10, function (e, history) { messenger.getMoreHistory(id, sig, 10, function (e, history) {
fetching = false; fetching = false;
if (e) { return void console.error(e); } if (e) { return void console.error(e); }
@ -145,7 +179,6 @@ define([
if (msg.sig === channel.TAIL) { if (msg.sig === channel.TAIL) {
console.error('No more messages to fetch'); console.error('No more messages to fetch');
channel.exhausted = true; channel.exhausted = true;
console.log(channel);
return void $moreHistory.addClass('cp-app-contacts-faded'); return void $moreHistory.addClass('cp-app-contacts-faded');
} else { } else {
channel.TAIL = msg.sig; channel.TAIL = msg.sig;
@ -156,9 +189,11 @@ define([
if (msg.type !== 'MSG') { return; } if (msg.type !== 'MSG') { return; }
// FIXME Schlameil the painter (performance does not scale well) // FIXME Schlameil the painter (performance does not scale well)
// XXX trust the server?
/*
if (channel.messages.some(function (old) { if (channel.messages.some(function (old) {
return msg.sig === old.sig; return msg.sig === old.sig;
})) { return; } })) { return; }*/
channel.messages.unshift(msg); channel.messages.unshift(msg);
var el_message = markup.message(msg); var el_message = markup.message(msg);
@ -173,15 +208,19 @@ define([
}); });
$(removeHistory).click(function () { $(removeHistory).click(function () {
// XXX
console.error("TODO: only display clear button if owned");
return;
UI.confirm(Messages.contacts_confirmRemoveHistory, function (yes) { UI.confirm(Messages.contacts_confirmRemoveHistory, function (yes) {
if (!yes) { return; } if (!yes) { return; }
messenger.clearOwnedChannel(data.channel, function (e) { messenger.clearOwnedChannel(id, function (e) {
if (e) { if (e) {
console.error(e); console.error(e);
UI.alert(Messages.contacts_removeHistoryServerError); UI.alert(Messages.contacts_removeHistoryServerError);
return; return;
} }
// XXX clear the UI?
}); });
}); });
}); });
@ -205,15 +244,18 @@ define([
]); ]);
var $avatar = $(avatar); var $avatar = $(avatar);
if (data.avatar && avatars[data.avatar]) { if (data.isFriendChat) {
$avatar.append(avatars[data.avatar]).append(rightCol); var friend = contactsData[curvePublic];
} else { if (friend.avatar && avatars[friend.avatar]) {
common.displayAvatar($avatar, data.avatar, data.displayName, function ($img) { $avatar.append(avatars[friend.avatar]).append(rightCol);
if (data.avatar && $img) { } else {
avatars[data.avatar] = $img[0].outerHTML; common.displayAvatar($avatar, friend.avatar, friend.displayName, function ($img) {
} if (friend.avatar && $img) {
$(rightCol).insertAfter($avatar); avatars[friend.avatar] = $img[0].outerHTML;
}); }
$(rightCol).insertAfter($avatar);
});
}
} }
var sending = false; var sending = false;
@ -221,14 +263,14 @@ define([
if (typeof(content) !== 'string' || !content.trim()) { return; } if (typeof(content) !== 'string' || !content.trim()) { return; }
if (sending) { return false; } if (sending) { return false; }
sending = true; sending = true;
messenger.sendMessage(curvePublic, content, function (e) { messenger.sendMessage(id, content, function (e) {
if (e) { if (e) {
// failed to send // failed to send
return void console.error('failed to send'); return void console.error('failed to send');
} }
input.value = ''; input.value = '';
sending = false; sending = false;
console.log('sent successfully'); debug('sent successfully');
var $messagebox = $(messages); var $messagebox = $(messages);
var height = $messagebox[0].scrollHeight; var height = $messagebox[0].scrollHeight;
@ -268,7 +310,8 @@ define([
$(sendButton).click(function () { send(input.value); }); $(sendButton).click(function () { send(input.value); });
return h('div.cp-app-contacts-chat', { return h('div.cp-app-contacts-chat', {
'data-key': curvePublic, 'data-key': id,
'data-user': data.isFriendChat && curvePublic
}, [ }, [
header, header,
messages, messages,
@ -283,16 +326,19 @@ define([
$messages.find('.cp-app-contacts-info').hide(); $messages.find('.cp-app-contacts-info').hide();
}; };
var updateStatus = function (curvePublic) { var showInfo = function () {
var $status = find.inList(curvePublic).find('.cp-app-contacts-status'); $messages.find('.cp-app-contacts-info').show();
// FIXME this stopped working :( };
messenger.getStatus(curvePublic, function (e, online) {
var updateStatus = function (id) {
var $status = find.inList(id).find('.cp-app-contacts-status');
messenger.getStatus(id, function (e, online) {
// if error maybe you shouldn't display this friend... // if error maybe you shouldn't display this friend...
if (e) { if (e) {
find.inList(curvePublic).hide(); find.inList(id).hide();
getChat(curvePublic).hide(); getChat(id).hide();
return void console.error(curvePublic, e); return void console.error(id, e);
} }
if (online) { if (online) {
return void $status return void $status
@ -302,20 +348,20 @@ define([
}); });
}; };
var display = function (curvePublic) { var display = function (chanId) {
var channel = state.channels[curvePublic]; var channel = state.channels[chanId];
var lastMsg = channel.messages.slice(-1)[0]; var lastMsg = channel.messages.slice(-1)[0];
if (lastMsg) { if (lastMsg) {
channel.HEAD = lastMsg.sig; channel.HEAD = lastMsg.sig;
messenger.setChannelHead(curvePublic, channel.HEAD, function (e) { messenger.setChannelHead(chanId, channel.HEAD, function (e) {
if (e) { console.error(e); } if (e) { console.error(e); }
}); });
} }
setActive(curvePublic); setActive(chanId);
unnotify(curvePublic); unnotify(chanId);
var $chat = getChat(curvePublic); var $chat = getChat(chanId);
hideInfo(); hideInfo();
$messages.find('div.cp-app-contacts-chat[data-key]').hide(); $messages.find('div.cp-app-contacts-chat[data-key]').hide();
if ($chat.length) { if ($chat.length) {
@ -325,26 +371,21 @@ define([
$more.click(); $more.click();
} }
return void $chat.show(); return void $chat.show();
} else {
console.error("Chat is missing... Please reload the page and try again.");
} }
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) { 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);
}); });
}; };
markup.friend = function (data) { markup.room = function (id, room, userlist) {
var curvePublic = data.curvePublic; var roomEl = h('div.cp-app-contacts-friend.cp-avatar', {
var friend = h('div.cp-app-contacts-friend.cp-avatar', { 'data-key': id,
'data-key': curvePublic, 'data-user': room.isFriendChat ? userlist[0].curvePublic : ''
}); });
var remove = h('span.cp-app-contacts-remove.fa.fa-user-times', { var remove = h('span.cp-app-contacts-remove.fa.fa-user-times', {
@ -352,46 +393,53 @@ define([
}); });
var status = h('span.cp-app-contacts-status'); var status = h('span.cp-app-contacts-status');
var rightCol = h('span.cp-app-contacts-right-col', [ var rightCol = h('span.cp-app-contacts-right-col', [
h('span.cp-app-contacts-name', [data.displayName]), h('span.cp-app-contacts-name', [room.name]),
remove, remove,
]); ]);
var $friend = $(friend) var friendData = room.isFriendChat ? userlist[0] : {};
.click(function () {
display(curvePublic); var $room = $(roomEl).click(function () {
}) display(id);
.dblclick(function () { }).dblclick(function () {
if (data.profile) { window.open(origin + '/profile/#' + data.profile); } if (friendData.profile) { window.open(origin + '/profile/#' + friendData.profile); }
}); });
$(remove).click(function (e) { $(remove).click(function (e) {
e.stopPropagation(); e.stopPropagation();
UI.confirm(Messages._getKey('contacts_confirmRemove', [ var channel = state.channels[id];
Util.fixHTML(data.displayName) if (channel.isFriendChat) {
]), function (yes) { var curvePublic = channel.curvePublic;
if (!yes) { return; } var friend = contactsData[curvePublic] || friendData;
removeFriend(curvePublic, function (e) { UI.confirm(Messages._getKey('contacts_confirmRemove', [
if (e) { return void console.error(e); } Util.fixHTML(friend.name)
}); ]), function (yes) {
// TODO remove friend from userlist ui if (!yes) { return; }
// FIXME seems to trigger EJOINED from netflux-websocket (from server); removeFriend(curvePublic, function (e) {
// (tried to join a channel in which you were already present) if (e) { return void console.error(e); }
}, undefined, true); });
// 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);
} else {
// TODO room remove room
}
}); });
if (data.avatar && avatars[data.avatar]) { if (friendData.avatar && avatars[friendData.avatar]) {
$friend.append(avatars[data.avatar]); $room.append(avatars[friendData.avatar]);
$friend.append(rightCol); $room.append(rightCol);
} else { } else {
common.displayAvatar($friend, data.avatar, data.displayName, function ($img) { common.displayAvatar($room, friendData.avatar, room.name, function ($img) {
if (data.avatar && $img) { if (friendData.avatar && $img) {
avatars[data.avatar] = $img[0].outerHTML; avatars[friendData.avatar] = $img[0].outerHTML;
} }
$friend.append(rightCol); $room.append(rightCol);
}); });
} }
$friend.append(status); $room.append(status);
return $friend; return $room;
}; };
var isBottomedOut = function ($elem) { var isBottomedOut = function ($elem) {
@ -401,19 +449,23 @@ define([
var initializing = true; var initializing = true;
messenger.on('message', function (message) { messenger.on('message', function (message) {
if (!initializing) { Notifier.notify(); } if (!initializing) { Notifier.notify(); }
var curvePublic = message.curve; var chanId = message.channel;
var name = displayNames[curvePublic]; var chat = getChat(chanId);
var chat = getChat(curvePublic, name);
console.log(message); debug(message);
var el_message = markup.message(message); var el_message = markup.message(message);
state.channels[curvePublic].messages.push(message); var channel = state.channels[chanId];
if (!channel) {
console.error('expected channel [%s] to be open', chanId);
return;
}
var $chat = $(chat); channel.messages.push(message);
var $chat = $(chat);
if (!$chat.length) { if (!$chat.length) {
console.error("Got a message but the chat isn't open"); console.error("Got a message but the chat isn't open");
} }
@ -428,110 +480,173 @@ define([
} }
normalizeLabels($messagebox); normalizeLabels($messagebox);
var channel = state.channels[curvePublic]; if (isActive(chanId)) {
if (!channel) {
console.error('expected channel [%s] to be open', curvePublic);
return;
}
if (isActive(curvePublic)) {
channel.HEAD = message.sig; channel.HEAD = message.sig;
messenger.setChannelHead(curvePublic, message.sig, function (e) { messenger.setChannelHead(chanId, message.sig, function (e) {
if (e) { return void console.error(e); } if (e) { return void console.error(e); }
}); });
return; return;
} }
var lastMsg = channel.messages.slice(-1)[0]; var lastMsg = channel.messages.slice(-1)[0];
if (lastMsg.sig !== channel.HEAD) { if (lastMsg.sig !== channel.HEAD) {
return void notify(curvePublic); return void notify(chanId);
} }
unnotify(curvePublic); unnotify(chanId);
}); });
messenger.on('join', function (curvePublic, channel) { messenger.on('join', function (data, channel) {
channel = channel; if (data.curvePublic) {
updateStatus(curvePublic); contactsData[data.curvePublic] = data;
}
updateStatus(channel);
// TODO room refresh online userlist
}); });
messenger.on('leave', function (curvePublic, channel) { messenger.on('leave', function (data, channel) {
channel = channel; if (contactsData[data.curvePublic]) {
updateStatus(curvePublic); delete contactsData[data.curvePublic];
}
updateStatus(channel);
// TODO room refresh online userlist
}); });
// change in your friend list // change in your friend list
messenger.on('update', function (info, curvePublic) { messenger.on('update', function (info, types) {
var name = displayNames[curvePublic] = info.displayName; if (!info || !info.curvePublic) { return; }
var curvePublic = info.curvePublic;
contactsData[curvePublic] = info;
if (types.indexOf('displayName') !== -1) {
var name = info.displayName;
// update label in friend list
$userlist.find(userQuery(curvePublic)).find('.cp-app-contacts-name').text(name);
// update label in friend list // update title bar and messages
find.inList(curvePublic).find('.cp-app-contacts-name').text(name); $messages.find(userQuery(curvePublic) + ' .cp-app-contacts-header ' +
'.cp-app-contacts-name, div.cp-app-contacts-message'+
userQuery(curvePublic) + ' div.cp-app-contacts-sender').text(name);
// update title bar and messages // XXX update name in state.channels[id] ??
$messages.find(dataQuery(curvePublic) + ' .cp-app-contacts-header ' +
'.cp-app-contacts-name, div.cp-app-contacts-message'+ // TODO room
dataQuery(curvePublic) + ' div.cp-app-contacts-sender').text(name).text(name); // Update name in room userlist
}
if (types.indexOf('profile') !== -1) {
// update dblclick event in friend list
$userlist.find(userQuery(curvePublic)).off('dblclick').dblclick(function () {
if (info.profile) { window.open(origin + '/profile/#' + info.profile); }
});
}
if (types.indexOf('avatar') !== -1) {
var $mAvatar = $messages
.find(userQuery(curvePublic) +' .cp-app-contacts-header .cp-avatar');
var $lAvatar = $userlist.find(userQuery(curvePublic));
$lAvatar.find('.cp-avatar-default, media-tag').remove();
var $div = $('<div>');
common.displayAvatar($div, info.avatar, info.displayName, function ($img) {
if (info.avatar && $img) {
avatars[info.avatar] = $img[0].outerHTML;
}
$mAvatar.html($div.html());
$lAvatar.find('.cp-app-contacts-right-col').before($div.html());
});
}
}); });
var connectToFriend = function (curvePublic, cb) { var execCommand = function (cmd, data, cb) {
messenger.getFriendInfo(curvePublic, function (e, info) { sframeChan.query('Q_CHAT_COMMAND', {cmd: cmd, data: data}, function (err, obj) {
if (e) { return void console.error(e); } if (err || obj.error) { return void cb(err || obj.error); }
var name = displayNames[curvePublic] = info.displayName; cb(void 0, obj);
initChannel(state, curvePublic, info); });
};
var initializeRoom = function (room) {
var id = room.id;
initChannel(state, room);
execCommand('GET_USERLIST', {id: id}, function (e, list) {
if (e || list.error) { return void console.error(e || list.error); }
if (!Array.isArray(list) || !list.length) {
return void console.error("Empty room!");
}
debug('userlist: ' + JSON.stringify(list));
// This is a friend, the userlist is only one user.
var friend = list[0];
contactsData[friend.curvePublic] = friend;
var chatbox = markup.chatbox(curvePublic, info); var chatbox = markup.chatbox(id, room, friend.curvePublic);
$(chatbox).hide(); $(chatbox).hide();
$messages.append(chatbox); $messages.append(chatbox);
var friend = markup.friend(info, name); var roomEl = markup.room(id, room, list);
$userlist.append(friend); $userlist.append(roomEl);
messenger.openFriendChannel(curvePublic, function (e) {
if (e) { return void console.error(e); } updateStatus(id);
cb();
updateStatus(curvePublic);
// don't add friends that are already in your userlist
//if (friendExistsInUserList(k)) { return; }
});
}); });
// TODO room group chat
}; };
messenger.on('friend', function (curvePublic) { messenger.on('friend', function (curvePublic) {
console.log('new friend: ', curvePublic); debug('new friend: ', curvePublic);
//console.error("TODO redraw user list"); execCommand('GET_ROOMS', curvePublic, function (err, rooms) {
//console.error("TODO connect to new friend"); if (err) { return void console.error(err); }
// FIXME this doesn't work right now because the friend hasn't been fully added? debug('rooms: ' + JSON.stringify(rooms));
connectToFriend(curvePublic, function () { rooms.forEach(initializeRoom);
//console.error('connected');
}); });
}); });
messenger.on('unfriend', function (curvePublic) { messenger.on('unfriend', function (curvePublic, removedByMe) {
console.log('unfriend', curvePublic); var channel = state.channels[state.active];
find.inList(curvePublic).remove(); $userlist.find(userQuery(curvePublic)).remove();
console.error('TODO remove chatbox'); $messages.find(userQuery(curvePublic)).remove();
console.error('TODO show something if that chatbox was active'); if (channel && channel.curvePublic === curvePublic) {
showInfo();
// TODO UI.alert if this is triggered by the other guy
// (we need more data on the 'unfriend' event to determine its origin)
}
}); });
common.getMetadataMgr().onChange(function () {
//messenger.checkNewFriends();
messenger.updateMyData();
});
// FIXME dirty hack // TODO room
// messenger.on('joinroom', function (chanid))
// messenger.on('leaveroom', function (chanid))
messenger.getMyInfo(function (e, info) { messenger.getMyInfo(function (e, info) {
displayNames[info.curvePublic] = info.displayName; contactsData[info.curvePublic] = info;
}); });
messenger.getFriendList(function (e, keys) { var ready = false;
var count = keys.length + 1; var onMessengerReady = function () {
var ready = function () { if (ready) { return; }
count--; ready = true;
if (count === 0) {
initializing = false; execCommand('GET_ROOMS', null, function (err, rooms) {
UI.removeLoadingScreen(); if (err) { return void console.error(err); }
}
}; debug('rooms: ' + JSON.stringify(rooms));
ready(); rooms.forEach(initializeRoom);
keys.forEach(function (curvePublic) {
connectToFriend(curvePublic, ready);
}); });
$container.removeClass('cp-app-contacts-initializing');
};
// Initialize chat when outer is ready (all channels loaded)
// TODO: try again in outer if fail to load a channel
execCommand('IS_READY', null, function (err, yes) {
if (yes) { onMessengerReady(); }
});
sframeChan.on('EV_CHAT_EVENT', function (data) {
if (data.ev === 'READY') {
onMessengerReady();
return;
}
}); });
}; };

Loading…
Cancel
Save