peer.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. function Peer(options) {
  2. if (!(this instanceof Peer)) return new Peer(options);
  3. EventEmitter.call(this);
  4. options = util.extend({
  5. debug: false,
  6. host: 'localhost',
  7. protocol: 'http',
  8. port: 80
  9. }, options);
  10. this.options = options;
  11. util.debug = options.debug;
  12. this._server = options.host + ':' + options.port;
  13. this._protocol = options.protocol;
  14. // Ensure alphanumeric_-
  15. if (options.id && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.id))
  16. throw new Error('Peer ID can only contain alphanumerics, "_", and "-".');
  17. this._id = options.id;
  18. // Not used unless using cloud server.
  19. this._apikey = options.apikey;
  20. // Check in with the server with ID or get an ID.
  21. // this._startXhrStream();
  22. this._checkIn();
  23. // Connections for this peer.
  24. this.connections = {};
  25. // Queued connections to make.
  26. this._queued = [];
  27. // Make sure connections are cleaned up.
  28. window.onbeforeunload = this._cleanup;
  29. };
  30. util.inherits(Peer, EventEmitter);
  31. /** Check in with ID or get one from server. */
  32. Peer.prototype._checkIn = function() {
  33. // If no ID provided, get a unique ID from server.
  34. var self = this;
  35. if (!this._id) {
  36. try {
  37. http = new XMLHttpRequest();
  38. // If there's no ID we need to wait for one before trying to init socket.
  39. http.open('get', this._protocol + '://' + this._server + '/id', true);
  40. http.onreadystatechange = function() {
  41. if (http.readyState > 2) {
  42. if (!!http.responseText) {
  43. try {
  44. var response = JSON.parse(http.responseText.split('\n').shift());
  45. if (!!response.id) {
  46. self._id = response.id;
  47. self.emit('ready', self._id);
  48. }
  49. } catch (e) {
  50. // Ignore
  51. }
  52. }
  53. }
  54. self._socketInit();
  55. self._handleStream(http, true);
  56. };
  57. http.send(null);
  58. } catch(e) {
  59. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  60. this._socketInit();
  61. }
  62. } else {
  63. this._socketInit();
  64. this._startXhrStream();
  65. }
  66. // TODO: may need to setInterval in case handleStream is not being called
  67. // enough.
  68. };
  69. Peer.prototype._startXhrStream = function() {
  70. try {
  71. var http = new XMLHttpRequest();
  72. var self = this;
  73. http.open('post', this._protocol + '://' + this._server + '/id', true);
  74. http.onreadystatechange = function() {
  75. self._handleStream(http);
  76. };
  77. http.send('id=' + this._id);
  78. // TODO: may need to setInterval in case handleStream is not being called
  79. // enough.
  80. } catch(e) {
  81. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  82. }
  83. };
  84. /** Handles onreadystatechange response as a stream. */
  85. Peer.prototype._handleStream = function(http, pad) {
  86. // 3 and 4 are loading/done state. All others are not relevant.
  87. if (http.readyState < 3) {
  88. return;
  89. } else if (http.readyState == 3 && http.status != 200) {
  90. return;
  91. } else if (http.readyState == 4 && http.status != 200) {
  92. // Clear setInterval here if using it.
  93. }
  94. if (this._index === undefined)
  95. this._index = pad ? 2 : 1;
  96. if (http.responseText === null)
  97. return;
  98. // TODO: handle
  99. var message = http.responseText.split('\n')[this._index];
  100. if (!!message)
  101. this._index += 1;
  102. if (http.readyState == 4 && !this._socketOpen)
  103. this._startXhrStream();
  104. };
  105. /** Start up websocket communications. */
  106. Peer.prototype._socketInit = function() {
  107. if (!!this._socket)
  108. return;
  109. this._socket = new WebSocket('ws://' + this._server + '/ws?id=' + this._id);
  110. var self = this;
  111. this._socket.onmessage = function(event) {
  112. var message = JSON.parse(event.data);
  113. var peer = message.src;
  114. var connection = self.connections[peer];
  115. switch (message.type) {
  116. case 'ID':
  117. if (!self._id) {
  118. // If we're just now getting an ID then we may have a queue.
  119. self._id = message.id;
  120. self.emit('ready', self._id);
  121. self._processQueue();
  122. }
  123. break;
  124. case 'OFFER':
  125. var options = {
  126. metadata: message.metadata,
  127. sdp: message.sdp
  128. };
  129. var connection = new DataConnection(self._id, peer, self._socket, function(err, connection) {
  130. if (!err) {
  131. self.emit('connection', connection, message.metadata);
  132. }
  133. }, options);
  134. self.connections[peer] = connection;
  135. break;
  136. case 'ANSWER':
  137. if (connection) connection.handleSDP(message);
  138. break;
  139. case 'CANDIDATE':
  140. if (connection) connection.handleCandidate(message);
  141. break;
  142. case 'LEAVE':
  143. if (connection) connection.handleLeave();
  144. break;
  145. case 'PORT':
  146. if (util.browserisms === 'Firefox') {
  147. connection.handlePort(message);
  148. break;
  149. }
  150. case 'DEFAULT':
  151. util.log('PEER: unrecognized message ', message.type);
  152. break;
  153. }
  154. };
  155. // Take care of the queue of connections if necessary and make sure Peer knows
  156. // socket is open.
  157. this._socket.onopen = function() {
  158. util.log('Socket open');
  159. self._socketOpen = true;
  160. if (self._id)
  161. self._processQueue();
  162. };
  163. };
  164. Peer.prototype._processQueue = function() {
  165. while (this._queued.length > 0) {
  166. var cdata = this._queued.pop();
  167. this.connect.apply(this, cdata);
  168. }
  169. };
  170. Peer.prototype._cleanup = function() {
  171. for (var peer in this.connections) {
  172. if (this.connections.hasOwnProperty(peer)) {
  173. this.connections[peer].close();
  174. }
  175. }
  176. };
  177. Peer.prototype.connect = function(peer, metadata, cb) {
  178. if (typeof metadata === 'function' && !cb) cb = metadata; metadata = false;
  179. if (!this._id) {
  180. this._queued.push(Array.prototype.slice.apply(arguments));
  181. return;
  182. }
  183. var options = {
  184. metadata: metadata
  185. };
  186. var connection = new DataConnection(this._id, peer, this._socket, cb, options);
  187. this.connections[peer] = connection;
  188. };
  189. exports.Peer = Peer;