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

conference.js 95KB

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