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

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