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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842
  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. CONFERENCE_AUDIO_INITIALLY_MUTED,
  14. CONFERENCE_SHARING_DESKTOP_START,
  15. CONFERENCE_SHARING_DESKTOP_STOP,
  16. CONFERENCE_VIDEO_INITIALLY_MUTED,
  17. DEVICE_LIST_CHANGED_AUDIO_MUTED,
  18. DEVICE_LIST_CHANGED_VIDEO_MUTED,
  19. SELECT_PARTICIPANT_FAILED,
  20. SETTINGS_CHANGE_DEVICE_AUDIO_OUT,
  21. SETTINGS_CHANGE_DEVICE_AUDIO_IN,
  22. SETTINGS_CHANGE_DEVICE_VIDEO,
  23. STREAM_SWITCH_DELAY,
  24. initAnalytics,
  25. sendAnalyticsEvent
  26. } from './react/features/analytics';
  27. import EventEmitter from 'events';
  28. import {
  29. AVATAR_ID_COMMAND,
  30. AVATAR_URL_COMMAND,
  31. conferenceFailed,
  32. conferenceJoined,
  33. conferenceLeft,
  34. conferenceWillJoin,
  35. dataChannelOpened,
  36. EMAIL_COMMAND,
  37. lockStateChanged,
  38. onStartMutedPolicyChanged,
  39. p2pStatusChanged,
  40. sendLocalParticipant
  41. } from './react/features/base/conference';
  42. import { updateDeviceList } from './react/features/base/devices';
  43. import {
  44. isAnalyticsEnabled,
  45. isFatalJitsiConnectionError,
  46. JitsiConferenceErrors,
  47. JitsiConferenceEvents,
  48. JitsiConnectionErrors,
  49. JitsiConnectionEvents,
  50. JitsiMediaDevicesEvents,
  51. JitsiParticipantConnectionStatus,
  52. JitsiTrackErrors,
  53. JitsiTrackEvents
  54. } from './react/features/base/lib-jitsi-meet';
  55. import {
  56. isVideoMutedByUser,
  57. MEDIA_TYPE,
  58. setAudioAvailable,
  59. setAudioMuted,
  60. setVideoAvailable,
  61. setVideoMuted
  62. } from './react/features/base/media';
  63. import {
  64. dominantSpeakerChanged,
  65. getLocalParticipant,
  66. getParticipantById,
  67. localParticipantConnectionStatusChanged,
  68. localParticipantRoleChanged,
  69. MAX_DISPLAY_NAME_LENGTH,
  70. participantConnectionStatusChanged,
  71. participantJoined,
  72. participantLeft,
  73. participantPresenceChanged,
  74. participantRoleChanged,
  75. participantUpdated
  76. } from './react/features/base/participants';
  77. import {
  78. createLocalTracksF,
  79. isLocalTrackMuted,
  80. replaceLocalTrack,
  81. trackAdded,
  82. trackRemoved
  83. } from './react/features/base/tracks';
  84. import { getLocationContextRoot } from './react/features/base/util';
  85. import { statsEmitter } from './react/features/connection-indicator';
  86. import { showDesktopPicker } from './react/features/desktop-picker';
  87. import { appendSuffix } from './react/features/display-name';
  88. import { maybeOpenFeedbackDialog } from './react/features/feedback';
  89. import {
  90. mediaPermissionPromptVisibilityChanged,
  91. suspendDetected
  92. } from './react/features/overlay';
  93. import {
  94. isButtonEnabled,
  95. showDesktopSharingButton
  96. } from './react/features/toolbox';
  97. const logger = require('jitsi-meet-logger').getLogger(__filename);
  98. const eventEmitter = new EventEmitter();
  99. let room;
  100. let connection;
  101. /*
  102. * Logic to open a desktop picker put on the window global for
  103. * lib-jitsi-meet to detect and invoke
  104. */
  105. window.JitsiMeetScreenObtainer = {
  106. openDesktopPicker(options, onSourceChoose) {
  107. APP.store.dispatch(showDesktopPicker(options, onSourceChoose));
  108. }
  109. };
  110. /**
  111. * Known custom conference commands.
  112. */
  113. const commands = {
  114. AVATAR_ID: AVATAR_ID_COMMAND,
  115. AVATAR_URL: AVATAR_URL_COMMAND,
  116. CUSTOM_ROLE: 'custom-role',
  117. EMAIL: EMAIL_COMMAND,
  118. ETHERPAD: 'etherpad',
  119. SHARED_VIDEO: 'shared-video'
  120. };
  121. /**
  122. * Open Connection. When authentication failed it shows auth dialog.
  123. * @param roomName the room name to use
  124. * @returns Promise<JitsiConnection>
  125. */
  126. function connect(roomName) {
  127. return openConnection({
  128. retry: true,
  129. roomName
  130. })
  131. .catch(err => {
  132. if (err === JitsiConnectionErrors.PASSWORD_REQUIRED) {
  133. APP.UI.notifyTokenAuthFailed();
  134. } else {
  135. APP.UI.notifyConnectionFailed(err);
  136. }
  137. throw err;
  138. });
  139. }
  140. /**
  141. * Share data to other users.
  142. * @param command the command
  143. * @param {string} value new value
  144. */
  145. function sendData(command, value) {
  146. if (!room) {
  147. return;
  148. }
  149. room.removeCommand(command);
  150. room.sendCommand(command, { value });
  151. }
  152. /**
  153. * Get user nickname by user id.
  154. * @param {string} id user id
  155. * @returns {string?} user nickname or undefined if user is unknown.
  156. */
  157. function getDisplayName(id) {
  158. const participant = getParticipantById(APP.store.getState(), id);
  159. return participant && participant.name;
  160. }
  161. /**
  162. * Mute or unmute local audio stream if it exists.
  163. * @param {boolean} muted - if audio stream should be muted or unmuted.
  164. */
  165. function muteLocalAudio(muted) {
  166. APP.store.dispatch(setAudioMuted(muted));
  167. }
  168. /**
  169. * Mute or unmute local video stream if it exists.
  170. * @param {boolean} muted if video stream should be muted or unmuted.
  171. *
  172. */
  173. function muteLocalVideo(muted) {
  174. APP.store.dispatch(setVideoMuted(muted));
  175. }
  176. /**
  177. * Check if the welcome page is enabled and redirects to it.
  178. * If requested show a thank you dialog before that.
  179. * If we have a close page enabled, redirect to it without
  180. * showing any other dialog.
  181. *
  182. * @param {object} options used to decide which particular close page to show
  183. * or if close page is disabled, whether we should show the thankyou dialog
  184. * @param {boolean} options.thankYouDialogVisible - whether we should
  185. * show thank you dialog
  186. * @param {boolean} options.feedbackSubmitted - whether feedback was submitted
  187. */
  188. function maybeRedirectToWelcomePage(options) {
  189. // if close page is enabled redirect to it, without further action
  190. if (config.enableClosePage) {
  191. const { isGuest } = APP.store.getState()['features/base/jwt'];
  192. // save whether current user is guest or not, before navigating
  193. // to close page
  194. window.sessionStorage.setItem('guest', isGuest);
  195. assignWindowLocationPathname(`static/${
  196. options.feedbackSubmitted ? 'close.html' : 'close2.html'}`);
  197. return;
  198. }
  199. // else: show thankYou dialog only if there is no feedback
  200. if (options.thankYouDialogVisible) {
  201. APP.UI.messageHandler.openMessageDialog(
  202. null, 'dialog.thankYou', { appName: interfaceConfig.APP_NAME });
  203. }
  204. // if Welcome page is enabled redirect to welcome page after 3 sec.
  205. if (config.enableWelcomePage) {
  206. setTimeout(
  207. () => {
  208. APP.settings.setWelcomePageEnabled(true);
  209. assignWindowLocationPathname('./');
  210. },
  211. 3000);
  212. }
  213. }
  214. /**
  215. * Assigns a specific pathname to window.location.pathname taking into account
  216. * the context root of the Web app.
  217. *
  218. * @param {string} pathname - The pathname to assign to
  219. * window.location.pathname. If the specified pathname is relative, the context
  220. * root of the Web app will be prepended to the specified pathname before
  221. * assigning it to window.location.pathname.
  222. * @return {void}
  223. */
  224. function assignWindowLocationPathname(pathname) {
  225. const windowLocation = window.location;
  226. let newPathname = pathname;
  227. if (!newPathname.startsWith('/')) {
  228. // A pathname equal to ./ specifies the current directory. It will be
  229. // fine but pointless to include it because contextRoot is the current
  230. // directory.
  231. newPathname.startsWith('./')
  232. && (newPathname = newPathname.substring(2));
  233. newPathname = getLocationContextRoot(windowLocation) + newPathname;
  234. }
  235. windowLocation.pathname = newPathname;
  236. }
  237. /**
  238. *
  239. */
  240. class ConferenceConnector {
  241. /**
  242. *
  243. */
  244. constructor(resolve, reject) {
  245. this._resolve = resolve;
  246. this._reject = reject;
  247. this.reconnectTimeout = null;
  248. room.on(JitsiConferenceEvents.CONFERENCE_JOINED,
  249. this._handleConferenceJoined.bind(this));
  250. room.on(JitsiConferenceEvents.CONFERENCE_FAILED,
  251. this._onConferenceFailed.bind(this));
  252. room.on(JitsiConferenceEvents.CONFERENCE_ERROR,
  253. this._onConferenceError.bind(this));
  254. }
  255. /**
  256. *
  257. */
  258. _handleConferenceFailed(err) {
  259. this._unsubscribe();
  260. this._reject(err);
  261. }
  262. /**
  263. *
  264. */
  265. _onConferenceFailed(err, ...params) {
  266. APP.store.dispatch(conferenceFailed(room, err, ...params));
  267. logger.error('CONFERENCE FAILED:', err, ...params);
  268. switch (err) {
  269. case JitsiConferenceErrors.CONNECTION_ERROR: {
  270. const [ msg ] = params;
  271. APP.UI.notifyConnectionFailed(msg);
  272. break;
  273. }
  274. case JitsiConferenceErrors.NOT_ALLOWED_ERROR: {
  275. // let's show some auth not allowed page
  276. assignWindowLocationPathname('static/authError.html');
  277. break;
  278. }
  279. // not enough rights to create conference
  280. case JitsiConferenceErrors.AUTHENTICATION_REQUIRED: {
  281. // Schedule reconnect to check if someone else created the room.
  282. this.reconnectTimeout = setTimeout(() => room.join(), 5000);
  283. const { password }
  284. = APP.store.getState()['features/base/conference'];
  285. AuthHandler.requireAuth(room, password);
  286. break;
  287. }
  288. case JitsiConferenceErrors.RESERVATION_ERROR: {
  289. const [ code, msg ] = params;
  290. APP.UI.notifyReservationError(code, msg);
  291. break;
  292. }
  293. case JitsiConferenceErrors.GRACEFUL_SHUTDOWN:
  294. APP.UI.notifyGracefulShutdown();
  295. break;
  296. case JitsiConferenceErrors.JINGLE_FATAL_ERROR: {
  297. const [ error ] = params;
  298. APP.UI.notifyInternalError(error);
  299. break;
  300. }
  301. case JitsiConferenceErrors.CONFERENCE_DESTROYED: {
  302. const [ reason ] = params;
  303. APP.UI.hideStats();
  304. APP.UI.notifyConferenceDestroyed(reason);
  305. break;
  306. }
  307. // FIXME FOCUS_DISCONNECTED is a confusing event name.
  308. // What really happens there is that the library is not ready yet,
  309. // because Jicofo is not available, but it is going to give it another
  310. // try.
  311. case JitsiConferenceErrors.FOCUS_DISCONNECTED: {
  312. const [ focus, retrySec ] = params;
  313. APP.UI.notifyFocusDisconnected(focus, retrySec);
  314. break;
  315. }
  316. case JitsiConferenceErrors.FOCUS_LEFT:
  317. case JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  318. // FIXME the conference should be stopped by the library and not by
  319. // the app. Both the errors above are unrecoverable from the library
  320. // perspective.
  321. room.leave().then(() => connection.disconnect());
  322. break;
  323. case JitsiConferenceErrors.CONFERENCE_MAX_USERS:
  324. connection.disconnect();
  325. APP.UI.notifyMaxUsersLimitReached();
  326. break;
  327. case JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  328. reload();
  329. break;
  330. default:
  331. this._handleConferenceFailed(err, ...params);
  332. }
  333. }
  334. /**
  335. *
  336. */
  337. _onConferenceError(err, ...params) {
  338. logger.error('CONFERENCE Error:', err, params);
  339. switch (err) {
  340. case JitsiConferenceErrors.CHAT_ERROR:
  341. logger.error('Chat error.', err);
  342. if (isButtonEnabled('chat')) {
  343. const [ code, msg ] = params;
  344. APP.UI.showChatError(code, msg);
  345. }
  346. break;
  347. default:
  348. logger.error('Unknown error.', err);
  349. }
  350. }
  351. /**
  352. *
  353. */
  354. _unsubscribe() {
  355. room.off(
  356. JitsiConferenceEvents.CONFERENCE_JOINED,
  357. this._handleConferenceJoined);
  358. room.off(
  359. JitsiConferenceEvents.CONFERENCE_FAILED,
  360. this._onConferenceFailed);
  361. if (this.reconnectTimeout !== null) {
  362. clearTimeout(this.reconnectTimeout);
  363. }
  364. AuthHandler.closeAuth();
  365. }
  366. /**
  367. *
  368. */
  369. _handleConferenceJoined() {
  370. this._unsubscribe();
  371. this._resolve();
  372. }
  373. /**
  374. *
  375. */
  376. connect() {
  377. room.join();
  378. }
  379. }
  380. /**
  381. * Disconnects the connection.
  382. * @returns resolved Promise. We need this in order to make the Promise.all
  383. * call in hangup() to resolve when all operations are finished.
  384. */
  385. function disconnect() {
  386. connection.disconnect();
  387. APP.API.notifyConferenceLeft(APP.conference.roomName);
  388. return Promise.resolve();
  389. }
  390. /**
  391. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  392. *
  393. * @param {JitsiConnectionError} error - The reported error.
  394. * @returns {void}
  395. * @private
  396. */
  397. function _connectionFailedHandler(error) {
  398. if (isFatalJitsiConnectionError(error)) {
  399. APP.connection.removeEventListener(
  400. JitsiConnectionEvents.CONNECTION_FAILED,
  401. _connectionFailedHandler);
  402. if (room) {
  403. room.leave();
  404. }
  405. }
  406. }
  407. export default {
  408. /**
  409. * Flag used to delay modification of the muted status of local media tracks
  410. * until those are created (or not, but at that point it's certain that
  411. * the tracks won't exist).
  412. */
  413. _localTracksInitialized: false,
  414. isModerator: false,
  415. isSharingScreen: false,
  416. /**
  417. * Indicates if the desktop sharing functionality has been enabled.
  418. * It takes into consideration {@link isDesktopSharingDisabledByConfig}
  419. * as well as the status returned by
  420. * {@link JitsiMeetJS.isDesktopSharingEnabled()}. The latter can be false
  421. * either if the desktop sharing is not supported by the current browser
  422. * or if it was disabled through lib-jitsi-meet specific options (check
  423. * config.js for listed options).
  424. */
  425. isDesktopSharingEnabled: false,
  426. /**
  427. * Set to <tt>true</tt> if the desktop sharing functionality has been
  428. * explicitly disabled in the config.
  429. */
  430. isDesktopSharingDisabledByConfig: false,
  431. /**
  432. * The text displayed when the desktop sharing button is disabled through
  433. * the config. The value is set through
  434. * {@link interfaceConfig.DESKTOP_SHARING_BUTTON_DISABLED_TOOLTIP}.
  435. */
  436. desktopSharingDisabledTooltip: null,
  437. /*
  438. * Whether the local "raisedHand" flag is on.
  439. */
  440. isHandRaised: false,
  441. /*
  442. * Whether the local participant is the dominant speaker in the conference.
  443. */
  444. isDominantSpeaker: false,
  445. /**
  446. * The local audio track (if any).
  447. * FIXME tracks from redux store should be the single source of truth
  448. * @type {JitsiLocalTrack|null}
  449. */
  450. localAudio: null,
  451. /**
  452. * The local video track (if any).
  453. * FIXME tracks from redux store should be the single source of truth, but
  454. * more refactoring is required around screen sharing ('localVideo' usages).
  455. * @type {JitsiLocalTrack|null}
  456. */
  457. localVideo: null,
  458. /**
  459. * Creates local media tracks and connects to a room. Will show error
  460. * dialogs in case accessing the local microphone and/or camera failed. Will
  461. * show guidance overlay for users on how to give access to camera and/or
  462. * microphone.
  463. * @param {string} roomName
  464. * @param {object} options
  465. * @param {boolean} options.startAudioOnly=false - if <tt>true</tt> then
  466. * only audio track will be created and the audio only mode will be turned
  467. * on.
  468. * @param {boolean} options.startScreenSharing=false - if <tt>true</tt>
  469. * should start with screensharing instead of camera video.
  470. * @param {boolean} options.startWithAudioMuted - will start the conference
  471. * without any audio tracks.
  472. * @param {boolean} options.startWithVideoMuted - will start the conference
  473. * without any video tracks.
  474. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  475. */
  476. createInitialLocalTracksAndConnect(roomName, options = {}) {
  477. let audioAndVideoError,
  478. audioOnlyError,
  479. screenSharingError,
  480. videoOnlyError;
  481. const initialDevices = [];
  482. let requestedAudio = false;
  483. let requestedVideo = false;
  484. if (!options.startWithAudioMuted) {
  485. initialDevices.push('audio');
  486. requestedAudio = true;
  487. }
  488. if (!options.startWithVideoMuted
  489. && !options.startAudioOnly
  490. && !options.startScreenSharing) {
  491. initialDevices.push('video');
  492. requestedVideo = true;
  493. }
  494. JitsiMeetJS.mediaDevices.addEventListener(
  495. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  496. browser =>
  497. APP.store.dispatch(
  498. mediaPermissionPromptVisibilityChanged(true, browser))
  499. );
  500. let tryCreateLocalTracks;
  501. // FIXME is there any simpler way to rewrite this spaghetti below ?
  502. if (options.startScreenSharing) {
  503. tryCreateLocalTracks = this._createDesktopTrack()
  504. .then(desktopStream => {
  505. if (!requestedAudio) {
  506. return [ desktopStream ];
  507. }
  508. return createLocalTracksF({ devices: [ 'audio' ] }, true)
  509. .then(([ audioStream ]) =>
  510. [ desktopStream, audioStream ])
  511. .catch(error => {
  512. audioOnlyError = error;
  513. return [ desktopStream ];
  514. });
  515. })
  516. .catch(error => {
  517. logger.error('Failed to obtain desktop stream', error);
  518. screenSharingError = error;
  519. return requestedAudio
  520. ? createLocalTracksF({ devices: [ 'audio' ] }, true)
  521. : [];
  522. })
  523. .catch(error => {
  524. audioOnlyError = error;
  525. return [];
  526. });
  527. } else if (!requestedAudio && !requestedVideo) {
  528. // Resolve with no tracks
  529. tryCreateLocalTracks = Promise.resolve([]);
  530. } else {
  531. tryCreateLocalTracks = createLocalTracksF(
  532. { devices: initialDevices }, true)
  533. .catch(err => {
  534. if (requestedAudio && requestedVideo) {
  535. // Try audio only...
  536. audioAndVideoError = err;
  537. return (
  538. createLocalTracksF({ devices: [ 'audio' ] }, true));
  539. } else if (requestedAudio && !requestedVideo) {
  540. audioOnlyError = err;
  541. return [];
  542. } else if (requestedVideo && !requestedAudio) {
  543. videoOnlyError = err;
  544. return [];
  545. }
  546. logger.error('Should never happen');
  547. })
  548. .catch(err => {
  549. // Log this just in case...
  550. if (!requestedAudio) {
  551. logger.error('The impossible just happened', err);
  552. }
  553. audioOnlyError = err;
  554. // Try video only...
  555. return requestedVideo
  556. ? createLocalTracksF({ devices: [ 'video' ] }, true)
  557. : [];
  558. })
  559. .catch(err => {
  560. // Log this just in case...
  561. if (!requestedVideo) {
  562. logger.error('The impossible just happened', err);
  563. }
  564. videoOnlyError = err;
  565. return [];
  566. });
  567. }
  568. // Hide the permissions prompt/overlay as soon as the tracks are
  569. // created. Don't wait for the connection to be made, since in some
  570. // cases, when auth is rquired, for instance, that won't happen until
  571. // the user inputs their credentials, but the dialog would be
  572. // overshadowed by the overlay.
  573. tryCreateLocalTracks.then(() =>
  574. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false)));
  575. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  576. .then(([ tracks, con ]) => {
  577. // FIXME If there will be microphone error it will cover any
  578. // screensharing dialog, but it's still better than in
  579. // the reverse order where the screensharing dialog will
  580. // sometimes be closing the microphone alert ($.prompt.close();
  581. // is called). Need to figure out dialogs chaining to fix that.
  582. if (screenSharingError) {
  583. this._handleScreenSharingError(screenSharingError);
  584. }
  585. if (audioAndVideoError || audioOnlyError) {
  586. if (audioOnlyError || videoOnlyError) {
  587. // If both requests for 'audio' + 'video' and 'audio'
  588. // only failed, we assume that there are some problems
  589. // with user's microphone and show corresponding dialog.
  590. APP.UI.showMicErrorNotification(audioOnlyError);
  591. APP.UI.showCameraErrorNotification(videoOnlyError);
  592. } else {
  593. // If request for 'audio' + 'video' failed, but request
  594. // for 'audio' only was OK, we assume that we had
  595. // problems with camera and show corresponding dialog.
  596. APP.UI.showCameraErrorNotification(audioAndVideoError);
  597. }
  598. }
  599. return [ tracks, con ];
  600. });
  601. },
  602. /**
  603. * Open new connection and join to the conference.
  604. * @param {object} options
  605. * @param {string} roomName name of the conference
  606. * @returns {Promise}
  607. */
  608. init(options) {
  609. this.roomName = options.roomName;
  610. // attaches global error handler, if there is already one, respect it
  611. if (JitsiMeetJS.getGlobalOnErrorHandler) {
  612. const oldOnErrorHandler = window.onerror;
  613. // eslint-disable-next-line max-params
  614. window.onerror = (message, source, lineno, colno, error) => {
  615. JitsiMeetJS.getGlobalOnErrorHandler(
  616. message, source, lineno, colno, error);
  617. if (oldOnErrorHandler) {
  618. oldOnErrorHandler(message, source, lineno, colno, error);
  619. }
  620. };
  621. const oldOnUnhandledRejection = window.onunhandledrejection;
  622. window.onunhandledrejection = function(event) {
  623. JitsiMeetJS.getGlobalOnErrorHandler(
  624. null, null, null, null, event.reason);
  625. if (oldOnUnhandledRejection) {
  626. oldOnUnhandledRejection(event);
  627. }
  628. };
  629. }
  630. return (
  631. JitsiMeetJS.init({
  632. enableAnalyticsLogging: isAnalyticsEnabled(APP.store),
  633. ...config
  634. }).then(() => {
  635. initAnalytics(APP.store);
  636. return this.createInitialLocalTracksAndConnect(
  637. options.roomName, {
  638. startAudioOnly: config.startAudioOnly,
  639. startScreenSharing: config.startScreenSharing,
  640. startWithAudioMuted: config.startWithAudioMuted,
  641. startWithVideoMuted: config.startWithVideoMuted
  642. });
  643. })
  644. .then(([ tracks, con ]) => {
  645. tracks.forEach(track => {
  646. if (track.isAudioTrack() && this.isLocalAudioMuted()) {
  647. sendAnalyticsEvent(CONFERENCE_AUDIO_INITIALLY_MUTED);
  648. logger.log('Audio mute: initially muted');
  649. track.mute();
  650. } else if (track.isVideoTrack()
  651. && this.isLocalVideoMuted()) {
  652. sendAnalyticsEvent(CONFERENCE_VIDEO_INITIALLY_MUTED);
  653. logger.log('Video mute: initially muted');
  654. track.mute();
  655. }
  656. });
  657. logger.log('initialized with %s local tracks', tracks.length);
  658. this._localTracksInitialized = true;
  659. con.addEventListener(
  660. JitsiConnectionEvents.CONNECTION_FAILED,
  661. _connectionFailedHandler);
  662. APP.connection = connection = con;
  663. // Desktop sharing related stuff:
  664. this.isDesktopSharingDisabledByConfig
  665. = config.disableDesktopSharing;
  666. this.isDesktopSharingEnabled
  667. = !this.isDesktopSharingDisabledByConfig
  668. && JitsiMeetJS.isDesktopSharingEnabled();
  669. this.desktopSharingDisabledTooltip
  670. = interfaceConfig.DESKTOP_SHARING_BUTTON_DISABLED_TOOLTIP;
  671. eventEmitter.emit(
  672. JitsiMeetConferenceEvents.DESKTOP_SHARING_ENABLED_CHANGED,
  673. this.isDesktopSharingEnabled);
  674. APP.store.dispatch(showDesktopSharingButton());
  675. this._createRoom(tracks);
  676. APP.remoteControl.init();
  677. // if user didn't give access to mic or camera or doesn't have
  678. // them at all, we mark corresponding toolbar buttons as muted,
  679. // so that the user can try unmute later on and add audio/video
  680. // to the conference
  681. if (!tracks.find(t => t.isAudioTrack())) {
  682. this.setAudioMuteStatus(true);
  683. }
  684. if (!tracks.find(t => t.isVideoTrack())) {
  685. this.setVideoMuteStatus(true);
  686. }
  687. this._initDeviceList();
  688. if (config.iAmRecorder) {
  689. this.recorder = new Recorder();
  690. }
  691. // XXX The API will take care of disconnecting from the XMPP
  692. // server (and, thus, leaving the room) on unload.
  693. return new Promise((resolve, reject) => {
  694. (new ConferenceConnector(resolve, reject)).connect();
  695. });
  696. })
  697. );
  698. },
  699. /**
  700. * Check if id is id of the local user.
  701. * @param {string} id id to check
  702. * @returns {boolean}
  703. */
  704. isLocalId(id) {
  705. return this.getMyUserId() === id;
  706. },
  707. /**
  708. * Tells whether the local video is muted or not.
  709. * @return {boolean}
  710. */
  711. isLocalVideoMuted() {
  712. // If the tracks are not ready, read from base/media state
  713. return this._localTracksInitialized
  714. ? isLocalTrackMuted(
  715. APP.store.getState()['features/base/tracks'],
  716. MEDIA_TYPE.VIDEO)
  717. : isVideoMutedByUser(APP.store);
  718. },
  719. /**
  720. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  721. * @param {boolean} mute true for mute and false for unmute.
  722. * @param {boolean} [showUI] when set to false will not display any error
  723. * dialogs in case of media permissions error.
  724. */
  725. muteAudio(mute, showUI = true) {
  726. // Not ready to modify track's state yet
  727. if (!this._localTracksInitialized) {
  728. // This will only modify base/media.audio.muted which is then synced
  729. // up with the track at the end of local tracks initialization.
  730. muteLocalAudio(mute);
  731. this.setAudioMuteStatus(mute);
  732. return;
  733. } else if (this.isLocalAudioMuted() === mute) {
  734. // NO-OP
  735. return;
  736. }
  737. if (!this.localAudio && !mute) {
  738. const maybeShowErrorDialog = error => {
  739. showUI && APP.UI.showMicErrorNotification(error);
  740. };
  741. createLocalTracksF({ devices: [ 'audio' ] }, false)
  742. .then(([ audioTrack ]) => audioTrack)
  743. .catch(error => {
  744. maybeShowErrorDialog(error);
  745. // Rollback the audio muted status by using null track
  746. return null;
  747. })
  748. .then(audioTrack => this.useAudioStream(audioTrack));
  749. } else {
  750. muteLocalAudio(mute);
  751. }
  752. },
  753. /**
  754. * Returns whether local audio is muted or not.
  755. * @returns {boolean}
  756. */
  757. isLocalAudioMuted() {
  758. // If the tracks are not ready, read from base/media state
  759. return this._localTracksInitialized
  760. ? isLocalTrackMuted(
  761. APP.store.getState()['features/base/tracks'],
  762. MEDIA_TYPE.AUDIO)
  763. : Boolean(
  764. APP.store.getState()['features/base/media'].audio.muted);
  765. },
  766. /**
  767. * Simulates toolbar button click for audio mute. Used by shortcuts
  768. * and API.
  769. * @param {boolean} [showUI] when set to false will not display any error
  770. * dialogs in case of media permissions error.
  771. */
  772. toggleAudioMuted(showUI = true) {
  773. this.muteAudio(!this.isLocalAudioMuted(), showUI);
  774. },
  775. /**
  776. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  777. * @param mute true for mute and false for unmute.
  778. * @param {boolean} [showUI] when set to false will not display any error
  779. * dialogs in case of media permissions error.
  780. */
  781. muteVideo(mute, showUI = true) {
  782. // If not ready to modify track's state yet adjust the base/media
  783. if (!this._localTracksInitialized) {
  784. // This will only modify base/media.video.muted which is then synced
  785. // up with the track at the end of local tracks initialization.
  786. muteLocalVideo(mute);
  787. this.setVideoMuteStatus(mute);
  788. return;
  789. } else if (this.isLocalVideoMuted() === mute) {
  790. // NO-OP
  791. return;
  792. }
  793. // FIXME it is possible to queue this task twice, but it's not causing
  794. // any issues. Specifically this can happen when the previous
  795. // get user media call is blocked on "ask user for permissions" dialog.
  796. if (!this.localVideo && !mute) {
  797. const maybeShowErrorDialog = error => {
  798. showUI && APP.UI.showCameraErrorNotification(error);
  799. };
  800. // Try to create local video if there wasn't any.
  801. // This handles the case when user joined with no video
  802. // (dismissed screen sharing screen or in audio only mode), but
  803. // decided to add it later on by clicking on muted video icon or
  804. // turning off the audio only mode.
  805. //
  806. // FIXME when local track creation is moved to react/redux
  807. // it should take care of the use case described above
  808. createLocalTracksF({ devices: [ 'video' ] }, false)
  809. .then(([ videoTrack ]) => videoTrack)
  810. .catch(error => {
  811. // FIXME should send some feedback to the API on error ?
  812. maybeShowErrorDialog(error);
  813. // Rollback the video muted status by using null track
  814. return null;
  815. })
  816. .then(videoTrack => this.useVideoStream(videoTrack));
  817. } else {
  818. // FIXME show error dialog if it fails (should be handled by react)
  819. muteLocalVideo(mute);
  820. }
  821. },
  822. /**
  823. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  824. * @param {boolean} [showUI] when set to false will not display any error
  825. * dialogs in case of media permissions error.
  826. */
  827. toggleVideoMuted(showUI = true) {
  828. this.muteVideo(!this.isLocalVideoMuted(), showUI);
  829. },
  830. /**
  831. * Retrieve list of conference participants (without local user).
  832. * @returns {JitsiParticipant[]}
  833. */
  834. listMembers() {
  835. return room.getParticipants();
  836. },
  837. /**
  838. * Retrieve list of ids of conference participants (without local user).
  839. * @returns {string[]}
  840. */
  841. listMembersIds() {
  842. return room.getParticipants().map(p => p.getId());
  843. },
  844. /**
  845. * Checks whether the participant identified by id is a moderator.
  846. * @id id to search for participant
  847. * @return {boolean} whether the participant is moderator
  848. */
  849. isParticipantModerator(id) {
  850. const user = room.getParticipantById(id);
  851. return user && user.isModerator();
  852. },
  853. get membersCount() {
  854. return room.getParticipants().length + 1;
  855. },
  856. /**
  857. * Returns true if the callstats integration is enabled, otherwise returns
  858. * false.
  859. *
  860. * @returns true if the callstats integration is enabled, otherwise returns
  861. * false.
  862. */
  863. isCallstatsEnabled() {
  864. return room && room.isCallstatsEnabled();
  865. },
  866. /**
  867. * Sends the given feedback through CallStats if enabled.
  868. *
  869. * @param overallFeedback an integer between 1 and 5 indicating the
  870. * user feedback
  871. * @param detailedFeedback detailed feedback from the user. Not yet used
  872. */
  873. sendFeedback(overallFeedback, detailedFeedback) {
  874. return room.sendFeedback(overallFeedback, detailedFeedback);
  875. },
  876. /**
  877. * Get speaker stats that track total dominant speaker time.
  878. *
  879. * @returns {object} A hash with keys being user ids and values being the
  880. * library's SpeakerStats model used for calculating time as dominant
  881. * speaker.
  882. */
  883. getSpeakerStats() {
  884. return room.getSpeakerStats();
  885. },
  886. /**
  887. * Returns the connection times stored in the library.
  888. */
  889. getConnectionTimes() {
  890. return this._room.getConnectionTimes();
  891. },
  892. // used by torture currently
  893. isJoined() {
  894. return this._room
  895. && this._room.isJoined();
  896. },
  897. getConnectionState() {
  898. return this._room
  899. && this._room.getConnectionState();
  900. },
  901. /**
  902. * Obtains current P2P ICE connection state.
  903. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  904. * P2P connection
  905. */
  906. getP2PConnectionState() {
  907. return this._room
  908. && this._room.getP2PConnectionState();
  909. },
  910. /**
  911. * Starts P2P (for tests only)
  912. * @private
  913. */
  914. _startP2P() {
  915. try {
  916. this._room && this._room.startP2PSession();
  917. } catch (error) {
  918. logger.error('Start P2P failed', error);
  919. throw error;
  920. }
  921. },
  922. /**
  923. * Stops P2P (for tests only)
  924. * @private
  925. */
  926. _stopP2P() {
  927. try {
  928. this._room && this._room.stopP2PSession();
  929. } catch (error) {
  930. logger.error('Stop P2P failed', error);
  931. throw error;
  932. }
  933. },
  934. /**
  935. * Checks whether or not our connection is currently in interrupted and
  936. * reconnect attempts are in progress.
  937. *
  938. * @returns {boolean} true if the connection is in interrupted state or
  939. * false otherwise.
  940. */
  941. isConnectionInterrupted() {
  942. return this._room.isConnectionInterrupted();
  943. },
  944. /**
  945. * Obtains the local display name.
  946. * @returns {string|undefined}
  947. */
  948. getLocalDisplayName() {
  949. return getDisplayName(this.getMyUserId());
  950. },
  951. /**
  952. * Finds JitsiParticipant for given id.
  953. *
  954. * @param {string} id participant's identifier(MUC nickname).
  955. *
  956. * @returns {JitsiParticipant|null} participant instance for given id or
  957. * null if not found.
  958. */
  959. getParticipantById(id) {
  960. return room ? room.getParticipantById(id) : null;
  961. },
  962. /**
  963. * Get participant connection status for the participant.
  964. *
  965. * @param {string} id participant's identifier(MUC nickname)
  966. *
  967. * @returns {ParticipantConnectionStatus|null} the status of the participant
  968. * or null if no such participant is found or participant is the local user.
  969. */
  970. getParticipantConnectionStatus(id) {
  971. const participant = this.getParticipantById(id);
  972. return participant ? participant.getConnectionStatus() : null;
  973. },
  974. /**
  975. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  976. * the given <tt>id</tt>.
  977. *
  978. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  979. *
  980. * @return {string} the participant's display name or the default string if
  981. * absent.
  982. */
  983. getParticipantDisplayName(id) {
  984. const displayName = getDisplayName(id);
  985. if (displayName) {
  986. return displayName;
  987. }
  988. if (APP.conference.isLocalId(id)) {
  989. return APP.translation.generateTranslationHTML(
  990. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  991. }
  992. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  993. },
  994. getMyUserId() {
  995. return this._room && this._room.myUserId();
  996. },
  997. /**
  998. * Indicates if recording is supported in this conference.
  999. */
  1000. isRecordingSupported() {
  1001. return this._room && this._room.isRecordingSupported();
  1002. },
  1003. /**
  1004. * Returns the recording state or undefined if the room is not defined.
  1005. */
  1006. getRecordingState() {
  1007. return this._room ? this._room.getRecordingState() : undefined;
  1008. },
  1009. /**
  1010. * Will be filled with values only when config.debug is enabled.
  1011. * Its used by torture to check audio levels.
  1012. */
  1013. audioLevelsMap: {},
  1014. /**
  1015. * Returns the stored audio level (stored only if config.debug is enabled)
  1016. * @param id the id for the user audio level to return (the id value is
  1017. * returned for the participant using getMyUserId() method)
  1018. */
  1019. getPeerSSRCAudioLevel(id) {
  1020. return this.audioLevelsMap[id];
  1021. },
  1022. /**
  1023. * @return {number} the number of participants in the conference with at
  1024. * least one track.
  1025. */
  1026. getNumberOfParticipantsWithTracks() {
  1027. return this._room.getParticipants()
  1028. .filter(p => p.getTracks().length > 0)
  1029. .length;
  1030. },
  1031. /**
  1032. * Returns the stats.
  1033. */
  1034. getStats() {
  1035. return room.connectionQuality.getStats();
  1036. },
  1037. // end used by torture
  1038. getLogs() {
  1039. return room.getLogs();
  1040. },
  1041. /**
  1042. * Download logs, a function that can be called from console while
  1043. * debugging.
  1044. * @param filename (optional) specify target filename
  1045. */
  1046. saveLogs(filename = 'meetlog.json') {
  1047. // this can be called from console and will not have reference to this
  1048. // that's why we reference the global var
  1049. const logs = APP.conference.getLogs();
  1050. const data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  1051. const elem = document.createElement('a');
  1052. elem.download = filename;
  1053. elem.href = `data:application/json;charset=utf-8,\n${data}`;
  1054. elem.dataset.downloadurl
  1055. = [ 'text/json', elem.download, elem.href ].join(':');
  1056. elem.dispatchEvent(new MouseEvent('click', {
  1057. view: window,
  1058. bubbles: true,
  1059. cancelable: false
  1060. }));
  1061. },
  1062. /**
  1063. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  1064. * desire to keep room private to this instance and (2) the need of other
  1065. * modules to send and receive commands to and from participants.
  1066. * Eventually, this instance remains in control with respect to the
  1067. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  1068. * JitsiConference) is to be used in the implementation of the Command(s)
  1069. * API of this instance.
  1070. */
  1071. commands: {
  1072. /**
  1073. * Known custom conference commands.
  1074. */
  1075. defaults: commands,
  1076. /**
  1077. * Receives notifications from other participants about commands aka
  1078. * custom events (sent by sendCommand or sendCommandOnce methods).
  1079. * @param command {String} the name of the command
  1080. * @param handler {Function} handler for the command
  1081. */
  1082. addCommandListener() {
  1083. // eslint-disable-next-line prefer-rest-params
  1084. room.addCommandListener(...arguments);
  1085. },
  1086. /**
  1087. * Removes command.
  1088. * @param name {String} the name of the command.
  1089. */
  1090. removeCommand() {
  1091. // eslint-disable-next-line prefer-rest-params
  1092. room.removeCommand(...arguments);
  1093. },
  1094. /**
  1095. * Sends command.
  1096. * @param name {String} the name of the command.
  1097. * @param values {Object} with keys and values that will be sent.
  1098. */
  1099. sendCommand() {
  1100. // eslint-disable-next-line prefer-rest-params
  1101. room.sendCommand(...arguments);
  1102. },
  1103. /**
  1104. * Sends command one time.
  1105. * @param name {String} the name of the command.
  1106. * @param values {Object} with keys and values that will be sent.
  1107. */
  1108. sendCommandOnce() {
  1109. // eslint-disable-next-line prefer-rest-params
  1110. room.sendCommandOnce(...arguments);
  1111. }
  1112. },
  1113. _createRoom(localTracks) {
  1114. room
  1115. = connection.initJitsiConference(
  1116. APP.conference.roomName,
  1117. this._getConferenceOptions());
  1118. APP.store.dispatch(conferenceWillJoin(room));
  1119. this._setLocalAudioVideoStreams(localTracks);
  1120. this._room = room; // FIXME do not use this
  1121. sendLocalParticipant(APP.store, room);
  1122. this._setupListeners();
  1123. },
  1124. /**
  1125. * Sets local video and audio streams.
  1126. * @param {JitsiLocalTrack[]} tracks=[]
  1127. * @returns {Promise[]}
  1128. * @private
  1129. */
  1130. _setLocalAudioVideoStreams(tracks = []) {
  1131. return tracks.map(track => {
  1132. if (track.isAudioTrack()) {
  1133. return this.useAudioStream(track);
  1134. } else if (track.isVideoTrack()) {
  1135. return this.useVideoStream(track);
  1136. }
  1137. logger.error(
  1138. 'Ignored not an audio nor a video track: ', track);
  1139. return Promise.resolve();
  1140. });
  1141. },
  1142. _getConferenceOptions() {
  1143. const options = config;
  1144. if (config.enableRecording && !config.recordingType) {
  1145. options.recordingType
  1146. = config.hosts && (typeof config.hosts.jirecon !== 'undefined')
  1147. ? 'jirecon'
  1148. : 'colibri';
  1149. }
  1150. const nick = APP.settings.getDisplayName();
  1151. if (nick) {
  1152. options.displayName = nick;
  1153. }
  1154. options.applicationName = interfaceConfig.APP_NAME;
  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. sendAnalyticsEvent(CONFERENCE_SHARING_DESKTOP_STOP);
  1271. logger.log('switched back to local 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 screenshairng 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. sendAnalyticsEvent(CONFERENCE_SHARING_DESKTOP_START);
  1432. logger.log('sharing local desktop');
  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. sendAnalyticsEvent(SELECT_PARTICIPANT_FAILED);
  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. APP.UI.setUserAvatarUrl(from, data.value);
  1819. });
  1820. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1821. (data, from) => {
  1822. APP.store.dispatch(
  1823. participantUpdated({
  1824. id: from,
  1825. avatarID: data.value
  1826. }));
  1827. APP.UI.setUserAvatarID(from, data.value);
  1828. });
  1829. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1830. this.changeLocalDisplayName.bind(this));
  1831. room.on(
  1832. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  1833. ({ audio, video }) => {
  1834. APP.store.dispatch(
  1835. onStartMutedPolicyChanged(audio, video));
  1836. }
  1837. );
  1838. room.on(JitsiConferenceEvents.STARTED_MUTED, () => {
  1839. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1840. && APP.UI.notifyInitiallyMuted();
  1841. });
  1842. room.on(
  1843. JitsiConferenceEvents.AVAILABLE_DEVICES_CHANGED,
  1844. (id, devices) => {
  1845. APP.UI.updateDevicesAvailability(id, devices);
  1846. }
  1847. );
  1848. room.on(
  1849. JitsiConferenceEvents.DATA_CHANNEL_OPENED, () => {
  1850. APP.store.dispatch(dataChannelOpened());
  1851. }
  1852. );
  1853. // call hangup
  1854. APP.UI.addListener(UIEvents.HANGUP, () => {
  1855. this.hangup(true);
  1856. });
  1857. // logout
  1858. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1859. AuthHandler.logout(room).then(url => {
  1860. if (url) {
  1861. UIUtil.redirect(url);
  1862. } else {
  1863. this.hangup(true);
  1864. }
  1865. });
  1866. });
  1867. /* eslint-disable max-params */
  1868. APP.UI.addListener(
  1869. UIEvents.RESOLUTION_CHANGED,
  1870. (id, oldResolution, newResolution, delay) => {
  1871. const logObject = {
  1872. id: 'resolution_change',
  1873. participant: id,
  1874. oldValue: oldResolution,
  1875. newValue: newResolution,
  1876. delay
  1877. };
  1878. room.sendApplicationLog(JSON.stringify(logObject));
  1879. // We only care about the delay between simulcast streams.
  1880. // Longer delays will be caused by something else and will just
  1881. // poison the data.
  1882. if (delay < 2000) {
  1883. sendAnalyticsEvent(STREAM_SWITCH_DELAY, { value: delay });
  1884. }
  1885. });
  1886. /* eslint-enable max-params */
  1887. // Starts or stops the recording for the conference.
  1888. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, options => {
  1889. room.toggleRecording(options);
  1890. });
  1891. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, topic => {
  1892. room.setSubject(topic);
  1893. });
  1894. room.on(JitsiConferenceEvents.SUBJECT_CHANGED, subject => {
  1895. APP.UI.setSubject(subject);
  1896. });
  1897. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1898. AuthHandler.authenticate(room);
  1899. });
  1900. APP.UI.addListener(
  1901. UIEvents.VIDEO_DEVICE_CHANGED,
  1902. cameraDeviceId => {
  1903. const videoWasMuted = this.isLocalVideoMuted();
  1904. sendAnalyticsEvent(SETTINGS_CHANGE_DEVICE_VIDEO);
  1905. createLocalTracksF({
  1906. devices: [ 'video' ],
  1907. cameraDeviceId,
  1908. micDeviceId: null
  1909. })
  1910. .then(([ stream ]) => {
  1911. // if we are in audio only mode or video was muted before
  1912. // changing device, then mute
  1913. if (this.isAudioOnly() || videoWasMuted) {
  1914. return stream.mute()
  1915. .then(() => stream);
  1916. }
  1917. return stream;
  1918. })
  1919. .then(stream => {
  1920. // if we are screen sharing we do not want to stop it
  1921. if (this.isSharingScreen) {
  1922. return Promise.resolve();
  1923. }
  1924. return this.useVideoStream(stream);
  1925. })
  1926. .then(() => {
  1927. logger.log('switched local video device');
  1928. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1929. })
  1930. .catch(err => {
  1931. APP.UI.showCameraErrorNotification(err);
  1932. });
  1933. }
  1934. );
  1935. APP.UI.addListener(
  1936. UIEvents.AUDIO_DEVICE_CHANGED,
  1937. micDeviceId => {
  1938. const audioWasMuted = this.isLocalAudioMuted();
  1939. sendAnalyticsEvent(SETTINGS_CHANGE_DEVICE_AUDIO_IN);
  1940. createLocalTracksF({
  1941. devices: [ 'audio' ],
  1942. cameraDeviceId: null,
  1943. micDeviceId
  1944. })
  1945. .then(([ stream ]) => {
  1946. // if audio was muted before changing the device, mute
  1947. // with the new device
  1948. if (audioWasMuted) {
  1949. return stream.mute()
  1950. .then(() => stream);
  1951. }
  1952. return stream;
  1953. })
  1954. .then(stream => {
  1955. this.useAudioStream(stream);
  1956. logger.log('switched local audio device');
  1957. APP.settings.setMicDeviceId(micDeviceId, true);
  1958. })
  1959. .catch(err => {
  1960. APP.UI.showMicErrorNotification(err);
  1961. });
  1962. }
  1963. );
  1964. APP.UI.addListener(
  1965. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1966. audioOutputDeviceId => {
  1967. sendAnalyticsEvent(SETTINGS_CHANGE_DEVICE_AUDIO_OUT);
  1968. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1969. .then(() => logger.log('changed audio output device'))
  1970. .catch(err => {
  1971. logger.warn('Failed to change audio output device. '
  1972. + 'Default or previously set audio output device '
  1973. + 'will be used instead.', err);
  1974. });
  1975. }
  1976. );
  1977. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  1978. // FIXME On web video track is stored both in redux and in
  1979. // 'localVideo' field, video is attempted to be unmuted twice when
  1980. // turning off the audio only mode. This will crash the app with
  1981. // 'unmute operation is already in progress'.
  1982. // Because there's no logic in redux about creating new track in
  1983. // case unmute when not track exists the things have to go through
  1984. // muteVideo logic in such case.
  1985. const tracks = APP.store.getState()['features/base/tracks'];
  1986. const isTrackInRedux
  1987. = Boolean(
  1988. tracks.find(
  1989. track => track.jitsiTrack
  1990. && track.jitsiTrack.getType() === 'video'));
  1991. if (!isTrackInRedux) {
  1992. this.muteVideo(audioOnly);
  1993. }
  1994. // Immediately update the UI by having remote videos and the large
  1995. // video update themselves instead of waiting for some other event
  1996. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  1997. // There is no guarantee another event will trigger the update
  1998. // immediately and in all situations, for example because a remote
  1999. // participant is having connection trouble so no status changes.
  2000. APP.UI.updateAllVideos();
  2001. });
  2002. APP.UI.addListener(
  2003. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  2004. );
  2005. /* eslint-disable max-params */
  2006. APP.UI.addListener(
  2007. UIEvents.UPDATE_SHARED_VIDEO,
  2008. (url, state, time, isMuted, volume) => {
  2009. /* eslint-enable max-params */
  2010. // send start and stop commands once, and remove any updates
  2011. // that had left
  2012. if (state === 'stop'
  2013. || state === 'start'
  2014. || state === 'playing') {
  2015. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  2016. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  2017. value: url,
  2018. attributes: {
  2019. state,
  2020. time,
  2021. muted: isMuted,
  2022. volume
  2023. }
  2024. });
  2025. } else {
  2026. // in case of paused, in order to allow late users to join
  2027. // paused
  2028. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  2029. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  2030. value: url,
  2031. attributes: {
  2032. state,
  2033. time,
  2034. muted: isMuted,
  2035. volume
  2036. }
  2037. });
  2038. }
  2039. });
  2040. room.addCommandListener(
  2041. this.commands.defaults.SHARED_VIDEO,
  2042. ({ value, attributes }, id) => {
  2043. if (attributes.state === 'stop') {
  2044. APP.UI.onSharedVideoStop(id, attributes);
  2045. } else if (attributes.state === 'start') {
  2046. APP.UI.onSharedVideoStart(id, value, attributes);
  2047. } else if (attributes.state === 'playing'
  2048. || attributes.state === 'pause') {
  2049. APP.UI.onSharedVideoUpdate(id, value, attributes);
  2050. }
  2051. });
  2052. },
  2053. /**
  2054. * Callback invoked when the conference has been successfully joined.
  2055. * Initializes the UI and various other features.
  2056. *
  2057. * @private
  2058. * @returns {void}
  2059. */
  2060. _onConferenceJoined() {
  2061. if (APP.logCollector) {
  2062. // Start the LogCollector's periodic "store logs" task
  2063. APP.logCollector.start();
  2064. APP.logCollectorStarted = true;
  2065. // Make an attempt to flush in case a lot of logs have been
  2066. // cached, before the collector was started.
  2067. APP.logCollector.flush();
  2068. // This event listener will flush the logs, before
  2069. // the statistics module (CallStats) is stopped.
  2070. //
  2071. // NOTE The LogCollector is not stopped, because this event can
  2072. // be triggered multiple times during single conference
  2073. // (whenever statistics module is stopped). That includes
  2074. // the case when Jicofo terminates the single person left in the
  2075. // room. It will then restart the media session when someone
  2076. // eventually join the room which will start the stats again.
  2077. APP.conference.addConferenceListener(
  2078. JitsiConferenceEvents.BEFORE_STATISTICS_DISPOSED,
  2079. () => {
  2080. if (APP.logCollector) {
  2081. APP.logCollector.flush();
  2082. }
  2083. }
  2084. );
  2085. }
  2086. APP.UI.initConference();
  2087. APP.keyboardshortcut.init();
  2088. if (config.requireDisplayName
  2089. && !APP.conference.getLocalDisplayName()) {
  2090. APP.UI.promptDisplayName();
  2091. }
  2092. APP.store.dispatch(conferenceJoined(room));
  2093. APP.UI.mucJoined();
  2094. const displayName = APP.settings.getDisplayName();
  2095. APP.API.notifyConferenceJoined(
  2096. this.roomName,
  2097. this._room.myUserId(),
  2098. {
  2099. displayName,
  2100. formattedDisplayName: appendSuffix(
  2101. displayName,
  2102. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME),
  2103. avatarURL: APP.UI.getAvatarUrl()
  2104. }
  2105. );
  2106. APP.UI.markVideoInterrupted(false);
  2107. },
  2108. /**
  2109. * Adds any room listener.
  2110. * @param {string} eventName one of the JitsiConferenceEvents
  2111. * @param {Function} listener the function to be called when the event
  2112. * occurs
  2113. */
  2114. addConferenceListener(eventName, listener) {
  2115. room.on(eventName, listener);
  2116. },
  2117. /**
  2118. * Removes any room listener.
  2119. * @param {string} eventName one of the JitsiConferenceEvents
  2120. * @param {Function} listener the listener to be removed.
  2121. */
  2122. removeConferenceListener(eventName, listener) {
  2123. room.off(eventName, listener);
  2124. },
  2125. /**
  2126. * Inits list of current devices and event listener for device change.
  2127. * @private
  2128. */
  2129. _initDeviceList() {
  2130. JitsiMeetJS.mediaDevices.isDeviceListAvailable()
  2131. .then(isDeviceListAvailable => {
  2132. if (isDeviceListAvailable
  2133. && JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  2134. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  2135. // Ugly way to synchronize real device IDs with local
  2136. // storage and settings menu. This is a workaround until
  2137. // getConstraints() method will be implemented
  2138. // in browsers.
  2139. if (this.localAudio) {
  2140. APP.settings.setMicDeviceId(
  2141. this.localAudio.getDeviceId(), false);
  2142. }
  2143. if (this.localVideo) {
  2144. APP.settings.setCameraDeviceId(
  2145. this.localVideo.getDeviceId(), false);
  2146. }
  2147. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2148. APP.UI.onAvailableDevicesChanged(devices);
  2149. APP.store.dispatch(updateDeviceList(devices));
  2150. });
  2151. this.deviceChangeListener = devices =>
  2152. window.setTimeout(
  2153. () => this._onDeviceListChanged(devices), 0);
  2154. JitsiMeetJS.mediaDevices.addEventListener(
  2155. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2156. this.deviceChangeListener);
  2157. }
  2158. })
  2159. .catch(error => {
  2160. logger.warn(`Error getting device list: ${error}`);
  2161. });
  2162. },
  2163. /**
  2164. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  2165. * handle change of available media devices.
  2166. * @private
  2167. * @param {MediaDeviceInfo[]} devices
  2168. * @returns {Promise}
  2169. */
  2170. _onDeviceListChanged(devices) {
  2171. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  2172. // Event handler can be fired before direct
  2173. // enumerateDevices() call, so handle this situation here.
  2174. if (!currentDevices.audioinput
  2175. && !currentDevices.videoinput
  2176. && !currentDevices.audiooutput) {
  2177. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2178. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  2179. }
  2180. const newDevices
  2181. = mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  2182. devices,
  2183. this.isSharingScreen,
  2184. this.localVideo,
  2185. this.localAudio);
  2186. const promises = [];
  2187. const audioWasMuted = this.isLocalAudioMuted();
  2188. const videoWasMuted = this.isLocalVideoMuted();
  2189. if (typeof newDevices.audiooutput !== 'undefined') {
  2190. // Just ignore any errors in catch block.
  2191. promises.push(APP.settings
  2192. .setAudioOutputDeviceId(newDevices.audiooutput)
  2193. .catch());
  2194. }
  2195. promises.push(
  2196. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  2197. createLocalTracksF,
  2198. newDevices.videoinput,
  2199. newDevices.audioinput)
  2200. .then(tracks =>
  2201. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  2202. .then(() => {
  2203. // If audio was muted before, or we unplugged current device
  2204. // and selected new one, then mute new audio track.
  2205. if (audioWasMuted) {
  2206. sendAnalyticsEvent(DEVICE_LIST_CHANGED_AUDIO_MUTED);
  2207. logger.log('Audio mute: device list changed');
  2208. muteLocalAudio(true);
  2209. }
  2210. // If video was muted before, or we unplugged current device
  2211. // and selected new one, then mute new video track.
  2212. if (!this.isSharingScreen && videoWasMuted) {
  2213. sendAnalyticsEvent(DEVICE_LIST_CHANGED_VIDEO_MUTED);
  2214. logger.log('Video mute: device list changed');
  2215. muteLocalVideo(true);
  2216. }
  2217. }));
  2218. return Promise.all(promises)
  2219. .then(() => {
  2220. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2221. APP.UI.onAvailableDevicesChanged(devices);
  2222. });
  2223. },
  2224. /**
  2225. * Determines whether or not the audio button should be enabled.
  2226. */
  2227. updateAudioIconEnabled() {
  2228. const audioMediaDevices
  2229. = mediaDeviceHelper.getCurrentMediaDevices().audioinput;
  2230. const audioDeviceCount
  2231. = audioMediaDevices ? audioMediaDevices.length : 0;
  2232. // The audio functionality is considered available if there are any
  2233. // audio devices detected or if the local audio stream already exists.
  2234. const available = audioDeviceCount > 0 || Boolean(this.localAudio);
  2235. logger.debug(
  2236. `Microphone button enabled: ${available}`,
  2237. `local audio: ${this.localAudio}`,
  2238. `audio devices: ${audioMediaDevices}`,
  2239. `device count: ${audioDeviceCount}`);
  2240. APP.store.dispatch(setAudioAvailable(available));
  2241. APP.API.notifyAudioAvailabilityChanged(available);
  2242. },
  2243. /**
  2244. * Determines whether or not the video button should be enabled.
  2245. */
  2246. updateVideoIconEnabled() {
  2247. const videoMediaDevices
  2248. = mediaDeviceHelper.getCurrentMediaDevices().videoinput;
  2249. const videoDeviceCount
  2250. = videoMediaDevices ? videoMediaDevices.length : 0;
  2251. // The video functionality is considered available if there are any
  2252. // video devices detected or if there is local video stream already
  2253. // active which could be either screensharing stream or a video track
  2254. // created before the permissions were rejected (through browser
  2255. // config).
  2256. const available = videoDeviceCount > 0 || Boolean(this.localVideo);
  2257. logger.debug(
  2258. `Camera button enabled: ${available}`,
  2259. `local video: ${this.localVideo}`,
  2260. `video devices: ${videoMediaDevices}`,
  2261. `device count: ${videoDeviceCount}`);
  2262. APP.store.dispatch(setVideoAvailable(available));
  2263. APP.API.notifyVideoAvailabilityChanged(available);
  2264. },
  2265. /**
  2266. * Toggles the local "raised hand" status.
  2267. */
  2268. maybeToggleRaisedHand() {
  2269. this.setRaisedHand(!this.isHandRaised);
  2270. },
  2271. /**
  2272. * Sets the local "raised hand" status to a particular value.
  2273. */
  2274. setRaisedHand(raisedHand) {
  2275. if (raisedHand !== this.isHandRaised) {
  2276. APP.UI.onLocalRaiseHandChanged(raisedHand);
  2277. this.isHandRaised = raisedHand;
  2278. // Advertise the updated status
  2279. room.setLocalParticipantProperty('raisedHand', raisedHand);
  2280. // Update the view
  2281. APP.UI.setLocalRaisedHandStatus(raisedHand);
  2282. }
  2283. },
  2284. /**
  2285. * Log event to callstats and analytics.
  2286. * @param {string} name the event name
  2287. * @param {int} value the value (it's int because google analytics supports
  2288. * only int).
  2289. * @param {string} label short text which provides more info about the event
  2290. * which allows to distinguish between few event cases of the same name
  2291. * NOTE: Should be used after conference.init
  2292. */
  2293. logEvent(name, value, label) {
  2294. sendAnalyticsEvent(name, {
  2295. value,
  2296. label
  2297. });
  2298. if (room) {
  2299. room.sendApplicationLog(JSON.stringify({ name,
  2300. value,
  2301. label }));
  2302. }
  2303. },
  2304. /**
  2305. * Methods logs an application event given in the JSON format.
  2306. * @param {string} logJSON an event to be logged in JSON format
  2307. */
  2308. logJSON(logJSON) {
  2309. if (room) {
  2310. room.sendApplicationLog(logJSON);
  2311. }
  2312. },
  2313. /**
  2314. * Disconnect from the conference and optionally request user feedback.
  2315. * @param {boolean} [requestFeedback=false] if user feedback should be
  2316. * requested
  2317. */
  2318. hangup(requestFeedback = false) {
  2319. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  2320. let requestFeedbackPromise;
  2321. if (requestFeedback) {
  2322. requestFeedbackPromise
  2323. = APP.store.dispatch(maybeOpenFeedbackDialog(room))
  2324. // false because the thank you dialog shouldn't be displayed
  2325. .catch(() => Promise.resolve(false));
  2326. } else {
  2327. requestFeedbackPromise = Promise.resolve(true);
  2328. }
  2329. // All promises are returning Promise.resolve to make Promise.all to
  2330. // be resolved when both Promises are finished. Otherwise Promise.all
  2331. // will reject on first rejected Promise and we can redirect the page
  2332. // before all operations are done.
  2333. Promise.all([
  2334. requestFeedbackPromise,
  2335. room.leave().then(disconnect, disconnect)
  2336. ]).then(values => {
  2337. APP.API.notifyReadyToClose();
  2338. maybeRedirectToWelcomePage(values[0]);
  2339. });
  2340. },
  2341. /**
  2342. * Changes the email for the local user
  2343. * @param email {string} the new email
  2344. */
  2345. changeLocalEmail(email = '') {
  2346. const localParticipant = getLocalParticipant(APP.store.getState());
  2347. const formattedEmail = String(email).trim();
  2348. if (formattedEmail === localParticipant.email) {
  2349. return;
  2350. }
  2351. const localId = localParticipant.id;
  2352. APP.store.dispatch(participantUpdated({
  2353. id: localId,
  2354. local: true,
  2355. formattedEmail
  2356. }));
  2357. APP.settings.setEmail(formattedEmail);
  2358. APP.UI.setUserEmail(localId, formattedEmail);
  2359. sendData(commands.EMAIL, formattedEmail);
  2360. },
  2361. /**
  2362. * Changes the avatar url for the local user
  2363. * @param url {string} the new url
  2364. */
  2365. changeLocalAvatarUrl(url = '') {
  2366. const { avatarURL, id } = getLocalParticipant(APP.store.getState());
  2367. const formattedUrl = String(url).trim();
  2368. if (formattedUrl === avatarURL) {
  2369. return;
  2370. }
  2371. APP.store.dispatch(participantUpdated({
  2372. id,
  2373. local: true,
  2374. avatarURL: formattedUrl
  2375. }));
  2376. APP.settings.setAvatarUrl(url);
  2377. APP.UI.setUserAvatarUrl(id, url);
  2378. sendData(commands.AVATAR_URL, url);
  2379. },
  2380. /**
  2381. * Sends a message via the data channel.
  2382. * @param {string} to the id of the endpoint that should receive the
  2383. * message. If "" - the message will be sent to all participants.
  2384. * @param {object} payload the payload of the message.
  2385. * @throws NetworkError or InvalidStateError or Error if the operation
  2386. * fails.
  2387. */
  2388. sendEndpointMessage(to, payload) {
  2389. room.sendEndpointMessage(to, payload);
  2390. },
  2391. /**
  2392. * Adds new listener.
  2393. * @param {String} eventName the name of the event
  2394. * @param {Function} listener the listener.
  2395. */
  2396. addListener(eventName, listener) {
  2397. eventEmitter.addListener(eventName, listener);
  2398. },
  2399. /**
  2400. * Removes listener.
  2401. * @param {String} eventName the name of the event that triggers the
  2402. * listener
  2403. * @param {Function} listener the listener.
  2404. */
  2405. removeListener(eventName, listener) {
  2406. eventEmitter.removeListener(eventName, listener);
  2407. },
  2408. /**
  2409. * Changes the display name for the local user
  2410. * @param nickname {string} the new display name
  2411. */
  2412. changeLocalDisplayName(nickname = '') {
  2413. const formattedNickname
  2414. = nickname.trim().substr(0, MAX_DISPLAY_NAME_LENGTH);
  2415. const { id, name } = getLocalParticipant(APP.store.getState());
  2416. if (formattedNickname === name) {
  2417. return;
  2418. }
  2419. APP.store.dispatch(participantUpdated({
  2420. id,
  2421. local: true,
  2422. name: formattedNickname
  2423. }));
  2424. APP.settings.setDisplayName(formattedNickname);
  2425. APP.API.notifyDisplayNameChanged(id, {
  2426. displayName: formattedNickname,
  2427. formattedDisplayName:
  2428. appendSuffix(
  2429. formattedNickname,
  2430. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME)
  2431. });
  2432. if (room) {
  2433. room.setDisplayName(formattedNickname);
  2434. APP.UI.changeDisplayName(id, formattedNickname);
  2435. }
  2436. },
  2437. /**
  2438. * Returns the desktop sharing source id or undefined if the desktop sharing
  2439. * is not active at the moment.
  2440. *
  2441. * @returns {string|undefined} - The source id. If the track is not desktop
  2442. * track or the source id is not available, undefined will be returned.
  2443. */
  2444. getDesktopSharingSourceId() {
  2445. return this.localVideo.sourceId;
  2446. },
  2447. /**
  2448. * Returns the desktop sharing source type or undefined if the desktop
  2449. * sharing is not active at the moment.
  2450. *
  2451. * @returns {'screen'|'window'|undefined} - The source type. If the track is
  2452. * not desktop track or the source type is not available, undefined will be
  2453. * returned.
  2454. */
  2455. getDesktopSharingSourceType() {
  2456. return this.localVideo.sourceType;
  2457. },
  2458. /**
  2459. * Sets the video muted status.
  2460. *
  2461. * @param {boolean} muted - New muted status.
  2462. */
  2463. setVideoMuteStatus(muted) {
  2464. APP.UI.setVideoMuted(this.getMyUserId(), muted);
  2465. APP.API.notifyVideoMutedStatusChanged(muted);
  2466. },
  2467. /**
  2468. * Sets the audio muted status.
  2469. *
  2470. * @param {boolean} muted - New muted status.
  2471. */
  2472. setAudioMuteStatus(muted) {
  2473. APP.UI.setAudioMuted(this.getMyUserId(), muted);
  2474. APP.API.notifyAudioMutedStatusChanged(muted);
  2475. }
  2476. };