You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 94KB

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