Ability to choose which protocol to use (Websocket or WebRTC) with Netflux

pull/1/head
Yann Flory 9 years ago
parent b7885eb539
commit ae8f6f7f2c

@ -1,11 +1,10 @@
'use strict' 'use strict'
let WebSocketServer = require('ws').Server let WebSocketServer = require('ws').Server
const PORT = 8000
const UNSUPPORTED_DATA = 1007 const UNSUPPORTED_DATA = 1007
const POLICY_VIOLATION = 1008 const POLICY_VIOLATION = 1008
const CLOSE_UNSUPPORTED = 1003 const CLOSE_UNSUPPORTED = 1003
var run = module.exports.run = function(storage, server) { var run = module.exports.run = function(server) {
server.on('connection', (socket) => { server.on('connection', (socket) => {
socket.on('message', (data) => { socket.on('message', (data) => {
try { try {
@ -15,7 +14,6 @@ var run = module.exports.run = function(storage, server) {
for (let master of server.clients) { for (let master of server.clients) {
if (master.key === msg.key) { if (master.key === msg.key) {
socket.close(POLICY_VIOLATION, 'The key already exists') socket.close(POLICY_VIOLATION, 'The key already exists')
console.log('ERROR key exists');
return return
} }
} }
@ -32,16 +30,13 @@ var run = module.exports.run = function(storage, server) {
} else if (msg.hasOwnProperty('join')) { } else if (msg.hasOwnProperty('join')) {
for (let master of server.clients) { for (let master of server.clients) {
if (master.key === msg.join) { if (master.key === msg.join) {
console.log('joined');
socket.master = master socket.master = master
master.joiningClients.push(socket) master.joiningClients.push(socket)
let id = master.joiningClients.length - 1 let id = master.joiningClients.length - 1
console.log(id);
master.send(JSON.stringify({id, data: msg.data})) master.send(JSON.stringify({id, data: msg.data}))
return return
} }
} }
console.log('ERROR unknown key');
socket.close(POLICY_VIOLATION, 'Unknown key') socket.close(POLICY_VIOLATION, 'Unknown key')
} else if (msg.hasOwnProperty('data') && socket.hasOwnProperty('master')) { } else if (msg.hasOwnProperty('data') && socket.hasOwnProperty('master')) {
let id = socket.master.joiningClients.indexOf(socket) let id = socket.master.joiningClients.indexOf(socket)
@ -55,31 +50,11 @@ var run = module.exports.run = function(storage, server) {
}) })
socket.on('close', (event) => { socket.on('close', (event) => {
console.log('someone has closed'); if (socket.hasOwnProperty('joiningClients')) {
// If not master for (let client of socket.joiningClients) {
if (socket.hasOwnProperty('master')) { client.close(POLICY_VIOLATION, 'The peer is no longer available')
let masterClients = socket.master.joiningClients
for (let client of masterClients) {
if(client.id === socket.id) {
console.log('close client '+client.key)
client.close(POLICY_VIOLATION, 'The peer is no longer available')
//masterClients.splice(masterClients.indexOf(client),1);
}
}
}
else if (socket.hasOwnProperty('joiningClients')) {
let firstClient
let masterClients = socket.joiningClients
for (let client of masterClients) {
firstClient = client
break;
} }
firstClient.close(POLICY_VIOLATION, 'The master is no longer available')
//masterClients.splice(masterClients.indexOf(firstClient),1);
firstClient.joiningClients = masterClients
console.log('change master from '+socket.key+' to '+firstClient.key)
socket = firstClient
} }
}) });
}) })
} }

@ -11,6 +11,8 @@ module.exports = {
httpPort: 3000, httpPort: 3000,
// the port used for websockets // the port used for websockets
websocketPort: 3001, websocketPort: 3001,
// the port used for webrtc (uncomment to use the WebRTC server)
// webrtcPort: 3002,
// You now have a choice of storage engines // You now have a choice of storage engines

@ -123,9 +123,12 @@
</p> </p>
</noscript> </noscript>
<script> <script>
require(['/common/crypto.js'], function (Crypto) { require(['/common/crypto.js', '/api/config?cb=' + Math.random().toString(16).substring(2)], function (Crypto, Config) {
document.getElementById('buttons').setAttribute('style', ''); document.getElementById('buttons').setAttribute('style', '');
document.getElementById('create-pad').setAttribute('href', '/pad/#' + Crypto.genKey()); document.getElementById('create-pad').setAttribute('href', '/pad/#' + Crypto.genKey());
if(Config.webrtcURL !== '') {
document.getElementById('create-rtcpad').setAttribute('href', '/vdom/?webrtc=1#' + Crypto.genKey());
}
document.getElementById('create-sheet').setAttribute('href', '/sheet/#' + Crypto.genKey()); document.getElementById('create-sheet').setAttribute('href', '/sheet/#' + Crypto.genKey());
document.getElementById('create-code').setAttribute('href', '/code/#' + Crypto.genKey()); document.getElementById('create-code').setAttribute('href', '/code/#' + Crypto.genKey());
}); });
@ -216,6 +219,7 @@
<div id="buttons" class="buttons" style="display:none;"> <div id="buttons" class="buttons" style="display:none;">
<a id="create-pad" class="button create" href="pad">CREATE NEW PAD</a> <a id="create-pad" class="button create" href="pad">CREATE NEW PAD</a>
<a id="create-rtcpad" class="button create" href="pad">CREATE NEW WEBRTC PAD</a>
<a id="create-sheet" class="button create" href="sheet">CREATE NEW SPREADSHEET</a> <a id="create-sheet" class="button create" href="sheet">CREATE NEW SPREADSHEET</a>
<a id="create-code" class="button create" href="code">CREATE NEW CODE COLLABORATION PAD</a> <a id="create-code" class="button create" href="code">CREATE NEW CODE COLLABORATION PAD</a>
</div> </div>

@ -62,7 +62,9 @@ app.get('/api/config', function(req, res){
res.setHeader('Content-Type', 'text/javascript'); res.setHeader('Content-Type', 'text/javascript');
res.send('define(' + JSON.stringify({ res.send('define(' + JSON.stringify({
websocketURL:'ws' + ((httpsOpts) ? 's' : '') + '://' + host + ':' + websocketURL:'ws' + ((httpsOpts) ? 's' : '') + '://' + host + ':' +
config.websocketPort + '/cryptpad_websocket' config.websocketPort + '/cryptpad_websocket',
webrtcURL: (config.webrtcPort) ? 'ws' + ((httpsOpts) ? 's' : '') + '://' + host + ':' +
config.webrtcPort : ''
}) + ');'); }) + ');');
}); });
@ -72,16 +74,31 @@ httpServer.listen(config.httpPort,config.httpAddress,function(){
console.log('listening on %s',config.httpPort); console.log('listening on %s',config.httpPort);
}); });
var wsConfig = { server: httpServer }; if(config.websocketPort) {
if (config.websocketPort !== config.httpPort) { var wsConfig = { server: httpServer };
console.log("setting up a new websocket server"); if (config.websocketPort !== config.httpPort) {
wsConfig = { port: config.websocketPort}; console.log("setting up a new websocket server");
wsConfig = { port: config.websocketPort};
}
var wsSrv = new WebSocketServer(wsConfig);
Storage.create(config, function (store) {
console.log('DB connected');
// ChainPadSrv.create(wsSrv, store);
NetfluxSrv.run(store, wsSrv);
//WebRTCSrv.run(store, wsSrv);
});
}
if(config.webrtcPort) {
var wrConfig = { server: httpServer };
if (config.webrtcPort !== config.httpPort) {
console.log("setting up a new webrtc server");
wrConfig = { port: config.webrtcPort};
}
var wrSrv = new WebSocketServer(wrConfig);
WebRTCSrv.run(wrSrv);
// Storage.create(config, function (store) {
// console.log('DB connected for WebRTC');
// ChainPadSrv.create(wsSrv, store);
//NetfluxSrv.run(store, wsSrv);
// });
} }
var wsSrv = new WebSocketServer(wsConfig);
Storage.create(config, function (store) {
console.log('DB connected');
// ChainPadSrv.create(wsSrv, store);
// NetfluxSrv.run(store, wsSrv);
WebRTCSrv.run(store, wsSrv);
});

@ -229,7 +229,7 @@ return /******/ (function(modules) { // webpackBootstrap
var channel = this; var channel = this;
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
if (channel.channels.size === 0) { if (channel.channels.size === 0) {
console.log('sizenull');resolve(); resolve();
} }
var protocol = _ServiceProvider2.default.get(channel.settings.protocol); var protocol = _ServiceProvider2.default.get(channel.settings.protocol);
channel.topologyService.broadcast(channel, protocol.message(cs.USER_DATA, { id: channel.myID, data: data })).then(resolve, reject); channel.topologyService.broadcast(channel, protocol.message(cs.USER_DATA, { id: channel.myID, data: data })).then(resolve, reject);
@ -240,8 +240,6 @@ return /******/ (function(modules) { // webpackBootstrap
value: function getHistory(historyKeeperID) { value: function getHistory(historyKeeperID) {
var channel = this; var channel = this;
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
console.log(channel);
console.log('Je veux history ' + channel.myID);
var protocol = _ServiceProvider2.default.get(channel.settings.protocol); var protocol = _ServiceProvider2.default.get(channel.settings.protocol);
channel.topologyService.sendTo(historyKeeperID, channel, protocol.message(cs.GET_HISTORY, { id: channel.myID, data: '' })).then(resolve, reject); channel.topologyService.sendTo(historyKeeperID, channel, protocol.message(cs.GET_HISTORY, { id: channel.myID, data: '' })).then(resolve, reject);
}); });
@ -407,7 +405,7 @@ return /******/ (function(modules) { // webpackBootstrap
value: function get(code) { value: function get(code) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var service = void 0; var service = undefined;
switch (code) { switch (code) {
case cs.WEBRTC_SERVICE: case cs.WEBRTC_SERVICE:
service = new _WebRTCService2.default(options); service = new _WebRTCService2.default(options);
@ -562,8 +560,6 @@ return /******/ (function(modules) { // webpackBootstrap
}, { }, {
key: 'sendTo', key: 'sendTo',
value: function sendTo(id, webChannel, data) { value: function sendTo(id, webChannel, data) {
console.log('sending to ' + id);
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
var _iteratorNormalCompletion2 = true; var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false; var _didIteratorError2 = false;
@ -646,60 +642,68 @@ return /******/ (function(modules) { // webpackBootstrap
_createClass(StarTopologyService, [{ _createClass(StarTopologyService, [{
key: "broadcast", key: "broadcast",
value: function broadcast(webChannel, data) { value: function broadcast(webChannel, data) {
var _iteratorNormalCompletion = true; return new Promise(function (resolve, reject) {
var _didIteratorError = false; var _iteratorNormalCompletion = true;
var _iteratorError = undefined; var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = webChannel.channels[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var c = _step.value;
var msg = JSON.stringify([c.seq++, data.type, webChannel.id, data.msg]);
c.send(msg);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try { try {
if (!_iteratorNormalCompletion && _iterator.return) { for (var _iterator = webChannel.channels[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
_iterator.return(); var c = _step.value;
var msg = JSON.stringify([c.seq++, data.type, webChannel.id, data.msg]);
c.send(msg);
} }
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally { } finally {
if (_didIteratorError) { try {
throw _iteratorError; if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
} }
} }
}
resolve();
});
} }
}, { }, {
key: "sendTo", key: "sendTo",
value: function sendTo(id, webChannel, data) { value: function sendTo(id, webChannel, data) {
var _iteratorNormalCompletion2 = true; return new Promise(function (resolve, reject) {
var _didIteratorError2 = false; var _iteratorNormalCompletion2 = true;
var _iteratorError2 = undefined; var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = webChannel.channels[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var c = _step2.value;
var msg = JSON.stringify([c.seq++, data.type, id, data.msg]);
c.send(msg);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try { try {
if (!_iteratorNormalCompletion2 && _iterator2.return) { for (var _iterator2 = webChannel.channels[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
_iterator2.return(); var c = _step2.value;
var msg = JSON.stringify([c.seq++, data.type, id, data.msg]);
c.send(msg);
} }
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally { } finally {
if (_didIteratorError2) { try {
throw _iteratorError2; if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
} }
} }
}
resolve();
});
} }
}]); }]);
@ -787,7 +791,6 @@ return /******/ (function(modules) { // webpackBootstrap
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
var connections = []; var connections = [];
console.log(settings);
var socket = new window.WebSocket(settings.signaling); var socket = new window.WebSocket(settings.signaling);
socket.onopen = function () { socket.onopen = function () {
socket.send(JSON.stringify({ key: settings.key })); socket.send(JSON.stringify({ key: settings.key }));
@ -843,12 +846,10 @@ return /******/ (function(modules) { // webpackBootstrap
var settings = Object.assign({}, this.settings, options); var settings = Object.assign({}, this.settings, options);
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
var connection = void 0; var connection = undefined;
var socket = new window.WebSocket(settings.signaling); var socket = new window.WebSocket(settings.signaling);
console.log('Socket created');
socket.onopen = function () { socket.onopen = function () {
connection = new _this2.RTCPeerConnection(settings.webRTCOptions); connection = new _this2.RTCPeerConnection(settings.webRTCOptions);
console.log('RTC created');
connection.onicecandidate = function (e) { connection.onicecandidate = function (e) {
if (e.candidate !== null) { if (e.candidate !== null) {
var candidate = { var candidate = {
@ -859,8 +860,6 @@ return /******/ (function(modules) { // webpackBootstrap
} }
}; };
var dc = connection.createDataChannel(key); var dc = connection.createDataChannel(key);
console.log('data channel created');
console.log(dc);
dc.onopen = function () { dc.onopen = function () {
resolve(dc); resolve(dc);
}; };
@ -872,8 +871,6 @@ return /******/ (function(modules) { // webpackBootstrap
}; };
socket.onmessage = function (e) { socket.onmessage = function (e) {
var msg = JSON.parse(e.data); var msg = JSON.parse(e.data);
console.log('message');
console.log(msg);
if (Reflect.has(msg, 'data')) { if (Reflect.has(msg, 'data')) {
if (Reflect.has(msg.data, 'answer')) { if (Reflect.has(msg.data, 'answer')) {
var sd = Object.assign(new _this2.RTCSessionDescription(), msg.data.answer); var sd = Object.assign(new _this2.RTCSessionDescription(), msg.data.answer);
@ -966,8 +963,8 @@ return /******/ (function(modules) { // webpackBootstrap
}, function () {}); }, function () {});
})(); })();
} else if (msg.sdp.type === 'answer') { } else if (msg.sdp.type === 'answer') {
var _sd = Object.assign(new this.RTCSessionDescription(), msg.sdp); var sd = Object.assign(new this.RTCSessionDescription(), msg.sdp);
webChannel.connections.get(msg.senderPeerID).setRemoteDescription(_sd, function () {}, function () {}); webChannel.connections.get(msg.senderPeerID).setRemoteDescription(sd, function () {}, function () {});
} }
} else if (Reflect.has(msg, 'candidate')) { } else if (Reflect.has(msg, 'candidate')) {
webChannel.connections.get(msg.senderPeerID).addIceCandidate(new this.RTCIceCandidate(msg.candidate)); webChannel.connections.get(msg.senderPeerID).addIceCandidate(new this.RTCIceCandidate(msg.candidate));
@ -1080,7 +1077,7 @@ return /******/ (function(modules) { // webpackBootstrap
var settings = Object.assign({}, this.settings, options); var settings = Object.assign({}, this.settings, options);
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
var connection = void 0; var connection = undefined;
var socket = new window.WebSocket(settings.signaling); var socket = new window.WebSocket(settings.signaling);
socket.seq = 1; socket.seq = 1;
socket.facade = options.facade || null; socket.facade = options.facade || null;
@ -1147,7 +1144,6 @@ return /******/ (function(modules) { // webpackBootstrap
webChannel.onmessage(msg.id, msg.data); webChannel.onmessage(msg.id, msg.data);
break; break;
case cs.GET_HISTORY: case cs.GET_HISTORY:
console.log("SOMEONE WANTS HISTORY");
webChannel.onPeerMessage(msg.id, msg.code); webChannel.onPeerMessage(msg.id, msg.code);
break; break;
case cs.SERVICE_DATA: case cs.SERVICE_DATA:
@ -1267,8 +1263,11 @@ return /******/ (function(modules) { // webpackBootstrap
if (msg[2] === 'MSG') {} if (msg[2] === 'MSG') {}
// We have received a new direct message from another user // We have received a new direct message from another user
if (msg[2] === 'MSG' && msg[3] === socket.uid) { if (msg[2] === 'MSG' && msg[3] === socket.uid) {
// Find the peer exists in one of our channels or create a new one // If it comes form the history keeper, send it to the user
if (typeof socket.facade._onPeerMessage === "function") socket.facade._onPeerMessage(msg[1], msg); if (msg[1] === '_HISTORY_KEEPER_') {
var msgHistory = JSON.parse(msg[4]);
webChannel.onmessage(msgHistory[1], msgHistory[4]);
}
} }
if (msg[2] === 'JOIN' && (webChannel.id == null || webChannel.id === msg[3])) { if (msg[2] === 'JOIN' && (webChannel.id == null || webChannel.id === msg[3])) {
if (!webChannel.id) { if (!webChannel.id) {
@ -1302,7 +1301,7 @@ return /******/ (function(modules) { // webpackBootstrap
if (msg[2] === 'MSG' && msg[3] === webChannel.id) { if (msg[2] === 'MSG' && msg[3] === webChannel.id) {
// Find the peer who sent the message and display it // Find the peer who sent the message and display it
//TODO Use Peer instead of peer.id (msg[1]) : //TODO Use Peer instead of peer.id (msg[1]) :
if (typeof webChannel.onMessage === "function") webChannel.onMessage(msg[1], msg[4]); if (typeof webChannel.onmessage === "function") webChannel.onmessage(msg[1], msg[4]);
} }
// Someone else has left the channel, remove him from the list of peers // Someone else has left the channel, remove him from the list of peers
if (msg[2] === 'LEAVE' && msg[3] === webChannel.id) { if (msg[2] === 'LEAVE' && msg[3] === webChannel.id) {
@ -1313,7 +1312,7 @@ return /******/ (function(modules) { // webpackBootstrap
}, { }, {
key: 'message', key: 'message',
value: function message(code, data) { value: function message(code, data) {
var type = void 0; var type = undefined;
switch (code) { switch (code) {
case cs.USER_DATA: case cs.USER_DATA:
type = 'MSG'; type = 'MSG';

@ -73,11 +73,22 @@ define([
unbind); unbind);
}; };
var getParameterByName = function (name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
var start = module.exports.start = var start = module.exports.start =
function (config) function (config)
{ {
var textarea = config.textarea; var textarea = config.textarea;
var websocketUrl = config.websocketURL; var websocketUrl = config.websocketURL;
var webrtcUrl = config.webrtcURL;
var userName = config.userName; var userName = config.userName;
var channel = config.channel; var channel = config.channel;
var cryptKey = config.cryptKey; var cryptKey = config.cryptKey;
@ -105,50 +116,39 @@ define([
var messagesHistory = []; var messagesHistory = [];
var options = { var options = {
signaling: websocketUrl,
// signaling: 'ws://localhost:8000',
key: channel key: channel
// topology: 'StarTopologyService',
// protocol: 'WebSocketProtocolService',
// connector: 'WebSocketService',
// openWebChannel: true
};
console.log(options);
var realtime;
// Add the Facade's peer messages handler
// Netflux._onPeerMessage = onPeerMessage;
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
} }
if(getParameterByName("server")) { var rtc = true;
console.log('SERVER'); var connected = false;
console.log(channel); var realtime;
var webchannel = Netflux.create();
webchannel.openForJoining(options).then(function(data) {
// console.log('resolved');
onOpen(webchannel);
}, function(err) { if(!getParameterByName("webrtc")) {
console.log('rejected'); rtc = false;
console.error(err); options.signaling = websocketUrl;
}); options.topology = 'StarTopologyService';
options.protocol = 'WebSocketProtocolService';
options.connector = 'WebSocketService';
options.openWebChannel = true;
} }
else { else {
console.log('CLIENT'); options.signaling = webrtcUrl;
console.log(channel); }
// Connect to the WebSocket server
if(rtc) {
// Check if the WebRTC channel exists and create it if necessary
var webchannel = Netflux.create();
webchannel.openForJoining(options).then(function(data) {
connected = true;
onOpen(webchannel);
}, function(error) {
warn(error);
});
}
if(!connected) {
// Connect to the WebSocket/WebRTC channel
Netflux.join(channel, options).then(function(wc) { Netflux.join(channel, options).then(function(wc) {
connected = true;
onOpen(wc); onOpen(wc);
}, function(error) { }, function(error) {
warn(error); warn(error);
@ -156,65 +156,64 @@ define([
} }
var onOpen = function(wc) { var onOpen = function(wc) {
// Add the handlers to the WebChannel
wc.onmessage = onMessage; // On receiving message
wc.onJoining = onJoining; // On user joining the session
wc.onLeaving = onLeaving; // On user leaving the session
wc.onPeerMessage = function(peerId, type) {
onPeerMessage(peerId, type, wc);
}
console.log('joined the channel'); // Open a Chainpad session
console.log(wc.myID); realtime = createRealtime();
wc.onmessage = onMessage; // On receiving message
wc.onJoining = onJoining; // On user joining the session
wc.onLeaving = onLeaving; // On user leaving the session
wc.onPeerMessage = function(peerId, type) {
onPeerMessage(peerId, wc); // On user leaving the session
}
// Open a Chainpad session // we're fully synced
realtime = createRealtime(); initializing = false;
// we're fully synced // execute an onReady callback if one was supplied
initializing = false; if (config.onReady) {
config.onReady();
}
// execute an onReady callback if one was supplied // On sending message
if (config.onReady) { realtime.onMessage(function(message) {
config.onReady(); // Prevent Chainpad from sending authentication messages since it is handled by Netflux
var parsed = parseMessage(message);
if (parsed.content[0] !== 0) {
message = Crypto.encrypt(message, cryptKey);
wc.send(message).then(function() {
// Send the message back to Chainpad once it is sent to all peers if using the WebRTC protocol
if(rtc) { onMessage('', message); }
});
} }
});
// On sending message // Get the channel history
realtime.onMessage(function(message) { var hc;
// TODO: put in ChaindpadAdapter if(rtc) {
// Do not send authentication messages since it is handled by Netflux
var parsed = parseMessage(message);
if (parsed.content[0] !== 0) {
console.log('ENVOI '+message);
message = Crypto.encrypt(message, cryptKey);
wc.send(message).then(function() {
onMessage('', message);
});
}
// END-TODO
});
var hc;
for (let c of wc.channels) { hc = c; break; } for (let c of wc.channels) { hc = c; break; }
if(hc) { if(hc) {
console.log('history keeper :');
console.log(hc);
console.log('onPeer '+hc.peerID)
wc.getHistory(hc.peerID); wc.getHistory(hc.peerID);
} }
// Get the channel history }
// var hc; else {
// wc.peers.forEach(function (p) { if (!hc || p.linkQuality > hc.linkQuality) { hc = p; } }); // TODO : Improve WebSocket service to use the latest Netflux's API
// hc.send(JSON.stringify(['GET_HISTORY', wc.id])); wc.peers.forEach(function (p) { if (!hc || p.linkQuality > hc.linkQuality) { hc = p; } });
hc.send(JSON.stringify(['GET_HISTORY', wc.id]));
}
// Check the connection to the channel // Check the connection to the channel
//checkConnection(wc); if(!rtc) {
// TODO
// checkConnection(wc);
}
bindAllEvents(textarea, doc, onEvent, false); bindAllEvents(textarea, doc, onEvent, false);
sharejs.attach(textarea, realtime); sharejs.attach(textarea, realtime);
bump = realtime.bumpSharejs; bump = realtime.bumpSharejs;
realtime.start(); realtime.start();
} }
@ -232,20 +231,17 @@ define([
return '\\' +c; return '\\' +c;
})); }));
var onPeerMessage = function(peerID, wc) { var onPeerMessage = function(peerID, type, wc) {
console.log(messagesHistory); if(type === 6) {
console.log('RTsendTo '+peerID); messagesHistory.forEach(function(msg) {
messagesHistory.forEach(function(msg) { console.log(msg);
console.log(msg); wc.sendTo(peerID, msg);
//var message = Crypto.encrypt('1:y'+msg, cryptKey); });
wc.sendTo(peerID, msg); }
});
}; };
var onMessage = function(peer, msg) { var onMessage = function(peer, msg) {
// TODO : put in ChainpadAdapter
// remove the password // remove the password
messagesHistory.push(msg); messagesHistory.push(msg);
var passLen = msg.substring(0,msg.indexOf(':')); var passLen = msg.substring(0,msg.indexOf(':'));
@ -253,10 +249,6 @@ define([
message = Crypto.decrypt(message, cryptKey); message = Crypto.decrypt(message, cryptKey);
console.log('RECOIS '+message);
// END-TODO ChainpadAdapter
verbose(message); verbose(message);
allMessages.push(message); allMessages.push(message);
if (!initializing) { if (!initializing) {

@ -31,6 +31,7 @@ define([
var config = { var config = {
textarea: $textarea[0], textarea: $textarea[0],
websocketURL: Config.websocketURL, websocketURL: Config.websocketURL,
webrtcURL: Config.webrtcURL,
userName: Crypto.rand64(8), userName: Crypto.rand64(8),
channel: key.channel, channel: key.channel,
cryptKey: key.cryptKey, cryptKey: key.cryptKey,

@ -170,6 +170,7 @@ define([
// the websocket URL (deprecated?) // the websocket URL (deprecated?)
websocketURL: Config.websocketURL, websocketURL: Config.websocketURL,
webrtcURL: Config.webrtcURL,
// our username // our username
userName: userName, userName: userName,

Loading…
Cancel
Save