peer.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. /**
  2. * A peer who can initiate connections with other peers.
  3. */
  4. function Peer(id, options) {
  5. if (id && id.constructor == Object) {
  6. options = id;
  7. id = undefined;
  8. }
  9. if (!(this instanceof Peer)) return new Peer(id, options);
  10. EventEmitter.call(this);
  11. // Detect relative URL host.
  12. if (options.host === '/') {
  13. options.host = window.location.hostname;
  14. }
  15. options = util.extend({
  16. debug: false,
  17. host: '0.peerjs.com',
  18. port: 9000,
  19. key: 'peerjs',
  20. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  21. }, options);
  22. this._options = options;
  23. util.debug = options.debug;
  24. // Ensure alphanumeric_-
  25. var self = this;
  26. if (id && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id)) {
  27. util.setZeroTimeout(function() {
  28. self._abort('invalid-id', 'ID "' + id + '" is invalid');
  29. });
  30. return
  31. }
  32. if (options.key && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.key)) {
  33. util.setZeroTimeout(function() {
  34. self._abort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  35. });
  36. return
  37. }
  38. // Connections for this peer.
  39. this.connections = {};
  40. // Connection managers.
  41. this.managers = {};
  42. // Queued connections to make.
  43. this._queued = [];
  44. // Init immediately if ID is given, otherwise ask server for ID
  45. if (id) {
  46. this.id = id;
  47. this._init();
  48. } else {
  49. this._getId();
  50. }
  51. };
  52. util.inherits(Peer, EventEmitter);
  53. Peer.prototype._getId = function(cb) {
  54. var self = this;
  55. try {
  56. var http = new XMLHttpRequest();
  57. var url = 'http://' + this._options.host + ':' + this._options.port + '/' + this._options.key + '/id';
  58. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  59. url += queryString;
  60. // If there's no ID we need to wait for one before trying to init socket.
  61. http.open('get', url, true);
  62. http.onreadystatechange = function() {
  63. if (http.readyState === 4) {
  64. self.id = http.responseText;
  65. self._init();
  66. }
  67. };
  68. http.send(null);
  69. } catch(e) {
  70. this._abort('server-error', 'Could not get an ID from the server');
  71. }
  72. };
  73. Peer.prototype._init = function() {
  74. var self = this;
  75. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  76. this._socket.on('message', function(data) {
  77. self._handleServerJSONMessage(data);
  78. });
  79. this._socket.on('error', function(error) {
  80. util.log(error);
  81. self._abort('socket-error', error);
  82. });
  83. this._socket.on('close', function() {
  84. var msg = 'Underlying socket has closed';
  85. util.log('error', msg);
  86. self._abort('socket-closed', msg);
  87. });
  88. this._socket.start();
  89. }
  90. Peer.prototype._handleServerJSONMessage = function(message) {
  91. var peer = message.src;
  92. var manager = this.managers[peer];
  93. var payload = message.payload;
  94. switch (message.type) {
  95. case 'OPEN':
  96. this._processQueue();
  97. this.emit('open', this.id);
  98. break;
  99. case 'ERROR':
  100. util.log(payload.msg);
  101. this._abort('server-error', payload.msg);
  102. break;
  103. case 'ID-TAKEN':
  104. this._abort('unavailable-id', 'ID `'+this.id+'` is taken');
  105. break;
  106. case 'OFFER':
  107. var options = {
  108. metadata: payload.metadata,
  109. serialization: payload.serialization,
  110. sdp: payload.sdp,
  111. reliable: payload.reliable,
  112. config: this._options.config
  113. };
  114. var manager = this.managers[peer];
  115. if (!!manager) {
  116. manager = new ConnectionManager(this.id, peer, this._socket, options);
  117. this._attachManagerListeners(manager);
  118. this.managers[peer] = manager;
  119. this.connections[peer] = {};
  120. }
  121. // MOVE THIS TO ONDATACHANNEL
  122. //this.emit('connection', connection, payload.metadata);
  123. break;
  124. case 'EXPIRE':
  125. if (manager) {
  126. manager.close();
  127. manager.emit('error', new Error('Could not connect to peer ' + manager.peer));
  128. }
  129. break;
  130. case 'ANSWER':
  131. if (manager) {
  132. manager.handleSDP(payload.sdp, message.type);
  133. }
  134. break;
  135. case 'CANDIDATE':
  136. if (manager) {
  137. manager.handleCandidate(payload);
  138. }
  139. break;
  140. case 'LEAVE':
  141. if (manager) {
  142. manager.handleLeave();
  143. }
  144. break;
  145. case 'INVALID-KEY':
  146. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  147. break;
  148. case 'PORT':
  149. //if (util.browserisms === 'Firefox') {
  150. // connection.handlePort(payload);
  151. // break;
  152. //}
  153. default:
  154. util.log('Unrecognized message type:', message.type);
  155. break;
  156. }
  157. };
  158. /** Process queued calls to connect. */
  159. Peer.prototype._processQueue = function() {
  160. while (this._queued.length > 0) {
  161. var conn = this._queued.pop();
  162. conn.initialize(this.id, this._socket);
  163. }
  164. };
  165. /** Destroys the Peer and emits an error message. */
  166. Peer.prototype._abort = function(type, message) {
  167. var err = new Error(message);
  168. err.type = type;
  169. this.destroy();
  170. this.emit('error', err);
  171. };
  172. Peer.prototype._cleanup = function() {
  173. var self = this;
  174. if (!!this.managers) {
  175. var peers = Object.keys(this.managers);
  176. for (var i = 0, ii = peers.length; i < ii; i++) {
  177. this.managers[peers[i]].close();
  178. }
  179. util.setZeroTimeout(function(){
  180. self._socket.close();
  181. });
  182. }
  183. this.emit('close');
  184. };
  185. /** Exposed connect function for users. Will try to connect later if user
  186. * is waiting for an ID. */
  187. // TODO: pause XHR streaming when not in use and start again when this is
  188. // called.
  189. Peer.prototype.connect = function(peer, options) {
  190. if (this.destroyed) {
  191. this._abort('peer-destroyed', 'This Peer has been destroyed and is no longer able to make connections.');
  192. return;
  193. }
  194. options = util.extend({
  195. config: this._options.config,
  196. label: 'peerjs'
  197. }, options);
  198. var manager = this.managers[peer];
  199. if (!!manager) {
  200. manager = new ConnectionManager(this.id, peer, this._socket, options);
  201. this._attachManagerListeners(manager);
  202. this.managers[peer] = manager;
  203. this.connections[peer] = {};
  204. }
  205. var connection = manager.connect(options.label);
  206. this.connections[peer][options.label] = connection;
  207. if (!this.id) {
  208. this._queued.push(manager);
  209. }
  210. return connection;
  211. };
  212. Peer.prototype.destroy = function() {
  213. if (!this.destroyed) {
  214. this._cleanup();
  215. this.destroyed = true;
  216. }
  217. };
  218. exports.Peer = Peer;