Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conference.js 92KB

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