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

conference.js 91KB

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