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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. import { openConnection } from './connection';
  3. import AuthHandler from './modules/UI/authentication/AuthHandler';
  4. import Recorder from './modules/recorder/Recorder';
  5. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  6. import { reload, reportError } from './modules/util/helpers';
  7. import * as RemoteControlEvents
  8. from './service/remotecontrol/RemoteControlEvents';
  9. import UIEvents from './service/UI/UIEvents';
  10. import UIUtil from './modules/UI/util/UIUtil';
  11. import * as JitsiMeetConferenceEvents from './ConferenceEvents';
  12. import { initAnalytics, sendAnalyticsEvent } from './react/features/analytics';
  13. import EventEmitter from 'events';
  14. import {
  15. AVATAR_ID_COMMAND,
  16. AVATAR_URL_COMMAND,
  17. conferenceFailed,
  18. conferenceJoined,
  19. conferenceLeft,
  20. conferenceWillJoin,
  21. dataChannelOpened,
  22. EMAIL_COMMAND,
  23. lockStateChanged,
  24. p2pStatusChanged,
  25. sendLocalParticipant
  26. } from './react/features/base/conference';
  27. import { updateDeviceList } from './react/features/base/devices';
  28. import {
  29. isAnalyticsEnabled,
  30. isFatalJitsiConnectionError,
  31. JitsiConferenceErrors,
  32. JitsiConferenceEvents,
  33. JitsiConnectionErrors,
  34. JitsiConnectionEvents,
  35. JitsiMediaDevicesEvents,
  36. JitsiParticipantConnectionStatus,
  37. JitsiTrackErrors,
  38. JitsiTrackEvents
  39. } from './react/features/base/lib-jitsi-meet';
  40. import {
  41. isVideoMutedByUser,
  42. MEDIA_TYPE,
  43. setAudioAvailable,
  44. setAudioMuted,
  45. setVideoAvailable,
  46. setVideoMuted
  47. } from './react/features/base/media';
  48. import {
  49. dominantSpeakerChanged,
  50. getLocalParticipant,
  51. getParticipantById,
  52. localParticipantConnectionStatusChanged,
  53. localParticipantRoleChanged,
  54. MAX_DISPLAY_NAME_LENGTH,
  55. participantConnectionStatusChanged,
  56. participantJoined,
  57. participantLeft,
  58. participantPresenceChanged,
  59. participantRoleChanged,
  60. participantUpdated
  61. } from './react/features/base/participants';
  62. import {
  63. createLocalTracksF,
  64. isLocalTrackMuted,
  65. replaceLocalTrack,
  66. trackAdded,
  67. trackRemoved
  68. } from './react/features/base/tracks';
  69. import { getLocationContextRoot } from './react/features/base/util';
  70. import { statsEmitter } from './react/features/connection-indicator';
  71. import { showDesktopPicker } from './react/features/desktop-picker';
  72. import { maybeOpenFeedbackDialog } from './react/features/feedback';
  73. import {
  74. mediaPermissionPromptVisibilityChanged,
  75. suspendDetected
  76. } from './react/features/overlay';
  77. import {
  78. isButtonEnabled,
  79. showDesktopSharingButton
  80. } from './react/features/toolbox';
  81. const logger = require('jitsi-meet-logger').getLogger(__filename);
  82. const eventEmitter = new EventEmitter();
  83. let room;
  84. let connection;
  85. /*
  86. * Logic to open a desktop picker put on the window global for
  87. * lib-jitsi-meet to detect and invoke
  88. */
  89. window.JitsiMeetScreenObtainer = {
  90. openDesktopPicker(options, onSourceChoose) {
  91. APP.store.dispatch(showDesktopPicker(options, onSourceChoose));
  92. }
  93. };
  94. /**
  95. * Known custom conference commands.
  96. */
  97. const commands = {
  98. AVATAR_ID: AVATAR_ID_COMMAND,
  99. AVATAR_URL: AVATAR_URL_COMMAND,
  100. CUSTOM_ROLE: 'custom-role',
  101. EMAIL: EMAIL_COMMAND,
  102. ETHERPAD: 'etherpad',
  103. SHARED_VIDEO: 'shared-video'
  104. };
  105. /**
  106. * Open Connection. When authentication failed it shows auth dialog.
  107. * @param roomName the room name to use
  108. * @returns Promise<JitsiConnection>
  109. */
  110. function connect(roomName) {
  111. return openConnection({
  112. retry: true,
  113. roomName
  114. })
  115. .catch(err => {
  116. if (err === JitsiConnectionErrors.PASSWORD_REQUIRED) {
  117. APP.UI.notifyTokenAuthFailed();
  118. } else {
  119. APP.UI.notifyConnectionFailed(err);
  120. }
  121. throw err;
  122. });
  123. }
  124. /**
  125. * Share data to other users.
  126. * @param command the command
  127. * @param {string} value new value
  128. */
  129. function sendData(command, value) {
  130. if (!room) {
  131. return;
  132. }
  133. room.removeCommand(command);
  134. room.sendCommand(command, { value });
  135. }
  136. /**
  137. * Get user nickname by user id.
  138. * @param {string} id user id
  139. * @returns {string?} user nickname or undefined if user is unknown.
  140. */
  141. function getDisplayName(id) {
  142. const participant = getParticipantById(APP.store.getState(), id);
  143. return participant && participant.name;
  144. }
  145. /**
  146. * Mute or unmute local audio stream if it exists.
  147. * @param {boolean} muted - if audio stream should be muted or unmuted.
  148. */
  149. function muteLocalAudio(muted) {
  150. APP.store.dispatch(setAudioMuted(muted));
  151. }
  152. /**
  153. * Mute or unmute local video stream if it exists.
  154. * @param {boolean} muted if video stream should be muted or unmuted.
  155. *
  156. */
  157. function muteLocalVideo(muted) {
  158. APP.store.dispatch(setVideoMuted(muted));
  159. }
  160. /**
  161. * Check if the welcome page is enabled and redirects to it.
  162. * If requested show a thank you dialog before that.
  163. * If we have a close page enabled, redirect to it without
  164. * showing any other dialog.
  165. *
  166. * @param {object} options used to decide which particular close page to show
  167. * or if close page is disabled, whether we should show the thankyou dialog
  168. * @param {boolean} options.thankYouDialogVisible - whether we should
  169. * show thank you dialog
  170. * @param {boolean} options.feedbackSubmitted - whether feedback was submitted
  171. */
  172. function maybeRedirectToWelcomePage(options) {
  173. // if close page is enabled redirect to it, without further action
  174. if (config.enableClosePage) {
  175. const { isGuest } = APP.store.getState()['features/base/jwt'];
  176. // save whether current user is guest or not, before navigating
  177. // to close page
  178. window.sessionStorage.setItem('guest', isGuest);
  179. assignWindowLocationPathname(`static/${
  180. options.feedbackSubmitted ? 'close.html' : 'close2.html'}`);
  181. return;
  182. }
  183. // else: show thankYou dialog only if there is no feedback
  184. if (options.thankYouDialogVisible) {
  185. APP.UI.messageHandler.openMessageDialog(
  186. null, 'dialog.thankYou', { appName: interfaceConfig.APP_NAME });
  187. }
  188. // if Welcome page is enabled redirect to welcome page after 3 sec.
  189. if (config.enableWelcomePage) {
  190. setTimeout(
  191. () => {
  192. APP.settings.setWelcomePageEnabled(true);
  193. assignWindowLocationPathname('./');
  194. },
  195. 3000);
  196. }
  197. }
  198. /**
  199. * Assigns a specific pathname to window.location.pathname taking into account
  200. * the context root of the Web app.
  201. *
  202. * @param {string} pathname - The pathname to assign to
  203. * window.location.pathname. If the specified pathname is relative, the context
  204. * root of the Web app will be prepended to the specified pathname before
  205. * assigning it to window.location.pathname.
  206. * @return {void}
  207. */
  208. function assignWindowLocationPathname(pathname) {
  209. const windowLocation = window.location;
  210. let newPathname = pathname;
  211. if (!newPathname.startsWith('/')) {
  212. // A pathname equal to ./ specifies the current directory. It will be
  213. // fine but pointless to include it because contextRoot is the current
  214. // directory.
  215. newPathname.startsWith('./')
  216. && (newPathname = newPathname.substring(2));
  217. newPathname = getLocationContextRoot(windowLocation) + newPathname;
  218. }
  219. windowLocation.pathname = newPathname;
  220. }
  221. /**
  222. *
  223. */
  224. class ConferenceConnector {
  225. /**
  226. *
  227. */
  228. constructor(resolve, reject) {
  229. this._resolve = resolve;
  230. this._reject = reject;
  231. this.reconnectTimeout = null;
  232. room.on(JitsiConferenceEvents.CONFERENCE_JOINED,
  233. this._handleConferenceJoined.bind(this));
  234. room.on(JitsiConferenceEvents.CONFERENCE_FAILED,
  235. this._onConferenceFailed.bind(this));
  236. room.on(JitsiConferenceEvents.CONFERENCE_ERROR,
  237. this._onConferenceError.bind(this));
  238. }
  239. /**
  240. *
  241. */
  242. _handleConferenceFailed(err) {
  243. this._unsubscribe();
  244. this._reject(err);
  245. }
  246. /**
  247. *
  248. */
  249. _onConferenceFailed(err, ...params) {
  250. APP.store.dispatch(conferenceFailed(room, err, ...params));
  251. logger.error('CONFERENCE FAILED:', err, ...params);
  252. switch (err) {
  253. case JitsiConferenceErrors.CONNECTION_ERROR: {
  254. const [ msg ] = params;
  255. APP.UI.notifyConnectionFailed(msg);
  256. break;
  257. }
  258. case JitsiConferenceErrors.NOT_ALLOWED_ERROR: {
  259. // let's show some auth not allowed page
  260. assignWindowLocationPathname('static/authError.html');
  261. break;
  262. }
  263. // not enough rights to create conference
  264. case JitsiConferenceErrors.AUTHENTICATION_REQUIRED: {
  265. // Schedule reconnect to check if someone else created the room.
  266. this.reconnectTimeout = setTimeout(() => room.join(), 5000);
  267. const { password }
  268. = APP.store.getState()['features/base/conference'];
  269. AuthHandler.requireAuth(room, password);
  270. break;
  271. }
  272. case JitsiConferenceErrors.RESERVATION_ERROR: {
  273. const [ code, msg ] = params;
  274. APP.UI.notifyReservationError(code, msg);
  275. break;
  276. }
  277. case JitsiConferenceErrors.GRACEFUL_SHUTDOWN:
  278. APP.UI.notifyGracefulShutdown();
  279. break;
  280. case JitsiConferenceErrors.JINGLE_FATAL_ERROR: {
  281. const [ error ] = params;
  282. APP.UI.notifyInternalError(error);
  283. break;
  284. }
  285. case JitsiConferenceErrors.CONFERENCE_DESTROYED: {
  286. const [ reason ] = params;
  287. APP.UI.hideStats();
  288. APP.UI.notifyConferenceDestroyed(reason);
  289. break;
  290. }
  291. // FIXME FOCUS_DISCONNECTED is a confusing event name.
  292. // What really happens there is that the library is not ready yet,
  293. // because Jicofo is not available, but it is going to give it another
  294. // try.
  295. case JitsiConferenceErrors.FOCUS_DISCONNECTED: {
  296. const [ focus, retrySec ] = params;
  297. APP.UI.notifyFocusDisconnected(focus, retrySec);
  298. break;
  299. }
  300. case JitsiConferenceErrors.FOCUS_LEFT:
  301. case JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  302. // FIXME the conference should be stopped by the library and not by
  303. // the app. Both the errors above are unrecoverable from the library
  304. // perspective.
  305. room.leave().then(() => connection.disconnect());
  306. break;
  307. case JitsiConferenceErrors.CONFERENCE_MAX_USERS:
  308. connection.disconnect();
  309. APP.UI.notifyMaxUsersLimitReached();
  310. break;
  311. case JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  312. reload();
  313. break;
  314. default:
  315. this._handleConferenceFailed(err, ...params);
  316. }
  317. }
  318. /**
  319. *
  320. */
  321. _onConferenceError(err, ...params) {
  322. logger.error('CONFERENCE Error:', err, params);
  323. switch (err) {
  324. case JitsiConferenceErrors.CHAT_ERROR:
  325. logger.error('Chat error.', err);
  326. if (isButtonEnabled('chat')) {
  327. const [ code, msg ] = params;
  328. APP.UI.showChatError(code, msg);
  329. }
  330. break;
  331. default:
  332. logger.error('Unknown error.', err);
  333. }
  334. }
  335. /**
  336. *
  337. */
  338. _unsubscribe() {
  339. room.off(
  340. JitsiConferenceEvents.CONFERENCE_JOINED,
  341. this._handleConferenceJoined);
  342. room.off(
  343. JitsiConferenceEvents.CONFERENCE_FAILED,
  344. this._onConferenceFailed);
  345. if (this.reconnectTimeout !== null) {
  346. clearTimeout(this.reconnectTimeout);
  347. }
  348. AuthHandler.closeAuth();
  349. }
  350. /**
  351. *
  352. */
  353. _handleConferenceJoined() {
  354. this._unsubscribe();
  355. this._resolve();
  356. }
  357. /**
  358. *
  359. */
  360. connect() {
  361. room.join();
  362. }
  363. }
  364. /**
  365. * Disconnects the connection.
  366. * @returns resolved Promise. We need this in order to make the Promise.all
  367. * call in hangup() to resolve when all operations are finished.
  368. */
  369. function disconnect() {
  370. connection.disconnect();
  371. APP.API.notifyConferenceLeft(APP.conference.roomName);
  372. return Promise.resolve();
  373. }
  374. /**
  375. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  376. *
  377. * @param {JitsiConnectionError} error - The reported error.
  378. * @returns {void}
  379. * @private
  380. */
  381. function _connectionFailedHandler(error) {
  382. if (isFatalJitsiConnectionError(error)) {
  383. APP.connection.removeEventListener(
  384. JitsiConnectionEvents.CONNECTION_FAILED,
  385. _connectionFailedHandler);
  386. if (room) {
  387. room.leave();
  388. }
  389. }
  390. }
  391. export default {
  392. /**
  393. * Flag used to delay modification of the muted status of local media tracks
  394. * until those are created (or not, but at that point it's certain that
  395. * the tracks won't exist).
  396. */
  397. _localTracksInitialized: false,
  398. isModerator: false,
  399. isSharingScreen: false,
  400. /**
  401. * Indicates if the desktop sharing functionality has been enabled.
  402. * It takes into consideration {@link isDesktopSharingDisabledByConfig}
  403. * as well as the status returned by
  404. * {@link JitsiMeetJS.isDesktopSharingEnabled()}. The latter can be false
  405. * either if the desktop sharing is not supported by the current browser
  406. * or if it was disabled through lib-jitsi-meet specific options (check
  407. * config.js for listed options).
  408. */
  409. isDesktopSharingEnabled: false,
  410. /**
  411. * Set to <tt>true</tt> if the desktop sharing functionality has been
  412. * explicitly disabled in the config.
  413. */
  414. isDesktopSharingDisabledByConfig: false,
  415. /**
  416. * The text displayed when the desktop sharing button is disabled through
  417. * the config. The value is set through
  418. * {@link interfaceConfig.DESKTOP_SHARING_BUTTON_DISABLED_TOOLTIP}.
  419. */
  420. desktopSharingDisabledTooltip: null,
  421. /*
  422. * Whether the local "raisedHand" flag is on.
  423. */
  424. isHandRaised: false,
  425. /*
  426. * Whether the local participant is the dominant speaker in the conference.
  427. */
  428. isDominantSpeaker: false,
  429. /**
  430. * The local audio track (if any).
  431. * FIXME tracks from redux store should be the single source of truth
  432. * @type {JitsiLocalTrack|null}
  433. */
  434. localAudio: null,
  435. /**
  436. * The local video track (if any).
  437. * FIXME tracks from redux store should be the single source of truth, but
  438. * more refactoring is required around screen sharing ('localVideo' usages).
  439. * @type {JitsiLocalTrack|null}
  440. */
  441. localVideo: null,
  442. /**
  443. * Creates local media tracks and connects to a room. Will show error
  444. * dialogs in case accessing the local microphone and/or camera failed. Will
  445. * show guidance overlay for users on how to give access to camera and/or
  446. * microphone.
  447. * @param {string} roomName
  448. * @param {object} options
  449. * @param {boolean} options.startAudioOnly=false - if <tt>true</tt> then
  450. * only audio track will be created and the audio only mode will be turned
  451. * on.
  452. * @param {boolean} options.startScreenSharing=false - if <tt>true</tt>
  453. * should start with screensharing instead of camera video.
  454. * @param {boolean} options.startWithAudioMuted - will start the conference
  455. * without any audio tracks.
  456. * @param {boolean} options.startWithVideoMuted - will start the conference
  457. * without any video tracks.
  458. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  459. */
  460. createInitialLocalTracksAndConnect(roomName, options = {}) {
  461. let audioAndVideoError,
  462. audioOnlyError,
  463. screenSharingError,
  464. videoOnlyError;
  465. const initialDevices = [];
  466. let requestedAudio = false;
  467. let requestedVideo = false;
  468. if (!options.startWithAudioMuted) {
  469. initialDevices.push('audio');
  470. requestedAudio = true;
  471. }
  472. if (!options.startWithVideoMuted
  473. && !options.startAudioOnly
  474. && !options.startScreenSharing) {
  475. initialDevices.push('video');
  476. requestedVideo = true;
  477. }
  478. JitsiMeetJS.mediaDevices.addEventListener(
  479. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  480. browser =>
  481. APP.store.dispatch(
  482. mediaPermissionPromptVisibilityChanged(true, browser))
  483. );
  484. let tryCreateLocalTracks;
  485. // FIXME is there any simpler way to rewrite this spaghetti below ?
  486. if (options.startScreenSharing) {
  487. tryCreateLocalTracks = this._createDesktopTrack()
  488. .then(desktopStream => {
  489. if (!requestedAudio) {
  490. return [ desktopStream ];
  491. }
  492. return createLocalTracksF({ devices: [ 'audio' ] }, true)
  493. .then(([ audioStream ]) =>
  494. [ desktopStream, audioStream ])
  495. .catch(error => {
  496. audioOnlyError = error;
  497. return [ desktopStream ];
  498. });
  499. })
  500. .catch(error => {
  501. logger.error('Failed to obtain desktop stream', error);
  502. screenSharingError = error;
  503. return requestedAudio
  504. ? createLocalTracksF({ devices: [ 'audio' ] }, true)
  505. : [];
  506. })
  507. .catch(error => {
  508. audioOnlyError = error;
  509. return [];
  510. });
  511. } else if (!requestedAudio && !requestedVideo) {
  512. // Resolve with no tracks
  513. tryCreateLocalTracks = Promise.resolve([]);
  514. } else {
  515. tryCreateLocalTracks = createLocalTracksF(
  516. { devices: initialDevices }, true)
  517. .catch(err => {
  518. if (requestedAudio && requestedVideo) {
  519. // Try audio only...
  520. audioAndVideoError = err;
  521. return (
  522. createLocalTracksF({ devices: [ 'audio' ] }, true));
  523. } else if (requestedAudio && !requestedVideo) {
  524. audioOnlyError = err;
  525. return [];
  526. } else if (requestedVideo && !requestedAudio) {
  527. videoOnlyError = err;
  528. return [];
  529. }
  530. logger.error('Should never happen');
  531. })
  532. .catch(err => {
  533. // Log this just in case...
  534. if (!requestedAudio) {
  535. logger.error('The impossible just happened', err);
  536. }
  537. audioOnlyError = err;
  538. // Try video only...
  539. return requestedVideo
  540. ? createLocalTracksF({ devices: [ 'video' ] }, true)
  541. : [];
  542. })
  543. .catch(err => {
  544. // Log this just in case...
  545. if (!requestedVideo) {
  546. logger.error('The impossible just happened', err);
  547. }
  548. videoOnlyError = err;
  549. return [];
  550. });
  551. }
  552. // Hide the permissions prompt/overlay as soon as the tracks are
  553. // created. Don't wait for the connection to be made, since in some
  554. // cases, when auth is rquired, for instance, that won't happen until
  555. // the user inputs their credentials, but the dialog would be
  556. // overshadowed by the overlay.
  557. tryCreateLocalTracks.then(() =>
  558. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false)));
  559. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  560. .then(([ tracks, con ]) => {
  561. // FIXME If there will be microphone error it will cover any
  562. // screensharing dialog, but it's still better than in
  563. // the reverse order where the screensharing dialog will
  564. // sometimes be closing the microphone alert ($.prompt.close();
  565. // is called). Need to figure out dialogs chaining to fix that.
  566. if (screenSharingError) {
  567. this._handleScreenSharingError(screenSharingError);
  568. }
  569. if (audioAndVideoError || audioOnlyError) {
  570. if (audioOnlyError || videoOnlyError) {
  571. // If both requests for 'audio' + 'video' and 'audio'
  572. // only failed, we assume that there are some problems
  573. // with user's microphone and show corresponding dialog.
  574. APP.UI.showMicErrorNotification(audioOnlyError);
  575. APP.UI.showCameraErrorNotification(videoOnlyError);
  576. } else {
  577. // If request for 'audio' + 'video' failed, but request
  578. // for 'audio' only was OK, we assume that we had
  579. // problems with camera and show corresponding dialog.
  580. APP.UI.showCameraErrorNotification(audioAndVideoError);
  581. }
  582. }
  583. return [ tracks, con ];
  584. });
  585. },
  586. /**
  587. * Open new connection and join to the conference.
  588. * @param {object} options
  589. * @param {string} roomName name of the conference
  590. * @returns {Promise}
  591. */
  592. init(options) {
  593. this.roomName = options.roomName;
  594. // attaches global error handler, if there is already one, respect it
  595. if (JitsiMeetJS.getGlobalOnErrorHandler) {
  596. const oldOnErrorHandler = window.onerror;
  597. // eslint-disable-next-line max-params
  598. window.onerror = (message, source, lineno, colno, error) => {
  599. JitsiMeetJS.getGlobalOnErrorHandler(
  600. message, source, lineno, colno, error);
  601. if (oldOnErrorHandler) {
  602. oldOnErrorHandler(message, source, lineno, colno, error);
  603. }
  604. };
  605. const oldOnUnhandledRejection = window.onunhandledrejection;
  606. window.onunhandledrejection = function(event) {
  607. JitsiMeetJS.getGlobalOnErrorHandler(
  608. null, null, null, null, event.reason);
  609. if (oldOnUnhandledRejection) {
  610. oldOnUnhandledRejection(event);
  611. }
  612. };
  613. }
  614. return (
  615. JitsiMeetJS.init({
  616. enableAnalyticsLogging: isAnalyticsEnabled(APP.store),
  617. ...config
  618. }).then(() => {
  619. initAnalytics(APP.store);
  620. return this.createInitialLocalTracksAndConnect(
  621. options.roomName, {
  622. startAudioOnly: config.startAudioOnly,
  623. startScreenSharing: config.startScreenSharing,
  624. startWithAudioMuted: config.startWithAudioMuted,
  625. startWithVideoMuted: config.startWithVideoMuted
  626. });
  627. })
  628. .then(([ tracks, con ]) => {
  629. tracks.forEach(track => {
  630. if (track.isAudioTrack() && this.isLocalAudioMuted()) {
  631. sendAnalyticsEvent('conference.audio.initiallyMuted');
  632. logger.log('Audio mute: initially muted');
  633. track.mute();
  634. } else if (track.isVideoTrack()
  635. && this.isLocalVideoMuted()) {
  636. sendAnalyticsEvent('conference.video.initiallyMuted');
  637. logger.log('Video mute: initially muted');
  638. track.mute();
  639. }
  640. });
  641. logger.log('initialized with %s local tracks', tracks.length);
  642. this._localTracksInitialized = true;
  643. con.addEventListener(
  644. JitsiConnectionEvents.CONNECTION_FAILED,
  645. _connectionFailedHandler);
  646. APP.connection = connection = con;
  647. // Desktop sharing related stuff:
  648. this.isDesktopSharingDisabledByConfig
  649. = config.disableDesktopSharing;
  650. this.isDesktopSharingEnabled
  651. = !this.isDesktopSharingDisabledByConfig
  652. && JitsiMeetJS.isDesktopSharingEnabled();
  653. this.desktopSharingDisabledTooltip
  654. = interfaceConfig.DESKTOP_SHARING_BUTTON_DISABLED_TOOLTIP;
  655. eventEmitter.emit(
  656. JitsiMeetConferenceEvents.DESKTOP_SHARING_ENABLED_CHANGED,
  657. this.isDesktopSharingEnabled);
  658. APP.store.dispatch(showDesktopSharingButton());
  659. this._createRoom(tracks);
  660. APP.remoteControl.init();
  661. // if user didn't give access to mic or camera or doesn't have
  662. // them at all, we mark corresponding toolbar buttons as muted,
  663. // so that the user can try unmute later on and add audio/video
  664. // to the conference
  665. if (!tracks.find(t => t.isAudioTrack())) {
  666. this.setAudioMuteStatus(true);
  667. }
  668. if (!tracks.find(t => t.isVideoTrack())) {
  669. this.setVideoMuteStatus(true);
  670. }
  671. this._initDeviceList();
  672. if (config.iAmRecorder) {
  673. this.recorder = new Recorder();
  674. }
  675. // XXX The API will take care of disconnecting from the XMPP
  676. // server (and, thus, leaving the room) on unload.
  677. return new Promise((resolve, reject) => {
  678. (new ConferenceConnector(resolve, reject)).connect();
  679. });
  680. })
  681. );
  682. },
  683. /**
  684. * Check if id is id of the local user.
  685. * @param {string} id id to check
  686. * @returns {boolean}
  687. */
  688. isLocalId(id) {
  689. return this.getMyUserId() === id;
  690. },
  691. /**
  692. * Tells whether the local video is muted or not.
  693. * @return {boolean}
  694. */
  695. isLocalVideoMuted() {
  696. // If the tracks are not ready, read from base/media state
  697. return this._localTracksInitialized
  698. ? isLocalTrackMuted(
  699. APP.store.getState()['features/base/tracks'],
  700. MEDIA_TYPE.VIDEO)
  701. : isVideoMutedByUser(APP.store);
  702. },
  703. /**
  704. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  705. * @param {boolean} mute true for mute and false for unmute.
  706. * @param {boolean} [showUI] when set to false will not display any error
  707. * dialogs in case of media permissions error.
  708. */
  709. muteAudio(mute, showUI = true) {
  710. // Not ready to modify track's state yet
  711. if (!this._localTracksInitialized) {
  712. // This will only modify base/media.audio.muted which is then synced
  713. // up with the track at the end of local tracks initialization.
  714. muteLocalAudio(mute);
  715. this.setAudioMuteStatus(mute);
  716. return;
  717. } else if (this.isLocalAudioMuted() === mute) {
  718. // NO-OP
  719. return;
  720. }
  721. if (!this.localAudio && !mute) {
  722. const maybeShowErrorDialog = error => {
  723. showUI && APP.UI.showMicErrorNotification(error);
  724. };
  725. createLocalTracksF({ devices: [ 'audio' ] }, false)
  726. .then(([ audioTrack ]) => audioTrack)
  727. .catch(error => {
  728. maybeShowErrorDialog(error);
  729. // Rollback the audio muted status by using null track
  730. return null;
  731. })
  732. .then(audioTrack => this.useAudioStream(audioTrack));
  733. } else {
  734. muteLocalAudio(mute);
  735. }
  736. },
  737. /**
  738. * Returns whether local audio is muted or not.
  739. * @returns {boolean}
  740. */
  741. isLocalAudioMuted() {
  742. // If the tracks are not ready, read from base/media state
  743. return this._localTracksInitialized
  744. ? isLocalTrackMuted(
  745. APP.store.getState()['features/base/tracks'],
  746. MEDIA_TYPE.AUDIO)
  747. : Boolean(
  748. APP.store.getState()['features/base/media'].audio.muted);
  749. },
  750. /**
  751. * Simulates toolbar button click for audio mute. Used by shortcuts
  752. * and API.
  753. * @param {boolean} [showUI] when set to false will not display any error
  754. * dialogs in case of media permissions error.
  755. */
  756. toggleAudioMuted(showUI = true) {
  757. this.muteAudio(!this.isLocalAudioMuted(), showUI);
  758. },
  759. /**
  760. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  761. * @param mute true for mute and false for unmute.
  762. * @param {boolean} [showUI] when set to false will not display any error
  763. * dialogs in case of media permissions error.
  764. */
  765. muteVideo(mute, showUI = true) {
  766. // If not ready to modify track's state yet adjust the base/media
  767. if (!this._localTracksInitialized) {
  768. // This will only modify base/media.video.muted which is then synced
  769. // up with the track at the end of local tracks initialization.
  770. muteLocalVideo(mute);
  771. this.setVideoMuteStatus(mute);
  772. return;
  773. } else if (this.isLocalVideoMuted() === mute) {
  774. // NO-OP
  775. return;
  776. }
  777. // FIXME it is possible to queue this task twice, but it's not causing
  778. // any issues. Specifically this can happen when the previous
  779. // get user media call is blocked on "ask user for permissions" dialog.
  780. if (!this.localVideo && !mute) {
  781. const maybeShowErrorDialog = error => {
  782. showUI && APP.UI.showCameraErrorNotification(error);
  783. };
  784. // Try to create local video if there wasn't any.
  785. // This handles the case when user joined with no video
  786. // (dismissed screen sharing screen or in audio only mode), but
  787. // decided to add it later on by clicking on muted video icon or
  788. // turning off the audio only mode.
  789. //
  790. // FIXME when local track creation is moved to react/redux
  791. // it should take care of the use case described above
  792. createLocalTracksF({ devices: [ 'video' ] }, false)
  793. .then(([ videoTrack ]) => videoTrack)
  794. .catch(error => {
  795. // FIXME should send some feedback to the API on error ?
  796. maybeShowErrorDialog(error);
  797. // Rollback the video muted status by using null track
  798. return null;
  799. })
  800. .then(videoTrack => this.useVideoStream(videoTrack));
  801. } else {
  802. // FIXME show error dialog if it fails (should be handled by react)
  803. muteLocalVideo(mute);
  804. }
  805. },
  806. /**
  807. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  808. * @param {boolean} [showUI] when set to false will not display any error
  809. * dialogs in case of media permissions error.
  810. */
  811. toggleVideoMuted(showUI = true) {
  812. this.muteVideo(!this.isLocalVideoMuted(), showUI);
  813. },
  814. /**
  815. * Retrieve list of conference participants (without local user).
  816. * @returns {JitsiParticipant[]}
  817. */
  818. listMembers() {
  819. return room.getParticipants();
  820. },
  821. /**
  822. * Retrieve list of ids of conference participants (without local user).
  823. * @returns {string[]}
  824. */
  825. listMembersIds() {
  826. return room.getParticipants().map(p => p.getId());
  827. },
  828. /**
  829. * Checks whether the participant identified by id is a moderator.
  830. * @id id to search for participant
  831. * @return {boolean} whether the participant is moderator
  832. */
  833. isParticipantModerator(id) {
  834. const user = room.getParticipantById(id);
  835. return user && user.isModerator();
  836. },
  837. get membersCount() {
  838. return room.getParticipants().length + 1;
  839. },
  840. /**
  841. * Returns true if the callstats integration is enabled, otherwise returns
  842. * false.
  843. *
  844. * @returns true if the callstats integration is enabled, otherwise returns
  845. * false.
  846. */
  847. isCallstatsEnabled() {
  848. return room && room.isCallstatsEnabled();
  849. },
  850. /**
  851. * Sends the given feedback through CallStats if enabled.
  852. *
  853. * @param overallFeedback an integer between 1 and 5 indicating the
  854. * user feedback
  855. * @param detailedFeedback detailed feedback from the user. Not yet used
  856. */
  857. sendFeedback(overallFeedback, detailedFeedback) {
  858. return room.sendFeedback(overallFeedback, detailedFeedback);
  859. },
  860. /**
  861. * Get speaker stats that track total dominant speaker time.
  862. *
  863. * @returns {object} A hash with keys being user ids and values being the
  864. * library's SpeakerStats model used for calculating time as dominant
  865. * speaker.
  866. */
  867. getSpeakerStats() {
  868. return room.getSpeakerStats();
  869. },
  870. /**
  871. * Returns the connection times stored in the library.
  872. */
  873. getConnectionTimes() {
  874. return this._room.getConnectionTimes();
  875. },
  876. // used by torture currently
  877. isJoined() {
  878. return this._room
  879. && this._room.isJoined();
  880. },
  881. getConnectionState() {
  882. return this._room
  883. && this._room.getConnectionState();
  884. },
  885. /**
  886. * Obtains current P2P ICE connection state.
  887. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  888. * P2P connection
  889. */
  890. getP2PConnectionState() {
  891. return this._room
  892. && this._room.getP2PConnectionState();
  893. },
  894. /**
  895. * Starts P2P (for tests only)
  896. * @private
  897. */
  898. _startP2P() {
  899. try {
  900. this._room && this._room.startP2PSession();
  901. } catch (error) {
  902. logger.error('Start P2P failed', error);
  903. throw error;
  904. }
  905. },
  906. /**
  907. * Stops P2P (for tests only)
  908. * @private
  909. */
  910. _stopP2P() {
  911. try {
  912. this._room && this._room.stopP2PSession();
  913. } catch (error) {
  914. logger.error('Stop P2P failed', error);
  915. throw error;
  916. }
  917. },
  918. /**
  919. * Checks whether or not our connection is currently in interrupted and
  920. * reconnect attempts are in progress.
  921. *
  922. * @returns {boolean} true if the connection is in interrupted state or
  923. * false otherwise.
  924. */
  925. isConnectionInterrupted() {
  926. return this._room.isConnectionInterrupted();
  927. },
  928. /**
  929. * Obtains the local display name.
  930. * @returns {string|undefined}
  931. */
  932. getLocalDisplayName() {
  933. return getDisplayName(this.getMyUserId());
  934. },
  935. /**
  936. * Finds JitsiParticipant for given id.
  937. *
  938. * @param {string} id participant's identifier(MUC nickname).
  939. *
  940. * @returns {JitsiParticipant|null} participant instance for given id or
  941. * null if not found.
  942. */
  943. getParticipantById(id) {
  944. return room ? room.getParticipantById(id) : null;
  945. },
  946. /**
  947. * Get participant connection status for the participant.
  948. *
  949. * @param {string} id participant's identifier(MUC nickname)
  950. *
  951. * @returns {ParticipantConnectionStatus|null} the status of the participant
  952. * or null if no such participant is found or participant is the local user.
  953. */
  954. getParticipantConnectionStatus(id) {
  955. const participant = this.getParticipantById(id);
  956. return participant ? participant.getConnectionStatus() : null;
  957. },
  958. /**
  959. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  960. * the given <tt>id</tt>.
  961. *
  962. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  963. *
  964. * @return {string} the participant's display name or the default string if
  965. * absent.
  966. */
  967. getParticipantDisplayName(id) {
  968. const displayName = getDisplayName(id);
  969. if (displayName) {
  970. return displayName;
  971. }
  972. if (APP.conference.isLocalId(id)) {
  973. return APP.translation.generateTranslationHTML(
  974. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  975. }
  976. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  977. },
  978. getMyUserId() {
  979. return this._room && this._room.myUserId();
  980. },
  981. /**
  982. * Indicates if recording is supported in this conference.
  983. */
  984. isRecordingSupported() {
  985. return this._room && this._room.isRecordingSupported();
  986. },
  987. /**
  988. * Returns the recording state or undefined if the room is not defined.
  989. */
  990. getRecordingState() {
  991. return this._room ? this._room.getRecordingState() : undefined;
  992. },
  993. /**
  994. * Will be filled with values only when config.debug is enabled.
  995. * Its used by torture to check audio levels.
  996. */
  997. audioLevelsMap: {},
  998. /**
  999. * Returns the stored audio level (stored only if config.debug is enabled)
  1000. * @param id the id for the user audio level to return (the id value is
  1001. * returned for the participant using getMyUserId() method)
  1002. */
  1003. getPeerSSRCAudioLevel(id) {
  1004. return this.audioLevelsMap[id];
  1005. },
  1006. /**
  1007. * @return {number} the number of participants in the conference with at
  1008. * least one track.
  1009. */
  1010. getNumberOfParticipantsWithTracks() {
  1011. return this._room.getParticipants()
  1012. .filter(p => p.getTracks().length > 0)
  1013. .length;
  1014. },
  1015. /**
  1016. * Returns the stats.
  1017. */
  1018. getStats() {
  1019. return room.connectionQuality.getStats();
  1020. },
  1021. // end used by torture
  1022. getLogs() {
  1023. return room.getLogs();
  1024. },
  1025. /**
  1026. * Download logs, a function that can be called from console while
  1027. * debugging.
  1028. * @param filename (optional) specify target filename
  1029. */
  1030. saveLogs(filename = 'meetlog.json') {
  1031. // this can be called from console and will not have reference to this
  1032. // that's why we reference the global var
  1033. const logs = APP.conference.getLogs();
  1034. const data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  1035. const elem = document.createElement('a');
  1036. elem.download = filename;
  1037. elem.href = `data:application/json;charset=utf-8,\n${data}`;
  1038. elem.dataset.downloadurl
  1039. = [ 'text/json', elem.download, elem.href ].join(':');
  1040. elem.dispatchEvent(new MouseEvent('click', {
  1041. view: window,
  1042. bubbles: true,
  1043. cancelable: false
  1044. }));
  1045. },
  1046. /**
  1047. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  1048. * desire to keep room private to this instance and (2) the need of other
  1049. * modules to send and receive commands to and from participants.
  1050. * Eventually, this instance remains in control with respect to the
  1051. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  1052. * JitsiConference) is to be used in the implementation of the Command(s)
  1053. * API of this instance.
  1054. */
  1055. commands: {
  1056. /**
  1057. * Known custom conference commands.
  1058. */
  1059. defaults: commands,
  1060. /**
  1061. * Receives notifications from other participants about commands aka
  1062. * custom events (sent by sendCommand or sendCommandOnce methods).
  1063. * @param command {String} the name of the command
  1064. * @param handler {Function} handler for the command
  1065. */
  1066. addCommandListener() {
  1067. // eslint-disable-next-line prefer-rest-params
  1068. room.addCommandListener(...arguments);
  1069. },
  1070. /**
  1071. * Removes command.
  1072. * @param name {String} the name of the command.
  1073. */
  1074. removeCommand() {
  1075. // eslint-disable-next-line prefer-rest-params
  1076. room.removeCommand(...arguments);
  1077. },
  1078. /**
  1079. * Sends command.
  1080. * @param name {String} the name of the command.
  1081. * @param values {Object} with keys and values that will be sent.
  1082. */
  1083. sendCommand() {
  1084. // eslint-disable-next-line prefer-rest-params
  1085. room.sendCommand(...arguments);
  1086. },
  1087. /**
  1088. * Sends command one time.
  1089. * @param name {String} the name of the command.
  1090. * @param values {Object} with keys and values that will be sent.
  1091. */
  1092. sendCommandOnce() {
  1093. // eslint-disable-next-line prefer-rest-params
  1094. room.sendCommandOnce(...arguments);
  1095. }
  1096. },
  1097. _createRoom(localTracks) {
  1098. room
  1099. = connection.initJitsiConference(
  1100. APP.conference.roomName,
  1101. this._getConferenceOptions());
  1102. APP.store.dispatch(conferenceWillJoin(room));
  1103. this._setLocalAudioVideoStreams(localTracks);
  1104. this._room = room; // FIXME do not use this
  1105. sendLocalParticipant(APP.store, room);
  1106. this._setupListeners();
  1107. },
  1108. /**
  1109. * Sets local video and audio streams.
  1110. * @param {JitsiLocalTrack[]} tracks=[]
  1111. * @returns {Promise[]}
  1112. * @private
  1113. */
  1114. _setLocalAudioVideoStreams(tracks = []) {
  1115. return tracks.map(track => {
  1116. if (track.isAudioTrack()) {
  1117. return this.useAudioStream(track);
  1118. } else if (track.isVideoTrack()) {
  1119. return this.useVideoStream(track);
  1120. }
  1121. logger.error(
  1122. 'Ignored not an audio nor a video track: ', track);
  1123. return Promise.resolve();
  1124. });
  1125. },
  1126. _getConferenceOptions() {
  1127. const options = config;
  1128. if (config.enableRecording && !config.recordingType) {
  1129. options.recordingType
  1130. = config.hosts && (typeof config.hosts.jirecon !== 'undefined')
  1131. ? 'jirecon'
  1132. : 'colibri';
  1133. }
  1134. const nick = APP.settings.getDisplayName();
  1135. if (nick) {
  1136. options.displayName = nick;
  1137. }
  1138. options.applicationName = interfaceConfig.APP_NAME;
  1139. return options;
  1140. },
  1141. /**
  1142. * Start using provided video stream.
  1143. * Stops previous video stream.
  1144. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1145. * @returns {Promise}
  1146. */
  1147. useVideoStream(newStream) {
  1148. return APP.store.dispatch(
  1149. replaceLocalTrack(this.localVideo, newStream, room))
  1150. .then(() => {
  1151. this.localVideo = newStream;
  1152. if (newStream) {
  1153. this.isSharingScreen = newStream.videoType === 'desktop';
  1154. APP.UI.addLocalStream(newStream);
  1155. } else {
  1156. this.isSharingScreen = false;
  1157. }
  1158. this.setVideoMuteStatus(this.isLocalVideoMuted());
  1159. APP.UI.updateDesktopSharingButtons();
  1160. });
  1161. },
  1162. /**
  1163. * Start using provided audio stream.
  1164. * Stops previous audio stream.
  1165. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1166. * @returns {Promise}
  1167. */
  1168. useAudioStream(newStream) {
  1169. return APP.store.dispatch(
  1170. replaceLocalTrack(this.localAudio, newStream, room))
  1171. .then(() => {
  1172. this.localAudio = newStream;
  1173. if (newStream) {
  1174. APP.UI.addLocalStream(newStream);
  1175. }
  1176. this.setAudioMuteStatus(this.isLocalAudioMuted());
  1177. });
  1178. },
  1179. /**
  1180. * Triggers a tooltip to display when a feature was attempted to be used
  1181. * while in audio only mode.
  1182. *
  1183. * @param {string} featureName - The name of the feature that attempted to
  1184. * toggle.
  1185. * @private
  1186. * @returns {void}
  1187. */
  1188. _displayAudioOnlyTooltip(featureName) {
  1189. let buttonName = null;
  1190. let tooltipElementId = null;
  1191. switch (featureName) {
  1192. case 'screenShare':
  1193. buttonName = 'desktop';
  1194. tooltipElementId = 'screenshareWhileAudioOnly';
  1195. break;
  1196. case 'videoMute':
  1197. buttonName = 'camera';
  1198. tooltipElementId = 'unmuteWhileAudioOnly';
  1199. break;
  1200. }
  1201. if (tooltipElementId) {
  1202. APP.UI.showToolbar(6000);
  1203. APP.UI.showCustomToolbarPopup(
  1204. buttonName, tooltipElementId, true, 5000);
  1205. }
  1206. },
  1207. /**
  1208. * Returns whether or not the conference is currently in audio only mode.
  1209. *
  1210. * @returns {boolean}
  1211. */
  1212. isAudioOnly() {
  1213. return Boolean(
  1214. APP.store.getState()['features/base/conference'].audioOnly);
  1215. },
  1216. videoSwitchInProgress: false,
  1217. /**
  1218. * This fields stores a handler which will create a Promise which turns off
  1219. * the screen sharing and restores the previous video state (was there
  1220. * any video, before switching to screen sharing ? was it muted ?).
  1221. *
  1222. * Once called this fields is cleared to <tt>null</tt>.
  1223. * @type {Function|null}
  1224. */
  1225. _untoggleScreenSharing: null,
  1226. /**
  1227. * Creates a Promise which turns off the screen sharing and restores
  1228. * the previous state described by the arguments.
  1229. *
  1230. * This method is bound to the appropriate values, after switching to screen
  1231. * sharing and stored in {@link _untoggleScreenSharing}.
  1232. *
  1233. * @param {boolean} didHaveVideo indicates if there was a camera video being
  1234. * used, before switching to screen sharing.
  1235. * @param {boolean} wasVideoMuted indicates if the video was muted, before
  1236. * switching to screen sharing.
  1237. * @return {Promise} resolved after the screen sharing is turned off, or
  1238. * rejected with some error (no idea what kind of error, possible GUM error)
  1239. * in case it fails.
  1240. * @private
  1241. */
  1242. _turnScreenSharingOff(didHaveVideo, wasVideoMuted) {
  1243. this._untoggleScreenSharing = null;
  1244. this.videoSwitchInProgress = true;
  1245. const { receiver } = APP.remoteControl;
  1246. if (receiver) {
  1247. receiver.stop();
  1248. }
  1249. let promise = null;
  1250. if (didHaveVideo) {
  1251. promise = createLocalTracksF({ devices: [ 'video' ] })
  1252. .then(([ stream ]) => this.useVideoStream(stream))
  1253. .then(() => {
  1254. sendAnalyticsEvent(
  1255. 'conference.sharingDesktop.stop');
  1256. logger.log('switched back to local video');
  1257. if (!this.localVideo && wasVideoMuted) {
  1258. return Promise.reject('No local video to be muted!');
  1259. } else if (wasVideoMuted && this.localVideo) {
  1260. return this.localVideo.mute();
  1261. }
  1262. })
  1263. .catch(error => {
  1264. logger.error('failed to switch back to local video', error);
  1265. return this.useVideoStream(null).then(() =>
  1266. // Still fail with the original err
  1267. Promise.reject(error)
  1268. );
  1269. });
  1270. } else {
  1271. promise = this.useVideoStream(null);
  1272. }
  1273. return promise.then(
  1274. () => {
  1275. this.videoSwitchInProgress = false;
  1276. },
  1277. error => {
  1278. this.videoSwitchInProgress = false;
  1279. throw error;
  1280. });
  1281. },
  1282. /**
  1283. * Toggles between screen sharing and camera video if the toggle parameter
  1284. * is not specified and starts the procedure for obtaining new screen
  1285. * sharing/video track otherwise.
  1286. *
  1287. * @param {boolean} [toggle] - If true - new screen sharing track will be
  1288. * obtained. If false - new video track will be obtain. If not specified -
  1289. * toggles between screen sharing and camera video.
  1290. * @param {Object} [options] - Screen sharing options that will be passed to
  1291. * createLocalTracks.
  1292. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  1293. * sources that have to be displayed in the desktop picker window ('screen',
  1294. * 'window', etc.).
  1295. * @return {Promise.<T>}
  1296. */
  1297. toggleScreenSharing(toggle = !this._untoggleScreenSharing, options = {}) {
  1298. if (this.videoSwitchInProgress) {
  1299. return Promise.reject('Switch in progress.');
  1300. }
  1301. if (!this.isDesktopSharingEnabled) {
  1302. return Promise.reject(
  1303. 'Cannot toggle screen sharing: not supported.');
  1304. }
  1305. if (this.isAudioOnly()) {
  1306. this._displayAudioOnlyTooltip('screenShare');
  1307. return Promise.reject('No screensharing in audio only mode');
  1308. }
  1309. if (toggle) {
  1310. return this._switchToScreenSharing(options);
  1311. }
  1312. return this._untoggleScreenSharing();
  1313. },
  1314. /**
  1315. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1316. * @param {Object} [options] - Screen sharing options that will be passed to
  1317. * createLocalTracks.
  1318. *
  1319. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1320. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1321. * {@link JitsiTrackError}.
  1322. *
  1323. * @private
  1324. */
  1325. _createDesktopTrack(options = {}) {
  1326. let externalInstallation = false;
  1327. let DSExternalInstallationInProgress = false;
  1328. const didHaveVideo = Boolean(this.localVideo);
  1329. const wasVideoMuted = this.isLocalVideoMuted();
  1330. return createLocalTracksF({
  1331. desktopSharingSources: options.desktopSharingSources,
  1332. devices: [ 'desktop' ],
  1333. desktopSharingExtensionExternalInstallation: {
  1334. interval: 500,
  1335. checkAgain: () => DSExternalInstallationInProgress,
  1336. listener: (status, url) => {
  1337. switch (status) {
  1338. case 'waitingForExtension': {
  1339. DSExternalInstallationInProgress = true;
  1340. externalInstallation = true;
  1341. const listener = () => {
  1342. // Wait a little bit more just to be sure that we
  1343. // won't miss the extension installation
  1344. setTimeout(
  1345. () => {
  1346. DSExternalInstallationInProgress = false;
  1347. },
  1348. 500);
  1349. APP.UI.removeListener(
  1350. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1351. listener);
  1352. };
  1353. APP.UI.addListener(
  1354. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1355. listener);
  1356. APP.UI.showExtensionExternalInstallationDialog(url);
  1357. break;
  1358. }
  1359. case 'extensionFound':
  1360. // Close the dialog.
  1361. externalInstallation && $.prompt.close();
  1362. break;
  1363. default:
  1364. // Unknown status
  1365. }
  1366. }
  1367. }
  1368. }).then(([ desktopStream ]) => {
  1369. // Stores the "untoggle" handler which remembers whether was
  1370. // there any video before and whether was it muted.
  1371. this._untoggleScreenSharing
  1372. = this._turnScreenSharingOff
  1373. .bind(this, didHaveVideo, wasVideoMuted);
  1374. desktopStream.on(
  1375. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1376. () => {
  1377. // If the stream was stopped during screen sharing
  1378. // session then we should switch back to video.
  1379. this.isSharingScreen
  1380. && this._untoggleScreenSharing
  1381. && this._untoggleScreenSharing();
  1382. }
  1383. );
  1384. // close external installation dialog on success.
  1385. externalInstallation && $.prompt.close();
  1386. return desktopStream;
  1387. }, error => {
  1388. DSExternalInstallationInProgress = false;
  1389. // close external installation dialog on success.
  1390. externalInstallation && $.prompt.close();
  1391. throw error;
  1392. });
  1393. },
  1394. /**
  1395. * Tries to switch to the screenshairng mode by disposing camera stream and
  1396. * replacing it with a desktop one.
  1397. *
  1398. * @param {Object} [options] - Screen sharing options that will be passed to
  1399. * createLocalTracks.
  1400. *
  1401. * @return {Promise} - A Promise resolved if the operation succeeds or
  1402. * rejected with some unknown type of error in case it fails. Promise will
  1403. * be rejected immediately if {@link videoSwitchInProgress} is true.
  1404. *
  1405. * @private
  1406. */
  1407. _switchToScreenSharing(options = {}) {
  1408. if (this.videoSwitchInProgress) {
  1409. return Promise.reject('Switch in progress.');
  1410. }
  1411. this.videoSwitchInProgress = true;
  1412. return this._createDesktopTrack(options)
  1413. .then(stream => this.useVideoStream(stream))
  1414. .then(() => {
  1415. this.videoSwitchInProgress = false;
  1416. sendAnalyticsEvent('conference.sharingDesktop.start');
  1417. logger.log('sharing local desktop');
  1418. })
  1419. .catch(error => {
  1420. this.videoSwitchInProgress = false;
  1421. // Pawel: With this call I'm trying to preserve the original
  1422. // behaviour although it is not clear why would we "untoggle"
  1423. // on failure. I suppose it was to restore video in case there
  1424. // was some problem during "this.useVideoStream(desktopStream)".
  1425. // It's important to note that the handler will not be available
  1426. // if we fail early on trying to get desktop media (which makes
  1427. // sense, because the camera video is still being used, so
  1428. // nothing to "untoggle").
  1429. if (this._untoggleScreenSharing) {
  1430. this._untoggleScreenSharing();
  1431. }
  1432. // FIXME the code inside of _handleScreenSharingError is
  1433. // asynchronous, but does not return a Promise and is not part
  1434. // of the current Promise chain.
  1435. this._handleScreenSharingError(error);
  1436. return Promise.reject(error);
  1437. });
  1438. },
  1439. /**
  1440. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1441. * trying to create screensharing track. It will either do nothing if
  1442. * the dialog was canceled on user's request or display inline installation
  1443. * dialog and ask the user to install the extension, once the extension is
  1444. * installed it will switch the conference to screensharing. The last option
  1445. * is that an unrecoverable error dialog will be displayed.
  1446. * @param {JitsiTrackError} error - The error returned by
  1447. * {@link _createDesktopTrack} Promise.
  1448. * @private
  1449. */
  1450. _handleScreenSharingError(error) {
  1451. if (error.name === JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1452. return;
  1453. }
  1454. logger.error('failed to share local desktop', error);
  1455. if (error.name
  1456. === JitsiTrackErrors.CHROME_EXTENSION_USER_GESTURE_REQUIRED) {
  1457. // If start with screen sharing the extension will fail to install
  1458. // (if not found), because the request has been triggered by the
  1459. // script. Show a dialog which asks user to click "install" and try
  1460. // again switching to the screen sharing.
  1461. APP.UI.showExtensionInlineInstallationDialog(
  1462. () => {
  1463. // eslint-disable-next-line no-empty-function
  1464. this.toggleScreenSharing().catch(() => {});
  1465. }
  1466. );
  1467. return;
  1468. } else if (error.name === JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED) {
  1469. APP.UI.showExtensionRequiredDialog(
  1470. config.desktopSharingFirefoxExtensionURL
  1471. );
  1472. return;
  1473. }
  1474. // Handling:
  1475. // JitsiTrackErrors.PERMISSION_DENIED
  1476. // JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1477. // JitsiTrackErrors.GENERAL
  1478. // and any other
  1479. let descriptionKey;
  1480. let titleKey;
  1481. if (error.name === JitsiTrackErrors.PERMISSION_DENIED) {
  1482. descriptionKey = 'dialog.screenSharingPermissionDeniedError';
  1483. titleKey = 'dialog.screenSharingFailedToInstallTitle';
  1484. } else {
  1485. descriptionKey = 'dialog.screenSharingFailedToInstall';
  1486. titleKey = 'dialog.screenSharingFailedToInstallTitle';
  1487. }
  1488. APP.UI.messageHandler.showError({
  1489. descriptionKey,
  1490. titleKey
  1491. });
  1492. },
  1493. /**
  1494. * Setup interaction between conference and UI.
  1495. */
  1496. _setupListeners() {
  1497. // add local streams when joined to the conference
  1498. room.on(JitsiConferenceEvents.CONFERENCE_JOINED, () => {
  1499. this._onConferenceJoined();
  1500. });
  1501. room.on(
  1502. JitsiConferenceEvents.CONFERENCE_LEFT,
  1503. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1504. room.on(
  1505. JitsiConferenceEvents.AUTH_STATUS_CHANGED,
  1506. (authEnabled, authLogin) =>
  1507. APP.UI.updateAuthInfo(authEnabled, authLogin));
  1508. room.on(JitsiConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1509. user => APP.UI.onUserFeaturesChanged(user));
  1510. room.on(JitsiConferenceEvents.USER_JOINED, (id, user) => {
  1511. if (user.isHidden()) {
  1512. return;
  1513. }
  1514. APP.store.dispatch(participantJoined({
  1515. id,
  1516. name: user.getDisplayName(),
  1517. role: user.getRole()
  1518. }));
  1519. logger.log('USER %s connnected', id, user);
  1520. APP.API.notifyUserJoined(id);
  1521. APP.UI.addUser(user);
  1522. // check the roles for the new user and reflect them
  1523. APP.UI.updateUserRole(user);
  1524. });
  1525. room.on(JitsiConferenceEvents.USER_LEFT, (id, user) => {
  1526. APP.store.dispatch(participantLeft(id, user));
  1527. logger.log('USER %s LEFT', id, user);
  1528. APP.API.notifyUserLeft(id);
  1529. APP.UI.removeUser(id, user.getDisplayName());
  1530. APP.UI.onSharedVideoStop(id);
  1531. });
  1532. room.on(JitsiConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1533. APP.store.dispatch(participantPresenceChanged(id, status));
  1534. const user = room.getParticipantById(id);
  1535. if (user) {
  1536. APP.UI.updateUserStatus(user, status);
  1537. }
  1538. });
  1539. room.on(JitsiConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1540. if (this.isLocalId(id)) {
  1541. logger.info(`My role changed, new role: ${role}`);
  1542. APP.store.dispatch(localParticipantRoleChanged(role));
  1543. if (this.isModerator !== room.isModerator()) {
  1544. this.isModerator = room.isModerator();
  1545. APP.UI.updateLocalRole(room.isModerator());
  1546. }
  1547. } else {
  1548. APP.store.dispatch(participantRoleChanged(id, role));
  1549. const user = room.getParticipantById(id);
  1550. if (user) {
  1551. APP.UI.updateUserRole(user);
  1552. }
  1553. }
  1554. });
  1555. room.on(JitsiConferenceEvents.TRACK_ADDED, track => {
  1556. if (!track || track.isLocal()) {
  1557. return;
  1558. }
  1559. APP.store.dispatch(trackAdded(track));
  1560. });
  1561. room.on(JitsiConferenceEvents.TRACK_REMOVED, track => {
  1562. if (!track || track.isLocal()) {
  1563. return;
  1564. }
  1565. APP.store.dispatch(trackRemoved(track));
  1566. });
  1567. room.on(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1568. let newLvl = lvl;
  1569. if (this.isLocalId(id)
  1570. && this.localAudio && this.localAudio.isMuted()) {
  1571. newLvl = 0;
  1572. }
  1573. if (config.debug) {
  1574. this.audioLevelsMap[id] = newLvl;
  1575. if (config.debugAudioLevels) {
  1576. logger.log(`AudioLevel:${id}/${newLvl}`);
  1577. }
  1578. }
  1579. APP.UI.setAudioLevel(id, newLvl);
  1580. });
  1581. room.on(JitsiConferenceEvents.TALK_WHILE_MUTED, () => {
  1582. APP.UI.showToolbar(6000);
  1583. APP.UI.showCustomToolbarPopup(
  1584. 'microphone', 'talkWhileMutedPopup', true, 5000);
  1585. });
  1586. room.on(
  1587. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1588. (leavingIds, enteringIds) =>
  1589. APP.UI.handleLastNEndpoints(leavingIds, enteringIds));
  1590. room.on(
  1591. JitsiConferenceEvents.P2P_STATUS,
  1592. (jitsiConference, p2p) =>
  1593. APP.store.dispatch(p2pStatusChanged(p2p)));
  1594. room.on(
  1595. JitsiConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1596. (id, connectionStatus) => {
  1597. APP.store.dispatch(participantConnectionStatusChanged(
  1598. id, connectionStatus));
  1599. APP.UI.participantConnectionStatusChanged(id);
  1600. });
  1601. room.on(JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED, id => {
  1602. APP.store.dispatch(dominantSpeakerChanged(id));
  1603. if (this.isLocalId(id)) {
  1604. this.isDominantSpeaker = true;
  1605. this.setRaisedHand(false);
  1606. } else {
  1607. this.isDominantSpeaker = false;
  1608. const participant = room.getParticipantById(id);
  1609. if (participant) {
  1610. APP.UI.setRaisedHandStatus(participant, false);
  1611. }
  1612. }
  1613. APP.UI.markDominantSpeaker(id);
  1614. });
  1615. if (!interfaceConfig.filmStripOnly) {
  1616. room.on(JitsiConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1617. APP.UI.markVideoInterrupted(true);
  1618. });
  1619. room.on(JitsiConferenceEvents.CONNECTION_RESTORED, () => {
  1620. APP.UI.markVideoInterrupted(false);
  1621. });
  1622. if (isButtonEnabled('chat')) {
  1623. room.on(
  1624. JitsiConferenceEvents.MESSAGE_RECEIVED,
  1625. (id, body, ts) => {
  1626. let nick = getDisplayName(id);
  1627. if (!nick) {
  1628. nick = `${
  1629. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME} (${
  1630. id})`;
  1631. }
  1632. APP.API.notifyReceivedChatMessage({
  1633. id,
  1634. nick,
  1635. body,
  1636. ts
  1637. });
  1638. APP.UI.addMessage(id, nick, body, ts);
  1639. }
  1640. );
  1641. APP.UI.addListener(UIEvents.MESSAGE_CREATED, message => {
  1642. APP.API.notifySendingChatMessage(message);
  1643. room.sendTextMessage(message);
  1644. });
  1645. }
  1646. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, id => {
  1647. try {
  1648. // do not try to select participant if there is none (we
  1649. // are alone in the room), otherwise an error will be
  1650. // thrown cause reporting mechanism is not available
  1651. // (datachannels currently)
  1652. if (room.getParticipants().length === 0) {
  1653. return;
  1654. }
  1655. room.selectParticipant(id);
  1656. } catch (e) {
  1657. sendAnalyticsEvent(
  1658. 'selectParticipant.failed');
  1659. reportError(e);
  1660. }
  1661. });
  1662. APP.UI.addListener(
  1663. UIEvents.VIDEO_UNMUTING_WHILE_AUDIO_ONLY,
  1664. () => this._displayAudioOnlyTooltip('videoMute'));
  1665. }
  1666. room.on(JitsiConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1667. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1668. JitsiParticipantConnectionStatus.INTERRUPTED));
  1669. APP.UI.showLocalConnectionInterrupted(true);
  1670. });
  1671. room.on(JitsiConferenceEvents.CONNECTION_RESTORED, () => {
  1672. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1673. JitsiParticipantConnectionStatus.ACTIVE));
  1674. APP.UI.showLocalConnectionInterrupted(false);
  1675. });
  1676. room.on(
  1677. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1678. (id, displayName) => {
  1679. const formattedDisplayName
  1680. = displayName.substr(0, MAX_DISPLAY_NAME_LENGTH);
  1681. APP.store.dispatch(participantUpdated({
  1682. id,
  1683. name: formattedDisplayName
  1684. }));
  1685. APP.API.notifyDisplayNameChanged(id, formattedDisplayName);
  1686. APP.UI.changeDisplayName(id, formattedDisplayName);
  1687. }
  1688. );
  1689. room.on(
  1690. JitsiConferenceEvents.LOCK_STATE_CHANGED,
  1691. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1692. APP.remoteControl.on(RemoteControlEvents.ACTIVE_CHANGED, isActive => {
  1693. room.setLocalParticipantProperty(
  1694. 'remoteControlSessionStatus',
  1695. isActive
  1696. );
  1697. APP.UI.setLocalRemoteControlActiveChanged();
  1698. });
  1699. /* eslint-disable max-params */
  1700. room.on(
  1701. JitsiConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1702. (participant, name, oldValue, newValue) => {
  1703. switch (name) {
  1704. case 'raisedHand':
  1705. APP.UI.setRaisedHandStatus(participant, newValue);
  1706. break;
  1707. case 'remoteControlSessionStatus':
  1708. APP.UI.setRemoteControlActiveStatus(
  1709. participant.getId(),
  1710. newValue);
  1711. break;
  1712. default:
  1713. // ignore
  1714. }
  1715. });
  1716. /* eslint-enable max-params */
  1717. room.on(
  1718. JitsiConferenceEvents.RECORDER_STATE_CHANGED,
  1719. (status, error) => {
  1720. logger.log('Received recorder status change: ', status, error);
  1721. APP.UI.updateRecordingState(status);
  1722. }
  1723. );
  1724. room.on(JitsiConferenceEvents.KICKED, () => {
  1725. APP.UI.hideStats();
  1726. APP.UI.notifyKicked();
  1727. // FIXME close
  1728. });
  1729. room.on(JitsiConferenceEvents.SUSPEND_DETECTED, () => {
  1730. APP.store.dispatch(suspendDetected());
  1731. // After wake up, we will be in a state where conference is left
  1732. // there will be dialog shown to user.
  1733. // We do not want video/audio as we show an overlay and after it
  1734. // user need to rejoin or close, while waking up we can detect
  1735. // camera wakeup as a problem with device.
  1736. // We also do not care about device change, which happens
  1737. // on resume after suspending PC.
  1738. if (this.deviceChangeListener) {
  1739. JitsiMeetJS.mediaDevices.removeEventListener(
  1740. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  1741. this.deviceChangeListener);
  1742. }
  1743. // stop local video
  1744. if (this.localVideo) {
  1745. this.localVideo.dispose();
  1746. this.localVideo = null;
  1747. }
  1748. // stop local audio
  1749. if (this.localAudio) {
  1750. this.localAudio.dispose();
  1751. this.localAudio = null;
  1752. }
  1753. });
  1754. room.on(
  1755. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1756. isDTMFSupported => {
  1757. APP.UI.updateDTMFSupport(isDTMFSupported);
  1758. }
  1759. );
  1760. APP.UI.addListener(UIEvents.AUDIO_MUTED, muted => {
  1761. this.muteAudio(muted);
  1762. });
  1763. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  1764. if (this.isAudioOnly() && !muted) {
  1765. this._displayAudioOnlyTooltip('videoMute');
  1766. } else {
  1767. this.muteVideo(muted);
  1768. }
  1769. });
  1770. statsEmitter.startListeningForStats(room);
  1771. room.addCommandListener(this.commands.defaults.ETHERPAD,
  1772. ({ value }) => {
  1773. APP.UI.initEtherpad(value);
  1774. }
  1775. );
  1776. APP.UI.addListener(UIEvents.EMAIL_CHANGED, this.changeLocalEmail);
  1777. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1778. APP.store.dispatch(participantUpdated({
  1779. id: from,
  1780. email: data.value
  1781. }));
  1782. APP.UI.setUserEmail(from, data.value);
  1783. });
  1784. room.addCommandListener(
  1785. this.commands.defaults.AVATAR_URL,
  1786. (data, from) => {
  1787. APP.store.dispatch(
  1788. participantUpdated({
  1789. id: from,
  1790. avatarURL: data.value
  1791. }));
  1792. APP.UI.setUserAvatarUrl(from, data.value);
  1793. });
  1794. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1795. (data, from) => {
  1796. APP.store.dispatch(
  1797. participantUpdated({
  1798. id: from,
  1799. avatarID: data.value
  1800. }));
  1801. APP.UI.setUserAvatarID(from, data.value);
  1802. });
  1803. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1804. this.changeLocalDisplayName.bind(this));
  1805. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1806. (startAudioMuted, startVideoMuted) => {
  1807. room.setStartMutedPolicy({
  1808. audio: startAudioMuted,
  1809. video: startVideoMuted
  1810. });
  1811. }
  1812. );
  1813. room.on(
  1814. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  1815. ({ audio, video }) => {
  1816. APP.UI.onStartMutedChanged(audio, video);
  1817. }
  1818. );
  1819. room.on(JitsiConferenceEvents.STARTED_MUTED, () => {
  1820. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1821. && APP.UI.notifyInitiallyMuted();
  1822. });
  1823. room.on(
  1824. JitsiConferenceEvents.AVAILABLE_DEVICES_CHANGED,
  1825. (id, devices) => {
  1826. APP.UI.updateDevicesAvailability(id, devices);
  1827. }
  1828. );
  1829. room.on(
  1830. JitsiConferenceEvents.DATA_CHANNEL_OPENED, () => {
  1831. APP.store.dispatch(dataChannelOpened());
  1832. }
  1833. );
  1834. // call hangup
  1835. APP.UI.addListener(UIEvents.HANGUP, () => {
  1836. this.hangup(true);
  1837. });
  1838. // logout
  1839. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1840. AuthHandler.logout(room).then(url => {
  1841. if (url) {
  1842. UIUtil.redirect(url);
  1843. } else {
  1844. this.hangup(true);
  1845. }
  1846. });
  1847. });
  1848. /* eslint-disable max-params */
  1849. APP.UI.addListener(
  1850. UIEvents.RESOLUTION_CHANGED,
  1851. (id, oldResolution, newResolution, delay) => {
  1852. const logObject = {
  1853. id: 'resolution_change',
  1854. participant: id,
  1855. oldValue: oldResolution,
  1856. newValue: newResolution,
  1857. delay
  1858. };
  1859. room.sendApplicationLog(JSON.stringify(logObject));
  1860. // We only care about the delay between simulcast streams.
  1861. // Longer delays will be caused by something else and will just
  1862. // poison the data.
  1863. if (delay < 2000) {
  1864. sendAnalyticsEvent('stream.switch.delay', { value: delay });
  1865. }
  1866. });
  1867. /* eslint-enable max-params */
  1868. // Starts or stops the recording for the conference.
  1869. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, options => {
  1870. room.toggleRecording(options);
  1871. });
  1872. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, topic => {
  1873. room.setSubject(topic);
  1874. });
  1875. room.on(JitsiConferenceEvents.SUBJECT_CHANGED, subject => {
  1876. APP.UI.setSubject(subject);
  1877. });
  1878. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1879. AuthHandler.authenticate(room);
  1880. });
  1881. APP.UI.addListener(
  1882. UIEvents.VIDEO_DEVICE_CHANGED,
  1883. cameraDeviceId => {
  1884. const videoWasMuted = this.isLocalVideoMuted();
  1885. sendAnalyticsEvent('settings.changeDevice.video');
  1886. createLocalTracksF({
  1887. devices: [ 'video' ],
  1888. cameraDeviceId,
  1889. micDeviceId: null
  1890. })
  1891. .then(([ stream ]) => {
  1892. // if we are in audio only mode or video was muted before
  1893. // changing device, then mute
  1894. if (this.isAudioOnly() || videoWasMuted) {
  1895. return stream.mute()
  1896. .then(() => stream);
  1897. }
  1898. return stream;
  1899. })
  1900. .then(stream => {
  1901. // if we are screen sharing we do not want to stop it
  1902. if (this.isSharingScreen) {
  1903. return Promise.resolve();
  1904. }
  1905. return this.useVideoStream(stream);
  1906. })
  1907. .then(() => {
  1908. logger.log('switched local video device');
  1909. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1910. })
  1911. .catch(err => {
  1912. APP.UI.showCameraErrorNotification(err);
  1913. });
  1914. }
  1915. );
  1916. APP.UI.addListener(
  1917. UIEvents.AUDIO_DEVICE_CHANGED,
  1918. micDeviceId => {
  1919. const audioWasMuted = this.isLocalAudioMuted();
  1920. sendAnalyticsEvent(
  1921. 'settings.changeDevice.audioIn');
  1922. createLocalTracksF({
  1923. devices: [ 'audio' ],
  1924. cameraDeviceId: null,
  1925. micDeviceId
  1926. })
  1927. .then(([ stream ]) => {
  1928. // if audio was muted before changing the device, mute
  1929. // with the new device
  1930. if (audioWasMuted) {
  1931. return stream.mute()
  1932. .then(() => stream);
  1933. }
  1934. return stream;
  1935. })
  1936. .then(stream => {
  1937. this.useAudioStream(stream);
  1938. logger.log('switched local audio device');
  1939. APP.settings.setMicDeviceId(micDeviceId, true);
  1940. })
  1941. .catch(err => {
  1942. APP.UI.showMicErrorNotification(err);
  1943. });
  1944. }
  1945. );
  1946. APP.UI.addListener(
  1947. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1948. audioOutputDeviceId => {
  1949. sendAnalyticsEvent(
  1950. 'settings.changeDevice.audioOut');
  1951. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1952. .then(() => logger.log('changed audio output device'))
  1953. .catch(err => {
  1954. logger.warn('Failed to change audio output device. '
  1955. + 'Default or previously set audio output device '
  1956. + 'will be used instead.', err);
  1957. });
  1958. }
  1959. );
  1960. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  1961. // FIXME On web video track is stored both in redux and in
  1962. // 'localVideo' field, video is attempted to be unmuted twice when
  1963. // turning off the audio only mode. This will crash the app with
  1964. // 'unmute operation is already in progress'.
  1965. // Because there's no logic in redux about creating new track in
  1966. // case unmute when not track exists the things have to go through
  1967. // muteVideo logic in such case.
  1968. const tracks = APP.store.getState()['features/base/tracks'];
  1969. const isTrackInRedux
  1970. = Boolean(
  1971. tracks.find(
  1972. track => track.jitsiTrack
  1973. && track.jitsiTrack.getType() === 'video'));
  1974. if (!isTrackInRedux) {
  1975. this.muteVideo(audioOnly);
  1976. }
  1977. // Immediately update the UI by having remote videos and the large
  1978. // video update themselves instead of waiting for some other event
  1979. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  1980. // There is no guarantee another event will trigger the update
  1981. // immediately and in all situations, for example because a remote
  1982. // participant is having connection trouble so no status changes.
  1983. APP.UI.updateAllVideos();
  1984. });
  1985. APP.UI.addListener(
  1986. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1987. );
  1988. /* eslint-disable max-params */
  1989. APP.UI.addListener(
  1990. UIEvents.UPDATE_SHARED_VIDEO,
  1991. (url, state, time, isMuted, volume) => {
  1992. /* eslint-enable max-params */
  1993. // send start and stop commands once, and remove any updates
  1994. // that had left
  1995. if (state === 'stop'
  1996. || state === 'start'
  1997. || state === 'playing') {
  1998. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1999. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  2000. value: url,
  2001. attributes: {
  2002. state,
  2003. time,
  2004. muted: isMuted,
  2005. volume
  2006. }
  2007. });
  2008. } else {
  2009. // in case of paused, in order to allow late users to join
  2010. // paused
  2011. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  2012. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  2013. value: url,
  2014. attributes: {
  2015. state,
  2016. time,
  2017. muted: isMuted,
  2018. volume
  2019. }
  2020. });
  2021. }
  2022. });
  2023. room.addCommandListener(
  2024. this.commands.defaults.SHARED_VIDEO,
  2025. ({ value, attributes }, id) => {
  2026. if (attributes.state === 'stop') {
  2027. APP.UI.onSharedVideoStop(id, attributes);
  2028. } else if (attributes.state === 'start') {
  2029. APP.UI.onSharedVideoStart(id, value, attributes);
  2030. } else if (attributes.state === 'playing'
  2031. || attributes.state === 'pause') {
  2032. APP.UI.onSharedVideoUpdate(id, value, attributes);
  2033. }
  2034. });
  2035. },
  2036. /**
  2037. * Callback invoked when the conference has been successfully joined.
  2038. * Initializes the UI and various other features.
  2039. *
  2040. * @private
  2041. * @returns {void}
  2042. */
  2043. _onConferenceJoined() {
  2044. if (APP.logCollector) {
  2045. // Start the LogCollector's periodic "store logs" task
  2046. APP.logCollector.start();
  2047. APP.logCollectorStarted = true;
  2048. // Make an attempt to flush in case a lot of logs have been
  2049. // cached, before the collector was started.
  2050. APP.logCollector.flush();
  2051. // This event listener will flush the logs, before
  2052. // the statistics module (CallStats) is stopped.
  2053. //
  2054. // NOTE The LogCollector is not stopped, because this event can
  2055. // be triggered multiple times during single conference
  2056. // (whenever statistics module is stopped). That includes
  2057. // the case when Jicofo terminates the single person left in the
  2058. // room. It will then restart the media session when someone
  2059. // eventually join the room which will start the stats again.
  2060. APP.conference.addConferenceListener(
  2061. JitsiConferenceEvents.BEFORE_STATISTICS_DISPOSED,
  2062. () => {
  2063. if (APP.logCollector) {
  2064. APP.logCollector.flush();
  2065. }
  2066. }
  2067. );
  2068. }
  2069. APP.UI.initConference();
  2070. APP.UI.addListener(
  2071. UIEvents.LANG_CHANGED,
  2072. language => APP.translation.setLanguage(language));
  2073. APP.keyboardshortcut.init();
  2074. if (config.requireDisplayName
  2075. && !APP.conference.getLocalDisplayName()) {
  2076. APP.UI.promptDisplayName();
  2077. }
  2078. APP.store.dispatch(conferenceJoined(room));
  2079. APP.UI.mucJoined();
  2080. APP.API.notifyConferenceJoined(APP.conference.roomName);
  2081. APP.UI.markVideoInterrupted(false);
  2082. },
  2083. /**
  2084. * Adds any room listener.
  2085. * @param {string} eventName one of the JitsiConferenceEvents
  2086. * @param {Function} listener the function to be called when the event
  2087. * occurs
  2088. */
  2089. addConferenceListener(eventName, listener) {
  2090. room.on(eventName, listener);
  2091. },
  2092. /**
  2093. * Removes any room listener.
  2094. * @param {string} eventName one of the JitsiConferenceEvents
  2095. * @param {Function} listener the listener to be removed.
  2096. */
  2097. removeConferenceListener(eventName, listener) {
  2098. room.off(eventName, listener);
  2099. },
  2100. /**
  2101. * Inits list of current devices and event listener for device change.
  2102. * @private
  2103. */
  2104. _initDeviceList() {
  2105. JitsiMeetJS.mediaDevices.isDeviceListAvailable()
  2106. .then(isDeviceListAvailable => {
  2107. if (isDeviceListAvailable
  2108. && JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  2109. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  2110. // Ugly way to synchronize real device IDs with local
  2111. // storage and settings menu. This is a workaround until
  2112. // getConstraints() method will be implemented
  2113. // in browsers.
  2114. if (this.localAudio) {
  2115. APP.settings.setMicDeviceId(
  2116. this.localAudio.getDeviceId(), false);
  2117. }
  2118. if (this.localVideo) {
  2119. APP.settings.setCameraDeviceId(
  2120. this.localVideo.getDeviceId(), false);
  2121. }
  2122. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2123. APP.UI.onAvailableDevicesChanged(devices);
  2124. APP.store.dispatch(updateDeviceList(devices));
  2125. });
  2126. this.deviceChangeListener = devices =>
  2127. window.setTimeout(
  2128. () => this._onDeviceListChanged(devices), 0);
  2129. JitsiMeetJS.mediaDevices.addEventListener(
  2130. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2131. this.deviceChangeListener);
  2132. }
  2133. })
  2134. .catch(error => {
  2135. logger.warn(`Error getting device list: ${error}`);
  2136. });
  2137. },
  2138. /**
  2139. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  2140. * handle change of available media devices.
  2141. * @private
  2142. * @param {MediaDeviceInfo[]} devices
  2143. * @returns {Promise}
  2144. */
  2145. _onDeviceListChanged(devices) {
  2146. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  2147. // Event handler can be fired before direct
  2148. // enumerateDevices() call, so handle this situation here.
  2149. if (!currentDevices.audioinput
  2150. && !currentDevices.videoinput
  2151. && !currentDevices.audiooutput) {
  2152. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2153. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  2154. }
  2155. const newDevices
  2156. = mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  2157. devices,
  2158. this.isSharingScreen,
  2159. this.localVideo,
  2160. this.localAudio);
  2161. const promises = [];
  2162. const audioWasMuted = this.isLocalAudioMuted();
  2163. const videoWasMuted = this.isLocalVideoMuted();
  2164. if (typeof newDevices.audiooutput !== 'undefined') {
  2165. // Just ignore any errors in catch block.
  2166. promises.push(APP.settings
  2167. .setAudioOutputDeviceId(newDevices.audiooutput)
  2168. .catch());
  2169. }
  2170. promises.push(
  2171. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  2172. createLocalTracksF,
  2173. newDevices.videoinput,
  2174. newDevices.audioinput)
  2175. .then(tracks =>
  2176. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  2177. .then(() => {
  2178. // If audio was muted before, or we unplugged current device
  2179. // and selected new one, then mute new audio track.
  2180. if (audioWasMuted) {
  2181. sendAnalyticsEvent('deviceListChanged.audio.muted');
  2182. logger.log('Audio mute: device list changed');
  2183. muteLocalAudio(true);
  2184. }
  2185. // If video was muted before, or we unplugged current device
  2186. // and selected new one, then mute new video track.
  2187. if (!this.isSharingScreen && videoWasMuted) {
  2188. sendAnalyticsEvent('deviceListChanged.video.muted');
  2189. logger.log('Video mute: device list changed');
  2190. muteLocalVideo(true);
  2191. }
  2192. }));
  2193. return Promise.all(promises)
  2194. .then(() => {
  2195. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2196. APP.UI.onAvailableDevicesChanged(devices);
  2197. });
  2198. },
  2199. /**
  2200. * Determines whether or not the audio button should be enabled.
  2201. */
  2202. updateAudioIconEnabled() {
  2203. const audioMediaDevices
  2204. = mediaDeviceHelper.getCurrentMediaDevices().audioinput;
  2205. const audioDeviceCount
  2206. = audioMediaDevices ? audioMediaDevices.length : 0;
  2207. // The audio functionality is considered available if there are any
  2208. // audio devices detected or if the local audio stream already exists.
  2209. const available = audioDeviceCount > 0 || Boolean(this.localAudio);
  2210. logger.debug(
  2211. `Microphone button enabled: ${available}`,
  2212. `local audio: ${this.localAudio}`,
  2213. `audio devices: ${audioMediaDevices}`,
  2214. `device count: ${audioDeviceCount}`);
  2215. APP.store.dispatch(setAudioAvailable(available));
  2216. APP.API.notifyAudioAvailabilityChanged(available);
  2217. },
  2218. /**
  2219. * Determines whether or not the video button should be enabled.
  2220. */
  2221. updateVideoIconEnabled() {
  2222. const videoMediaDevices
  2223. = mediaDeviceHelper.getCurrentMediaDevices().videoinput;
  2224. const videoDeviceCount
  2225. = videoMediaDevices ? videoMediaDevices.length : 0;
  2226. // The video functionality is considered available if there are any
  2227. // video devices detected or if there is local video stream already
  2228. // active which could be either screensharing stream or a video track
  2229. // created before the permissions were rejected (through browser
  2230. // config).
  2231. const available = videoDeviceCount > 0 || Boolean(this.localVideo);
  2232. logger.debug(
  2233. `Camera button enabled: ${available}`,
  2234. `local video: ${this.localVideo}`,
  2235. `video devices: ${videoMediaDevices}`,
  2236. `device count: ${videoDeviceCount}`);
  2237. APP.store.dispatch(setVideoAvailable(available));
  2238. APP.API.notifyVideoAvailabilityChanged(available);
  2239. },
  2240. /**
  2241. * Toggles the local "raised hand" status.
  2242. */
  2243. maybeToggleRaisedHand() {
  2244. this.setRaisedHand(!this.isHandRaised);
  2245. },
  2246. /**
  2247. * Sets the local "raised hand" status to a particular value.
  2248. */
  2249. setRaisedHand(raisedHand) {
  2250. if (raisedHand !== this.isHandRaised) {
  2251. APP.UI.onLocalRaiseHandChanged(raisedHand);
  2252. this.isHandRaised = raisedHand;
  2253. // Advertise the updated status
  2254. room.setLocalParticipantProperty('raisedHand', raisedHand);
  2255. // Update the view
  2256. APP.UI.setLocalRaisedHandStatus(raisedHand);
  2257. }
  2258. },
  2259. /**
  2260. * Log event to callstats and analytics.
  2261. * @param {string} name the event name
  2262. * @param {int} value the value (it's int because google analytics supports
  2263. * only int).
  2264. * @param {string} label short text which provides more info about the event
  2265. * which allows to distinguish between few event cases of the same name
  2266. * NOTE: Should be used after conference.init
  2267. */
  2268. logEvent(name, value, label) {
  2269. sendAnalyticsEvent(name, {
  2270. value,
  2271. label
  2272. });
  2273. if (room) {
  2274. room.sendApplicationLog(JSON.stringify({ name,
  2275. value,
  2276. label }));
  2277. }
  2278. },
  2279. /**
  2280. * Methods logs an application event given in the JSON format.
  2281. * @param {string} logJSON an event to be logged in JSON format
  2282. */
  2283. logJSON(logJSON) {
  2284. if (room) {
  2285. room.sendApplicationLog(logJSON);
  2286. }
  2287. },
  2288. /**
  2289. * Disconnect from the conference and optionally request user feedback.
  2290. * @param {boolean} [requestFeedback=false] if user feedback should be
  2291. * requested
  2292. */
  2293. hangup(requestFeedback = false) {
  2294. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  2295. let requestFeedbackPromise;
  2296. if (requestFeedback) {
  2297. requestFeedbackPromise
  2298. = APP.store.dispatch(maybeOpenFeedbackDialog(room))
  2299. // false because the thank you dialog shouldn't be displayed
  2300. .catch(() => Promise.resolve(false));
  2301. } else {
  2302. requestFeedbackPromise = Promise.resolve(true);
  2303. }
  2304. // All promises are returning Promise.resolve to make Promise.all to
  2305. // be resolved when both Promises are finished. Otherwise Promise.all
  2306. // will reject on first rejected Promise and we can redirect the page
  2307. // before all operations are done.
  2308. Promise.all([
  2309. requestFeedbackPromise,
  2310. room.leave().then(disconnect, disconnect)
  2311. ]).then(values => {
  2312. APP.API.notifyReadyToClose();
  2313. maybeRedirectToWelcomePage(values[0]);
  2314. });
  2315. },
  2316. /**
  2317. * Changes the email for the local user
  2318. * @param email {string} the new email
  2319. */
  2320. changeLocalEmail(email = '') {
  2321. const localParticipant = getLocalParticipant(APP.store.getState());
  2322. const formattedEmail = String(email).trim();
  2323. if (formattedEmail === localParticipant.email) {
  2324. return;
  2325. }
  2326. const localId = localParticipant.id;
  2327. APP.store.dispatch(participantUpdated({
  2328. id: localId,
  2329. local: true,
  2330. formattedEmail
  2331. }));
  2332. APP.settings.setEmail(formattedEmail);
  2333. APP.UI.setUserEmail(localId, formattedEmail);
  2334. sendData(commands.EMAIL, formattedEmail);
  2335. },
  2336. /**
  2337. * Changes the avatar url for the local user
  2338. * @param url {string} the new url
  2339. */
  2340. changeLocalAvatarUrl(url = '') {
  2341. const { avatarURL, id } = getLocalParticipant(APP.store.getState());
  2342. const formattedUrl = String(url).trim();
  2343. if (formattedUrl === avatarURL) {
  2344. return;
  2345. }
  2346. APP.store.dispatch(participantUpdated({
  2347. id,
  2348. local: true,
  2349. avatarURL: formattedUrl
  2350. }));
  2351. APP.settings.setAvatarUrl(url);
  2352. APP.UI.setUserAvatarUrl(id, url);
  2353. sendData(commands.AVATAR_URL, url);
  2354. },
  2355. /**
  2356. * Sends a message via the data channel.
  2357. * @param {string} to the id of the endpoint that should receive the
  2358. * message. If "" - the message will be sent to all participants.
  2359. * @param {object} payload the payload of the message.
  2360. * @throws NetworkError or InvalidStateError or Error if the operation
  2361. * fails.
  2362. */
  2363. sendEndpointMessage(to, payload) {
  2364. room.sendEndpointMessage(to, payload);
  2365. },
  2366. /**
  2367. * Adds new listener.
  2368. * @param {String} eventName the name of the event
  2369. * @param {Function} listener the listener.
  2370. */
  2371. addListener(eventName, listener) {
  2372. eventEmitter.addListener(eventName, listener);
  2373. },
  2374. /**
  2375. * Removes listener.
  2376. * @param {String} eventName the name of the event that triggers the
  2377. * listener
  2378. * @param {Function} listener the listener.
  2379. */
  2380. removeListener(eventName, listener) {
  2381. eventEmitter.removeListener(eventName, listener);
  2382. },
  2383. /**
  2384. * Changes the display name for the local user
  2385. * @param nickname {string} the new display name
  2386. */
  2387. changeLocalDisplayName(nickname = '') {
  2388. const formattedNickname
  2389. = nickname.trim().substr(0, MAX_DISPLAY_NAME_LENGTH);
  2390. const { id, name } = getLocalParticipant(APP.store.getState());
  2391. if (formattedNickname === name) {
  2392. return;
  2393. }
  2394. APP.store.dispatch(participantUpdated({
  2395. id,
  2396. local: true,
  2397. name: formattedNickname
  2398. }));
  2399. APP.settings.setDisplayName(formattedNickname);
  2400. if (room) {
  2401. room.setDisplayName(formattedNickname);
  2402. APP.UI.changeDisplayName(id, formattedNickname);
  2403. }
  2404. },
  2405. /**
  2406. * Returns the desktop sharing source id or undefined if the desktop sharing
  2407. * is not active at the moment.
  2408. *
  2409. * @returns {string|undefined} - The source id. If the track is not desktop
  2410. * track or the source id is not available, undefined will be returned.
  2411. */
  2412. getDesktopSharingSourceId() {
  2413. return this.localVideo.sourceId;
  2414. },
  2415. /**
  2416. * Returns the desktop sharing source type or undefined if the desktop
  2417. * sharing is not active at the moment.
  2418. *
  2419. * @returns {'screen'|'window'|undefined} - The source type. If the track is
  2420. * not desktop track or the source type is not available, undefined will be
  2421. * returned.
  2422. */
  2423. getDesktopSharingSourceType() {
  2424. return this.localVideo.sourceType;
  2425. },
  2426. /**
  2427. * Sets the video muted status.
  2428. *
  2429. * @param {boolean} muted - New muted status.
  2430. */
  2431. setVideoMuteStatus(muted) {
  2432. APP.UI.setVideoMuted(this.getMyUserId(), muted);
  2433. APP.API.notifyVideoMutedStatusChanged(muted);
  2434. },
  2435. /**
  2436. * Sets the audio muted status.
  2437. *
  2438. * @param {boolean} muted - New muted status.
  2439. */
  2440. setAudioMuteStatus(muted) {
  2441. APP.UI.setAudioMuted(this.getMyUserId(), muted);
  2442. APP.API.notifyAudioMutedStatusChanged(muted);
  2443. }
  2444. };