您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 92KB

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