peer.js 6.2 KB

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