Преглед на файлове

DataChannels work on the surface

Michelle Bu преди 12 години
родител
ревизия
1f4dc894ea
променени са 9 файла, в които са добавени 706 реда и са изтрити 748 реда
  1. 1 1
      bin/build.js
  2. 642 693
      dist/peer.js
  3. 0 0
      dist/peer.min.js
  4. 4 5
      examples/helloworld.html
  5. 7 8
      lib/dataconnection.js
  6. 1 1
      lib/mediaconnection.js
  7. 34 29
      lib/negotiator.js
  8. 11 9
      lib/peer.js
  9. 6 2
      lib/util.js

+ 1 - 1
bin/build.js

@@ -47,7 +47,7 @@ var base = [
   , 'peer.js'
   , 'dataconnection.js'
   , 'mediaconnection.js'
-  , 'connectionmanager.js'
+  , 'negotiator.js'
   , 'socket.js'
 
 ];

Файловите разлики са ограничени, защото са твърде много
+ 642 - 693
dist/peer.js


Файловите разлики са ограничени, защото са твърде много
+ 0 - 0
dist/peer.min.js


+ 4 - 5
examples/helloworld.html

@@ -7,12 +7,12 @@
 
 <script>
   // Just for demo.
-  console._log = console.log;
+  /*console._log = console.log;
   console.error = console.log = function() {
     var copy = Array.prototype.slice.call(arguments).join(' ');
     $('.log').append(copy + '<br>');
     console._log(copy);
-  };
+  };*/
 </script>
 
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
@@ -22,13 +22,12 @@
   // example.
 
   $(document).ready(function() {
-    var peer1, peer2, peerId1;
 
     // Create a new Peer with our demo API key, with debug set to true so we can
     // see what's going on.
-    peer1 = new Peer({ key: 'lwjd5qra8257b9', debug: true });
+    peer1 = new Peer({ key: 'lwjd5qra8257b9', debug: 3});
     // Create another Peer with our demo API key to connect to.
-    peer2 = new Peer({ key: 'lwjd5qra8257b9', debug: true });
+    peer2 = new Peer({ key: 'lwjd5qra8257b9', debug: 3});
 
     // The `open` event signifies that the Peer is ready to connect with other
     // Peers and, if we didn't provide the Peer with an ID, that an ID has been

+ 7 - 8
lib/dataconnection.js

@@ -16,14 +16,14 @@ function DataConnection(peer, provider, options) {
   this.peer = peer;
   this.provider = provider;
 
-  this.label = this.options.label;
+  this.id = this.options.connectionId || DataConnection._idPrefix + util.randomToken();
+
+  this.label = this.options.label || this.id;
   this.metadata = this.options.metadata; // TODO: metadata could also be a part of the paylod.
   this.serialization = this.options.serialization;
   this.reliable = this.options.reliable;
 
-  this.id = this.options.connection_id || DataConnection._idPrefix + util.randomToken();
-
-  this.pc = Negotiator.startConnection(
+  Negotiator.startConnection(
     this,
     this.options._payload || {
       originator: true,
@@ -74,11 +74,10 @@ DataConnection.prototype._configureDataChannel = function() {
     };
   }
   this._dc.onclose = function(e) {
-    util.log('DataChannel closed.');
+    util.log('DataChannel closed for:', self.peer);
     self.close();
   };
-
-};
+}
 
 DataConnection.prototype._cleanup = function() {
   if (this._dc && this._dc.readyState !== 'closed') {
@@ -88,7 +87,7 @@ DataConnection.prototype._cleanup = function() {
   this.open = false;
   // Negotiator will listen for this and take care of the PC if appropriate.
   this.emit('close');
-};
+}
 
 // Handles a DataChannel message.
 DataConnection.prototype._handleDataMessage = function(e) {

+ 1 - 1
lib/mediaconnection.js

@@ -15,7 +15,7 @@ function MediaConnection(peer, provider, options) {
   this.metadata = this.options.metadata;
   this.localStream = this.options._stream;
 
-  this.id = this.options.connection_id || MediaConnection._idPrefix + util.randomToken();
+  this.id = this.options.connectionId || MediaConnection._idPrefix + util.randomToken();
   if (this.localStream) {
     this.pc = Negotiator.startConnection(
       this,

+ 34 - 29
lib/negotiator.js

@@ -7,12 +7,12 @@ var Negotiator = {
   pcs: {
     data: {},
     media: {}
-  }, // type => {peer_id: {pc_id: pc}}.
+  }, // type => {peerId: {pc_id: pc}}.
   //providers: {}, // provider's id => providers (there may be multiple providers/client.
   queue: [] // connections that are delayed due to a PC being in use.
 }
 
-Negotiator._idPrefix = 'pc_'
+Negotiator._idPrefix = 'pc_';
 
 /** Returns a PeerConnection object set up correctly (for data, media). */
 // Options preceeded with _ are ones we add artificially.
@@ -25,11 +25,14 @@ Negotiator.startConnection = function(connection, options) {
     pc.addStream(options._stream);
   }
 
+  // Set the connection's PC.
+  connection.pc = pc;
+
   // What do we need to do now?
   if (options.originator) {
     if (connection.type === 'data') {
       // Create the datachannel.
-      var dc = pc.createDataChannel(options.label, {reliable: reliable});
+      var dc = pc.createDataChannel(connection.label, {reliable: options.reliable});
       connection.initialize(dc);
     }
 
@@ -39,8 +42,6 @@ Negotiator.startConnection = function(connection, options) {
   } else {
     Negotiator.handleSDP('OFFER', connection, options.sdp);
   }
-
-  return pc;
 }
 
 Negotiator._getPeerConnection = function(connection, options) {
@@ -51,14 +52,14 @@ Negotiator._getPeerConnection = function(connection, options) {
   if (!Negotiator.pcs[connection.type][connection.peer]) {
     Negotiator.pcs[connection.type][connection.peer] = {};
   }
-  peer_connections = Negotiator.pcs[connection.type][connection.peer];
+  var peerConnections = Negotiator.pcs[connection.type][connection.peer];
 
   var pc;
   if (options.multiplex) {
     // Find an existing PC to use.
-    ids = Object.keys(peer_connections);
+    ids = Object.keys(peerConnections);
     for (var i = 0, ii = ids.length; i < ii; i += 1) {
-      pc = peer_connections[ids[i]];
+      pc = peerConnections[ids[i]];
       if (pc.signalingState === 'stable') {
         break; // We can go ahead and use this PC.
       }
@@ -101,22 +102,23 @@ Negotiator._startPeerConnection = function(connection) {
 
 /** Set up various WebRTC listeners. */
 Negotiator._setupListeners = function(connection, pc, pc_id) {
-  var peer_id = connection.peer;
-  var connection_id = connection.id;
+  var peerId = connection.peer;
+  var connectionId = connection.id;
   var provider = connection.provider;
 
   // ICE CANDIDATES.
   util.log('Listening for ICE candidates.');
   pc.onicecandidate = function(evt) {
     if (evt.candidate) {
-      util.log('Received ICE candidates.');
+      util.log('Received ICE candidates for:', connection.peer);
       provider.socket.send({
         type: 'CANDIDATE',
         payload: {
           candidate: evt.candidate,
-          connection_id: connection.id
+          type: connection.type,
+          connectionId: connection.id
         },
-        dst: peer_id,
+        dst: peerId,
       });
     }
   };
@@ -124,7 +126,7 @@ Negotiator._setupListeners = function(connection, pc, pc_id) {
   pc.oniceconnectionstatechange = function() {
     switch (pc.iceConnectionState) {
       case 'failed':
-        util.log('iceConnectionState is disconnected, closing connections to ' + peer_id);
+        util.log('iceConnectionState is disconnected, closing connections to ' + peerId);
         Negotiator._cleanup();
         break;
       case 'completed':
@@ -150,7 +152,7 @@ Negotiator._setupListeners = function(connection, pc, pc_id) {
   pc.ondatachannel = function(evt) {
     util.log('Received data channel');
     var dc = evt.channel;
-    var connection = provider.getConnection(peer_id, connection_id);
+    var connection = provider.getConnection(peerId, connectionId);
     connection.initialize(dc);
   };
 
@@ -159,21 +161,21 @@ Negotiator._setupListeners = function(connection, pc, pc_id) {
   pc.onaddstream = function(evt) {
     util.log('Received remote stream');
     var stream = evt.stream;
-    provider.getConnection(peer_id, id).receiveStream(stream);
+    provider.getConnection(peerId, id).receiveStream(stream);
   };
 }
 
-Negotiator._cleanup = function(provider, peer_id, connection_id) {
-  // TODO
-  util.log('Cleanup PeerConnection for ' + peer_id);
-  if (!!this.pc && (this.pc.readyState !== 'closed' || this.pc.signalingState !== 'closed')) {
+Negotiator._cleanup = function(provider, peerId, connectionId) {
+  // TODO: close PeerConnection when all connections are closed.
+  util.log('Cleanup PeerConnection for ' + peerId);
+  /*if (!!this.pc && (this.pc.readyState !== 'closed' || this.pc.signalingState !== 'closed')) {
     this.pc.close();
     this.pc = null;
-  }
+  }*/
 
   provider.socket.send({
     type: 'LEAVE',
-    dst: peer_id
+    dst: peerId
   });
 }
 
@@ -188,12 +190,13 @@ Negotiator._makeOffer = function(connection) {
     }
 
     pc.setLocalDescription(offer, function() {
-      util.log('Set localDescription to offer');
+      util.log('Set localDescription: offer', 'for:', connection.peer);
       connection.provider.socket.send({
         type: 'OFFER',
         payload: {
           sdp: offer,
-          connection_id: connection.id
+          type: connection.type,
+          connectionId: connection.id
         },
         dst: connection.peer,
       });
@@ -219,12 +222,13 @@ Negotiator._makeAnswer = function(connection) {
     }
 
     pc.setLocalDescription(answer, function() {
-      util.log('Set localDescription to answer.');
+      util.log('Set localDescription: answer', 'for:', connection.peer);
       connection.provider.socket.send({
         type: 'ANSWER',
         payload: {
           sdp: answer,
-          connection_id: connection.id
+          type: connection.type,
+          connectionId: connection.id
         },
         dst: connection.peer
       });
@@ -243,8 +247,9 @@ Negotiator.handleSDP = function(type, connection, sdp) {
   sdp = new RTCSessionDescription(sdp);
   var pc = connection.pc;
 
+  util.log('Setting remote description', sdp);
   pc.setRemoteDescription(sdp, function() {
-    util.log('Set remoteDescription: ' + type);
+    util.log('Set remoteDescription:', type, 'for:', connection.peer);
 
     if (type === 'OFFER') {
       if (connection.type === 'media') {
@@ -258,7 +263,7 @@ Negotiator.handleSDP = function(type, connection, sdp) {
         });
       }
       // TODO. also, why setZeroTimeout up there?
-      Negotiator._makeAnswer();
+      Negotiator._makeAnswer(connection);
     }
   }, function(err) {
     connection.provider.emit('error', err);
@@ -270,7 +275,7 @@ Negotiator.handleSDP = function(type, connection, sdp) {
 Negotiator.handleCandidate = function(connection, candidate) {
   var candidate = new RTCIceCandidate(candidate);
   connection.pc.addIceCandidate(candidate);
-  util.log('Added ICE candidate.');
+  util.log('Added ICE candidate for:', connection.peer);
 }
 
 /** Handle peer leaving. */

+ 11 - 9
lib/peer.js

@@ -35,7 +35,7 @@ function Peer(id, options) {
   // TODO: document this feature
   // Set a custom log function if present
   if (options.logFunction) {
-    util.setLogFunction(options.logFunction):
+    util.setLogFunction(options.logFunction);
   }
   util.setLogLevel(options.debug);
   //
@@ -169,25 +169,25 @@ Peer.prototype._handleMessage = function(message) {
       this.emit('error', new Error('Could not connect to peer ' + peer));
       break;
     case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
-      var connection_id = payload.connection_id;
-      var connection = this.getConnection(peer, connection_id);
+      var connectionId = payload.connectionId;
+      var connection = this.getConnection(peer, connectionId);
 
       if (connection) {
-        util.warn('Offer received for existing Connection ID:', connection_id);
+        util.warn('Offer received for existing Connection ID:', connectionId);
         //connection.handleMessage(message);
       } else {
         // Create a new connection.
         if (payload.type === 'call') {
           var call = new MediaConnection(peer, this, {
-            connection_id: connection_id,
+            connectionId: connectionId,
             _payload: payload, // A regular *Connection would have no payload.
             metadata: payload.metadata,
           });
           this._addConnection(peer, call);
           this.emit('call', call);
-        } else if (payload.type === 'connect') {
+        } else if (payload.type === 'data') {
           var connection = new DataConnection(peer, this, {
-            connection_id: connection_id,
+            connectionId: connectionId,
             _payload: payload,
             metadata: payload.metadata,
             label: payload.label,
@@ -197,16 +197,18 @@ Peer.prototype._handleMessage = function(message) {
           this._addConnection(peer, connection);
           this.emit('connection', connection);
         } else {
-          util.warn('Received malformed connection type.');
+          util.warn('Received malformed connection type:', payload.type);
         }
       }
       break;
     default:
+      // TODO: if out of order, must queue.
       if (!payload) {
         util.warn('You received a malformed message from ' + peer);
+        return;
       }
 
-      var id = payload.connection_id;
+      var id = payload.connectionId;
       var connection = this.getConnection(peer, id);
 
       if (connection) {

+ 6 - 2
lib/util.js

@@ -30,7 +30,7 @@ var util = {
   },
 
   _printWith: function(prefix) {
-    return function() {}
+    return function() {
       var copy = Array.prototype.slice.call(arguments);
       copy.unshift(prefix);
       util._print.apply(util, copy);
@@ -56,7 +56,7 @@ var util = {
     return {
       audioVideo: true,
       data: true,
-      binary: true,
+      binary: false,
       reliable: true,
       onnegotiationneeded: true
     };
@@ -196,5 +196,9 @@ var util = {
       }
     }
     return false;
+  },
+
+  isSecure: function() {
+    return location.protocol === 'https:';
   }
 };

Някои файлове не бяха показани, защото твърде много файлове са промени