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

conference.js 95KB

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