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 61KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789
  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 Recorder from './modules/recorder/Recorder';
  9. import CQEvents from './service/connectionquality/CQEvents';
  10. import UIEvents from './service/UI/UIEvents';
  11. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  12. import {reportError} from './modules/util/helpers';
  13. import UIUtil from './modules/UI/util/UIUtil';
  14. const ConnectionErrors = JitsiMeetJS.errors.connection;
  15. const ConferenceEvents = JitsiMeetJS.events.conference;
  16. const ConferenceErrors = JitsiMeetJS.errors.conference;
  17. const TrackEvents = JitsiMeetJS.events.track;
  18. const TrackErrors = JitsiMeetJS.errors.track;
  19. let room, connection, localAudio, localVideo, roomLocker;
  20. /**
  21. * Indicates whether the connection is interrupted or not.
  22. */
  23. let connectionIsInterrupted = false;
  24. /**
  25. * Indicates whether extension external installation is in progress or not.
  26. */
  27. let DSExternalInstallationInProgress = false;
  28. /**
  29. * Listens whether conference had been left from local user when we are trying
  30. * to navigate away from current page.
  31. * @type {HangupConferenceLeftListener}
  32. */
  33. let conferenceLeftListener = null;
  34. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/VideoContainer";
  35. /**
  36. * Known custom conference commands.
  37. */
  38. const commands = {
  39. CONNECTION_QUALITY: "stats",
  40. EMAIL: "email",
  41. AVATAR_URL: "avatar-url",
  42. AVATAR_ID: "avatar-id",
  43. ETHERPAD: "etherpad",
  44. SHARED_VIDEO: "shared-video",
  45. CUSTOM_ROLE: "custom-role"
  46. };
  47. /**
  48. * Open Connection. When authentication failed it shows auth dialog.
  49. * @param roomName the room name to use
  50. * @returns Promise<JitsiConnection>
  51. */
  52. function connect(roomName) {
  53. return openConnection({retry: true, roomName: roomName})
  54. .catch(function (err) {
  55. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  56. APP.UI.notifyTokenAuthFailed();
  57. } else {
  58. APP.UI.notifyConnectionFailed(err);
  59. }
  60. throw err;
  61. });
  62. }
  63. /**
  64. * Creates local media tracks and connects to room. Will show error
  65. * dialogs in case if accessing local microphone and/or camera failed. Will
  66. * show guidance overlay for users on how to give access to camera and/or
  67. * microphone,
  68. * @param {string} roomName
  69. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  70. */
  71. function createInitialLocalTracksAndConnect(roomName) {
  72. let audioAndVideoError,
  73. audioOnlyError;
  74. JitsiMeetJS.mediaDevices.addEventListener(
  75. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  76. browser => APP.UI.showUserMediaPermissionsGuidanceOverlay(browser));
  77. // First try to retrieve both audio and video.
  78. let tryCreateLocalTracks = createLocalTracks(
  79. { devices: ['audio', 'video'] }, true)
  80. .catch(err => {
  81. // If failed then try to retrieve only audio.
  82. audioAndVideoError = err;
  83. return createLocalTracks({ devices: ['audio'] }, true);
  84. })
  85. .catch(err => {
  86. // If audio failed too then just return empty array for tracks.
  87. audioOnlyError = err;
  88. return [];
  89. });
  90. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  91. .then(([tracks, con]) => {
  92. APP.UI.hideUserMediaPermissionsGuidanceOverlay();
  93. if (audioAndVideoError) {
  94. if (audioOnlyError) {
  95. // If both requests for 'audio' + 'video' and 'audio' only
  96. // failed, we assume that there is some problems with user's
  97. // microphone and show corresponding dialog.
  98. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  99. } else {
  100. // If request for 'audio' + 'video' failed, but request for
  101. // 'audio' only was OK, we assume that we had problems with
  102. // camera and show corresponding dialog.
  103. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  104. }
  105. }
  106. return [tracks, con];
  107. });
  108. }
  109. /**
  110. * Share data to other users.
  111. * @param command the command
  112. * @param {string} value new value
  113. */
  114. function sendData (command, value) {
  115. room.removeCommand(command);
  116. room.sendCommand(command, {value: value});
  117. }
  118. /**
  119. * Get user nickname by user id.
  120. * @param {string} id user id
  121. * @returns {string?} user nickname or undefined if user is unknown.
  122. */
  123. function getDisplayName (id) {
  124. if (APP.conference.isLocalId(id)) {
  125. return APP.settings.getDisplayName();
  126. }
  127. let participant = room.getParticipantById(id);
  128. if (participant && participant.getDisplayName()) {
  129. return participant.getDisplayName();
  130. }
  131. }
  132. /**
  133. * Mute or unmute local audio stream if it exists.
  134. * @param {boolean} muted - if audio stream should be muted or unmuted.
  135. * @param {boolean} userInteraction - indicates if this local audio mute was a
  136. * result of user interaction
  137. */
  138. function muteLocalAudio (muted) {
  139. muteLocalMedia(localAudio, muted, 'Audio');
  140. }
  141. function muteLocalMedia(localMedia, muted, localMediaTypeString) {
  142. if (!localMedia) {
  143. return;
  144. }
  145. const method = muted ? 'mute' : 'unmute';
  146. localMedia[method]().catch(reason => {
  147. console.warn(`${localMediaTypeString} ${method} was rejected:`, reason);
  148. });
  149. }
  150. /**
  151. * Mute or unmute local video stream if it exists.
  152. * @param {boolean} muted if video stream should be muted or unmuted.
  153. */
  154. function muteLocalVideo (muted) {
  155. muteLocalMedia(localVideo, muted, 'Video');
  156. }
  157. /**
  158. * Check if the welcome page is enabled and redirects to it.
  159. * If requested show a thank you dialog before that.
  160. * If we have a close page enabled, redirect to it without
  161. * showing any other dialog.
  162. * @param {boolean} showThankYou whether we should show a thank you dialog
  163. */
  164. function maybeRedirectToWelcomePage(showThankYou) {
  165. // if close page is enabled redirect to it, without further action
  166. if (config.enableClosePage) {
  167. window.location.pathname = "close.html";
  168. return;
  169. }
  170. if (showThankYou) {
  171. APP.UI.messageHandler.openMessageDialog(
  172. null, null, null,
  173. APP.translation.translateString(
  174. "dialog.thankYou", {appName:interfaceConfig.APP_NAME}
  175. )
  176. );
  177. }
  178. if (!config.enableWelcomePage) {
  179. return;
  180. }
  181. // redirect to welcome page
  182. setTimeout(() => {
  183. APP.settings.setWelcomePageEnabled(true);
  184. window.location.pathname = "/";
  185. }, 3000);
  186. }
  187. /**
  188. * Listens for CONFERENCE_LEFT event after hangup function has been executed.
  189. */
  190. class HangupConferenceLeftListener {
  191. /**
  192. * Creates HangupConferenceLeftListener and start listening for conference
  193. * left event. On CONFERENCE_LEFT event calls should disconnect the user
  194. * and maybe show the feedback dialog.
  195. * @param {boolean} [requestFeedback=false] if user feedback should be
  196. * requested
  197. */
  198. constructor(requestFeedback) {
  199. this.requestFeedback = requestFeedback;
  200. room.on(ConferenceEvents.CONFERENCE_LEFT,
  201. this._handleConferenceLeft.bind(this));
  202. }
  203. /**
  204. * Handles the conference left event.
  205. * @private
  206. */
  207. _handleConferenceLeft() {
  208. this._disconnectAndShowFeedback()
  209. .then(() => {
  210. APP.API.notifyReadyToClose();
  211. maybeRedirectToWelcomePage();
  212. }).catch(console.log);
  213. }
  214. /**
  215. * Executes connection.disconnect and shows the feedback dialog
  216. * @returns Promise.
  217. * @private
  218. */
  219. _disconnectAndShowFeedback() {
  220. APP.UI.hideRingOverLay();
  221. connection.disconnect();
  222. APP.API.notifyConferenceLeft(APP.conference.roomName);
  223. return (this.requestFeedback) ?
  224. APP.UI.requestFeedback() : Promise.resolve();
  225. }
  226. }
  227. /**
  228. * Create local tracks of specified types.
  229. * @param {Object} options
  230. * @param {string[]} options.devices - required track types
  231. * ('audio', 'video' etc.)
  232. * @param {string|null} (options.cameraDeviceId) - camera device id, if
  233. * undefined - one from settings will be used
  234. * @param {string|null} (options.micDeviceId) - microphone device id, if
  235. * undefined - one from settings will be used
  236. * @param {boolean} (checkForPermissionPrompt) - if lib-jitsi-meet should check
  237. * for gUM permission prompt
  238. * @returns {Promise<JitsiLocalTrack[]>}
  239. */
  240. function createLocalTracks (options, checkForPermissionPrompt) {
  241. options || (options = {});
  242. return JitsiMeetJS
  243. .createLocalTracks({
  244. // copy array to avoid mutations inside library
  245. devices: options.devices.slice(0),
  246. resolution: config.resolution,
  247. cameraDeviceId: typeof options.cameraDeviceId === 'undefined' ||
  248. options.cameraDeviceId === null
  249. ? APP.settings.getCameraDeviceId()
  250. : options.cameraDeviceId,
  251. micDeviceId: typeof options.micDeviceId === 'undefined' ||
  252. options.micDeviceId === null
  253. ? APP.settings.getMicDeviceId()
  254. : options.micDeviceId,
  255. // adds any ff fake device settings if any
  256. firefox_fake_device: config.firefox_fake_device,
  257. desktopSharingExtensionExternalInstallation:
  258. options.desktopSharingExtensionExternalInstallation
  259. }, checkForPermissionPrompt).then( (tracks) => {
  260. tracks.forEach((track) => {
  261. track.on(TrackEvents.NO_DATA_FROM_SOURCE,
  262. APP.UI.showTrackNotWorkingDialog.bind(null, track));
  263. });
  264. return tracks;
  265. }).catch(function (err) {
  266. console.error(
  267. 'failed to create local tracks', options.devices, err);
  268. return Promise.reject(err);
  269. });
  270. }
  271. /**
  272. * Changes the email for the local user
  273. * @param email {string} the new email
  274. */
  275. function changeLocalEmail(email = '') {
  276. email = email.trim();
  277. if (email === APP.settings.getEmail()) {
  278. return;
  279. }
  280. APP.settings.setEmail(email);
  281. APP.UI.setUserEmail(room.myUserId(), email);
  282. sendData(commands.EMAIL, email);
  283. }
  284. /**
  285. * Changes the display name for the local user
  286. * @param nickname {string} the new display name
  287. */
  288. function changeLocalDisplayName(nickname = '') {
  289. nickname = nickname.trim();
  290. if (nickname === APP.settings.getDisplayName()) {
  291. return;
  292. }
  293. APP.settings.setDisplayName(nickname);
  294. room.setDisplayName(nickname);
  295. APP.UI.changeDisplayName(APP.conference.getMyUserId(), nickname);
  296. }
  297. class ConferenceConnector {
  298. constructor(resolve, reject) {
  299. this._resolve = resolve;
  300. this._reject = reject;
  301. this.reconnectTimeout = null;
  302. room.on(ConferenceEvents.CONFERENCE_JOINED,
  303. this._handleConferenceJoined.bind(this));
  304. room.on(ConferenceEvents.CONFERENCE_FAILED,
  305. this._onConferenceFailed.bind(this));
  306. room.on(ConferenceEvents.CONFERENCE_ERROR,
  307. this._onConferenceError.bind(this));
  308. }
  309. _handleConferenceFailed(err) {
  310. this._unsubscribe();
  311. this._reject(err);
  312. }
  313. _onConferenceFailed(err, ...params) {
  314. console.error('CONFERENCE FAILED:', err, ...params);
  315. APP.UI.hideRingOverLay();
  316. switch (err) {
  317. // room is locked by the password
  318. case ConferenceErrors.PASSWORD_REQUIRED:
  319. APP.UI.markRoomLocked(true);
  320. roomLocker.requirePassword().then(function () {
  321. let pass = roomLocker.password;
  322. // we received that password is required, but user is trying
  323. // anyway to login without a password, mark room as not locked
  324. // in case he succeeds (maybe someone removed the password
  325. // meanwhile), if it is still locked another password required
  326. // will be received and the room again will be marked as locked
  327. if (!pass)
  328. APP.UI.markRoomLocked(false);
  329. room.join(roomLocker.password);
  330. });
  331. break;
  332. case ConferenceErrors.CONNECTION_ERROR:
  333. {
  334. let [msg] = params;
  335. APP.UI.notifyConnectionFailed(msg);
  336. }
  337. break;
  338. case ConferenceErrors.NOT_ALLOWED_ERROR:
  339. {
  340. // let's show some auth not allowed page
  341. window.location.pathname = "authError.html";
  342. }
  343. break;
  344. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  345. APP.UI.notifyBridgeDown();
  346. break;
  347. // not enough rights to create conference
  348. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  349. // schedule reconnect to check if someone else created the room
  350. this.reconnectTimeout = setTimeout(function () {
  351. room.join();
  352. }, 5000);
  353. // notify user that auth is required
  354. AuthHandler.requireAuth(room, roomLocker.password);
  355. break;
  356. case ConferenceErrors.RESERVATION_ERROR:
  357. {
  358. let [code, msg] = params;
  359. APP.UI.notifyReservationError(code, msg);
  360. }
  361. break;
  362. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  363. APP.UI.notifyGracefulShutdown();
  364. break;
  365. case ConferenceErrors.JINGLE_FATAL_ERROR:
  366. APP.UI.notifyInternalError();
  367. break;
  368. case ConferenceErrors.CONFERENCE_DESTROYED:
  369. {
  370. let [reason] = params;
  371. APP.UI.hideStats();
  372. APP.UI.notifyConferenceDestroyed(reason);
  373. }
  374. break;
  375. case ConferenceErrors.FOCUS_DISCONNECTED:
  376. {
  377. let [focus, retrySec] = params;
  378. APP.UI.notifyFocusDisconnected(focus, retrySec);
  379. }
  380. break;
  381. case ConferenceErrors.FOCUS_LEFT:
  382. room.leave().then(() => connection.disconnect());
  383. APP.UI.notifyFocusLeft();
  384. break;
  385. case ConferenceErrors.CONFERENCE_MAX_USERS:
  386. connection.disconnect();
  387. APP.UI.notifyMaxUsersLimitReached();
  388. break;
  389. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  390. window.location.reload();
  391. break;
  392. default:
  393. this._handleConferenceFailed(err, ...params);
  394. }
  395. }
  396. _onConferenceError(err, ...params) {
  397. console.error('CONFERENCE Error:', err, params);
  398. switch (err) {
  399. case ConferenceErrors.CHAT_ERROR:
  400. {
  401. let [code, msg] = params;
  402. APP.UI.showChatError(code, msg);
  403. }
  404. break;
  405. default:
  406. console.error("Unknown error.");
  407. }
  408. }
  409. _unsubscribe() {
  410. room.off(
  411. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  412. room.off(
  413. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  414. if (this.reconnectTimeout !== null) {
  415. clearTimeout(this.reconnectTimeout);
  416. }
  417. AuthHandler.closeAuth();
  418. }
  419. _handleConferenceJoined() {
  420. this._unsubscribe();
  421. this._resolve();
  422. }
  423. connect() {
  424. room.join();
  425. }
  426. }
  427. export default {
  428. isModerator: false,
  429. audioMuted: false,
  430. videoMuted: false,
  431. isSharingScreen: false,
  432. isDesktopSharingEnabled: false,
  433. /*
  434. * Whether the local "raisedHand" flag is on.
  435. */
  436. isHandRaised: false,
  437. /*
  438. * Whether the local participant is the dominant speaker in the conference.
  439. */
  440. isDominantSpeaker: false,
  441. /**
  442. * Open new connection and join to the conference.
  443. * @param {object} options
  444. * @param {string} roomName name of the conference
  445. * @returns {Promise}
  446. */
  447. init(options) {
  448. this.roomName = options.roomName;
  449. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  450. // attaches global error handler, if there is already one, respect it
  451. if(JitsiMeetJS.getGlobalOnErrorHandler){
  452. var oldOnErrorHandler = window.onerror;
  453. window.onerror = function (message, source, lineno, colno, error) {
  454. JitsiMeetJS.getGlobalOnErrorHandler(
  455. message, source, lineno, colno, error);
  456. if(oldOnErrorHandler)
  457. oldOnErrorHandler(message, source, lineno, colno, error);
  458. };
  459. var oldOnUnhandledRejection = window.onunhandledrejection;
  460. window.onunhandledrejection = function(event) {
  461. JitsiMeetJS.getGlobalOnErrorHandler(
  462. null, null, null, null, event.reason);
  463. if(oldOnUnhandledRejection)
  464. oldOnUnhandledRejection(event);
  465. };
  466. }
  467. return JitsiMeetJS.init(config)
  468. .then(() => createInitialLocalTracksAndConnect(options.roomName))
  469. .then(([tracks, con]) => {
  470. console.log('initialized with %s local tracks', tracks.length);
  471. APP.connection = connection = con;
  472. this._createRoom(tracks);
  473. this.isDesktopSharingEnabled =
  474. JitsiMeetJS.isDesktopSharingEnabled();
  475. // if user didn't give access to mic or camera or doesn't have
  476. // them at all, we disable corresponding toolbar buttons
  477. if (!tracks.find((t) => t.isAudioTrack())) {
  478. APP.UI.disableMicrophoneButton(true);
  479. }
  480. if (!tracks.find((t) => t.isVideoTrack())) {
  481. APP.UI.disableCameraButton(true);
  482. }
  483. this._initDeviceList();
  484. if (config.iAmRecorder)
  485. this.recorder = new Recorder();
  486. // XXX The API will take care of disconnecting from the XMPP
  487. // server (and, thus, leaving the room) on unload.
  488. return new Promise((resolve, reject) => {
  489. (new ConferenceConnector(resolve, reject)).connect();
  490. });
  491. });
  492. },
  493. /**
  494. * Check if id is id of the local user.
  495. * @param {string} id id to check
  496. * @returns {boolean}
  497. */
  498. isLocalId (id) {
  499. return this.getMyUserId() === id;
  500. },
  501. /**
  502. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  503. * @param mute true for mute and false for unmute.
  504. */
  505. muteAudio (mute) {
  506. muteLocalAudio(mute);
  507. },
  508. /**
  509. * Returns whether local audio is muted or not.
  510. * @returns {boolean}
  511. */
  512. isLocalAudioMuted() {
  513. return this.audioMuted;
  514. },
  515. /**
  516. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  517. */
  518. toggleAudioMuted () {
  519. this.muteAudio(!this.audioMuted);
  520. },
  521. /**
  522. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  523. * @param mute true for mute and false for unmute.
  524. */
  525. muteVideo (mute) {
  526. muteLocalVideo(mute);
  527. },
  528. /**
  529. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  530. */
  531. toggleVideoMuted () {
  532. this.muteVideo(!this.videoMuted);
  533. },
  534. /**
  535. * Retrieve list of conference participants (without local user).
  536. * @returns {JitsiParticipant[]}
  537. */
  538. listMembers () {
  539. return room.getParticipants();
  540. },
  541. /**
  542. * Retrieve list of ids of conference participants (without local user).
  543. * @returns {string[]}
  544. */
  545. listMembersIds () {
  546. return room.getParticipants().map(p => p.getId());
  547. },
  548. /**
  549. * Checks whether the participant identified by id is a moderator.
  550. * @id id to search for participant
  551. * @return {boolean} whether the participant is moderator
  552. */
  553. isParticipantModerator (id) {
  554. let user = room.getParticipantById(id);
  555. return user && user.isModerator();
  556. },
  557. /**
  558. * Check if SIP is supported.
  559. * @returns {boolean}
  560. */
  561. sipGatewayEnabled () {
  562. return room.isSIPCallingSupported();
  563. },
  564. get membersCount () {
  565. return room.getParticipants().length + 1;
  566. },
  567. /**
  568. * Returns true if the callstats integration is enabled, otherwise returns
  569. * false.
  570. *
  571. * @returns true if the callstats integration is enabled, otherwise returns
  572. * false.
  573. */
  574. isCallstatsEnabled () {
  575. return room.isCallstatsEnabled();
  576. },
  577. /**
  578. * Sends the given feedback through CallStats if enabled.
  579. *
  580. * @param overallFeedback an integer between 1 and 5 indicating the
  581. * user feedback
  582. * @param detailedFeedback detailed feedback from the user. Not yet used
  583. */
  584. sendFeedback (overallFeedback, detailedFeedback) {
  585. return room.sendFeedback (overallFeedback, detailedFeedback);
  586. },
  587. /**
  588. * Returns the connection times stored in the library.
  589. */
  590. getConnectionTimes () {
  591. return this._room.getConnectionTimes();
  592. },
  593. // used by torture currently
  594. isJoined () {
  595. return this._room
  596. && this._room.isJoined();
  597. },
  598. getConnectionState () {
  599. return this._room
  600. && this._room.getConnectionState();
  601. },
  602. /**
  603. * Checks whether or not our connection is currently in interrupted and
  604. * reconnect attempts are in progress.
  605. *
  606. * @returns {boolean} true if the connection is in interrupted state or
  607. * false otherwise.
  608. */
  609. isConnectionInterrupted () {
  610. return connectionIsInterrupted;
  611. },
  612. /**
  613. * Finds JitsiParticipant for given id.
  614. *
  615. * @param {string} id participant's identifier(MUC nickname).
  616. *
  617. * @returns {JitsiParticipant|null} participant instance for given id or
  618. * null if not found.
  619. */
  620. getParticipantById (id) {
  621. return room ? room.getParticipantById(id) : null;
  622. },
  623. /**
  624. * Checks whether the user identified by given id is currently connected.
  625. *
  626. * @param {string} id participant's identifier(MUC nickname)
  627. *
  628. * @returns {boolean|null} true if participant's connection is ok or false
  629. * if the user is having connectivity issues.
  630. */
  631. isParticipantConnectionActive (id) {
  632. let participant = this.getParticipantById(id);
  633. return participant ? participant.isConnectionActive() : null;
  634. },
  635. /**
  636. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  637. * the given <tt>id</tt>.
  638. *
  639. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  640. *
  641. * @return {string} the participant's display name or the default string if
  642. * absent.
  643. */
  644. getParticipantDisplayName (id) {
  645. let displayName = getDisplayName(id);
  646. if (displayName) {
  647. return displayName;
  648. } else {
  649. if (APP.conference.isLocalId(id)) {
  650. return APP.translation.generateTranslationHTML(
  651. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  652. } else {
  653. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  654. }
  655. }
  656. },
  657. getMyUserId () {
  658. return this._room
  659. && this._room.myUserId();
  660. },
  661. /**
  662. * Indicates if recording is supported in this conference.
  663. */
  664. isRecordingSupported() {
  665. return this._room && this._room.isRecordingSupported();
  666. },
  667. /**
  668. * Returns the recording state or undefined if the room is not defined.
  669. */
  670. getRecordingState() {
  671. return (this._room) ? this._room.getRecordingState() : undefined;
  672. },
  673. /**
  674. * Will be filled with values only when config.debug is enabled.
  675. * Its used by torture to check audio levels.
  676. */
  677. audioLevelsMap: {},
  678. /**
  679. * Returns the stored audio level (stored only if config.debug is enabled)
  680. * @param id the id for the user audio level to return (the id value is
  681. * returned for the participant using getMyUserId() method)
  682. */
  683. getPeerSSRCAudioLevel (id) {
  684. return this.audioLevelsMap[id];
  685. },
  686. /**
  687. * @return {number} the number of participants in the conference with at
  688. * least one track.
  689. */
  690. getNumberOfParticipantsWithTracks() {
  691. return this._room.getParticipants()
  692. .filter((p) => p.getTracks().length > 0)
  693. .length;
  694. },
  695. /**
  696. * Returns the stats.
  697. */
  698. getStats() {
  699. return ConnectionQuality.getStats();
  700. },
  701. // end used by torture
  702. getLogs () {
  703. return room.getLogs();
  704. },
  705. /**
  706. * Download logs, a function that can be called from console while
  707. * debugging.
  708. * @param filename (optional) specify target filename
  709. */
  710. saveLogs (filename = 'meetlog.json') {
  711. // this can be called from console and will not have reference to this
  712. // that's why we reference the global var
  713. let logs = APP.conference.getLogs();
  714. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  715. let elem = document.createElement('a');
  716. elem.download = filename;
  717. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  718. elem.dataset.downloadurl
  719. = ['text/json', elem.download, elem.href].join(':');
  720. elem.dispatchEvent(new MouseEvent('click', {
  721. view: window,
  722. bubbles: true,
  723. cancelable: false
  724. }));
  725. },
  726. /**
  727. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  728. * desire to keep room private to this instance and (2) the need of other
  729. * modules to send and receive commands to and from participants.
  730. * Eventually, this instance remains in control with respect to the
  731. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  732. * JitsiConference) is to be used in the implementation of the Command(s)
  733. * API of this instance.
  734. */
  735. commands: {
  736. /**
  737. * Known custom conference commands.
  738. */
  739. defaults: commands,
  740. /**
  741. * Receives notifications from other participants about commands aka
  742. * custom events (sent by sendCommand or sendCommandOnce methods).
  743. * @param command {String} the name of the command
  744. * @param handler {Function} handler for the command
  745. */
  746. addCommandListener () {
  747. room.addCommandListener.apply(room, arguments);
  748. },
  749. /**
  750. * Removes command.
  751. * @param name {String} the name of the command.
  752. */
  753. removeCommand () {
  754. room.removeCommand.apply(room, arguments);
  755. },
  756. /**
  757. * Sends command.
  758. * @param name {String} the name of the command.
  759. * @param values {Object} with keys and values that will be sent.
  760. */
  761. sendCommand () {
  762. room.sendCommand.apply(room, arguments);
  763. },
  764. /**
  765. * Sends command one time.
  766. * @param name {String} the name of the command.
  767. * @param values {Object} with keys and values that will be sent.
  768. */
  769. sendCommandOnce () {
  770. room.sendCommandOnce.apply(room, arguments);
  771. }
  772. },
  773. _createRoom (localTracks) {
  774. room = connection.initJitsiConference(APP.conference.roomName,
  775. this._getConferenceOptions());
  776. this._setLocalAudioVideoStreams(localTracks);
  777. roomLocker = createRoomLocker(room);
  778. this._room = room; // FIXME do not use this
  779. let email = APP.settings.getEmail();
  780. email && sendData(this.commands.defaults.EMAIL, email);
  781. let avatarUrl = APP.settings.getAvatarUrl();
  782. avatarUrl && sendData(this.commands.defaults.AVATAR_URL,
  783. avatarUrl);
  784. !email && sendData(
  785. this.commands.defaults.AVATAR_ID, APP.settings.getAvatarId());
  786. let nick = APP.settings.getDisplayName();
  787. if (config.useNicks && !nick) {
  788. nick = APP.UI.askForNickname();
  789. APP.settings.setDisplayName(nick);
  790. }
  791. nick && room.setDisplayName(nick);
  792. this._setupListeners();
  793. },
  794. /**
  795. * Sets local video and audio streams.
  796. * @param {JitsiLocalTrack[]} tracks=[]
  797. * @returns {Promise[]}
  798. * @private
  799. */
  800. _setLocalAudioVideoStreams(tracks = []) {
  801. return tracks.map(track => {
  802. if (track.isAudioTrack()) {
  803. return this.useAudioStream(track);
  804. } else if (track.isVideoTrack()) {
  805. return this.useVideoStream(track);
  806. } else {
  807. console.error(
  808. "Ignored not an audio nor a video track: ", track);
  809. return Promise.resolve();
  810. }
  811. });
  812. },
  813. _getConferenceOptions() {
  814. let options = config;
  815. if(config.enableRecording && !config.recordingType) {
  816. options.recordingType = (config.hosts &&
  817. (typeof config.hosts.jirecon != "undefined"))?
  818. "jirecon" : "colibri";
  819. }
  820. return options;
  821. },
  822. /**
  823. * Start using provided video stream.
  824. * Stops previous video stream.
  825. * @param {JitsiLocalTrack} [stream] new stream to use or null
  826. * @returns {Promise}
  827. */
  828. useVideoStream (stream) {
  829. let promise = Promise.resolve();
  830. if (localVideo) {
  831. // this calls room.removeTrack internally
  832. // so we don't need to remove it manually
  833. promise = localVideo.dispose();
  834. }
  835. localVideo = stream;
  836. return promise.then(function () {
  837. if (stream) {
  838. return room.addTrack(stream);
  839. }
  840. }).then(() => {
  841. if (stream) {
  842. this.videoMuted = stream.isMuted();
  843. this.isSharingScreen = stream.videoType === 'desktop';
  844. APP.UI.addLocalStream(stream);
  845. stream.videoType === 'camera'
  846. && APP.UI.disableCameraButton(false);
  847. } else {
  848. this.videoMuted = false;
  849. this.isSharingScreen = false;
  850. }
  851. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  852. APP.UI.updateDesktopSharingButtons();
  853. });
  854. },
  855. /**
  856. * Start using provided audio stream.
  857. * Stops previous audio stream.
  858. * @param {JitsiLocalTrack} [stream] new stream to use or null
  859. * @returns {Promise}
  860. */
  861. useAudioStream (stream) {
  862. let promise = Promise.resolve();
  863. if (localAudio) {
  864. // this calls room.removeTrack internally
  865. // so we don't need to remove it manually
  866. promise = localAudio.dispose();
  867. }
  868. localAudio = stream;
  869. return promise.then(function () {
  870. if (stream) {
  871. return room.addTrack(stream);
  872. }
  873. }).then(() => {
  874. if (stream) {
  875. this.audioMuted = stream.isMuted();
  876. APP.UI.addLocalStream(stream);
  877. } else {
  878. this.audioMuted = false;
  879. }
  880. APP.UI.disableMicrophoneButton(false);
  881. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  882. });
  883. },
  884. videoSwitchInProgress: false,
  885. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  886. if (this.videoSwitchInProgress) {
  887. console.warn("Switch in progress.");
  888. return;
  889. }
  890. if (!this.isDesktopSharingEnabled) {
  891. console.warn("Cannot toggle screen sharing: not supported.");
  892. return;
  893. }
  894. this.videoSwitchInProgress = true;
  895. let externalInstallation = false;
  896. if (shareScreen) {
  897. createLocalTracks({
  898. devices: ['desktop'],
  899. desktopSharingExtensionExternalInstallation: {
  900. interval: 500,
  901. checkAgain: () => {
  902. return DSExternalInstallationInProgress;
  903. },
  904. listener: (status, url) => {
  905. switch(status) {
  906. case "waitingForExtension":
  907. DSExternalInstallationInProgress = true;
  908. externalInstallation = true;
  909. APP.UI.showExtensionExternalInstallationDialog(
  910. url);
  911. break;
  912. case "extensionFound":
  913. if(externalInstallation) //close the dialog
  914. $.prompt.close();
  915. break;
  916. default:
  917. //Unknown status
  918. }
  919. }
  920. }
  921. }).then(([stream]) => {
  922. DSExternalInstallationInProgress = false;
  923. // close external installation dialog on success.
  924. if(externalInstallation)
  925. $.prompt.close();
  926. stream.on(
  927. TrackEvents.LOCAL_TRACK_STOPPED,
  928. () => {
  929. // if stream was stopped during screensharing session
  930. // then we should switch to video
  931. // otherwise we stopped it because we already switched
  932. // to video, so nothing to do here
  933. if (this.isSharingScreen) {
  934. this.toggleScreenSharing(false);
  935. }
  936. }
  937. );
  938. return this.useVideoStream(stream);
  939. }).then(() => {
  940. this.videoSwitchInProgress = false;
  941. JitsiMeetJS.analytics.sendEvent(
  942. 'conference.sharingDesktop.start');
  943. console.log('sharing local desktop');
  944. }).catch((err) => {
  945. // close external installation dialog to show the error.
  946. if(externalInstallation)
  947. $.prompt.close();
  948. this.videoSwitchInProgress = false;
  949. this.toggleScreenSharing(false);
  950. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  951. return;
  952. }
  953. console.error('failed to share local desktop', err);
  954. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  955. APP.UI.showExtensionRequiredDialog(
  956. config.desktopSharingFirefoxExtensionURL
  957. );
  958. return;
  959. }
  960. // Handling:
  961. // TrackErrors.PERMISSION_DENIED
  962. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  963. // TrackErrors.GENERAL
  964. // and any other
  965. let dialogTxt;
  966. let dialogTitle;
  967. if (err.name === TrackErrors.PERMISSION_DENIED) {
  968. dialogTxt = APP.translation.generateTranslationHTML(
  969. "dialog.screenSharingPermissionDeniedError");
  970. dialogTitle = APP.translation.generateTranslationHTML(
  971. "dialog.error");
  972. } else {
  973. dialogTxt = APP.translation.generateTranslationHTML(
  974. "dialog.failtoinstall");
  975. dialogTitle = APP.translation.generateTranslationHTML(
  976. "dialog.permissionDenied");
  977. }
  978. APP.UI.messageHandler.openDialog(dialogTitle, dialogTxt, false);
  979. });
  980. } else {
  981. createLocalTracks({ devices: ['video'] }).then(
  982. ([stream]) => this.useVideoStream(stream)
  983. ).then(() => {
  984. this.videoSwitchInProgress = false;
  985. JitsiMeetJS.analytics.sendEvent(
  986. 'conference.sharingDesktop.stop');
  987. console.log('sharing local video');
  988. }).catch((err) => {
  989. this.useVideoStream(null);
  990. this.videoSwitchInProgress = false;
  991. console.error('failed to share local video', err);
  992. });
  993. }
  994. },
  995. /**
  996. * Setup interaction between conference and UI.
  997. */
  998. _setupListeners () {
  999. // add local streams when joined to the conference
  1000. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1001. APP.UI.mucJoined();
  1002. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1003. connectionIsInterrupted = false;
  1004. APP.UI.markVideoInterrupted(false);
  1005. });
  1006. room.on(
  1007. ConferenceEvents.AUTH_STATUS_CHANGED,
  1008. function (authEnabled, authLogin) {
  1009. APP.UI.updateAuthInfo(authEnabled, authLogin);
  1010. }
  1011. );
  1012. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1013. if (user.isHidden())
  1014. return;
  1015. console.log('USER %s connnected', id, user);
  1016. APP.API.notifyUserJoined(id);
  1017. APP.UI.addUser(user);
  1018. // check the roles for the new user and reflect them
  1019. APP.UI.updateUserRole(user);
  1020. });
  1021. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1022. console.log('USER %s LEFT', id, user);
  1023. APP.API.notifyUserLeft(id);
  1024. APP.UI.removeUser(id, user.getDisplayName());
  1025. APP.UI.onSharedVideoStop(id);
  1026. });
  1027. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1028. if (this.isLocalId(id)) {
  1029. console.info(`My role changed, new role: ${role}`);
  1030. if (this.isModerator !== room.isModerator()) {
  1031. this.isModerator = room.isModerator();
  1032. APP.UI.updateLocalRole(room.isModerator());
  1033. }
  1034. } else {
  1035. let user = room.getParticipantById(id);
  1036. if (user) {
  1037. APP.UI.updateUserRole(user);
  1038. }
  1039. }
  1040. });
  1041. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1042. if(!track || track.isLocal())
  1043. return;
  1044. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1045. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1046. });
  1047. APP.UI.addRemoteStream(track);
  1048. });
  1049. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1050. if(!track || track.isLocal())
  1051. return;
  1052. APP.UI.removeRemoteStream(track);
  1053. });
  1054. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1055. if(!track)
  1056. return;
  1057. const handler = (track.getType() === "audio")?
  1058. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1059. let id;
  1060. const mute = track.isMuted();
  1061. if(track.isLocal()){
  1062. id = APP.conference.getMyUserId();
  1063. if(track.getType() === "audio") {
  1064. this.audioMuted = mute;
  1065. } else {
  1066. this.videoMuted = mute;
  1067. }
  1068. } else {
  1069. id = track.getParticipantId();
  1070. }
  1071. handler(id , mute);
  1072. });
  1073. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1074. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1075. lvl = 0;
  1076. }
  1077. if(config.debug)
  1078. {
  1079. this.audioLevelsMap[id] = lvl;
  1080. if(config.debugAudioLevels)
  1081. console.log("AudioLevel:" + id + "/" + lvl);
  1082. }
  1083. APP.UI.setAudioLevel(id, lvl);
  1084. });
  1085. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1086. APP.UI.showToolbar(6000);
  1087. UIUtil.animateShowElement($("#talkWhileMutedPopup"), true, 5000);
  1088. });
  1089. /*
  1090. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  1091. //FIXME
  1092. if (config.muteLocalVideoIfNotInLastN) {
  1093. // TODO mute or unmute if required
  1094. // mark video on UI
  1095. // APP.UI.markVideoMuted(true/false);
  1096. }
  1097. });
  1098. */
  1099. room.on(
  1100. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  1101. APP.UI.handleLastNEndpoints(ids, enteringIds);
  1102. });
  1103. room.on(
  1104. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1105. (id, isActive) => {
  1106. APP.UI.participantConnectionStatusChanged(id, isActive);
  1107. });
  1108. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1109. if (this.isLocalId(id)) {
  1110. this.isDominantSpeaker = true;
  1111. this.setRaisedHand(false);
  1112. } else {
  1113. this.isDominantSpeaker = false;
  1114. var participant = room.getParticipantById(id);
  1115. if (participant) {
  1116. APP.UI.setRaisedHandStatus(participant, false);
  1117. }
  1118. }
  1119. APP.UI.markDominantSpeaker(id);
  1120. });
  1121. if (!interfaceConfig.filmStripOnly) {
  1122. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1123. APP.UI.markVideoInterrupted(true);
  1124. });
  1125. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1126. APP.UI.markVideoInterrupted(false);
  1127. });
  1128. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1129. let nick = getDisplayName(id);
  1130. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1131. APP.UI.addMessage(id, nick, text, ts);
  1132. });
  1133. }
  1134. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1135. connectionIsInterrupted = true;
  1136. ConnectionQuality.updateLocalConnectionQuality(0);
  1137. APP.UI.showLocalConnectionInterrupted(true);
  1138. });
  1139. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1140. connectionIsInterrupted = false;
  1141. APP.UI.showLocalConnectionInterrupted(false);
  1142. });
  1143. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1144. APP.API.notifyDisplayNameChanged(id, displayName);
  1145. APP.UI.changeDisplayName(id, displayName);
  1146. });
  1147. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1148. (participant, name, oldValue, newValue) => {
  1149. if (name === "raisedHand") {
  1150. APP.UI.setRaisedHandStatus(participant, newValue);
  1151. }
  1152. });
  1153. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1154. console.log("Received recorder status change: ", status, error);
  1155. APP.UI.updateRecordingState(status);
  1156. });
  1157. room.on(ConferenceEvents.LOCK_STATE_CHANGED, (state, error) => {
  1158. console.log("Received channel password lock change: ", state,
  1159. error);
  1160. APP.UI.markRoomLocked(state);
  1161. roomLocker.lockedElsewhere = state;
  1162. });
  1163. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  1164. APP.UI.updateUserStatus(id, status);
  1165. });
  1166. room.on(ConferenceEvents.KICKED, () => {
  1167. APP.UI.hideStats();
  1168. APP.UI.notifyKicked();
  1169. // FIXME close
  1170. });
  1171. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1172. APP.UI.updateDTMFSupport(isDTMFSupported);
  1173. });
  1174. APP.UI.addListener(UIEvents.EXTERNAL_INSTALLATION_CANCELED, () => {
  1175. // Wait a little bit more just to be sure that we won't miss the
  1176. // extension installation
  1177. setTimeout(() => DSExternalInstallationInProgress = false, 500);
  1178. });
  1179. APP.UI.addListener(UIEvents.OPEN_EXTENSION_STORE, (url) => {
  1180. window.open(
  1181. url, "extension_store_window",
  1182. "resizable,scrollbars=yes,status=1");
  1183. });
  1184. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  1185. if (room.isModerator()) {
  1186. let promise = roomLocker.isLocked
  1187. ? roomLocker.askToUnlock()
  1188. : roomLocker.askToLock();
  1189. promise.then(() => {
  1190. APP.UI.markRoomLocked(roomLocker.isLocked);
  1191. });
  1192. } else {
  1193. roomLocker.notifyModeratorRequired();
  1194. }
  1195. });
  1196. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1197. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1198. if (!interfaceConfig.filmStripOnly) {
  1199. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1200. APP.API.notifySendingChatMessage(message);
  1201. room.sendTextMessage(message);
  1202. });
  1203. }
  1204. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  1205. ConnectionQuality.updateLocalStats(stats, connectionIsInterrupted);
  1206. });
  1207. ConnectionQuality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1208. (percent, stats) => {
  1209. APP.UI.updateLocalStats(percent, stats);
  1210. // Send only the data that remote participants care about.
  1211. let data = {
  1212. bitrate: stats.bitrate,
  1213. packetLoss: stats.packetLoss};
  1214. try {
  1215. room.broadcastEndpointMessage({
  1216. type: this.commands.defaults.CONNECTION_QUALITY,
  1217. values: data });
  1218. } catch (e) {
  1219. reportError(e);
  1220. }
  1221. });
  1222. room.on(ConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1223. (participant, payload) => {
  1224. switch(payload.type) {
  1225. case this.commands.defaults.CONNECTION_QUALITY:
  1226. ConnectionQuality.updateRemoteStats(participant.getId(),
  1227. payload.values);
  1228. break;
  1229. default:
  1230. console.warn("Unknown datachannel message", payload);
  1231. }
  1232. });
  1233. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1234. (id, percent, stats) => {
  1235. APP.UI.updateRemoteStats(id, percent, stats);
  1236. });
  1237. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1238. APP.UI.initEtherpad(value);
  1239. });
  1240. APP.UI.addListener(UIEvents.EMAIL_CHANGED, changeLocalEmail);
  1241. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1242. APP.UI.setUserEmail(from, data.value);
  1243. });
  1244. room.addCommandListener(this.commands.defaults.AVATAR_URL,
  1245. (data, from) => {
  1246. APP.UI.setUserAvatarUrl(from, data.value);
  1247. });
  1248. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1249. (data, from) => {
  1250. APP.UI.setUserAvatarID(from, data.value);
  1251. });
  1252. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, changeLocalDisplayName);
  1253. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1254. (startAudioMuted, startVideoMuted) => {
  1255. room.setStartMutedPolicy({
  1256. audio: startAudioMuted,
  1257. video: startVideoMuted
  1258. });
  1259. }
  1260. );
  1261. room.on(
  1262. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1263. ({ audio, video }) => {
  1264. APP.UI.onStartMutedChanged(audio, video);
  1265. }
  1266. );
  1267. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1268. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1269. && APP.UI.notifyInitiallyMuted();
  1270. });
  1271. room.on(
  1272. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1273. APP.UI.updateDevicesAvailability(id, devices);
  1274. }
  1275. );
  1276. // call hangup
  1277. APP.UI.addListener(UIEvents.HANGUP, () => {
  1278. this.hangup(true);
  1279. });
  1280. // logout
  1281. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1282. AuthHandler.logout(room).then(url => {
  1283. if (url) {
  1284. window.location.href = url;
  1285. } else {
  1286. this.hangup(true);
  1287. }
  1288. });
  1289. });
  1290. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1291. room.dial(sipNumber);
  1292. });
  1293. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1294. (id, oldResolution, newResolution, delay) => {
  1295. var logObject = {
  1296. id: "resolution_change",
  1297. participant: id,
  1298. oldValue: oldResolution,
  1299. newValue: newResolution,
  1300. delay: delay
  1301. };
  1302. room.sendApplicationLog(JSON.stringify(logObject));
  1303. // We only care about the delay between simulcast streams.
  1304. // Longer delays will be caused by something else and will just
  1305. // poison the data.
  1306. if (delay < 2000) {
  1307. JitsiMeetJS.analytics.sendEvent('stream.switch.delay', delay);
  1308. }
  1309. });
  1310. // Starts or stops the recording for the conference.
  1311. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1312. room.toggleRecording(options);
  1313. });
  1314. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1315. room.setSubject(topic);
  1316. });
  1317. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1318. APP.UI.setSubject(subject);
  1319. });
  1320. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1321. room.kickParticipant(id);
  1322. });
  1323. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1324. room.muteParticipant(id);
  1325. });
  1326. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1327. AuthHandler.authenticate(room);
  1328. });
  1329. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1330. try {
  1331. // do not try to select participant if there is none (we are
  1332. // alone in the room), otherwise an error will be thrown cause
  1333. // reporting mechanism is not available (datachannels currently)
  1334. if (room.getParticipants().length === 0)
  1335. return;
  1336. room.selectParticipant(id);
  1337. } catch (e) {
  1338. JitsiMeetJS.analytics.sendEvent('selectParticipant.failed');
  1339. reportError(e);
  1340. }
  1341. });
  1342. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1343. var smallVideoId = smallVideo.getId();
  1344. // FIXME why VIDEO_CONTAINER_TYPE instead of checking if
  1345. // the participant is on the large video ?
  1346. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1347. && !APP.conference.isLocalId(smallVideoId)) {
  1348. // When the library starts supporting multiple pins we would
  1349. // pass the isPinned parameter together with the identifier,
  1350. // but currently we send null to indicate that we unpin the
  1351. // last pinned.
  1352. try {
  1353. room.pinParticipant(isPinned ? smallVideoId : null);
  1354. } catch (e) {
  1355. reportError(e);
  1356. }
  1357. }
  1358. });
  1359. APP.UI.addListener(
  1360. UIEvents.VIDEO_DEVICE_CHANGED,
  1361. (cameraDeviceId) => {
  1362. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1363. createLocalTracks({
  1364. devices: ['video'],
  1365. cameraDeviceId: cameraDeviceId,
  1366. micDeviceId: null
  1367. })
  1368. .then(([stream]) => {
  1369. this.useVideoStream(stream);
  1370. console.log('switched local video device');
  1371. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1372. })
  1373. .catch((err) => {
  1374. APP.UI.showDeviceErrorDialog(null, err);
  1375. APP.UI.setSelectedCameraFromSettings();
  1376. });
  1377. }
  1378. );
  1379. APP.UI.addListener(
  1380. UIEvents.AUDIO_DEVICE_CHANGED,
  1381. (micDeviceId) => {
  1382. JitsiMeetJS.analytics.sendEvent(
  1383. 'settings.changeDevice.audioIn');
  1384. createLocalTracks({
  1385. devices: ['audio'],
  1386. cameraDeviceId: null,
  1387. micDeviceId: micDeviceId
  1388. })
  1389. .then(([stream]) => {
  1390. this.useAudioStream(stream);
  1391. console.log('switched local audio device');
  1392. APP.settings.setMicDeviceId(micDeviceId, true);
  1393. })
  1394. .catch((err) => {
  1395. APP.UI.showDeviceErrorDialog(err, null);
  1396. APP.UI.setSelectedMicFromSettings();
  1397. });
  1398. }
  1399. );
  1400. APP.UI.addListener(
  1401. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1402. (audioOutputDeviceId) => {
  1403. JitsiMeetJS.analytics.sendEvent(
  1404. 'settings.changeDevice.audioOut');
  1405. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1406. .then(() => console.log('changed audio output device'))
  1407. .catch((err) => {
  1408. console.warn('Failed to change audio output device. ' +
  1409. 'Default or previously set audio output device ' +
  1410. 'will be used instead.', err);
  1411. APP.UI.setSelectedAudioOutputFromSettings();
  1412. });
  1413. }
  1414. );
  1415. APP.UI.addListener(
  1416. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1417. );
  1418. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1419. (url, state, time, isMuted, volume) => {
  1420. // send start and stop commands once, and remove any updates
  1421. // that had left
  1422. if (state === 'stop' || state === 'start' || state === 'playing') {
  1423. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1424. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1425. value: url,
  1426. attributes: {
  1427. state: state,
  1428. time: time,
  1429. muted: isMuted,
  1430. volume: volume
  1431. }
  1432. });
  1433. }
  1434. else {
  1435. // in case of paused, in order to allow late users to join
  1436. // paused
  1437. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1438. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1439. value: url,
  1440. attributes: {
  1441. state: state,
  1442. time: time,
  1443. muted: isMuted,
  1444. volume: volume
  1445. }
  1446. });
  1447. }
  1448. });
  1449. room.addCommandListener(
  1450. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1451. if (attributes.state === 'stop') {
  1452. APP.UI.onSharedVideoStop(id, attributes);
  1453. }
  1454. else if (attributes.state === 'start') {
  1455. APP.UI.onSharedVideoStart(id, value, attributes);
  1456. }
  1457. else if (attributes.state === 'playing'
  1458. || attributes.state === 'pause') {
  1459. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1460. }
  1461. });
  1462. },
  1463. /**
  1464. * Adds any room listener.
  1465. * @param eventName one of the ConferenceEvents
  1466. * @param callBack the function to be called when the event occurs
  1467. */
  1468. addConferenceListener(eventName, callBack) {
  1469. room.on(eventName, callBack);
  1470. },
  1471. /**
  1472. * Inits list of current devices and event listener for device change.
  1473. * @private
  1474. */
  1475. _initDeviceList() {
  1476. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1477. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1478. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1479. // Ugly way to synchronize real device IDs with local
  1480. // storage and settings menu. This is a workaround until
  1481. // getConstraints() method will be implemented in browsers.
  1482. if (localAudio) {
  1483. APP.settings.setMicDeviceId(
  1484. localAudio.getDeviceId(), false);
  1485. }
  1486. if (localVideo) {
  1487. APP.settings.setCameraDeviceId(
  1488. localVideo.getDeviceId(), false);
  1489. }
  1490. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1491. APP.UI.onAvailableDevicesChanged(devices);
  1492. });
  1493. JitsiMeetJS.mediaDevices.addEventListener(
  1494. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1495. (devices) =>
  1496. window.setTimeout(
  1497. () => this._onDeviceListChanged(devices), 0));
  1498. }
  1499. },
  1500. /**
  1501. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1502. * handle change of available media devices.
  1503. * @private
  1504. * @param {MediaDeviceInfo[]} devices
  1505. * @returns {Promise}
  1506. */
  1507. _onDeviceListChanged(devices) {
  1508. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1509. // Event handler can be fired before direct
  1510. // enumerateDevices() call, so handle this situation here.
  1511. if (!currentDevices.audioinput &&
  1512. !currentDevices.videoinput &&
  1513. !currentDevices.audiooutput) {
  1514. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1515. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1516. }
  1517. let newDevices =
  1518. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1519. devices, this.isSharingScreen, localVideo, localAudio);
  1520. let promises = [];
  1521. let audioWasMuted = this.audioMuted;
  1522. let videoWasMuted = this.videoMuted;
  1523. let availableAudioInputDevices =
  1524. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1525. let availableVideoInputDevices =
  1526. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1527. if (typeof newDevices.audiooutput !== 'undefined') {
  1528. // Just ignore any errors in catch block.
  1529. promises.push(APP.settings
  1530. .setAudioOutputDeviceId(newDevices.audiooutput)
  1531. .catch());
  1532. }
  1533. promises.push(
  1534. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1535. createLocalTracks,
  1536. newDevices.videoinput,
  1537. newDevices.audioinput)
  1538. .then(tracks =>
  1539. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1540. .then(() => {
  1541. // If audio was muted before, or we unplugged current device
  1542. // and selected new one, then mute new audio track.
  1543. if (audioWasMuted ||
  1544. currentDevices.audioinput.length >
  1545. availableAudioInputDevices.length) {
  1546. muteLocalAudio(true);
  1547. }
  1548. // If video was muted before, or we unplugged current device
  1549. // and selected new one, then mute new video track.
  1550. if (videoWasMuted ||
  1551. currentDevices.videoinput.length >
  1552. availableVideoInputDevices.length) {
  1553. muteLocalVideo(true);
  1554. }
  1555. }));
  1556. return Promise.all(promises)
  1557. .then(() => {
  1558. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1559. APP.UI.onAvailableDevicesChanged(devices);
  1560. });
  1561. },
  1562. /**
  1563. * Toggles the local "raised hand" status.
  1564. */
  1565. maybeToggleRaisedHand() {
  1566. this.setRaisedHand(!this.isHandRaised);
  1567. },
  1568. /**
  1569. * Sets the local "raised hand" status to a particular value.
  1570. */
  1571. setRaisedHand(raisedHand) {
  1572. if (raisedHand !== this.isHandRaised)
  1573. {
  1574. APP.UI.onLocalRaiseHandChanged(raisedHand);
  1575. this.isHandRaised = raisedHand;
  1576. // Advertise the updated status
  1577. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1578. // Update the view
  1579. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1580. }
  1581. },
  1582. /**
  1583. * Log event to callstats and analytics.
  1584. * @param {string} name the event name
  1585. * @param {int} value the value (it's int because google analytics supports
  1586. * only int).
  1587. * NOTE: Should be used after conference.init
  1588. */
  1589. logEvent(name, value) {
  1590. if(JitsiMeetJS.analytics) {
  1591. JitsiMeetJS.analytics.sendEvent(name, value);
  1592. }
  1593. if(room) {
  1594. room.sendApplicationLog(JSON.stringify({name, value}));
  1595. }
  1596. },
  1597. /**
  1598. * Disconnect from the conference and optionally request user feedback.
  1599. * @param {boolean} [requestFeedback=false] if user feedback should be
  1600. * requested
  1601. */
  1602. hangup (requestFeedback = false) {
  1603. if (!conferenceLeftListener) {
  1604. conferenceLeftListener
  1605. = new HangupConferenceLeftListener(requestFeedback);
  1606. }
  1607. //FIXME: Do something for the use case when we are not receiving
  1608. // CONFERENCE_LEFT for some reason
  1609. room.leave();
  1610. }
  1611. };