peer.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] },
  9. port: 80
  10. }, options);
  11. this.options = options;
  12. util.debug = options.debug;
  13. this._server = options.host + ':' + options.port;
  14. this._httpUrl = options.protocol + '://' + 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. // Make sure connections are cleaned up.
  29. window.onbeforeunload = this._cleanup;
  30. };
  31. util.inherits(Peer, EventEmitter);
  32. /** Check in with ID or get one from server. */
  33. Peer.prototype._checkIn = function() {
  34. // If no ID provided, get a unique ID from server.
  35. var self = this;
  36. if (!this._id) {
  37. try {
  38. var http = new XMLHttpRequest();
  39. // If there's no ID we need to wait for one before trying to init socket.
  40. http.open('get', this._httpUrl + '/id', 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 }));
  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. this._socket = new WebSocket('ws://' + this._server + '/ws?id=' + this._id);
  109. var self = this;
  110. this._socket.onmessage = function(event) {
  111. self._handleServerMessage(event.data);
  112. };
  113. // Take care of the queue of connections if necessary and make sure Peer knows
  114. // socket is open.
  115. this._socket.onopen = function() {
  116. util.log('Socket open');
  117. self._socketOpen = true;
  118. var ids = Object.keys(self.connections)
  119. for (var i = 0, ii = ids.length; i < ii; i += 1) {
  120. self.connections[ids[i]].setSocketOpen();
  121. }
  122. if (self._id)
  123. self._processQueue();
  124. };
  125. };
  126. Peer.prototype._handleServerMessage = function(message) {
  127. var msg;
  128. try {
  129. msg = JSON.parse(message);
  130. } catch(e) {
  131. switch (message) {
  132. case 'end':
  133. util.log('XHR stream timed out.');
  134. if (!this._socketOpen)
  135. this._startXhrStream();
  136. break;
  137. case 'socket':
  138. util.log('XHR stream closed, WebSocket connected.');
  139. break;
  140. case 'error':
  141. util.log('Something went wrong.');
  142. break;
  143. default:
  144. util.log('Message unrecognized:', message);
  145. break;
  146. }
  147. return;
  148. }
  149. var peer = msg.src;
  150. var connection = this.connections[peer];
  151. switch (msg.type) {
  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 = msg.id;
  156. this.emit('ready', this._id);
  157. this._processQueue();
  158. }
  159. break;
  160. case 'ERROR':
  161. this.emit('error', msg.msg);
  162. util.log(msg.msg);
  163. break;
  164. case 'OFFER':
  165. var options = {
  166. metadata: msg.metadata,
  167. sdp: msg.sdp,
  168. socketOpen: this._socketOpen,
  169. config: this._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, msg.metadata);
  175. }
  176. }, options);
  177. this._attachConnectionListeners(connection);
  178. this.connections[peer] = connection;
  179. break;
  180. case 'ANSWER':
  181. if (connection) connection.handleSDP(msg);
  182. break;
  183. case 'CANDIDATE':
  184. if (connection) connection.handleCandidate(msg);
  185. break;
  186. case 'LEAVE':
  187. if (connection) connection.handleLeave();
  188. break;
  189. case 'PORT':
  190. if (util.browserisms === 'Firefox') {
  191. connection.handlePort(msg);
  192. break;
  193. }
  194. case 'DEFAULT':
  195. util.log('Unrecognized message type:', msg.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. if (this._socketOpen) {
  208. this._socket.send(JSON.stringify({ type: 'LEAVE', src: this._id }));
  209. } else {
  210. var http = new XMLHttpRequest();
  211. http.open('post', this._httpUrl + '/leave', true);
  212. http.setRequestHeader('Content-Type', 'application/json');
  213. http.send(JSON.stringify({ type: 'LEAVE', src: this._id }));
  214. }
  215. for (var peer in this.connections) {
  216. if (this.connections.hasOwnProperty(peer)) {
  217. this.connections[peer].close();
  218. }
  219. }
  220. };
  221. /** Listeners for DataConnection events. */
  222. Peer.prototype._attachConnectionListeners = function(connection) {
  223. var self = this;
  224. connection.on('close', function(peer) {
  225. if (self.connections[peer]) delete self.connections[peer];
  226. });
  227. };
  228. /** Exposed connect function for users. Will try to connect later if user
  229. * is waiting for an ID. */
  230. Peer.prototype.connect = function(peer, metadata, cb) {
  231. if (typeof metadata === 'function' && !cb) cb = metadata; metadata = false;
  232. if (!this._id) {
  233. this._queued.push(Array.prototype.slice.apply(arguments));
  234. return;
  235. }
  236. var options = {
  237. metadata: metadata,
  238. socketOpen: this._socketOpen,
  239. config: this._config
  240. };
  241. var connection = new DataConnection(this._id, peer, this._socket, this._httpUrl, cb, options);
  242. this._attachConnectionListeners(connection);
  243. this.connections[peer] = connection;
  244. };
  245. Peer.prototype.destroy = function() {
  246. this._cleanup();
  247. };
  248. exports.Peer = Peer;