Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

conference.js 32KB

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