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

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