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

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