peer.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /**
  2. * A peer who can initiate connections with other peers.
  3. */
  4. function Peer(id, options) {
  5. if (!(this instanceof Peer)) return new Peer(id, options);
  6. EventEmitter.call(this);
  7. // Deal with overloading
  8. if (id && id.constructor == Object) {
  9. options = id;
  10. id = undefined;
  11. } else {
  12. // Ensure id is a string
  13. id = id.toString();
  14. }
  15. //
  16. // Configurize options
  17. options = util.extend({
  18. debug: 0, // 1: Errors, 2: Warnings, 3: All logs
  19. host: '0.peerjs.com',
  20. port: 9000,
  21. key: 'peerjs',
  22. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  23. }, options);
  24. this.options = options;
  25. // Detect relative URL host.
  26. if (options.host === '/') {
  27. options.host = window.location.hostname;
  28. }
  29. // Set whether we use SSL to same as current host
  30. if (options.secure === undefined) {
  31. options.secure = util.isSecure();
  32. }
  33. // TODO: document this feature
  34. // Set a custom log function if present
  35. if (options.logFunction) {
  36. util.setLogFunction(options.logFunction):
  37. }
  38. util.setLogLevel(options.debug);
  39. //
  40. // Sanity checks
  41. // Ensure WebRTC supported
  42. if (!util.supports.audioVideo && !util.supports.data ) {
  43. this._delayedAbort('browser-incompatible', 'The current browser does not support WebRTC');
  44. return;
  45. }
  46. // Ensure alphanumeric id
  47. if (!util.validateId(id)) {
  48. this._delayedAbort('invalid-id', 'ID "' + id + '" is invalid');
  49. return;
  50. }
  51. // Ensure valid key
  52. if (!util.validateKey(options.key)) {
  53. this._delayedAbort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  54. return;
  55. }
  56. // Ensure not using unsecure cloud server on SSL page
  57. if (options.secure && options.host === '0.peerjs.com') {
  58. this._delayedAbort('ssl-unavailable',
  59. 'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.');
  60. return;
  61. }
  62. //
  63. // States.
  64. this.destroyed = false; // Connections have been killed
  65. this.disconnected = false; // Connection to PeerServer killed but P2P connections still active
  66. //
  67. // References
  68. this.connections = {}; // DataConnections for this peer.
  69. this.calls = {}; // MediaConnections for this peer
  70. //
  71. // Internal references
  72. this._managers = {}; // Managers for peer connections
  73. this._queued = []; // Queued connections to make.
  74. //
  75. // Start the connections
  76. if (id) {
  77. this._initialize(id);
  78. } else {
  79. this._retrieveId();
  80. }
  81. };
  82. util.inherits(Peer, EventEmitter);
  83. Peer.prototype._retrieveId = function(cb) {
  84. var self = this;
  85. var http = new XMLHttpRequest();
  86. var protocol = this.options.secure ? 'https://' : 'http://';
  87. var url = protocol + this.options.host + ':' + this.options.port + '/' + this.options.key + '/id';
  88. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  89. url += queryString;
  90. // If there's no ID we need to wait for one before trying to init socket.
  91. http.open('get', url, true);
  92. http.onerror = function(e) {
  93. util.error('Error retrieving ID', e);
  94. self._abort('server-error', 'Could not get an ID from the server');
  95. }
  96. http.onreadystatechange = function() {
  97. if (http.readyState !== 4) {
  98. return;
  99. }
  100. if (http.status !== 200) {
  101. http.onerror();
  102. return;
  103. }
  104. self._initialize(http.responseText);
  105. };
  106. http.send(null);
  107. };
  108. Peer.prototype._initialize = function(id) {
  109. var self = this;
  110. this.id = id;
  111. this.socket = new Socket(this.secure, this.options.host, this.options.port, this.options.key, this.id);
  112. this.socket.on('message', function(data) {
  113. self._dispatchMessage(data);
  114. });
  115. this.socket.on('error', function(error) {
  116. self._abort('socket-error', error);
  117. });
  118. this.socket.on('close', function() {
  119. // TODO: What if we disconnected on purpose?
  120. self._abort('socket-closed', 'Underlying socket has closed');
  121. });
  122. this.socket.start();
  123. }
  124. Peer.prototype._dispatchMessage = function(message) {
  125. var type = message.type;
  126. // Message types that don't involve a peer
  127. switch (type) {
  128. case 'OPEN':
  129. this._processQueue();
  130. this.emit('open', this.id);
  131. break;
  132. case 'ERROR':
  133. this._abort('server-error', payload.msg);
  134. break;
  135. case 'ID-TAKEN':
  136. this._abort('unavailable-id', 'ID `'+this.id+'` is taken');
  137. break;
  138. case 'INVALID-KEY':
  139. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  140. break;
  141. }
  142. var peer = message.src;
  143. var managerId = message.manager;
  144. var manager = this._getManager(peer, managerId);
  145. var payload = message.payload;
  146. switch (message.type) {
  147. case 'OFFER':
  148. var options = {
  149. sdp: payload.sdp,
  150. labels: payload.labels,
  151. config: this.options.config
  152. };
  153. // Either forward to or create new manager
  154. if (!manager) {
  155. manager = this._createManager(managerId, peer, options);
  156. }
  157. manager.handleUpdate(options.labels);
  158. manager.handleSDP(payload.sdp, message.type, payload.call);
  159. break;
  160. case 'EXPIRE':
  161. peer.emit('error', new Error('Could not connect to peer ' + manager.peer));
  162. break;
  163. case 'ANSWER':
  164. // Forward to specific manager
  165. if (manager) {
  166. manager.handleSDP(payload.sdp, message.type);
  167. }
  168. break;
  169. case 'CANDIDATE':
  170. // Forward to specific manager
  171. if (manager) {
  172. manager.handleCandidate(payload);
  173. }
  174. break;
  175. case 'LEAVE':
  176. // Leave on all managers for a user
  177. if (this._managers[peer]) {
  178. var ids = Object.keys(this._managers[peer].managers);
  179. for (var i = 0; i < ids.length; i++) {
  180. this._managers[peer].managers[ids[i]].handleLeave();
  181. }
  182. }
  183. break;
  184. default:
  185. util.warn('Unrecognized message type:', message.type);
  186. break;
  187. }
  188. };
  189. /** Process queued calls to connect. */
  190. Peer.prototype._processQueue = function() {
  191. while (this._queued.length > 0) {
  192. var manager = this._queued.pop();
  193. manager.initialize(this.id, this.socket);
  194. }
  195. };
  196. /** Listeners for manager. */
  197. Peer.prototype._attachManagerListeners = function(manager) {
  198. var self = this;
  199. // Handle receiving a connection.
  200. manager.on('connection', function(connection) {
  201. self._managers[manager.peer].dataManager = manager;
  202. self.connections[connection.label] = connection;
  203. self.emit('connection', connection);
  204. });
  205. // Handle receiving a call
  206. manager.on('call', function(call) {
  207. self.calls[call.label] = call;
  208. self.emit('call', call);
  209. });
  210. // Handle a connection closing.
  211. manager.on('close', function() {
  212. if (!!self._managers[manager.peer]) {
  213. delete self._managers[manager.peer];
  214. // TODO: delete relevant calls and connections
  215. }
  216. });
  217. manager.on('error', function(err) {
  218. self.emit('error', err);
  219. });
  220. };
  221. Peer.prototype._getManager = function(peer, managerId) {
  222. if (this._managers[peer]) {
  223. return this._managers[peer].managers[managerId];
  224. }
  225. }
  226. Peer.prototype._getDataManager = function(peer) {
  227. if (this._managers[peer]) {
  228. return this._managers[peer].dataManager;
  229. }
  230. }
  231. /** Exposed connect function for users. Will try to connect later if user
  232. * is waiting for an ID. */
  233. Peer.prototype._createManager = function(managerId, peer, options) {
  234. if (this.disconnected) {
  235. var err = new Error('This Peer has been disconnected from the server and can no longer make connections.');
  236. err.type = 'server-disconnected';
  237. this.emit('error', err);
  238. return;
  239. }
  240. options = util.extend({
  241. config: this.options.config
  242. }, options);
  243. if (!this._managers[peer]) {
  244. this._managers[peer] = {nextId: 0, managers: {}};
  245. }
  246. managerId = managerId || peer + this._managers[peer].nextId++;
  247. var manager = new ConnectionManager(managerId, peer, options);
  248. if (!!this.id && !!this.socket) {
  249. manager.initialize(this.id, this.socket);
  250. } else {
  251. this._queued.push(manager);
  252. }
  253. this._attachManagerListeners(manager);
  254. this._managers[peer].managers[manager._managerId] = manager;
  255. return manager;
  256. };
  257. Peer.prototype.connect = function(peer, options) {
  258. var manager = this._getDataManager(peer);
  259. if (!manager) {
  260. manager = this._createManager(false, peer, options);
  261. }
  262. var connection = manager.connect(options);
  263. return connection;
  264. }
  265. Peer.prototype.call = function(peer, stream, options) {
  266. var manager = this._createManager(false, peer, options);
  267. var connection = manager.call(stream, options);
  268. return connection;
  269. }
  270. Peer.prototype._delayedAbort = function(type, message) {
  271. var self = this;
  272. util.setZeroTimeout(function(){
  273. self._abort(type, message);
  274. });
  275. }
  276. /** Destroys the Peer and emits an error message. */
  277. Peer.prototype._abort = function(type, message) {
  278. util.error('Aborting. Error:', message);
  279. var err = new Error(message);
  280. err.type = type;
  281. this.destroy();
  282. this.emit('error', err);
  283. };
  284. /**
  285. * Destroys the Peer: closes all active connections as well as the connection
  286. * to the server.
  287. * Warning: The peer can no longer create or accept connections after being
  288. * destroyed.
  289. */
  290. Peer.prototype.destroy = function() {
  291. if (!this.destroyed) {
  292. this._cleanup();
  293. this.destroyed = true;
  294. }
  295. };
  296. // TODO: UPDATE
  297. Peer.prototype._cleanup = function() {
  298. var self = this;
  299. if (!!this._managers) {
  300. var peers = Object.keys(this._managers);
  301. for (var i = 0, ii = peers.length; i < ii; i++) {
  302. var ids = Object.keys(this._managers[peers[i]]);
  303. for (var j = 0, jj = peers.length; j < jj; j++) {
  304. this._managers[peers[i]][ids[j]].close();
  305. }
  306. }
  307. }
  308. util.setZeroTimeout(function(){
  309. self.disconnect();
  310. });
  311. this.emit('close');
  312. };
  313. /**
  314. * Disconnects the Peer's connection to the PeerServer. Does not close any
  315. * active connections.
  316. * Warning: The peer can no longer create or accept connections after being
  317. * disconnected. It also cannot reconnect to the server.
  318. */
  319. Peer.prototype.disconnect = function() {
  320. if (!this.disconnected) {
  321. if (!!this.socket) {
  322. this.socket.close();
  323. }
  324. this.id = null;
  325. this.disconnected = true;
  326. }
  327. };
  328. /** The current browser. */
  329. Peer.browser = util.browserisms;
  330. exports.Peer = Peer;