peer.js 7.6 KB

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