Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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