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

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