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

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