Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JitsiConference.js 41KB

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