peer.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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._getId();
  61. }
  62. };
  63. util.inherits(Peer, EventEmitter);
  64. Peer.prototype._getId = 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. self.id = http.responseText;
  76. self._init();
  77. }
  78. };
  79. http.send(null);
  80. } catch(e) {
  81. this._abort('server-error', 'Could not get an ID from the server');
  82. }
  83. };
  84. Peer.prototype._init = function() {
  85. var self = this;
  86. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  87. this._socket.on('message', function(data) {
  88. self._handleServerJSONMessage(data);
  89. });
  90. this._socket.on('error', function(error) {
  91. util.log(error);
  92. self._abort('socket-error', error);
  93. });
  94. this._socket.on('close', function() {
  95. var msg = 'Underlying socket has closed';
  96. util.log('error', msg);
  97. self._abort('socket-closed', msg);
  98. });
  99. this._socket.start();
  100. }
  101. Peer.prototype._handleServerJSONMessage = function(message) {
  102. var peer = message.src;
  103. var manager = this.managers[peer];
  104. var payload = message.payload;
  105. switch (message.type) {
  106. case 'OPEN':
  107. this._processQueue();
  108. this.emit('open', this.id);
  109. break;
  110. case 'ERROR':
  111. util.log(payload.msg);
  112. this._abort('server-error', payload.msg);
  113. break;
  114. case 'ID-TAKEN':
  115. this._abort('unavailable-id', 'ID `'+this.id+'` is taken');
  116. break;
  117. case 'OFFER':
  118. var options = {
  119. sdp: payload.sdp,
  120. labels: payload.labels,
  121. config: this._options.config
  122. };
  123. var manager = this.managers[peer];
  124. if (!manager) {
  125. manager = new ConnectionManager(this.id, peer, this._socket, options);
  126. this._attachManagerListeners(manager);
  127. this.managers[peer] = manager;
  128. this.connections[peer] = manager.connections;
  129. }
  130. manager.update(options.labels);
  131. manager.handleSDP(payload.sdp, message.type);
  132. break;
  133. case 'EXPIRE':
  134. if (manager) {
  135. manager.close();
  136. manager.emit('error', new Error('Could not connect to peer ' + manager.peer));
  137. }
  138. break;
  139. case 'ANSWER':
  140. if (manager) {
  141. manager.handleSDP(payload.sdp, message.type);
  142. }
  143. break;
  144. case 'CANDIDATE':
  145. if (manager) {
  146. manager.handleCandidate(payload);
  147. }
  148. break;
  149. case 'LEAVE':
  150. if (manager) {
  151. manager.handleLeave();
  152. }
  153. break;
  154. case 'INVALID-KEY':
  155. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  156. break;
  157. case 'PORT':
  158. //if (util.browserisms === 'Firefox') {
  159. // connection.handlePort(payload);
  160. // break;
  161. //}
  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. var err = new Error(message);
  195. err.type = type;
  196. this.destroy();
  197. this.emit('error', err);
  198. };
  199. Peer.prototype._cleanup = function() {
  200. var self = this;
  201. if (!!this.managers) {
  202. var peers = Object.keys(this.managers);
  203. for (var i = 0, ii = peers.length; i < ii; i++) {
  204. this.managers[peers[i]].close();
  205. }
  206. util.setZeroTimeout(function(){
  207. self.disconnect();
  208. });
  209. }
  210. this.emit('close');
  211. };
  212. /** Exposed connect function for users. Will try to connect later if user
  213. * is waiting for an ID. */
  214. Peer.prototype.connect = function(peer, options) {
  215. if (this.disconnected) {
  216. var err = new Error('This Peer has been disconnected from the server and can no longer make connections.');
  217. err.type = 'server-disconnected';
  218. this.emit('error', err);
  219. return;
  220. }
  221. options = util.extend({
  222. config: this._options.config
  223. }, options);
  224. var manager = this.managers[peer];
  225. if (!manager) {
  226. manager = new ConnectionManager(this.id, peer, this._socket, options);
  227. this._attachManagerListeners(manager);
  228. this.managers[peer] = manager;
  229. this.connections[peer] = {};
  230. }
  231. var connection = manager.connect(options);
  232. if (!this.id) {
  233. this._queued.push(manager);
  234. }
  235. return connection;
  236. };
  237. /**
  238. * Return the peer id or null, if there's no id at the moment.
  239. * Reasons for no id could be 'connect in progress' or 'disconnected'
  240. */
  241. Peer.prototype.getId = function() {
  242. return this.id;
  243. };
  244. /**
  245. * Destroys the Peer: closes all active connections as well as the connection
  246. * to the server.
  247. * Warning: The peer can no longer create or accept connections after being
  248. * destroyed.
  249. */
  250. Peer.prototype.destroy = function() {
  251. if (!this.destroyed) {
  252. this._cleanup();
  253. this.destroyed = true;
  254. }
  255. };
  256. /**
  257. * Disconnects the Peer's connection to the PeerServer. Does not close any
  258. * active connections.
  259. * Warning: The peer can no longer create or accept connections after being
  260. * disconnected. It also cannot reconnect to the server.
  261. */
  262. Peer.prototype.disconnect = function() {
  263. if (!this.disconnected) {
  264. this._socket.close();
  265. this.id = null;
  266. this.disconnected = true;
  267. }
  268. };
  269. /**
  270. * Provides a clean method for checking if there's an active connection to the
  271. * peer server.
  272. */
  273. Peer.prototype.isConnected = function() {
  274. return !this.disconnected;
  275. };
  276. /**
  277. * Returns true if this peer is destroyed and can no longer be used.
  278. */
  279. Peer.prototype.isDestroyed = function() {
  280. return this.destroyed;
  281. };
  282. exports.Peer = Peer;