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

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