peer.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] },
  8. port: 80
  9. }, options);
  10. this.options = options;
  11. util.debug = options.debug;
  12. // TODO: default should be the cloud server.
  13. this._server = options.host + ':' + options.port;
  14. this._httpUrl = 'http://' + this._server;
  15. this._config = options.config;
  16. // Ensure alphanumeric_-
  17. if (options.id && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.id))
  18. throw new Error('Peer ID can only contain alphanumerics, "_", and "-".');
  19. this._id = options.id;
  20. // Not used unless using cloud server.
  21. this._apikey = options.apikey;
  22. // Check in with the server with ID or get an ID.
  23. this._checkIn();
  24. // Connections for this peer.
  25. this.connections = {};
  26. // Queued connections to make.
  27. this._queued = [];
  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. var url = this._httpUrl + '/id';
  38. console.log(this._apikey);
  39. if (!!this._apikey)
  40. url += '?key=' + this._apikey;
  41. // If there's no ID we need to wait for one before trying to init socket.
  42. http.open('get', url, true);
  43. http.onreadystatechange = function() {
  44. if (!self._id && http.readyState > 2 && !!http.responseText) {
  45. try {
  46. var response = JSON.parse(http.responseText.split('\n').shift());
  47. if (!!response.id) {
  48. self._id = response.id;
  49. self._socketInit();
  50. self.emit('ready', self._id);
  51. self._processQueue();
  52. }
  53. } catch (e) {
  54. self._socketInit();
  55. }
  56. }
  57. self._handleStream(http, true);
  58. };
  59. http.send(null);
  60. } catch(e) {
  61. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  62. this._socketInit();
  63. }
  64. } else {
  65. this._startXhrStream();
  66. this._socketInit();
  67. }
  68. // TODO: may need to setInterval in case handleStream is not being called
  69. // enough.
  70. };
  71. Peer.prototype._startXhrStream = function() {
  72. try {
  73. var http = new XMLHttpRequest();
  74. var self = this;
  75. http.open('post', this._httpUrl + '/id', true);
  76. http.setRequestHeader('Content-Type', 'application/json');
  77. http.onreadystatechange = function() {
  78. self._handleStream(http);
  79. };
  80. http.send(JSON.stringify({ id: this._id, key: this._apikey }));
  81. } catch(e) {
  82. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  83. }
  84. };
  85. /** Handles onreadystatechange response as a stream. */
  86. Peer.prototype._handleStream = function(http, pad) {
  87. // 3 and 4 are loading/done state. All others are not relevant.
  88. if (http.readyState < 3) {
  89. return;
  90. } else if (http.readyState == 3 && http.status != 200) {
  91. return;
  92. }
  93. if (this._index === undefined)
  94. this._index = pad ? 2 : 1;
  95. if (http.responseText === null)
  96. return;
  97. // TODO: handle
  98. var message = http.responseText.split('\n')[this._index];
  99. if (!!message && http.readyState == 3) {
  100. this._index += 1;
  101. this._handleServerMessage(message);
  102. } else if (http.readyState == 4) {
  103. this._index = 1;
  104. }
  105. };
  106. /** Start up websocket communications. */
  107. Peer.prototype._socketInit = function() {
  108. if (!!this._socket)
  109. return;
  110. var wsurl = 'ws://' + this._server + '/ws';
  111. if (!!this._id) {
  112. wsurl += '?id=' + this._id;
  113. if (!!this._apikey)
  114. wsurl += '&key=' + this._apikey;
  115. } else if (!!this._apikey) {
  116. wsurl += '?key=' + this._apikey;
  117. }
  118. this._socket = new WebSocket(wsurl);
  119. var self = this;
  120. this._socket.onmessage = function(event) {
  121. self._handleServerMessage(event.data);
  122. };
  123. // Take care of the queue of connections if necessary and make sure Peer knows
  124. // socket is open.
  125. this._socket.onopen = function() {
  126. util.log('Socket open');
  127. self._socketOpen = true;
  128. var ids = Object.keys(self.connections)
  129. for (var i = 0, ii = ids.length; i < ii; i += 1) {
  130. self.connections[ids[i]].setSocketOpen();
  131. }
  132. if (self._id)
  133. self._processQueue();
  134. };
  135. };
  136. Peer.prototype._handleServerMessage = function(message) {
  137. message = JSON.parse(message);
  138. var peer = message.src;
  139. var connection = this.connections[peer];
  140. switch (message.type) {
  141. // XHR stream closed by timeout.
  142. case 'HTTP-END':
  143. util.log('XHR stream timed out.');
  144. if (!this._socketOpen)
  145. this._startXhrStream();
  146. break;
  147. // XHR stream closed by socket connect.
  148. case 'HTTP-SOCKET':
  149. util.log('XHR stream closed, WebSocket connected.');
  150. break;
  151. case 'HTTP-ERROR':
  152. util.log('Something went wrong.');
  153. break;
  154. case 'ID':
  155. if (!this._id) {
  156. // If we're just now getting an ID then we may have a queue.
  157. this._id = message.id;
  158. this.emit('ready', this._id);
  159. this._processQueue();
  160. }
  161. break;
  162. case 'ERROR':
  163. this.emit('error', message.msg);
  164. util.log(message.msg);
  165. break;
  166. case 'OFFER':
  167. var options = {
  168. metadata: message.metadata,
  169. sdp: message.sdp,
  170. socketOpen: this._socketOpen,
  171. config: this._config
  172. };
  173. var self = this;
  174. var connection = new DataConnection(this._id, peer, this._socket, this._httpUrl, function(err, connection) {
  175. if (!err) {
  176. self.emit('connection', connection, message.metadata);
  177. }
  178. }, options);
  179. this._attachConnectionListeners(connection);
  180. this.connections[peer] = connection;
  181. break;
  182. case 'ANSWER':
  183. if (connection) connection.handleSDP(message);
  184. break;
  185. case 'CANDIDATE':
  186. if (connection) connection.handleCandidate(message);
  187. break;
  188. case 'LEAVE':
  189. if (connection) connection.handleLeave();
  190. break;
  191. case 'PORT':
  192. if (util.browserisms === 'Firefox') {
  193. connection.handlePort(message);
  194. break;
  195. }
  196. case 'DEFAULT':
  197. util.log('Unrecognized message type:', message.type);
  198. break;
  199. }
  200. };
  201. /** Process queued calls to connect. */
  202. Peer.prototype._processQueue = function() {
  203. while (this._queued.length > 0) {
  204. var cdata = this._queued.pop();
  205. this.connect.apply(this, cdata);
  206. }
  207. };
  208. Peer.prototype._cleanup = function() {
  209. for (var peer in this.connections) {
  210. if (this.connections.hasOwnProperty(peer)) {
  211. this.connections[peer].close();
  212. }
  213. }
  214. if (this._socketOpen)
  215. this._socket.close();
  216. };
  217. /** Listeners for DataConnection events. */
  218. Peer.prototype._attachConnectionListeners = function(connection) {
  219. var self = this;
  220. connection.on('close', function(peer) {
  221. if (self.connections[peer]) delete self.connections[peer];
  222. });
  223. };
  224. /** Exposed connect function for users. Will try to connect later if user
  225. * is waiting for an ID. */
  226. // TODO: pause XHR streaming when not in use and start again when this is
  227. // called.
  228. Peer.prototype.connect = function(peer, metadata, cb) {
  229. if (typeof metadata === 'function' && !cb) cb = metadata; metadata = false;
  230. if (!this._id) {
  231. this._queued.push(Array.prototype.slice.apply(arguments));
  232. return;
  233. }
  234. var options = {
  235. metadata: metadata,
  236. socketOpen: this._socketOpen,
  237. config: this._config
  238. };
  239. var connection = new DataConnection(this._id, peer, this._socket, this._httpUrl, cb, options);
  240. this._attachConnectionListeners(connection);
  241. this.connections[peer] = connection;
  242. };
  243. Peer.prototype.destroy = function() {
  244. this._cleanup();
  245. };
  246. exports.Peer = Peer;