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

conference.js 33KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. import {openConnection} from './connection';
  3. //FIXME:
  4. import createRoomLocker from './modules/UI/authentication/RoomLocker';
  5. //FIXME:
  6. import AuthHandler from './modules/UI/authentication/AuthHandler';
  7. import ConnectionQuality from './modules/connectionquality/connectionquality';
  8. import CQEvents from './service/connectionquality/CQEvents';
  9. import UIEvents from './service/UI/UIEvents';
  10. const ConnectionEvents = JitsiMeetJS.events.connection;
  11. const ConnectionErrors = JitsiMeetJS.errors.connection;
  12. const ConferenceEvents = JitsiMeetJS.events.conference;
  13. const ConferenceErrors = JitsiMeetJS.errors.conference;
  14. const TrackEvents = JitsiMeetJS.events.track;
  15. const TrackErrors = JitsiMeetJS.errors.track;
  16. let room, connection, localAudio, localVideo, roomLocker;
  17. /**
  18. * Known custom conference commands.
  19. */
  20. const Commands = {
  21. CONNECTION_QUALITY: "stats",
  22. EMAIL: "email",
  23. ETHERPAD: "etherpad",
  24. PREZI: "prezi",
  25. STOP_PREZI: "stop-prezi"
  26. };
  27. /**
  28. * Open Connection. When authentication failed it shows auth dialog.
  29. * @param roomName the room name to use
  30. * @returns Promise<JitsiConnection>
  31. */
  32. function connect(roomName) {
  33. return openConnection({retry: true, roomName: roomName})
  34. .catch(function (err) {
  35. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  36. APP.UI.notifyTokenAuthFailed();
  37. } else {
  38. APP.UI.notifyConnectionFailed(err);
  39. }
  40. throw err;
  41. });
  42. }
  43. /**
  44. * Share email with other users.
  45. * @param {string} email new email
  46. */
  47. function sendEmail (email) {
  48. room.sendCommand(Commands.EMAIL, {
  49. value: email,
  50. attributes: {
  51. id: room.myUserId()
  52. }
  53. });
  54. }
  55. /**
  56. * Get user nickname by user id.
  57. * @param {string} id user id
  58. * @returns {string?} user nickname or undefined if user is unknown.
  59. */
  60. function getDisplayName (id) {
  61. if (APP.conference.isLocalId(id)) {
  62. return APP.settings.getDisplayName();
  63. }
  64. let participant = room.getParticipantById(id);
  65. if (participant && participant.getDisplayName()) {
  66. return participant.getDisplayName();
  67. }
  68. }
  69. /**
  70. * Mute or unmute local audio stream if it exists.
  71. * @param {boolean} muted if audio stream should be muted or unmuted.
  72. */
  73. function muteLocalAudio (muted) {
  74. if (!localAudio) {
  75. return;
  76. }
  77. if (muted) {
  78. localAudio.mute().then(function(value) {},
  79. function(value) {
  80. console.warn('Audio Mute was rejected:', value);
  81. }
  82. );
  83. } else {
  84. localAudio.unmute().then(function(value) {},
  85. function(value) {
  86. console.warn('Audio unmute was rejected:', value);
  87. }
  88. );
  89. }
  90. }
  91. /**
  92. * Mute or unmute local video stream if it exists.
  93. * @param {boolean} muted if video stream should be muted or unmuted.
  94. */
  95. function muteLocalVideo (muted) {
  96. if (!localVideo) {
  97. return;
  98. }
  99. if (muted) {
  100. localVideo.mute().then(function(value) {},
  101. function(value) {
  102. console.warn('Video mute was rejected:', value);
  103. }
  104. );
  105. } else {
  106. localVideo.unmute().then(function(value) {},
  107. function(value) {
  108. console.warn('Video unmute was rejected:', value);
  109. }
  110. );
  111. }
  112. }
  113. /**
  114. * Disconnect from the conference and optionally request user feedback.
  115. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  116. */
  117. function hangup (requestFeedback = false) {
  118. let promise = Promise.resolve();
  119. if (requestFeedback) {
  120. promise = APP.UI.requestFeedback();
  121. }
  122. promise.then(function () {
  123. connection.disconnect();
  124. if (!config.enableWelcomePage) {
  125. return;
  126. }
  127. // redirect to welcome page
  128. setTimeout(() => {
  129. APP.settings.setWelcomePageEnabled(true);
  130. window.location.pathname = "/";
  131. }, 3000);
  132. }, function (err) {
  133. console.error('Failed to hangup the call:', err);
  134. });
  135. }
  136. /**
  137. * Create local tracks of specified types.
  138. * @param {string[]} devices required track types ('audio', 'video' etc.)
  139. * @returns {Promise<JitsiLocalTrack[]>}
  140. */
  141. function createLocalTracks (...devices) {
  142. return JitsiMeetJS.createLocalTracks({
  143. // copy array to avoid mutations inside library
  144. devices: devices.slice(0),
  145. resolution: config.resolution,
  146. cameraDeviceId: APP.settings.getCameraDeviceId(),
  147. micDeviceId: APP.settings.getMicDeviceId(),
  148. // adds any ff fake device settings if any
  149. firefox_fake_device: config.firefox_fake_device
  150. }).catch(function (err) {
  151. console.error('failed to create local tracks', ...devices, err);
  152. return Promise.reject(err);
  153. });
  154. }
  155. class ConferenceConnector {
  156. constructor(resolve, reject) {
  157. this._resolve = resolve;
  158. this._reject = reject;
  159. this.reconnectTimeout = null;
  160. room.on(ConferenceEvents.CONFERENCE_JOINED,
  161. this._handleConferenceJoined.bind(this));
  162. room.on(ConferenceEvents.CONFERENCE_FAILED,
  163. this._onConferenceFailed.bind(this));
  164. room.on(ConferenceEvents.CONFERENCE_ERROR,
  165. this._onConferenceError.bind(this));
  166. }
  167. _handleConferenceFailed(err, msg) {
  168. this._unsubscribe();
  169. this._reject(err);
  170. }
  171. _onConferenceFailed(err, ...params) {
  172. console.error('CONFERENCE FAILED:', err, ...params);
  173. switch (err) {
  174. // room is locked by the password
  175. case ConferenceErrors.PASSWORD_REQUIRED:
  176. APP.UI.markRoomLocked(true);
  177. roomLocker.requirePassword().then(function () {
  178. room.join(roomLocker.password);
  179. });
  180. break;
  181. case ConferenceErrors.CONNECTION_ERROR:
  182. {
  183. let [msg] = params;
  184. APP.UI.notifyConnectionFailed(msg);
  185. }
  186. break;
  187. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  188. APP.UI.notifyBridgeDown();
  189. break;
  190. // not enough rights to create conference
  191. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  192. // schedule reconnect to check if someone else created the room
  193. this.reconnectTimeout = setTimeout(function () {
  194. room.join();
  195. }, 5000);
  196. // notify user that auth is required
  197. AuthHandler.requireAuth(room, roomLocker.password);
  198. break;
  199. case ConferenceErrors.RESERVATION_ERROR:
  200. {
  201. let [code, msg] = params;
  202. APP.UI.notifyReservationError(code, msg);
  203. }
  204. break;
  205. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  206. APP.UI.notifyGracefulShutdown();
  207. break;
  208. case ConferenceErrors.JINGLE_FATAL_ERROR:
  209. APP.UI.notifyInternalError();
  210. break;
  211. case ConferenceErrors.CONFERENCE_DESTROYED:
  212. {
  213. let [reason] = params;
  214. APP.UI.hideStats();
  215. APP.UI.notifyConferenceDestroyed(reason);
  216. }
  217. break;
  218. case ConferenceErrors.FOCUS_DISCONNECTED:
  219. {
  220. let [focus, retrySec] = params;
  221. APP.UI.notifyFocusDisconnected(focus, retrySec);
  222. }
  223. break;
  224. case ConferenceErrors.FOCUS_LEFT:
  225. room.leave().then(() => connection.disconnect());
  226. APP.UI.notifyFocusLeft();
  227. break;
  228. case ConferenceErrors.CONFERENCE_MAX_USERS:
  229. connection.disconnect();
  230. APP.UI.notifyMaxUsersLimitReached();
  231. break;
  232. default:
  233. this._handleConferenceFailed(err, ...params);
  234. }
  235. }
  236. _onConferenceError(err, ...params) {
  237. console.error('CONFERENCE Error:', err, params);
  238. switch (err) {
  239. case ConferenceErrors.CHAT_ERROR:
  240. {
  241. let [code, msg] = params;
  242. APP.UI.showChatError(code, msg);
  243. }
  244. break;
  245. default:
  246. console.error("Unknown error.");
  247. }
  248. }
  249. _unsubscribe() {
  250. room.off(
  251. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  252. room.off(
  253. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  254. if (this.reconnectTimeout !== null) {
  255. clearTimeout(this.reconnectTimeout);
  256. }
  257. AuthHandler.closeAuth();
  258. }
  259. _handleConferenceJoined() {
  260. this._unsubscribe();
  261. this._resolve();
  262. }
  263. connect() {
  264. room.join();
  265. }
  266. }
  267. export default {
  268. localId: undefined,
  269. isModerator: false,
  270. audioMuted: false,
  271. videoMuted: false,
  272. isSharingScreen: false,
  273. isDesktopSharingEnabled: false,
  274. /**
  275. * Open new connection and join to the conference.
  276. * @param {object} options
  277. * @param {string} roomName name of the conference
  278. * @returns {Promise}
  279. */
  280. init(options) {
  281. this.roomName = options.roomName;
  282. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  283. return JitsiMeetJS.init(config).then(() => {
  284. return Promise.all([
  285. // try to retrieve audio and video
  286. createLocalTracks('audio', 'video')
  287. // if failed then try to retrieve only audio
  288. .catch(() => createLocalTracks('audio'))
  289. // if audio also failed then just return empty array
  290. .catch(() => []),
  291. connect(options.roomName)
  292. ]);
  293. }).then(([tracks, con]) => {
  294. console.log('initialized with %s local tracks', tracks.length);
  295. connection = con;
  296. this._createRoom(tracks);
  297. this.isDesktopSharingEnabled =
  298. JitsiMeetJS.isDesktopSharingEnabled();
  299. // update list of available devices
  300. if (JitsiMeetJS.isDeviceListAvailable() &&
  301. JitsiMeetJS.isDeviceChangeAvailable()) {
  302. JitsiMeetJS.enumerateDevices(
  303. devices => APP.UI.onAvailableDevicesChanged(devices)
  304. );
  305. }
  306. // XXX The API will take care of disconnecting from the XMPP server
  307. // (and, thus, leaving the room) on unload.
  308. return new Promise((resolve, reject) => {
  309. (new ConferenceConnector(resolve, reject)).connect();
  310. });
  311. });
  312. },
  313. /**
  314. * Check if id is id of the local user.
  315. * @param {string} id id to check
  316. * @returns {boolean}
  317. */
  318. isLocalId (id) {
  319. return this.localId === id;
  320. },
  321. /**
  322. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  323. * @param mute true for mute and false for unmute.
  324. */
  325. muteAudio (mute) {
  326. muteLocalAudio(mute);
  327. },
  328. /**
  329. * Returns whether local audio is muted or not.
  330. * @returns {boolean}
  331. */
  332. isLocalAudioMuted() {
  333. return this.audioMuted;
  334. },
  335. /**
  336. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  337. */
  338. toggleAudioMuted () {
  339. this.muteAudio(!this.audioMuted);
  340. },
  341. /**
  342. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  343. * @param mute true for mute and false for unmute.
  344. */
  345. muteVideo (mute) {
  346. muteLocalVideo(mute);
  347. },
  348. /**
  349. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  350. */
  351. toggleVideoMuted () {
  352. this.muteVideo(!this.videoMuted);
  353. },
  354. /**
  355. * Retrieve list of conference participants (without local user).
  356. * @returns {JitsiParticipant[]}
  357. */
  358. listMembers () {
  359. return room.getParticipants();
  360. },
  361. /**
  362. * Retrieve list of ids of conference participants (without local user).
  363. * @returns {string[]}
  364. */
  365. listMembersIds () {
  366. return room.getParticipants().map(p => p.getId());
  367. },
  368. /**
  369. * Check if SIP is supported.
  370. * @returns {boolean}
  371. */
  372. sipGatewayEnabled () {
  373. return room.isSIPCallingSupported();
  374. },
  375. get membersCount () {
  376. return room.getParticipants().length + 1;
  377. },
  378. /**
  379. * Returns true if the callstats integration is enabled, otherwise returns
  380. * false.
  381. *
  382. * @returns true if the callstats integration is enabled, otherwise returns
  383. * false.
  384. */
  385. isCallstatsEnabled () {
  386. return room.isCallstatsEnabled();
  387. },
  388. /**
  389. * Sends the given feedback through CallStats if enabled.
  390. *
  391. * @param overallFeedback an integer between 1 and 5 indicating the
  392. * user feedback
  393. * @param detailedFeedback detailed feedback from the user. Not yet used
  394. */
  395. sendFeedback (overallFeedback, detailedFeedback) {
  396. return room.sendFeedback (overallFeedback, detailedFeedback);
  397. },
  398. // used by torture currently
  399. isJoined () {
  400. return this._room
  401. && this._room.isJoined();
  402. },
  403. getConnectionState () {
  404. return this._room
  405. && this._room.getConnectionState();
  406. },
  407. getMyUserId () {
  408. return this._room
  409. && this._room.myUserId();
  410. },
  411. /**
  412. * Will be filled with values only when config.debug is enabled.
  413. * Its used by torture to check audio levels.
  414. */
  415. audioLevelsMap: {},
  416. /**
  417. * Returns the stored audio level (stored only if config.debug is enabled)
  418. * @param id the id for the user audio level to return (the id value is
  419. * returned for the participant using getMyUserId() method)
  420. */
  421. getPeerSSRCAudioLevel (id) {
  422. return this.audioLevelsMap[id];
  423. },
  424. /**
  425. * Will check for number of remote particiapnts that have at least one
  426. * remote track.
  427. * @return {boolean} whether we have enough participants with remote streams
  428. */
  429. checkEnoughParticipants (number) {
  430. var participants = this._room.getParticipants();
  431. var foundParticipants = 0;
  432. for (var i = 0; i < participants.length; i += 1) {
  433. if (participants[i].getTracks().length > 0) {
  434. foundParticipants++;
  435. }
  436. }
  437. return foundParticipants >= number;
  438. },
  439. /**
  440. * Returns the stats.
  441. */
  442. getStats() {
  443. return ConnectionQuality.getStats();
  444. },
  445. // end used by torture
  446. getLogs () {
  447. return room.getLogs();
  448. },
  449. _createRoom (localTracks) {
  450. room = connection.initJitsiConference(APP.conference.roomName,
  451. this._getConferenceOptions());
  452. this.localId = room.myUserId();
  453. localTracks.forEach((track) => {
  454. if (track.isAudioTrack()) {
  455. this.useAudioStream(track);
  456. } else if (track.isVideoTrack()) {
  457. this.useVideoStream(track);
  458. }
  459. });
  460. roomLocker = createRoomLocker(room);
  461. this._room = room; // FIXME do not use this
  462. let email = APP.settings.getEmail();
  463. email && sendEmail(email);
  464. let nick = APP.settings.getDisplayName();
  465. if (config.useNicks && !nick) {
  466. nick = APP.UI.askForNickname();
  467. APP.settings.setDisplayName(nick);
  468. }
  469. nick && room.setDisplayName(nick);
  470. this._setupListeners();
  471. },
  472. _getConferenceOptions() {
  473. let options = config;
  474. if(config.enableRecording) {
  475. options.recordingType = (config.hosts &&
  476. (typeof config.hosts.jirecon != "undefined"))?
  477. "jirecon" : "colibri";
  478. }
  479. return options;
  480. },
  481. /**
  482. * Start using provided video stream.
  483. * Stops previous video stream.
  484. * @param {JitsiLocalTrack} [stream] new stream to use or null
  485. * @returns {Promise}
  486. */
  487. useVideoStream (stream) {
  488. let promise = Promise.resolve();
  489. if (localVideo) {
  490. // this calls room.removeTrack internally
  491. // so we don't need to remove it manually
  492. promise = localVideo.dispose();
  493. }
  494. localVideo = stream;
  495. return promise.then(function () {
  496. if (stream) {
  497. return room.addTrack(stream);
  498. }
  499. }).then(() => {
  500. if (stream) {
  501. this.videoMuted = stream.isMuted();
  502. this.isSharingScreen = stream.videoType === 'desktop';
  503. APP.UI.addLocalStream(stream);
  504. } else {
  505. this.videoMuted = false;
  506. this.isSharingScreen = false;
  507. }
  508. APP.UI.setVideoMuted(this.localId, this.videoMuted);
  509. APP.UI.updateDesktopSharingButtons();
  510. });
  511. },
  512. /**
  513. * Start using provided audio stream.
  514. * Stops previous audio stream.
  515. * @param {JitsiLocalTrack} [stream] new stream to use or null
  516. * @returns {Promise}
  517. */
  518. useAudioStream (stream) {
  519. let promise = Promise.resolve();
  520. if (localAudio) {
  521. // this calls room.removeTrack internally
  522. // so we don't need to remove it manually
  523. promise = localAudio.dispose();
  524. }
  525. localAudio = stream;
  526. return promise.then(function () {
  527. if (stream) {
  528. return room.addTrack(stream);
  529. }
  530. }).then(() => {
  531. if (stream) {
  532. this.audioMuted = stream.isMuted();
  533. APP.UI.addLocalStream(stream);
  534. } else {
  535. this.audioMuted = false;
  536. }
  537. APP.UI.setAudioMuted(this.localId, this.audioMuted);
  538. });
  539. },
  540. videoSwitchInProgress: false,
  541. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  542. if (this.videoSwitchInProgress) {
  543. console.warn("Switch in progress.");
  544. return;
  545. }
  546. if (!this.isDesktopSharingEnabled) {
  547. console.warn("Cannot toggle screen sharing: not supported.");
  548. return;
  549. }
  550. this.videoSwitchInProgress = true;
  551. if (shareScreen) {
  552. createLocalTracks('desktop').then(([stream]) => {
  553. stream.on(
  554. TrackEvents.LOCAL_TRACK_STOPPED,
  555. () => {
  556. // if stream was stopped during screensharing session
  557. // then we should switch to video
  558. // otherwise we stopped it because we already switched
  559. // to video, so nothing to do here
  560. if (this.isSharingScreen) {
  561. this.toggleScreenSharing(false);
  562. }
  563. }
  564. );
  565. return this.useVideoStream(stream);
  566. }).then(() => {
  567. this.videoSwitchInProgress = false;
  568. console.log('sharing local desktop');
  569. }).catch((err) => {
  570. this.videoSwitchInProgress = false;
  571. this.toggleScreenSharing(false);
  572. if(err === TrackErrors.CHROME_EXTENSION_USER_CANCELED)
  573. return;
  574. console.error('failed to share local desktop', err);
  575. if (err === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  576. APP.UI.showExtensionRequiredDialog(
  577. config.desktopSharingFirefoxExtensionURL
  578. );
  579. return;
  580. }
  581. // Handling:
  582. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  583. // TrackErrors.GENERAL
  584. // and any other
  585. let dialogTxt = APP.translation
  586. .generateTranslationHTML("dialog.failtoinstall");
  587. let dialogTitle = APP.translation
  588. .generateTranslationHTML("dialog.error");
  589. APP.UI.messageHandler.openDialog(
  590. dialogTitle,
  591. dialogTxt,
  592. false
  593. );
  594. });
  595. } else {
  596. createLocalTracks('video').then(
  597. ([stream]) => this.useVideoStream(stream)
  598. ).then(() => {
  599. this.videoSwitchInProgress = false;
  600. console.log('sharing local video');
  601. }).catch((err) => {
  602. this.useVideoStream(null);
  603. this.videoSwitchInProgress = false;
  604. console.error('failed to share local video', err);
  605. });
  606. }
  607. },
  608. /**
  609. * Setup interaction between conference and UI.
  610. */
  611. _setupListeners () {
  612. // add local streams when joined to the conference
  613. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  614. APP.UI.mucJoined();
  615. });
  616. room.on(
  617. ConferenceEvents.AUTH_STATUS_CHANGED,
  618. function (authEnabled, authLogin) {
  619. APP.UI.updateAuthInfo(authEnabled, authLogin);
  620. }
  621. );
  622. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  623. console.log('USER %s connnected', id, user);
  624. APP.API.notifyUserJoined(id);
  625. APP.UI.addUser(id, user.getDisplayName());
  626. // chek the roles for the new user and reflect them
  627. APP.UI.updateUserRole(user);
  628. });
  629. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  630. console.log('USER %s LEFT', id, user);
  631. APP.API.notifyUserLeft(id);
  632. APP.UI.removeUser(id, user.getDisplayName());
  633. APP.UI.stopPrezi(id);
  634. });
  635. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  636. if (this.isLocalId(id)) {
  637. console.info(`My role changed, new role: ${role}`);
  638. this.isModerator = room.isModerator();
  639. APP.UI.updateLocalRole(room.isModerator());
  640. } else {
  641. let user = room.getParticipantById(id);
  642. if (user) {
  643. APP.UI.updateUserRole(user);
  644. }
  645. }
  646. });
  647. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  648. if(!track || track.isLocal())
  649. return;
  650. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  651. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  652. });
  653. APP.UI.addRemoteStream(track);
  654. });
  655. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  656. if(!track || track.isLocal())
  657. return;
  658. APP.UI.removeRemoteStream(track);
  659. });
  660. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  661. if(!track)
  662. return;
  663. const handler = (track.getType() === "audio")?
  664. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  665. let id;
  666. const mute = track.isMuted();
  667. if(track.isLocal()){
  668. id = this.localId;
  669. if(track.getType() === "audio") {
  670. this.audioMuted = mute;
  671. } else {
  672. this.videoMuted = mute;
  673. }
  674. } else {
  675. id = track.getParticipantId();
  676. }
  677. handler(id , mute);
  678. });
  679. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  680. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  681. lvl = 0;
  682. }
  683. if(config.debug)
  684. {
  685. this.audioLevelsMap[id] = lvl;
  686. console.log("AudioLevel:" + id + "/" + lvl);
  687. }
  688. APP.UI.setAudioLevel(id, lvl);
  689. });
  690. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  691. //FIXME
  692. if (config.muteLocalVideoIfNotInLastN) {
  693. // TODO mute or unmute if required
  694. // mark video on UI
  695. // APP.UI.markVideoMuted(true/false);
  696. }
  697. });
  698. room.on(
  699. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  700. APP.UI.handleLastNEndpoints(ids, enteringIds);
  701. });
  702. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  703. APP.UI.markDominantSpeaker(id);
  704. });
  705. if (!interfaceConfig.filmStripOnly) {
  706. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  707. APP.UI.markVideoInterrupted(true);
  708. });
  709. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  710. APP.UI.markVideoInterrupted(false);
  711. });
  712. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  713. let nick = getDisplayName(id);
  714. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  715. APP.UI.addMessage(id, nick, text, ts);
  716. });
  717. }
  718. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  719. APP.API.notifyDisplayNameChanged(id, displayName);
  720. APP.UI.changeDisplayName(id, displayName);
  721. });
  722. room.on(ConferenceEvents.RECORDING_STATE_CHANGED, (status, error) => {
  723. if(status == "error") {
  724. console.error(error);
  725. return;
  726. }
  727. APP.UI.updateRecordingState(status);
  728. });
  729. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  730. APP.UI.updateUserStatus(id, status);
  731. });
  732. room.on(ConferenceEvents.KICKED, () => {
  733. APP.UI.hideStats();
  734. APP.UI.notifyKicked();
  735. // FIXME close
  736. });
  737. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  738. APP.UI.updateDTMFSupport(isDTMFSupported);
  739. });
  740. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  741. if (room.isModerator()) {
  742. let promise = roomLocker.isLocked
  743. ? roomLocker.askToUnlock()
  744. : roomLocker.askToLock();
  745. promise.then(() => {
  746. APP.UI.markRoomLocked(roomLocker.isLocked);
  747. });
  748. } else {
  749. roomLocker.notifyModeratorRequired();
  750. }
  751. });
  752. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  753. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  754. if (!interfaceConfig.filmStripOnly) {
  755. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  756. APP.API.notifySendingChatMessage(message);
  757. room.sendTextMessage(message);
  758. });
  759. }
  760. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  761. ConnectionQuality.updateLocalStats(stats);
  762. });
  763. ConnectionQuality.addListener(
  764. CQEvents.LOCALSTATS_UPDATED,
  765. (percent, stats) => {
  766. APP.UI.updateLocalStats(percent, stats);
  767. // send local stats to other users
  768. room.sendCommandOnce(Commands.CONNECTION_QUALITY, {
  769. children: ConnectionQuality.convertToMUCStats(stats),
  770. attributes: {
  771. xmlns: 'http://jitsi.org/jitmeet/stats'
  772. }
  773. });
  774. }
  775. );
  776. // listen to remote stats
  777. room.addCommandListener(Commands.CONNECTION_QUALITY,(values, from) => {
  778. ConnectionQuality.updateRemoteStats(from, values);
  779. });
  780. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  781. (id, percent, stats) => {
  782. APP.UI.updateRemoteStats(id, percent, stats);
  783. });
  784. room.addCommandListener(Commands.ETHERPAD, ({value}) => {
  785. APP.UI.initEtherpad(value);
  786. });
  787. room.addCommandListener(Commands.PREZI, ({value, attributes}) => {
  788. APP.UI.showPrezi(attributes.id, value, attributes.slide);
  789. });
  790. room.addCommandListener(Commands.STOP_PREZI, ({attributes}) => {
  791. APP.UI.stopPrezi(attributes.id);
  792. });
  793. APP.UI.addListener(UIEvents.SHARE_PREZI, (url, slide) => {
  794. console.log('Sharing Prezi %s slide %s', url, slide);
  795. room.removeCommand(Commands.PREZI);
  796. room.sendCommand(Commands.PREZI, {
  797. value: url,
  798. attributes: {
  799. id: room.myUserId(),
  800. slide
  801. }
  802. });
  803. });
  804. APP.UI.addListener(UIEvents.STOP_SHARING_PREZI, () => {
  805. room.removeCommand(Commands.PREZI);
  806. room.sendCommandOnce(Commands.STOP_PREZI, {
  807. attributes: {
  808. id: room.myUserId()
  809. }
  810. });
  811. });
  812. APP.UI.addListener(UIEvents.EMAIL_CHANGED, (email = '') => {
  813. email = email.trim();
  814. if (email === APP.settings.getEmail()) {
  815. return;
  816. }
  817. APP.settings.setEmail(email);
  818. APP.UI.setUserAvatar(room.myUserId(), email);
  819. sendEmail(email);
  820. });
  821. room.addCommandListener(Commands.EMAIL, (data) => {
  822. APP.UI.setUserAvatar(data.attributes.id, data.value);
  823. });
  824. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, (nickname = '') => {
  825. nickname = nickname.trim();
  826. if (nickname === APP.settings.getDisplayName()) {
  827. return;
  828. }
  829. APP.settings.setDisplayName(nickname);
  830. room.setDisplayName(nickname);
  831. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  832. });
  833. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  834. (startAudioMuted, startVideoMuted) => {
  835. room.setStartMutedPolicy({
  836. audio: startAudioMuted,
  837. video: startVideoMuted
  838. });
  839. }
  840. );
  841. room.on(
  842. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  843. ({ audio, video }) => {
  844. APP.UI.onStartMutedChanged(audio, video);
  845. }
  846. );
  847. room.on(ConferenceEvents.STARTED_MUTED, () => {
  848. (room.isStartAudioMuted() || room.isStartVideoMuted())
  849. && APP.UI.notifyInitiallyMuted();
  850. });
  851. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  852. APP.UI.inviteParticipants(
  853. roomUrl,
  854. APP.conference.roomName,
  855. roomLocker.password,
  856. APP.settings.getDisplayName()
  857. );
  858. });
  859. room.on(
  860. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  861. APP.UI.updateDevicesAvailability(id, devices);
  862. }
  863. );
  864. // call hangup
  865. APP.UI.addListener(UIEvents.HANGUP, () => {
  866. hangup(true);
  867. });
  868. // logout
  869. APP.UI.addListener(UIEvents.LOGOUT, () => {
  870. AuthHandler.logout(room).then(function (url) {
  871. if (url) {
  872. window.location.href = url;
  873. } else {
  874. hangup(true);
  875. }
  876. });
  877. });
  878. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  879. room.dial(sipNumber);
  880. });
  881. // Starts or stops the recording for the conference.
  882. APP.UI.addListener(UIEvents.RECORDING_TOGGLE, (predefinedToken) => {
  883. if (predefinedToken) {
  884. room.toggleRecording({token: predefinedToken});
  885. return;
  886. }
  887. APP.UI.requestRecordingToken().then((token) => {
  888. room.toggleRecording({token: token});
  889. });
  890. });
  891. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  892. room.setSubject(topic);
  893. });
  894. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  895. APP.UI.setSubject(subject);
  896. });
  897. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  898. room.kickParticipant(id);
  899. });
  900. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  901. room.muteParticipant(id);
  902. });
  903. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  904. AuthHandler.authenticate(room);
  905. });
  906. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  907. room.selectParticipant(id);
  908. });
  909. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (id) => {
  910. room.pinParticipant(id);
  911. });
  912. APP.UI.addListener(
  913. UIEvents.VIDEO_DEVICE_CHANGED,
  914. (cameraDeviceId) => {
  915. APP.settings.setCameraDeviceId(cameraDeviceId);
  916. createLocalTracks('video').then(([stream]) => {
  917. this.useVideoStream(stream);
  918. console.log('switched local video device');
  919. });
  920. }
  921. );
  922. APP.UI.addListener(
  923. UIEvents.AUDIO_DEVICE_CHANGED,
  924. (micDeviceId) => {
  925. APP.settings.setMicDeviceId(micDeviceId);
  926. createLocalTracks('audio').then(([stream]) => {
  927. this.useAudioStream(stream);
  928. console.log('switched local audio device');
  929. });
  930. }
  931. );
  932. APP.UI.addListener(
  933. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  934. );
  935. }
  936. };