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

conference.js 95KB

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