選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

conference.js 91KB

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