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

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