peer.js 8.3 KB

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