You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiConference.js 41KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  1. /* global Strophe, $, Promise */
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var RTC = require("./modules/RTC/RTC");
  4. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  5. var EventEmitter = require("events");
  6. import * as JitsiConferenceErrors from "./JitsiConferenceErrors";
  7. import * as JitsiConferenceEvents from "./JitsiConferenceEvents";
  8. import JitsiParticipant from "./JitsiParticipant";
  9. var Statistics = require("./modules/statistics/statistics");
  10. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  11. import JitsiTrackError from "./JitsiTrackError";
  12. import * as JitsiTrackErrors from "./JitsiTrackErrors";
  13. import * as JitsiTrackEvents from "./JitsiTrackEvents";
  14. var Settings = require("./modules/settings/Settings");
  15. var ComponentsVersions = require("./modules/version/ComponentsVersions");
  16. var GlobalOnErrorHandler = require("./modules/util/GlobalOnErrorHandler");
  17. var JitsiConferenceEventManager = require("./JitsiConferenceEventManager");
  18. var VideoType = require('./service/RTC/VideoType');
  19. var Transcriber = require("./modules/transcription/transcriber");
  20. import ParticipantConnectionStatus
  21. from "./modules/connectivity/ParticipantConnectionStatus";
  22. import TalkMutedDetection from "./modules/TalkMutedDetection";
  23. import ConnectionQuality from "./modules/connectivity/ConnectionQuality";
  24. /**
  25. * Creates a JitsiConference object with the given name and properties.
  26. * Note: this constructor is not a part of the public API (objects should be
  27. * created using JitsiConnection.createConference).
  28. * @param options.config properties / settings related to the conference that will be created.
  29. * @param options.name the name of the conference
  30. * @param options.connection the JitsiConnection object for this JitsiConference.
  31. * @constructor
  32. */
  33. function JitsiConference(options) {
  34. if(!options.name || options.name.toLowerCase() !== options.name) {
  35. var errmsg
  36. = "Invalid conference name (no conference name passed or it "
  37. + "contains invalid characters like capital letters)!";
  38. logger.error(errmsg);
  39. throw new Error(errmsg);
  40. }
  41. this.eventEmitter = new EventEmitter();
  42. this.settings = new Settings();
  43. this.options = options;
  44. this.eventManager = new JitsiConferenceEventManager(this);
  45. this._init(options);
  46. this.componentsVersions = new ComponentsVersions(this);
  47. this.participants = {};
  48. this.lastDominantSpeaker = null;
  49. this.dtmfManager = null;
  50. this.somebodySupportsDTMF = false;
  51. this.authEnabled = false;
  52. this.authIdentity;
  53. this.startAudioMuted = false;
  54. this.startVideoMuted = false;
  55. this.startMutedPolicy = {audio: false, video: false};
  56. this.availableDevices = {
  57. audio: undefined,
  58. video: undefined
  59. };
  60. this.isMutedByFocus = false;
  61. // Flag indicates if the 'onCallEnded' method was ever called on this
  62. // instance. Used to log extra analytics event for debugging purpose.
  63. // We need to know if the potential issue happened before or after
  64. // the restart.
  65. this.wasStopped = false;
  66. /**
  67. * The object which monitors local and remote connection statistics (e.g.
  68. * sending bitrate) and calculates a number which represents the connection
  69. * quality.
  70. */
  71. this.connectionQuality
  72. = new ConnectionQuality(this, this.eventEmitter, options);
  73. /**
  74. * Indicates whether the connection is interrupted or not.
  75. */
  76. this.connectionIsInterrupted = false;
  77. }
  78. /**
  79. * Initializes the conference object properties
  80. * @param options {object}
  81. * @param connection {JitsiConnection} overrides this.connection
  82. */
  83. JitsiConference.prototype._init = function (options) {
  84. if(!options)
  85. options = {};
  86. // Override connection and xmpp properties (Usefull if the connection
  87. // reloaded)
  88. if(options.connection) {
  89. this.connection = options.connection;
  90. this.xmpp = this.connection.xmpp;
  91. // Setup XMPP events only if we have new connection object.
  92. this.eventManager.setupXMPPListeners();
  93. }
  94. this.room = this.xmpp.createRoom(this.options.name, this.options.config,
  95. this.settings);
  96. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  97. if(!this.rtc) {
  98. this.rtc = new RTC(this, options);
  99. this.eventManager.setupRTCListeners();
  100. }
  101. this.participantConnectionStatus
  102. = new ParticipantConnectionStatus(
  103. this.rtc, this,
  104. options.config.peerDisconnectedThroughRtcTimeout);
  105. this.participantConnectionStatus.init();
  106. if(!this.statistics) {
  107. this.statistics = new Statistics(this.xmpp, {
  108. callStatsID: this.options.config.callStatsID,
  109. callStatsSecret: this.options.config.callStatsSecret,
  110. callStatsCustomScriptUrl:
  111. this.options.config.callStatsCustomScriptUrl,
  112. roomName: this.options.name
  113. });
  114. }
  115. this.eventManager.setupChatRoomListeners();
  116. // Always add listeners because on reload we are executing leave and the
  117. // listeners are removed from statistics module.
  118. this.eventManager.setupStatisticsListeners();
  119. if (this.options.config.enableTalkWhileMuted) {
  120. new TalkMutedDetection(this, () => {
  121. this.eventEmitter.emit(JitsiConferenceEvents.TALK_WHILE_MUTED);
  122. });
  123. }
  124. };
  125. /**
  126. * Joins the conference.
  127. * @param password {string} the password
  128. */
  129. JitsiConference.prototype.join = function (password) {
  130. if(this.room)
  131. this.room.join(password);
  132. };
  133. /**
  134. * Check if joined to the conference.
  135. */
  136. JitsiConference.prototype.isJoined = function () {
  137. return this.room && this.room.joined;
  138. };
  139. /**
  140. * Leaves the conference.
  141. * @returns {Promise}
  142. */
  143. JitsiConference.prototype.leave = function () {
  144. if (this.participantConnectionStatus) {
  145. this.participantConnectionStatus.dispose();
  146. this.participantConnectionStatus = null;
  147. }
  148. this.getLocalTracks().forEach(track => this.onTrackRemoved(track));
  149. this.rtc.closeAllDataChannels();
  150. if(this.statistics)
  151. this.statistics.dispose();
  152. // leave the conference
  153. if (this.room) {
  154. let room = this.room;
  155. this.room = null;
  156. return room.leave().catch(() => {
  157. // remove all participants because currently the conference won't
  158. // be usable anyway. This is done on success automatically by the
  159. // ChatRoom instance.
  160. this.getParticipants().forEach(
  161. participant => this.onMemberLeft(participant.getJid()));
  162. });
  163. }
  164. // If this.room == null we are calling second time leave().
  165. return Promise.reject(
  166. new Error("The conference is has been already left"));
  167. };
  168. /**
  169. * Returns name of this conference.
  170. */
  171. JitsiConference.prototype.getName = function () {
  172. return this.options.name;
  173. };
  174. /**
  175. * Check if authentication is enabled for this conference.
  176. */
  177. JitsiConference.prototype.isAuthEnabled = function () {
  178. return this.authEnabled;
  179. };
  180. /**
  181. * Check if user is logged in.
  182. */
  183. JitsiConference.prototype.isLoggedIn = function () {
  184. return !!this.authIdentity;
  185. };
  186. /**
  187. * Get authorized login.
  188. */
  189. JitsiConference.prototype.getAuthLogin = function () {
  190. return this.authIdentity;
  191. };
  192. /**
  193. * Check if external authentication is enabled for this conference.
  194. */
  195. JitsiConference.prototype.isExternalAuthEnabled = function () {
  196. return this.room && this.room.moderator.isExternalAuthEnabled();
  197. };
  198. /**
  199. * Get url for external authentication.
  200. * @param {boolean} [urlForPopup] if true then return url for login popup,
  201. * else url of login page.
  202. * @returns {Promise}
  203. */
  204. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  205. return new Promise(function (resolve, reject) {
  206. if (!this.isExternalAuthEnabled()) {
  207. reject();
  208. return;
  209. }
  210. if (urlForPopup) {
  211. this.room.moderator.getPopupLoginUrl(resolve, reject);
  212. } else {
  213. this.room.moderator.getLoginUrl(resolve, reject);
  214. }
  215. }.bind(this));
  216. };
  217. /**
  218. * Returns the local tracks.
  219. */
  220. JitsiConference.prototype.getLocalTracks = function () {
  221. if (this.rtc) {
  222. return this.rtc.localTracks.slice();
  223. } else {
  224. return [];
  225. }
  226. };
  227. /**
  228. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  229. * in JitsiConferenceEvents.
  230. * @param eventId the event ID.
  231. * @param handler handler for the event.
  232. *
  233. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  234. */
  235. JitsiConference.prototype.on = function (eventId, handler) {
  236. if(this.eventEmitter)
  237. this.eventEmitter.on(eventId, handler);
  238. };
  239. /**
  240. * Removes event listener
  241. * @param eventId the event ID.
  242. * @param [handler] optional, the specific handler to unbind
  243. *
  244. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  245. */
  246. JitsiConference.prototype.off = function (eventId, handler) {
  247. if(this.eventEmitter)
  248. this.eventEmitter.removeListener(eventId, handler);
  249. };
  250. // Common aliases for event emitter
  251. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  252. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  253. /**
  254. * Receives notifications from other participants about commands / custom events
  255. * (sent by sendCommand or sendCommandOnce methods).
  256. * @param command {String} the name of the command
  257. * @param handler {Function} handler for the command
  258. */
  259. JitsiConference.prototype.addCommandListener = function (command, handler) {
  260. if(this.room)
  261. this.room.addPresenceListener(command, handler);
  262. };
  263. /**
  264. * Removes command listener
  265. * @param command {String} the name of the command
  266. */
  267. JitsiConference.prototype.removeCommandListener = function (command) {
  268. if(this.room)
  269. this.room.removePresenceListener(command);
  270. };
  271. /**
  272. * Sends text message to the other participants in the conference
  273. * @param message the text message.
  274. */
  275. JitsiConference.prototype.sendTextMessage = function (message) {
  276. if(this.room)
  277. this.room.sendMessage(message);
  278. };
  279. /**
  280. * Send presence command.
  281. * @param name {String} the name of the command.
  282. * @param values {Object} with keys and values that will be sent.
  283. **/
  284. JitsiConference.prototype.sendCommand = function (name, values) {
  285. if(this.room) {
  286. this.room.addToPresence(name, values);
  287. this.room.sendPresence();
  288. }
  289. };
  290. /**
  291. * Send presence command one time.
  292. * @param name {String} the name of the command.
  293. * @param values {Object} with keys and values that will be sent.
  294. **/
  295. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  296. this.sendCommand(name, values);
  297. this.removeCommand(name);
  298. };
  299. /**
  300. * Removes presence command.
  301. * @param name {String} the name of the command.
  302. **/
  303. JitsiConference.prototype.removeCommand = function (name) {
  304. if(this.room)
  305. this.room.removeFromPresence(name);
  306. };
  307. /**
  308. * Sets the display name for this conference.
  309. * @param name the display name to set
  310. */
  311. JitsiConference.prototype.setDisplayName = function(name) {
  312. if(this.room){
  313. // remove previously set nickname
  314. this.room.removeFromPresence("nick");
  315. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  316. this.room.sendPresence();
  317. }
  318. };
  319. /**
  320. * Set new subject for this conference. (available only for moderator)
  321. * @param {string} subject new subject
  322. */
  323. JitsiConference.prototype.setSubject = function (subject) {
  324. if (this.room && this.isModerator()) {
  325. this.room.setSubject(subject);
  326. }
  327. };
  328. /**
  329. * Get a transcriber object for all current participants in this conference
  330. * @return {Transcriber} the transcriber object
  331. */
  332. JitsiConference.prototype.getTranscriber = function(){
  333. if(this.transcriber === undefined){
  334. this.transcriber = new Transcriber();
  335. //add all existing local audio tracks to the transcriber
  336. this.rtc.localTracks.forEach(function (localTrack) {
  337. if(localTrack.isAudioTrack()){
  338. this.transcriber.addTrack(localTrack);
  339. }
  340. }.bind(this));
  341. //and all remote audio tracks
  342. this.rtc.remoteTracks.forEach(function (remoteTrack){
  343. if(remoteTrack.isAudioTrack()){
  344. this.transcriber.addTrack(remoteTrack);
  345. }
  346. }.bind(this));
  347. }
  348. return this.transcriber;
  349. };
  350. /**
  351. * Adds JitsiLocalTrack object to the conference.
  352. * @param track the JitsiLocalTrack object.
  353. * @returns {Promise<JitsiLocalTrack>}
  354. * @throws {Error} if the specified track is a video track and there is already
  355. * another video track in the conference.
  356. */
  357. JitsiConference.prototype.addTrack = function (track) {
  358. if (track.disposed) {
  359. return Promise.reject(
  360. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  361. }
  362. if (track.isVideoTrack()) {
  363. // Ensure there's exactly 1 local video track in the conference.
  364. var localVideoTrack = this.rtc.getLocalVideoTrack();
  365. if (localVideoTrack) {
  366. // Don't be excessively harsh and severe if the API client happens
  367. // to attempt to add the same local video track twice.
  368. if (track === localVideoTrack) {
  369. return Promise.resolve(track);
  370. } else {
  371. return Promise.reject(new Error(
  372. "cannot add second video track to the conference"));
  373. }
  374. }
  375. }
  376. track.ssrcHandler = function (conference, ssrcMap) {
  377. if(ssrcMap[this.getMSID()]){
  378. this._setSSRC(ssrcMap[this.getMSID()]);
  379. conference.room.removeListener(XMPPEvents.SENDRECV_STREAMS_CHANGED,
  380. this.ssrcHandler);
  381. }
  382. }.bind(track, this);
  383. this.room.addListener(XMPPEvents.SENDRECV_STREAMS_CHANGED,
  384. track.ssrcHandler);
  385. if(track.isAudioTrack() || (track.isVideoTrack() &&
  386. track.videoType !== VideoType.DESKTOP)) {
  387. // Report active device to statistics
  388. var devices = RTC.getCurrentlyAvailableMediaDevices();
  389. var device = devices.find(function (d) {
  390. return d.kind === track.getTrack().kind + 'input'
  391. && d.label === track.getTrack().label;
  392. });
  393. if(device)
  394. Statistics.sendActiveDeviceListEvent(
  395. RTC.getEventDataForActiveDevice(device));
  396. }
  397. return new Promise(function (resolve, reject) {
  398. this.room.addStream(track.getOriginalStream(), function () {
  399. if (track.isVideoTrack()) {
  400. this.removeCommand("videoType");
  401. this.sendCommand("videoType", {
  402. value: track.videoType,
  403. attributes: {
  404. xmlns: 'http://jitsi.org/jitmeet/video'
  405. }
  406. });
  407. }
  408. this.rtc.addLocalTrack(track);
  409. if (track.startMuted) {
  410. track.mute();
  411. }
  412. // ensure that we're sharing proper "is muted" state
  413. if (track.isAudioTrack()) {
  414. this.room.setAudioMute(track.isMuted());
  415. } else {
  416. this.room.setVideoMute(track.isMuted());
  417. }
  418. track.muteHandler = this._fireMuteChangeEvent.bind(this, track);
  419. track.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  420. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  421. track.muteHandler);
  422. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  423. track.audioLevelHandler);
  424. track._setConference(this);
  425. // send event for starting screen sharing
  426. // FIXME: we assume we have only one screen sharing track
  427. // if we change this we need to fix this check
  428. if (track.isVideoTrack() && track.videoType === VideoType.DESKTOP)
  429. this.statistics.sendScreenSharingEvent(true);
  430. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  431. resolve(track);
  432. }.bind(this), function (error) {
  433. reject(error);
  434. });
  435. }.bind(this));
  436. };
  437. /**
  438. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  439. * @param audioLevel the audio level
  440. */
  441. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  442. this.eventEmitter.emit(
  443. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  444. this.myUserId(), audioLevel);
  445. };
  446. /**
  447. * Fires TRACK_MUTE_CHANGED change conference event.
  448. * @param track the JitsiTrack object related to the event.
  449. */
  450. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  451. // check if track was muted by focus and now is unmuted by user
  452. if (this.isMutedByFocus && track.isAudioTrack() && !track.isMuted()) {
  453. this.isMutedByFocus = false;
  454. // unmute local user on server
  455. this.room.muteParticipant(this.room.myroomjid, false);
  456. }
  457. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  458. };
  459. /**
  460. * Clear JitsiLocalTrack properties and listeners.
  461. * @param track the JitsiLocalTrack object.
  462. */
  463. JitsiConference.prototype.onTrackRemoved = function (track) {
  464. track._setSSRC(null);
  465. track._setConference(null);
  466. this.rtc.removeLocalTrack(track);
  467. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  468. track.muteHandler);
  469. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  470. track.audioLevelHandler);
  471. this.room.removeListener(XMPPEvents.SENDRECV_STREAMS_CHANGED,
  472. track.ssrcHandler);
  473. // send event for stopping screen sharing
  474. // FIXME: we assume we have only one screen sharing track
  475. // if we change this we need to fix this check
  476. if (track.isVideoTrack() && track.videoType === VideoType.DESKTOP)
  477. this.statistics.sendScreenSharingEvent(false);
  478. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  479. };
  480. /**
  481. * Removes JitsiLocalTrack object to the conference.
  482. * @param track the JitsiLocalTrack object.
  483. * @returns {Promise}
  484. */
  485. JitsiConference.prototype.removeTrack = function (track) {
  486. if (track.disposed) {
  487. return Promise.reject(
  488. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  489. }
  490. if(!this.room){
  491. if(this.rtc) {
  492. this.onTrackRemoved(track);
  493. }
  494. return Promise.resolve();
  495. }
  496. return new Promise(function (resolve, reject) {
  497. this.room.removeStream(track.getOriginalStream(), function(){
  498. this.onTrackRemoved(track);
  499. resolve();
  500. }.bind(this), function (error) {
  501. reject(error);
  502. }, {
  503. mtype: track.getType(),
  504. type: "remove",
  505. ssrc: track.ssrc});
  506. }.bind(this));
  507. };
  508. /**
  509. * Get role of the local user.
  510. * @returns {string} user role: 'moderator' or 'none'
  511. */
  512. JitsiConference.prototype.getRole = function () {
  513. return this.room.role;
  514. };
  515. /**
  516. * Check if local user is moderator.
  517. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  518. * we're no longer in the conference room then <tt>null</tt> is returned.
  519. */
  520. JitsiConference.prototype.isModerator = function () {
  521. return this.room ? this.room.isModerator() : null;
  522. };
  523. /**
  524. * Set password for the room.
  525. * @param {string} password new password for the room.
  526. * @returns {Promise}
  527. */
  528. JitsiConference.prototype.lock = function (password) {
  529. if (!this.isModerator()) {
  530. return Promise.reject();
  531. }
  532. var conference = this;
  533. return new Promise(function (resolve, reject) {
  534. conference.room.lockRoom(password || "", function () {
  535. resolve();
  536. }, function (err) {
  537. reject(err);
  538. }, function () {
  539. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  540. });
  541. });
  542. };
  543. /**
  544. * Remove password from the room.
  545. * @returns {Promise}
  546. */
  547. JitsiConference.prototype.unlock = function () {
  548. return this.lock();
  549. };
  550. /**
  551. * Elects the participant with the given id to be the selected participant in
  552. * order to receive higher video quality (if simulcast is enabled).
  553. * Or cache it if channel is not created and send it once channel is available.
  554. * @param participantId the identifier of the participant
  555. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  556. */
  557. JitsiConference.prototype.selectParticipant = function(participantId) {
  558. this.rtc.selectEndpoint(participantId);
  559. };
  560. /**
  561. * Elects the participant with the given id to be the pinned participant in
  562. * order to always receive video for this participant (even when last n is
  563. * enabled).
  564. * @param participantId the identifier of the participant
  565. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  566. */
  567. JitsiConference.prototype.pinParticipant = function(participantId) {
  568. this.rtc.pinEndpoint(participantId);
  569. };
  570. /**
  571. * Returns the list of participants for this conference.
  572. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  573. */
  574. JitsiConference.prototype.getParticipants = function() {
  575. return Object.keys(this.participants).map(function (key) {
  576. return this.participants[key];
  577. }, this);
  578. };
  579. /**
  580. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  581. * undefined if there isn't one).
  582. * @param id the id of the participant.
  583. */
  584. JitsiConference.prototype.getParticipantById = function(id) {
  585. return this.participants[id];
  586. };
  587. /**
  588. * Kick participant from this conference.
  589. * @param {string} id id of the participant to kick
  590. */
  591. JitsiConference.prototype.kickParticipant = function (id) {
  592. var participant = this.getParticipantById(id);
  593. if (!participant) {
  594. return;
  595. }
  596. this.room.kick(participant.getJid());
  597. };
  598. /**
  599. * Kick participant from this conference.
  600. * @param {string} id id of the participant to kick
  601. */
  602. JitsiConference.prototype.muteParticipant = function (id) {
  603. var participant = this.getParticipantById(id);
  604. if (!participant) {
  605. return;
  606. }
  607. this.room.muteParticipant(participant.getJid(), true);
  608. };
  609. /**
  610. * Indicates that a participant has joined the conference.
  611. *
  612. * @param jid the jid of the participant in the MUC
  613. * @param nick the display name of the participant
  614. * @param role the role of the participant in the MUC
  615. * @param isHidden indicates if this is a hidden participant (sysem participant,
  616. * for example a recorder).
  617. */
  618. JitsiConference.prototype.onMemberJoined
  619. = function (jid, nick, role, isHidden) {
  620. var id = Strophe.getResourceFromJid(jid);
  621. if (id === 'focus' || this.myUserId() === id) {
  622. return;
  623. }
  624. var participant = new JitsiParticipant(jid, this, nick, isHidden);
  625. participant._role = role;
  626. this.participants[id] = participant;
  627. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  628. // XXX Since disco is checked in multiple places (e.g.
  629. // modules/xmpp/strophe.jingle.js, modules/xmpp/strophe.rayo.js), check it
  630. // here as well.
  631. var disco = this.xmpp.connection.disco;
  632. if (disco) {
  633. disco.info(
  634. jid, "node", function(iq) {
  635. participant._supportsDTMF = $(iq).find(
  636. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  637. this.updateDTMFSupport();
  638. }.bind(this)
  639. );
  640. } else {
  641. // FIXME Should participant._supportsDTMF be assigned false here (and
  642. // this.updateDTMFSupport invoked)?
  643. }
  644. };
  645. JitsiConference.prototype.onMemberLeft = function (jid) {
  646. var id = Strophe.getResourceFromJid(jid);
  647. if (id === 'focus' || this.myUserId() === id) {
  648. return;
  649. }
  650. var participant = this.participants[id];
  651. delete this.participants[id];
  652. var removedTracks = this.rtc.removeRemoteTracks(id);
  653. removedTracks.forEach(function (track) {
  654. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  655. }.bind(this));
  656. // there can be no participant in case the member that left is focus
  657. if (participant)
  658. this.eventEmitter.emit(
  659. JitsiConferenceEvents.USER_LEFT, id, participant);
  660. };
  661. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  662. var id = Strophe.getResourceFromJid(jid);
  663. var participant = this.getParticipantById(id);
  664. if (!participant) {
  665. return;
  666. }
  667. participant._role = role;
  668. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  669. };
  670. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  671. var id = Strophe.getResourceFromJid(jid);
  672. var participant = this.getParticipantById(id);
  673. if (!participant) {
  674. return;
  675. }
  676. if (participant._displayName === displayName)
  677. return;
  678. participant._displayName = displayName;
  679. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  680. };
  681. /**
  682. * Notifies this JitsiConference that a JitsiRemoteTrack was added (into the
  683. * ChatRoom of this JitsiConference).
  684. *
  685. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  686. * JitsiConference
  687. */
  688. JitsiConference.prototype.onTrackAdded = function (track) {
  689. var id = track.getParticipantId();
  690. var participant = this.getParticipantById(id);
  691. if (!participant) {
  692. return;
  693. }
  694. // Add track to JitsiParticipant.
  695. participant._tracks.push(track);
  696. if(this.transcriber){
  697. this.transcriber.addTrack(track);
  698. }
  699. var emitter = this.eventEmitter;
  700. track.addEventListener(
  701. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  702. function () {
  703. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  704. }
  705. );
  706. track.addEventListener(
  707. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  708. function (audioLevel) {
  709. emitter.emit(
  710. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  711. id,
  712. audioLevel);
  713. }
  714. );
  715. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  716. };
  717. /**
  718. * Handles incoming call event.
  719. */
  720. JitsiConference.prototype.onIncomingCall =
  721. function (jingleSession, jingleOffer, now) {
  722. if (!this.room.isFocus(jingleSession.peerjid)) {
  723. // Error cause this should never happen unless something is wrong!
  724. var errmsg = "Rejecting session-initiate from non-focus user: "
  725. + jingleSession.peerjid;
  726. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  727. logger.error(errmsg);
  728. // Terminate the jingle session with a reason
  729. jingleSession.terminate(
  730. 'security-error', 'Only focus can start new sessions',
  731. null /* success callback => we don't care */,
  732. function (error) {
  733. logger.warn(
  734. "An error occurred while trying to terminate"
  735. + " invalid Jingle session", error);
  736. });
  737. return;
  738. }
  739. // Accept incoming call
  740. this.room.setJingleSession(jingleSession);
  741. this.room.connectionTimes["session.initiate"] = now;
  742. // Log "session.restart"
  743. if (this.wasStopped) {
  744. Statistics.sendEventToAll("session.restart");
  745. }
  746. // add info whether call is cross-region
  747. var crossRegion = null;
  748. if (window.jitsiRegionInfo)
  749. crossRegion = window.jitsiRegionInfo["CrossRegion"];
  750. Statistics.analytics.sendEvent("session.initiate",{
  751. value: now - this.room.connectionTimes["muc.joined"],
  752. label: crossRegion
  753. });
  754. try{
  755. jingleSession.initialize(false /* initiator */,this.room);
  756. } catch (error) {
  757. GlobalOnErrorHandler.callErrorHandler(error);
  758. }
  759. this.rtc.onIncommingCall(jingleSession);
  760. // Add local Tracks to the ChatRoom
  761. this.rtc.localTracks.forEach(function(localTrack) {
  762. var ssrcInfo = null;
  763. if(localTrack.isVideoTrack() && localTrack.isMuted()) {
  764. /**
  765. * Handles issues when the stream is added before the peerconnection
  766. * is created. The peerconnection is created when second participant
  767. * enters the call. In that use case the track doesn't have
  768. * information about it's ssrcs and no jingle packets are sent. That
  769. * can cause inconsistent behavior later.
  770. *
  771. * For example:
  772. * If we mute the stream and than second participant enter it's
  773. * remote SDP won't include that track. On unmute we are not sending
  774. * any jingle packets which will brake the unmute.
  775. *
  776. * In order to solve issues like the above one here we have to
  777. * generate the ssrc information for the track .
  778. */
  779. localTrack._setSSRC(
  780. this.room.generateNewStreamSSRCInfo());
  781. ssrcInfo = {
  782. mtype: localTrack.getType(),
  783. type: "addMuted",
  784. ssrc: localTrack.ssrc,
  785. msid: localTrack.initialMSID
  786. };
  787. }
  788. try {
  789. this.room.addStream(
  790. localTrack.getOriginalStream(), function () {}, function () {},
  791. ssrcInfo, true);
  792. } catch(e) {
  793. GlobalOnErrorHandler.callErrorHandler(e);
  794. logger.error(e);
  795. }
  796. }.bind(this));
  797. jingleSession.acceptOffer(jingleOffer, null,
  798. function (error) {
  799. GlobalOnErrorHandler.callErrorHandler(error);
  800. logger.error(
  801. "Failed to accept incoming Jingle session", error);
  802. }
  803. );
  804. // Start callstats as soon as peerconnection is initialized,
  805. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  806. // happen in case if user doesn't have or denied permission to
  807. // both camera and microphone.
  808. this.statistics.startCallStats(jingleSession, this.settings);
  809. this.statistics.startRemoteStats(jingleSession.peerconnection);
  810. };
  811. /**
  812. * Handles the call ended event.
  813. * @param {JingleSessionPC} JingleSession the jingle session which has been
  814. * terminated.
  815. * @param {String} reasonCondition the Jingle reason condition.
  816. * @param {String|null} reasonText human readable reason text which may provide
  817. * more details about why the call has been terminated.
  818. */
  819. JitsiConference.prototype.onCallEnded
  820. = function (JingleSession, reasonCondition, reasonText) {
  821. logger.info("Call ended: " + reasonCondition + " - " + reasonText);
  822. this.wasStopped = true;
  823. // Send session.terminate event
  824. Statistics.sendEventToAll("session.terminate");
  825. // Stop the stats
  826. if (this.statistics) {
  827. this.statistics.stopRemoteStats();
  828. this.statistics.stopCallStats();
  829. }
  830. // Current JingleSession is invalid so set it to null on the room
  831. this.room.setJingleSession(null);
  832. // Let the RTC service do any cleanups
  833. this.rtc.onCallEnded();
  834. // PeerConnection has been closed which means that SSRCs stored in
  835. // JitsiLocalTrack will not match those assigned by the old PeerConnection
  836. // and SSRC replacement logic will not work as expected.
  837. // We want to re-register 'ssrcHandler' of our local tracks, so that they
  838. // will learn what their SSRC from the new PeerConnection which will be
  839. // created on incoming call event.
  840. var self = this;
  841. this.rtc.localTracks.forEach(function(localTrack) {
  842. // Reset SSRC as it will no longer be valid
  843. localTrack._setSSRC(null);
  844. // Bind the handler to fetch new SSRC, it will un register itself once
  845. // it reads the values
  846. self.room.addListener(
  847. XMPPEvents.SENDRECV_STREAMS_CHANGED, localTrack.ssrcHandler);
  848. });
  849. };
  850. JitsiConference.prototype.updateDTMFSupport = function () {
  851. var somebodySupportsDTMF = false;
  852. var participants = this.getParticipants();
  853. // check if at least 1 participant supports DTMF
  854. for (var i = 0; i < participants.length; i += 1) {
  855. if (participants[i].supportsDTMF()) {
  856. somebodySupportsDTMF = true;
  857. break;
  858. }
  859. }
  860. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  861. this.somebodySupportsDTMF = somebodySupportsDTMF;
  862. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  863. }
  864. };
  865. /**
  866. * Allows to check if there is at least one user in the conference
  867. * that supports DTMF.
  868. * @returns {boolean} true if somebody supports DTMF, false otherwise
  869. */
  870. JitsiConference.prototype.isDTMFSupported = function () {
  871. return this.somebodySupportsDTMF;
  872. };
  873. /**
  874. * Returns the local user's ID
  875. * @return {string} local user's ID
  876. */
  877. JitsiConference.prototype.myUserId = function () {
  878. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  879. };
  880. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  881. if (!this.dtmfManager) {
  882. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  883. if (!connection) {
  884. logger.warn("cannot sendTones: no conneciton");
  885. return;
  886. }
  887. var tracks = this.getLocalTracks().filter(function (track) {
  888. return track.isAudioTrack();
  889. });
  890. if (!tracks.length) {
  891. logger.warn("cannot sendTones: no local audio stream");
  892. return;
  893. }
  894. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  895. }
  896. this.dtmfManager.sendTones(tones, duration, pause);
  897. };
  898. /**
  899. * Returns true if the recording is supproted and false if not.
  900. */
  901. JitsiConference.prototype.isRecordingSupported = function () {
  902. if(this.room)
  903. return this.room.isRecordingSupported();
  904. return false;
  905. };
  906. /**
  907. * Returns null if the recording is not supported, "on" if the recording started
  908. * and "off" if the recording is not started.
  909. */
  910. JitsiConference.prototype.getRecordingState = function () {
  911. return (this.room) ? this.room.getRecordingState() : undefined;
  912. };
  913. /**
  914. * Returns the url of the recorded video.
  915. */
  916. JitsiConference.prototype.getRecordingURL = function () {
  917. return (this.room) ? this.room.getRecordingURL() : null;
  918. };
  919. /**
  920. * Starts/stops the recording
  921. */
  922. JitsiConference.prototype.toggleRecording = function (options) {
  923. if(this.room)
  924. return this.room.toggleRecording(options, function (status, error) {
  925. this.eventEmitter.emit(
  926. JitsiConferenceEvents.RECORDER_STATE_CHANGED, status, error);
  927. }.bind(this));
  928. this.eventEmitter.emit(
  929. JitsiConferenceEvents.RECORDER_STATE_CHANGED, "error",
  930. new Error("The conference is not created yet!"));
  931. };
  932. /**
  933. * Returns true if the SIP calls are supported and false otherwise
  934. */
  935. JitsiConference.prototype.isSIPCallingSupported = function () {
  936. if(this.room)
  937. return this.room.isSIPCallingSupported();
  938. return false;
  939. };
  940. /**
  941. * Dials a number.
  942. * @param number the number
  943. */
  944. JitsiConference.prototype.dial = function (number) {
  945. if(this.room)
  946. return this.room.dial(number);
  947. return new Promise(function(resolve, reject){
  948. reject(new Error("The conference is not created yet!"));});
  949. };
  950. /**
  951. * Hangup an existing call
  952. */
  953. JitsiConference.prototype.hangup = function () {
  954. if(this.room)
  955. return this.room.hangup();
  956. return new Promise(function(resolve, reject){
  957. reject(new Error("The conference is not created yet!"));});
  958. };
  959. /**
  960. * Returns the phone number for joining the conference.
  961. */
  962. JitsiConference.prototype.getPhoneNumber = function () {
  963. if(this.room)
  964. return this.room.getPhoneNumber();
  965. return null;
  966. };
  967. /**
  968. * Returns the pin for joining the conference with phone.
  969. */
  970. JitsiConference.prototype.getPhonePin = function () {
  971. if(this.room)
  972. return this.room.getPhonePin();
  973. return null;
  974. };
  975. /**
  976. * Returns the connection state for the current room. Its ice connection state
  977. * for its session.
  978. */
  979. JitsiConference.prototype.getConnectionState = function () {
  980. if(this.room)
  981. return this.room.getConnectionState();
  982. return null;
  983. };
  984. /**
  985. * Make all new participants mute their audio/video on join.
  986. * @param policy {Object} object with 2 boolean properties for video and audio:
  987. * @param {boolean} audio if audio should be muted.
  988. * @param {boolean} video if video should be muted.
  989. */
  990. JitsiConference.prototype.setStartMutedPolicy = function (policy) {
  991. if (!this.isModerator()) {
  992. return;
  993. }
  994. this.startMutedPolicy = policy;
  995. this.room.removeFromPresence("startmuted");
  996. this.room.addToPresence("startmuted", {
  997. attributes: {
  998. audio: policy.audio,
  999. video: policy.video,
  1000. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  1001. }
  1002. });
  1003. this.room.sendPresence();
  1004. };
  1005. /**
  1006. * Returns current start muted policy
  1007. * @returns {Object} with 2 proprties - audio and video.
  1008. */
  1009. JitsiConference.prototype.getStartMutedPolicy = function () {
  1010. return this.startMutedPolicy;
  1011. };
  1012. /**
  1013. * Check if audio is muted on join.
  1014. */
  1015. JitsiConference.prototype.isStartAudioMuted = function () {
  1016. return this.startAudioMuted;
  1017. };
  1018. /**
  1019. * Check if video is muted on join.
  1020. */
  1021. JitsiConference.prototype.isStartVideoMuted = function () {
  1022. return this.startVideoMuted;
  1023. };
  1024. /**
  1025. * Get object with internal logs.
  1026. */
  1027. JitsiConference.prototype.getLogs = function () {
  1028. var data = this.xmpp.getJingleLog();
  1029. var metadata = {};
  1030. metadata.time = new Date();
  1031. metadata.url = window.location.href;
  1032. metadata.ua = navigator.userAgent;
  1033. var log = this.xmpp.getXmppLog();
  1034. if (log) {
  1035. metadata.xmpp = log;
  1036. }
  1037. data.metadata = metadata;
  1038. return data;
  1039. };
  1040. /**
  1041. * Returns measured connectionTimes.
  1042. */
  1043. JitsiConference.prototype.getConnectionTimes = function () {
  1044. return this.room.connectionTimes;
  1045. };
  1046. /**
  1047. * Sets a property for the local participant.
  1048. */
  1049. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  1050. this.sendCommand("jitsi_participant_" + name, {value: value});
  1051. };
  1052. /**
  1053. * Sends the given feedback through CallStats if enabled.
  1054. *
  1055. * @param overallFeedback an integer between 1 and 5 indicating the
  1056. * user feedback
  1057. * @param detailedFeedback detailed feedback from the user. Not yet used
  1058. */
  1059. JitsiConference.prototype.sendFeedback =
  1060. function(overallFeedback, detailedFeedback){
  1061. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  1062. };
  1063. /**
  1064. * Returns true if the callstats integration is enabled, otherwise returns
  1065. * false.
  1066. *
  1067. * @returns true if the callstats integration is enabled, otherwise returns
  1068. * false.
  1069. */
  1070. JitsiConference.prototype.isCallstatsEnabled = function () {
  1071. return this.statistics.isCallstatsEnabled();
  1072. };
  1073. /**
  1074. * Handles track attached to container (Calls associateStreamWithVideoTag method
  1075. * from statistics module)
  1076. * @param track the track
  1077. * @param container the container
  1078. */
  1079. JitsiConference.prototype._onTrackAttach = function(track, container) {
  1080. var ssrc = track.getSSRC();
  1081. if (!container.id || !ssrc) {
  1082. return;
  1083. }
  1084. this.statistics.associateStreamWithVideoTag(
  1085. ssrc, track.isLocal(), track.getUsageLabel(), container.id);
  1086. };
  1087. /**
  1088. * Logs an "application log" message.
  1089. * @param message {string} The message to log. Note that while this can be a
  1090. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  1091. * log valid JSON strings, with an "id" field used for distinguishing between
  1092. * message types. E.g.: {id: "recorder_status", status: "off"}
  1093. */
  1094. JitsiConference.prototype.sendApplicationLog = function(message) {
  1095. Statistics.sendLog(message);
  1096. };
  1097. /**
  1098. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1099. * focus.
  1100. * @param mucJid the full MUC address of the user to be checked.
  1101. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  1102. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  1103. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  1104. */
  1105. JitsiConference.prototype._isFocus = function (mucJid) {
  1106. return this.room ? this.room.isFocus(mucJid) : null;
  1107. };
  1108. /**
  1109. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  1110. */
  1111. JitsiConference.prototype._fireIncompatibleVersionsEvent = function () {
  1112. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  1113. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  1114. };
  1115. /**
  1116. * Sends message via the datachannels.
  1117. * @param to {string} the id of the endpoint that should receive the message.
  1118. * If "" the message will be sent to all participants.
  1119. * @param payload {object} the payload of the message.
  1120. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1121. */
  1122. JitsiConference.prototype.sendEndpointMessage = function (to, payload) {
  1123. this.rtc.sendDataChannelMessage(to, payload);
  1124. };
  1125. /**
  1126. * Sends broadcast message via the datachannels.
  1127. * @param payload {object} the payload of the message.
  1128. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1129. */
  1130. JitsiConference.prototype.broadcastEndpointMessage = function (payload) {
  1131. this.sendEndpointMessage("", payload);
  1132. };
  1133. JitsiConference.prototype.isConnectionInterrupted = function () {
  1134. return this.connectionIsInterrupted;
  1135. };
  1136. module.exports = JitsiConference;