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

conference.js 92KB

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