peer.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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._getId();
  60. }
  61. };
  62. util.inherits(Peer, EventEmitter);
  63. Peer.prototype._getId = function(cb) {
  64. var self = this;
  65. try {
  66. var http = new XMLHttpRequest();
  67. var url = 'http://' + this._options.host + ':' + this._options.port + '/' + this._options.key + '/id';
  68. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  69. url += queryString;
  70. // If there's no ID we need to wait for one before trying to init socket.
  71. http.open('get', url, true);
  72. http.onreadystatechange = function() {
  73. if (http.readyState === 4) {
  74. self.id = http.responseText;
  75. self._init();
  76. }
  77. };
  78. http.send(null);
  79. } catch(e) {
  80. this._abort('server-error', 'Could not get an ID from the server');
  81. }
  82. };
  83. Peer.prototype._init = function() {
  84. var self = this;
  85. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  86. this._socket.on('message', function(data) {
  87. self._handleServerJSONMessage(data);
  88. });
  89. this._socket.on('error', function(error) {
  90. util.log(error);
  91. self._abort('socket-error', error);
  92. });
  93. this._socket.on('close', function() {
  94. var msg = 'Underlying socket has closed';
  95. util.log('error', msg);
  96. self._abort('socket-closed', msg);
  97. });
  98. this._socket.start();
  99. }
  100. Peer.prototype._handleServerJSONMessage = function(message) {
  101. var peer = message.src;
  102. var manager = this.managers[peer];
  103. var payload = message.payload;
  104. switch (message.type) {
  105. case 'OPEN':
  106. this._processQueue();
  107. this.emit('open', this.id);
  108. break;
  109. case 'ERROR':
  110. util.log(payload.msg);
  111. this._abort('server-error', payload.msg);
  112. break;
  113. case 'ID-TAKEN':
  114. this._abort('unavailable-id', 'ID `'+this.id+'` is taken');
  115. break;
  116. case 'OFFER':
  117. var options = {
  118. sdp: payload.sdp,
  119. labels: payload.labels,
  120. config: this._options.config
  121. };
  122. var manager = this.managers[peer];
  123. if (!manager) {
  124. manager = new ConnectionManager(this.id, peer, this._socket, options);
  125. this._attachManagerListeners(manager);
  126. this.managers[peer] = manager;
  127. this.connections[peer] = {};
  128. }
  129. manager.update(options.labels);
  130. manager.handleSDP(payload.sdp, message.type);
  131. break;
  132. case 'EXPIRE':
  133. if (manager) {
  134. manager.close();
  135. manager.emit('error', new Error('Could not connect to peer ' + manager.peer));
  136. }
  137. break;
  138. case 'ANSWER':
  139. if (manager) {
  140. manager.handleSDP(payload.sdp, message.type);
  141. }
  142. break;
  143. case 'CANDIDATE':
  144. if (manager) {
  145. manager.handleCandidate(payload);
  146. }
  147. break;
  148. case 'LEAVE':
  149. if (manager) {
  150. manager.handleLeave();
  151. }
  152. break;
  153. case 'INVALID-KEY':
  154. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  155. break;
  156. case 'PORT':
  157. //if (util.browserisms === 'Firefox') {
  158. // connection.handlePort(payload);
  159. // break;
  160. //}
  161. default:
  162. util.log('Unrecognized message type:', message.type);
  163. break;
  164. }
  165. };
  166. /** Process queued calls to connect. */
  167. Peer.prototype._processQueue = function() {
  168. while (this._queued.length > 0) {
  169. var manager = this._queued.pop();
  170. manager.initialize(this.id, this._socket);
  171. }
  172. };
  173. /** Listeners for manager. */
  174. Peer.prototype._attachManagerListeners = function(manager) {
  175. var self = this;
  176. // Handle receiving a connection.
  177. manager.on('connection', function(connection) {
  178. self.connections[connection.peer][connection.label] = 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. }
  186. });
  187. manager.on('error', function(err) {
  188. self.emit('error', err);
  189. });
  190. };
  191. /** Destroys the Peer and emits an error message. */
  192. Peer.prototype._abort = function(type, message) {
  193. var err = new Error(message);
  194. err.type = type;
  195. this.destroy();
  196. this.emit('error', err);
  197. };
  198. Peer.prototype._cleanup = function() {
  199. var self = this;
  200. if (!!this.managers) {
  201. var peers = Object.keys(this.managers);
  202. for (var i = 0, ii = peers.length; i < ii; i++) {
  203. this.managers[peers[i]].close();
  204. }
  205. util.setZeroTimeout(function(){
  206. self.disconnect();
  207. });
  208. }
  209. this.emit('close');
  210. };
  211. /** Exposed connect function for users. Will try to connect later if user
  212. * is waiting for an ID. */
  213. Peer.prototype.connect = function(peer, options) {
  214. if (this.disconnected) {
  215. var err = new Error('This Peer has been disconnected from the server and');
  216. err.type = 'peer-disconnected';
  217. this.emit('error', err);
  218. return;
  219. }
  220. options = util.extend({
  221. config: this._options.config
  222. }, options);
  223. var manager = this.managers[peer];
  224. if (!manager) {
  225. manager = new ConnectionManager(this.id, peer, this._socket, options);
  226. this._attachManagerListeners(manager);
  227. this.managers[peer] = manager;
  228. this.connections[peer] = {};
  229. }
  230. var connectionInfo = manager.connect(options);
  231. if (!!connectionInfo) {
  232. this.connections[peer][connectionInfo[0]] = connectionInfo[1];
  233. }
  234. if (!this.id) {
  235. this._queued.push(manager);
  236. }
  237. return connectionInfo[1];
  238. };
  239. /**
  240. * Destroys the Peer: closes all active connections as well as the connection
  241. * to the server.
  242. * Warning: The peer can no longer create or accept connections after being
  243. * destroyed.
  244. */
  245. Peer.prototype.destroy = function() {
  246. if (!this.destroyed) {
  247. this._cleanup();
  248. this.destroyed = true;
  249. }
  250. };
  251. /**
  252. * Disconnects the Peer's connection to the PeerServer. Does not close any
  253. * active connections.
  254. * Warning: The peer can no longer create or accept connections after being
  255. * disconnected. It also cannot reconnect to the server.
  256. */
  257. Peer.prototype.disconnect = function() {
  258. if (!this.disconnected) {
  259. this._socket.close();
  260. this.disconnected = true;
  261. }
  262. };
  263. exports.Peer = Peer;