peer.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. // First check if browser can use PeerConnection/DataChannels.
  12. // TODO: when media is supported, lower browser version limit and move DC
  13. // check to where`connect` is called.
  14. var self = this;
  15. if (!util.isBrowserCompatible()) {
  16. util.setZeroTimeout(function() {
  17. self._abort('browser-incompatible', 'The current browser does not support WebRTC DataChannels');
  18. });
  19. return;
  20. }
  21. // Detect relative URL host.
  22. if (options.host === '/') {
  23. options.host = window.location.hostname;
  24. }
  25. options = util.extend({
  26. debug: false,
  27. host: '0.peerjs.com',
  28. port: 9000,
  29. key: 'peerjs',
  30. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  31. }, options);
  32. this._options = options;
  33. util.debug = options.debug;
  34. // Ensure alphanumeric_-
  35. if (id && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id)) {
  36. util.setZeroTimeout(function() {
  37. self._abort('invalid-id', 'ID "' + id + '" is invalid');
  38. });
  39. return;
  40. }
  41. if (options.key && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.key)) {
  42. util.setZeroTimeout(function() {
  43. self._abort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  44. });
  45. return;
  46. }
  47. // States.
  48. this.destroyed = false;
  49. this.disconnected = false;
  50. // Connections for this peer.
  51. this.connections = {};
  52. // Connection managers.
  53. this.managers = {};
  54. // Queued connections to make.
  55. this._queued = [];
  56. // Init immediately if ID is given, otherwise ask server for ID
  57. if (id) {
  58. this.id = id;
  59. this._init();
  60. } else {
  61. this.id = null;
  62. this._retrieveId();
  63. }
  64. };
  65. util.inherits(Peer, EventEmitter);
  66. Peer.prototype._retrieveId = function(cb) {
  67. var self = this;
  68. try {
  69. var http = new XMLHttpRequest();
  70. var url = 'http://' + this._options.host + ':' + this._options.port + '/' + this._options.key + '/id';
  71. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  72. url += queryString;
  73. // If there's no ID we need to wait for one before trying to init socket.
  74. http.open('get', url, true);
  75. http.onreadystatechange = function() {
  76. if (http.readyState === 4) {
  77. if (http.status !== 200) {
  78. throw 'Retrieve id response not 200';
  79. return;
  80. }
  81. self.id = http.responseText;
  82. self._init();
  83. }
  84. };
  85. http.send(null);
  86. } catch(e) {
  87. this._abort('server-error', 'Could not get an ID from the server');
  88. }
  89. };
  90. Peer.prototype._init = function() {
  91. var self = this;
  92. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  93. this._socket.on('message', function(data) {
  94. self._handleServerJSONMessage(data);
  95. });
  96. this._socket.on('error', function(error) {
  97. util.log(error);
  98. self._abort('socket-error', error);
  99. });
  100. this._socket.on('close', function() {
  101. var msg = 'Underlying socket has closed';
  102. util.log('error', msg);
  103. self._abort('socket-closed', msg);
  104. });
  105. this._socket.start();
  106. }
  107. Peer.prototype._handleServerJSONMessage = function(message) {
  108. var peer = message.src;
  109. var manager = this.managers[peer];
  110. var payload = message.payload;
  111. switch (message.type) {
  112. case 'OPEN':
  113. this._processQueue();
  114. this.emit('open', this.id);
  115. break;
  116. case 'ERROR':
  117. this._abort('server-error', payload.msg);
  118. break;
  119. case 'ID-TAKEN':
  120. this._abort('unavailable-id', 'ID `'+this.id+'` is taken');
  121. break;
  122. case 'OFFER':
  123. var options = {
  124. sdp: payload.sdp,
  125. labels: payload.labels,
  126. config: this._options.config
  127. };
  128. var manager = this.managers[peer];
  129. if (!manager) {
  130. manager = new ConnectionManager(this.id, peer, this._socket, options);
  131. this._attachManagerListeners(manager);
  132. this.managers[peer] = manager;
  133. this.connections[peer] = manager.connections;
  134. }
  135. manager.update(options.labels);
  136. manager.handleSDP(payload.sdp, message.type);
  137. break;
  138. case 'EXPIRE':
  139. if (manager) {
  140. manager.close();
  141. manager.emit('error', new Error('Could not connect to peer ' + manager.peer));
  142. }
  143. break;
  144. case 'ANSWER':
  145. if (manager) {
  146. manager.handleSDP(payload.sdp, message.type);
  147. }
  148. break;
  149. case 'CANDIDATE':
  150. if (manager) {
  151. manager.handleCandidate(payload);
  152. }
  153. break;
  154. case 'LEAVE':
  155. if (manager) {
  156. manager.handleLeave();
  157. }
  158. break;
  159. case 'INVALID-KEY':
  160. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  161. break;
  162. default:
  163. util.log('Unrecognized message type:', message.type);
  164. break;
  165. }
  166. };
  167. /** Process queued calls to connect. */
  168. Peer.prototype._processQueue = function() {
  169. while (this._queued.length > 0) {
  170. var manager = this._queued.pop();
  171. manager.initialize(this.id, this._socket);
  172. }
  173. };
  174. /** Listeners for manager. */
  175. Peer.prototype._attachManagerListeners = function(manager) {
  176. var self = this;
  177. // Handle receiving a connection.
  178. manager.on('connection', function(connection) {
  179. self.emit('connection', connection);
  180. });
  181. // Handle a connection closing.
  182. manager.on('close', function() {
  183. if (!!self.managers[manager.peer]) {
  184. delete self.managers[manager.peer];
  185. delete self.connections[manager.peer];
  186. }
  187. });
  188. manager.on('error', function(err) {
  189. self.emit('error', err);
  190. });
  191. };
  192. /** Destroys the Peer and emits an error message. */
  193. Peer.prototype._abort = function(type, message) {
  194. util.log('Aborting. Error:', message);
  195. var err = new Error(message);
  196. err.type = type;
  197. this.destroy();
  198. this.emit('error', err);
  199. };
  200. Peer.prototype._cleanup = function() {
  201. var self = this;
  202. if (!!this.managers) {
  203. var peers = Object.keys(this.managers);
  204. for (var i = 0, ii = peers.length; i < ii; i++) {
  205. this.managers[peers[i]].close();
  206. }
  207. }
  208. util.setZeroTimeout(function(){
  209. self.disconnect();
  210. });
  211. this.emit('close');
  212. };
  213. /** Exposed connect function for users. Will try to connect later if user
  214. * is waiting for an ID. */
  215. Peer.prototype.connect = function(peer, options) {
  216. if (this.disconnected) {
  217. var err = new Error('This Peer has been disconnected from the server and can no longer make connections.');
  218. err.type = 'server-disconnected';
  219. this.emit('error', err);
  220. return;
  221. }
  222. options = util.extend({
  223. config: this._options.config
  224. }, options);
  225. var manager = this.managers[peer];
  226. // Firefox currently does not support multiplexing once an offer is made.
  227. if (util.browserisms === 'Firefox' && !!manager && manager.firefoxSingular) {
  228. var err = new Error('Firefox currently does not support multiplexing after a DataChannel has already been established');
  229. err.type = 'firefoxism';
  230. this.emit('error', err);
  231. return;
  232. }
  233. if (!manager) {
  234. manager = new ConnectionManager(this.id, peer, this._socket, options);
  235. this._attachManagerListeners(manager);
  236. this.managers[peer] = manager;
  237. this.connections[peer] = manager.connections;
  238. }
  239. var connection = manager.connect(options);
  240. if (!this.id) {
  241. this._queued.push(manager);
  242. }
  243. return connection;
  244. };
  245. /**
  246. * Return the peer id or null, if there's no id at the moment.
  247. * Reasons for no id could be 'connect in progress' or 'disconnected'
  248. */
  249. Peer.prototype.getId = function() {
  250. return this.id;
  251. };
  252. /**
  253. * Destroys the Peer: closes all active connections as well as the connection
  254. * to the server.
  255. * Warning: The peer can no longer create or accept connections after being
  256. * destroyed.
  257. */
  258. Peer.prototype.destroy = function() {
  259. if (!this.destroyed) {
  260. this._cleanup();
  261. this.destroyed = true;
  262. }
  263. };
  264. /**
  265. * Disconnects the Peer's connection to the PeerServer. Does not close any
  266. * active connections.
  267. * Warning: The peer can no longer create or accept connections after being
  268. * disconnected. It also cannot reconnect to the server.
  269. */
  270. Peer.prototype.disconnect = function() {
  271. if (!this.disconnected) {
  272. this._socket.close();
  273. this.id = null;
  274. this.disconnected = true;
  275. }
  276. };
  277. /** The current browser. */
  278. Peer.browser = util.browserisms;
  279. /**
  280. * Provides a clean method for checking if there's an active connection to the
  281. * peer server.
  282. */
  283. Peer.prototype.isConnected = function() {
  284. return !this.disconnected;
  285. };
  286. /**
  287. * Returns true if this peer is destroyed and can no longer be used.
  288. */
  289. Peer.prototype.isDestroyed = function() {
  290. return this.destroyed;
  291. };
  292. exports.Peer = Peer;