您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 40KB

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