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

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