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

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