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'
let WebSocketServer = require('ws').Server
const PORT = 8000
const UNSUPPORTED_DATA = 1007
const POLICY_VIOLATION = 1008
const CLOSE_UNSUPPORTED = 1003
var run = module.exports.run = function(storage, server) {
var run = module.exports.run = function(server) {
server.on('connection', (socket) => {
socket.on('message', (data) => {
try {
@ -15,7 +14,6 @@ var run = module.exports.run = function(storage, server) {
for (let master of server.clients) {
if (master.key === msg.key) {
socket.close(POLICY_VIOLATION, 'The key already exists')
console.log('ERROR key exists');
return
}
}
@ -32,16 +30,13 @@ var run = module.exports.run = function(storage, server) {
} else if (msg.hasOwnProperty('join')) {
for (let master of server.clients) {
if (master.key === msg.join) {
console.log('joined');
socket.master = master
master.joiningClients.push(socket)
let id = master.joiningClients.length - 1
console.log(id);
master.send(JSON.stringify({id, data: msg.data}))
return
}
}
console.log('ERROR unknown key');
socket.close(POLICY_VIOLATION, 'Unknown key')
} else if (msg.hasOwnProperty('data') && socket.hasOwnProperty('master')) {
let id = socket.master.joiningClients.indexOf(socket)
@ -55,31 +50,11 @@ var run = module.exports.run = function(storage, server) {
})
socket.on('close', (event) => {
console.log('someone has closed');
// If not master
if (socket.hasOwnProperty('master')) {
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;
if (socket.hasOwnProperty('joiningClients')) {
for (let client of socket.joiningClients) {
client.close(POLICY_VIOLATION, 'The peer is no longer available')
}
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,
// the port used for websockets
websocketPort: 3001,
// the port used for webrtc (uncomment to use the WebRTC server)
// webrtcPort: 3002,
// You now have a choice of storage engines

@ -123,9 +123,12 @@
</p>
</noscript>
<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('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-code').setAttribute('href', '/code/#' + Crypto.genKey());
});
@ -216,6 +219,7 @@
<div id="buttons" class="buttons" style="display:none;">
<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-code" class="button create" href="code">CREATE NEW CODE COLLABORATION PAD</a>
</div>

@ -62,7 +62,9 @@ app.get('/api/config', function(req, res){
res.setHeader('Content-Type', 'text/javascript');
res.send('define(' + JSON.stringify({
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);
});
var wsConfig = { server: httpServer };
if (config.websocketPort !== config.httpPort) {
console.log("setting up a new websocket server");
wsConfig = { port: config.websocketPort};
if(config.websocketPort) {
var wsConfig = { server: httpServer };
if (config.websocketPort !== config.httpPort) {
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;
return new Promise(function (resolve, reject) {
if (channel.channels.size === 0) {
console.log('sizenull');resolve();
resolve();
}
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);
@ -240,8 +240,6 @@ return /******/ (function(modules) { // webpackBootstrap
value: function getHistory(historyKeeperID) {
var channel = this;
return new Promise(function (resolve, reject) {
console.log(channel);
console.log('Je veux history ' + channel.myID);
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);
});
@ -407,7 +405,7 @@ return /******/ (function(modules) { // webpackBootstrap
value: function get(code) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var service = void 0;
var service = undefined;
switch (code) {
case cs.WEBRTC_SERVICE:
service = new _WebRTCService2.default(options);
@ -562,8 +560,6 @@ return /******/ (function(modules) { // webpackBootstrap
}, {
key: 'sendTo',
value: function sendTo(id, webChannel, data) {
console.log('sending to ' + id);
return new Promise(function (resolve, reject) {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
@ -646,60 +642,68 @@ return /******/ (function(modules) { // webpackBootstrap
_createClass(StarTopologyService, [{
key: "broadcast",
value: function broadcast(webChannel, data) {
var _iteratorNormalCompletion = true;
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;
return new Promise(function (resolve, reject) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
var msg = JSON.stringify([c.seq++, data.type, webChannel.id, data.msg]);
c.send(msg);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
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 {
if (_didIteratorError) {
throw _iteratorError;
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
resolve();
});
}
}, {
key: "sendTo",
value: function sendTo(id, webChannel, data) {
var _iteratorNormalCompletion2 = true;
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;
return new Promise(function (resolve, reject) {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
var msg = JSON.stringify([c.seq++, data.type, id, data.msg]);
c.send(msg);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
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 {
if (_didIteratorError2) {
throw _iteratorError2;
try {
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) {
var connections = [];
console.log(settings);
var socket = new window.WebSocket(settings.signaling);
socket.onopen = function () {
socket.send(JSON.stringify({ key: settings.key }));
@ -843,12 +846,10 @@ return /******/ (function(modules) { // webpackBootstrap
var settings = Object.assign({}, this.settings, options);
return new Promise(function (resolve, reject) {
var connection = void 0;
var connection = undefined;
var socket = new window.WebSocket(settings.signaling);
console.log('Socket created');
socket.onopen = function () {
connection = new _this2.RTCPeerConnection(settings.webRTCOptions);
console.log('RTC created');
connection.onicecandidate = function (e) {
if (e.candidate !== null) {
var candidate = {
@ -859,8 +860,6 @@ return /******/ (function(modules) { // webpackBootstrap
}
};
var dc = connection.createDataChannel(key);
console.log('data channel created');
console.log(dc);
dc.onopen = function () {
resolve(dc);
};
@ -872,8 +871,6 @@ return /******/ (function(modules) { // webpackBootstrap
};
socket.onmessage = function (e) {
var msg = JSON.parse(e.data);
console.log('message');
console.log(msg);
if (Reflect.has(msg, 'data')) {
if (Reflect.has(msg.data, 'answer')) {
var sd = Object.assign(new _this2.RTCSessionDescription(), msg.data.answer);
@ -966,8 +963,8 @@ return /******/ (function(modules) { // webpackBootstrap
}, function () {});
})();
} else if (msg.sdp.type === 'answer') {
var _sd = Object.assign(new this.RTCSessionDescription(), msg.sdp);
webChannel.connections.get(msg.senderPeerID).setRemoteDescription(_sd, function () {}, function () {});
var sd = Object.assign(new this.RTCSessionDescription(), msg.sdp);
webChannel.connections.get(msg.senderPeerID).setRemoteDescription(sd, function () {}, function () {});
}
} else if (Reflect.has(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);
return new Promise(function (resolve, reject) {
var connection = void 0;
var connection = undefined;
var socket = new window.WebSocket(settings.signaling);
socket.seq = 1;
socket.facade = options.facade || null;
@ -1147,7 +1144,6 @@ return /******/ (function(modules) { // webpackBootstrap
webChannel.onmessage(msg.id, msg.data);
break;
case cs.GET_HISTORY:
console.log("SOMEONE WANTS HISTORY");
webChannel.onPeerMessage(msg.id, msg.code);
break;
case cs.SERVICE_DATA:
@ -1267,8 +1263,11 @@ return /******/ (function(modules) { // webpackBootstrap
if (msg[2] === 'MSG') {}
// We have received a new direct message from another user
if (msg[2] === 'MSG' && msg[3] === socket.uid) {
// Find the peer exists in one of our channels or create a new one
if (typeof socket.facade._onPeerMessage === "function") socket.facade._onPeerMessage(msg[1], msg);
// If it comes form the history keeper, send it to the user
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 (!webChannel.id) {
@ -1302,7 +1301,7 @@ return /******/ (function(modules) { // webpackBootstrap
if (msg[2] === 'MSG' && msg[3] === webChannel.id) {
// Find the peer who sent the message and display it
//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
if (msg[2] === 'LEAVE' && msg[3] === webChannel.id) {
@ -1313,7 +1312,7 @@ return /******/ (function(modules) { // webpackBootstrap
}, {
key: 'message',
value: function message(code, data) {
var type = void 0;
var type = undefined;
switch (code) {
case cs.USER_DATA:
type = 'MSG';

@ -72,12 +72,23 @@ define([
onEvent,
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 =
function (config)
{
var textarea = config.textarea;
var websocketUrl = config.websocketURL;
var webrtcUrl = config.webrtcURL;
var userName = config.userName;
var channel = config.channel;
var cryptKey = config.cryptKey;
@ -103,52 +114,41 @@ define([
var bump = function () {};
var messagesHistory = [];
var options = {
signaling: websocketUrl,
// signaling: 'ws://localhost:8000',
key: channel
// topology: 'StarTopologyService',
// protocol: 'WebSocketProtocolService',
// connector: 'WebSocketService',
// openWebChannel: true
};
console.log(options);
}
var rtc = true;
var connected = false;
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("webrtc")) {
rtc = false;
options.signaling = websocketUrl;
options.topology = 'StarTopologyService';
options.protocol = 'WebSocketProtocolService';
options.connector = 'WebSocketService';
options.openWebChannel = true;
}
else {
options.signaling = webrtcUrl;
}
if(getParameterByName("server")) {
console.log('SERVER');
console.log(channel);
var webchannel = Netflux.create();
webchannel.openForJoining(options).then(function(data) {
// console.log('resolved');
onOpen(webchannel);
}, function(err) {
console.log('rejected');
console.error(err);
});
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);
});
}
else {
console.log('CLIENT');
console.log(channel);
// Connect to the WebSocket server
if(!connected) {
// Connect to the WebSocket/WebRTC channel
Netflux.join(channel, options).then(function(wc) {
connected = true;
onOpen(wc);
}, function(error) {
warn(error);
@ -156,65 +156,64 @@ define([
}
var onOpen = function(wc) {
console.log('joined the channel');
console.log(wc.myID);
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
}
// 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);
}
// Open a Chainpad session
realtime = createRealtime();
// we're fully synced
initializing = false;
// Open a Chainpad session
realtime = createRealtime();
// we're fully synced
initializing = false;
// execute an onReady callback if one was supplied
if (config.onReady) {
config.onReady();
// execute an onReady callback if one was supplied
if (config.onReady) {
config.onReady();
}
// On sending message
realtime.onMessage(function(message) {
// 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
realtime.onMessage(function(message) {
// TODO: put in ChaindpadAdapter
// 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;
});
// Get the channel history
var hc;
if(rtc) {
for (let c of wc.channels) { hc = c; break; }
if(hc) {
console.log('history keeper :');
console.log(hc);
console.log('onPeer '+hc.peerID)
wc.getHistory(hc.peerID);
}
// Get the channel history
// var hc;
// 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
//checkConnection(wc);
}
else {
// TODO : Improve WebSocket service to use the latest Netflux's API
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
if(!rtc) {
// TODO
// checkConnection(wc);
}
bindAllEvents(textarea, doc, onEvent, false);
bindAllEvents(textarea, doc, onEvent, false);
sharejs.attach(textarea, realtime);
bump = realtime.bumpSharejs;
sharejs.attach(textarea, realtime);
bump = realtime.bumpSharejs;
realtime.start();
realtime.start();
}
@ -232,20 +231,17 @@ define([
return '\\' +c;
}));
var onPeerMessage = function(peerID, wc) {
console.log(messagesHistory);
console.log('RTsendTo '+peerID);
messagesHistory.forEach(function(msg) {
console.log(msg);
//var message = Crypto.encrypt('1:y'+msg, cryptKey);
wc.sendTo(peerID, msg);
});
var onPeerMessage = function(peerID, type, wc) {
if(type === 6) {
messagesHistory.forEach(function(msg) {
console.log(msg);
wc.sendTo(peerID, msg);
});
}
};
var onMessage = function(peer, msg) {
// TODO : put in ChainpadAdapter
// remove the password
messagesHistory.push(msg);
var passLen = msg.substring(0,msg.indexOf(':'));
@ -253,10 +249,6 @@ define([
message = Crypto.decrypt(message, cryptKey);
console.log('RECOIS '+message);
// END-TODO ChainpadAdapter
verbose(message);
allMessages.push(message);
if (!initializing) {

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

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

Loading…
Cancel
Save