Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

conference.js 115KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236
  1. /* global APP, JitsiMeetJS, config, interfaceConfig */
  2. import { jitsiLocalStorage } from '@jitsi/js-utils';
  3. import Logger from '@jitsi/logger';
  4. import EventEmitter from 'events';
  5. import { openConnection } from './connection';
  6. import { ENDPOINT_TEXT_MESSAGE_NAME } from './modules/API/constants';
  7. import { AUDIO_ONLY_SCREEN_SHARE_NO_TRACK } from './modules/UI/UIErrors';
  8. import AuthHandler from './modules/UI/authentication/AuthHandler';
  9. import UIUtil from './modules/UI/util/UIUtil';
  10. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  11. import Recorder from './modules/recorder/Recorder';
  12. import { createTaskQueue } from './modules/util/helpers';
  13. import {
  14. createDeviceChangedEvent,
  15. createStartSilentEvent,
  16. createScreenSharingEvent,
  17. createTrackMutedEvent,
  18. sendAnalytics
  19. } from './react/features/analytics';
  20. import {
  21. maybeRedirectToWelcomePage,
  22. redirectToStaticPage,
  23. reloadWithStoredParams
  24. } from './react/features/app/actions';
  25. import { showModeratedNotification } from './react/features/av-moderation/actions';
  26. import { shouldShowModeratedNotification } from './react/features/av-moderation/functions';
  27. import {
  28. AVATAR_URL_COMMAND,
  29. EMAIL_COMMAND,
  30. _conferenceWillJoin,
  31. authStatusChanged,
  32. commonUserJoinedHandling,
  33. commonUserLeftHandling,
  34. conferenceFailed,
  35. conferenceJoined,
  36. conferenceLeft,
  37. conferenceSubjectChanged,
  38. conferenceTimestampChanged,
  39. conferenceUniqueIdSet,
  40. conferenceWillJoin,
  41. conferenceWillLeave,
  42. dataChannelOpened,
  43. getConferenceOptions,
  44. kickedOut,
  45. lockStateChanged,
  46. onStartMutedPolicyChanged,
  47. p2pStatusChanged,
  48. sendLocalParticipant,
  49. nonParticipantMessageReceived
  50. } from './react/features/base/conference';
  51. import { getReplaceParticipant } from './react/features/base/config/functions';
  52. import {
  53. checkAndNotifyForNewDevice,
  54. getAvailableDevices,
  55. getDefaultDeviceId,
  56. notifyCameraError,
  57. notifyMicError,
  58. setAudioOutputDeviceId,
  59. updateDeviceList
  60. } from './react/features/base/devices';
  61. import {
  62. browser,
  63. isFatalJitsiConnectionError,
  64. JitsiConferenceErrors,
  65. JitsiConferenceEvents,
  66. JitsiConnectionErrors,
  67. JitsiConnectionEvents,
  68. JitsiMediaDevicesEvents,
  69. JitsiParticipantConnectionStatus,
  70. JitsiTrackErrors,
  71. JitsiTrackEvents
  72. } from './react/features/base/lib-jitsi-meet';
  73. import {
  74. getStartWithAudioMuted,
  75. getStartWithVideoMuted,
  76. isVideoMutedByUser,
  77. MEDIA_TYPE,
  78. setAudioAvailable,
  79. setAudioMuted,
  80. setVideoAvailable,
  81. setVideoMuted
  82. } from './react/features/base/media';
  83. import {
  84. dominantSpeakerChanged,
  85. getLocalParticipant,
  86. getNormalizedDisplayName,
  87. getParticipantById,
  88. localParticipantConnectionStatusChanged,
  89. localParticipantRoleChanged,
  90. participantConnectionStatusChanged,
  91. participantKicked,
  92. participantMutedUs,
  93. participantPresenceChanged,
  94. participantRoleChanged,
  95. participantUpdated,
  96. updateRemoteParticipantFeatures
  97. } from './react/features/base/participants';
  98. import {
  99. getUserSelectedCameraDeviceId,
  100. updateSettings
  101. } from './react/features/base/settings';
  102. import {
  103. createLocalPresenterTrack,
  104. createLocalTracksF,
  105. destroyLocalTracks,
  106. getLocalJitsiAudioTrack,
  107. getLocalJitsiVideoTrack,
  108. getLocalTracks,
  109. getLocalVideoTrack,
  110. isLocalCameraTrackMuted,
  111. isLocalTrackMuted,
  112. isUserInteractionRequiredForUnmute,
  113. replaceLocalTrack,
  114. trackAdded,
  115. trackRemoved
  116. } from './react/features/base/tracks';
  117. import { downloadJSON } from './react/features/base/util/downloadJSON';
  118. import { showDesktopPicker } from './react/features/desktop-picker';
  119. import { appendSuffix } from './react/features/display-name';
  120. import {
  121. maybeOpenFeedbackDialog,
  122. submitFeedback
  123. } from './react/features/feedback';
  124. import { isModerationNotificationDisplayed, showNotification } from './react/features/notifications';
  125. import { mediaPermissionPromptVisibilityChanged, toggleSlowGUMOverlay } from './react/features/overlay';
  126. import { suspendDetected } from './react/features/power-monitor';
  127. import {
  128. initPrejoin,
  129. isPrejoinPageEnabled,
  130. isPrejoinPageVisible,
  131. makePrecallTest,
  132. setJoiningInProgress,
  133. setPrejoinPageVisibility
  134. } from './react/features/prejoin';
  135. import { disableReceiver, stopReceiver } from './react/features/remote-control';
  136. import { setScreenAudioShareState, isScreenAudioShared } from './react/features/screen-share/';
  137. import { toggleScreenshotCaptureSummary } from './react/features/screenshot-capture';
  138. import { AudioMixerEffect } from './react/features/stream-effects/audio-mixer/AudioMixerEffect';
  139. import { createPresenterEffect } from './react/features/stream-effects/presenter';
  140. import { createRnnoiseProcessor } from './react/features/stream-effects/rnnoise';
  141. import { endpointMessageReceived } from './react/features/subtitles';
  142. import UIEvents from './service/UI/UIEvents';
  143. const logger = Logger.getLogger(__filename);
  144. const eventEmitter = new EventEmitter();
  145. let room;
  146. let connection;
  147. /**
  148. * The promise is used when the prejoin screen is shown.
  149. * While the user configures the devices the connection can be made.
  150. *
  151. * @type {Promise<Object>}
  152. * @private
  153. */
  154. let _connectionPromise;
  155. /**
  156. * We are storing the resolve function of a Promise that waits for the _connectionPromise to be created. This is needed
  157. * when the prejoin button was pressed before the conference object was initialized and the _connectionPromise has not
  158. * been initialized when we tried to execute prejoinStart. In this case in prejoinStart we create a new Promise, assign
  159. * the resolve function to this variable and wait for the promise to resolve before we continue. The
  160. * _onConnectionPromiseCreated will be called once the _connectionPromise is created.
  161. */
  162. let _onConnectionPromiseCreated;
  163. /**
  164. * This promise is used for chaining mutePresenterVideo calls in order to avoid calling GUM multiple times if it takes
  165. * a while to finish.
  166. *
  167. * @type {Promise<void>}
  168. * @private
  169. */
  170. let _prevMutePresenterVideo = Promise.resolve();
  171. /*
  172. * Logic to open a desktop picker put on the window global for
  173. * lib-jitsi-meet to detect and invoke
  174. */
  175. window.JitsiMeetScreenObtainer = {
  176. openDesktopPicker(options, onSourceChoose) {
  177. APP.store.dispatch(showDesktopPicker(options, onSourceChoose));
  178. }
  179. };
  180. /**
  181. * Known custom conference commands.
  182. */
  183. const commands = {
  184. AVATAR_URL: AVATAR_URL_COMMAND,
  185. CUSTOM_ROLE: 'custom-role',
  186. EMAIL: EMAIL_COMMAND,
  187. ETHERPAD: 'etherpad'
  188. };
  189. /**
  190. * Open Connection. When authentication failed it shows auth dialog.
  191. * @param roomName the room name to use
  192. * @returns Promise<JitsiConnection>
  193. */
  194. function connect(roomName) {
  195. return openConnection({
  196. retry: true,
  197. roomName
  198. })
  199. .catch(err => {
  200. if (err === JitsiConnectionErrors.PASSWORD_REQUIRED) {
  201. APP.UI.notifyTokenAuthFailed();
  202. } else {
  203. APP.UI.notifyConnectionFailed(err);
  204. }
  205. throw err;
  206. });
  207. }
  208. /**
  209. * Share data to other users.
  210. * @param command the command
  211. * @param {string} value new value
  212. */
  213. function sendData(command, value) {
  214. if (!room) {
  215. return;
  216. }
  217. room.removeCommand(command);
  218. room.sendCommand(command, { value });
  219. }
  220. /**
  221. * Get user nickname by user id.
  222. * @param {string} id user id
  223. * @returns {string?} user nickname or undefined if user is unknown.
  224. */
  225. function getDisplayName(id) {
  226. const participant = getParticipantById(APP.store.getState(), id);
  227. return participant && participant.name;
  228. }
  229. /**
  230. * Mute or unmute local audio stream if it exists.
  231. * @param {boolean} muted - if audio stream should be muted or unmuted.
  232. */
  233. function muteLocalAudio(muted) {
  234. APP.store.dispatch(setAudioMuted(muted));
  235. }
  236. /**
  237. * Mute or unmute local video stream if it exists.
  238. * @param {boolean} muted if video stream should be muted or unmuted.
  239. *
  240. */
  241. function muteLocalVideo(muted) {
  242. APP.store.dispatch(setVideoMuted(muted));
  243. }
  244. /**
  245. * A queue for the async replaceLocalTrack action so that multiple audio
  246. * replacements cannot happen simultaneously. This solves the issue where
  247. * replaceLocalTrack is called multiple times with an oldTrack of null, causing
  248. * multiple local tracks of the same type to be used.
  249. *
  250. * @private
  251. * @type {Object}
  252. */
  253. const _replaceLocalAudioTrackQueue = createTaskQueue();
  254. /**
  255. * A task queue for replacement local video tracks. This separate queue exists
  256. * so video replacement is not blocked by audio replacement tasks in the queue
  257. * {@link _replaceLocalAudioTrackQueue}.
  258. *
  259. * @private
  260. * @type {Object}
  261. */
  262. const _replaceLocalVideoTrackQueue = createTaskQueue();
  263. /**
  264. *
  265. */
  266. class ConferenceConnector {
  267. /**
  268. *
  269. */
  270. constructor(resolve, reject) {
  271. this._resolve = resolve;
  272. this._reject = reject;
  273. this.reconnectTimeout = null;
  274. room.on(JitsiConferenceEvents.CONFERENCE_JOINED,
  275. this._handleConferenceJoined.bind(this));
  276. room.on(JitsiConferenceEvents.CONFERENCE_FAILED,
  277. this._onConferenceFailed.bind(this));
  278. }
  279. /**
  280. *
  281. */
  282. _handleConferenceFailed(err) {
  283. this._unsubscribe();
  284. this._reject(err);
  285. }
  286. /**
  287. *
  288. */
  289. _onConferenceFailed(err, ...params) {
  290. APP.store.dispatch(conferenceFailed(room, err, ...params));
  291. logger.error('CONFERENCE FAILED:', err, ...params);
  292. switch (err) {
  293. case JitsiConferenceErrors.NOT_ALLOWED_ERROR: {
  294. // let's show some auth not allowed page
  295. APP.store.dispatch(redirectToStaticPage('static/authError.html'));
  296. break;
  297. }
  298. // not enough rights to create conference
  299. case JitsiConferenceErrors.AUTHENTICATION_REQUIRED: {
  300. const replaceParticipant = getReplaceParticipant(APP.store.getState());
  301. // Schedule reconnect to check if someone else created the room.
  302. this.reconnectTimeout = setTimeout(() => {
  303. APP.store.dispatch(conferenceWillJoin(room));
  304. room.join(null, replaceParticipant);
  305. }, 5000);
  306. const { password }
  307. = APP.store.getState()['features/base/conference'];
  308. AuthHandler.requireAuth(room, password);
  309. break;
  310. }
  311. case JitsiConferenceErrors.RESERVATION_ERROR: {
  312. const [ code, msg ] = params;
  313. APP.UI.notifyReservationError(code, msg);
  314. break;
  315. }
  316. case JitsiConferenceErrors.GRACEFUL_SHUTDOWN:
  317. APP.UI.notifyGracefulShutdown();
  318. break;
  319. // FIXME FOCUS_DISCONNECTED is a confusing event name.
  320. // What really happens there is that the library is not ready yet,
  321. // because Jicofo is not available, but it is going to give it another
  322. // try.
  323. case JitsiConferenceErrors.FOCUS_DISCONNECTED: {
  324. const [ focus, retrySec ] = params;
  325. APP.UI.notifyFocusDisconnected(focus, retrySec);
  326. break;
  327. }
  328. case JitsiConferenceErrors.FOCUS_LEFT:
  329. case JitsiConferenceErrors.ICE_FAILED:
  330. case JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  331. case JitsiConferenceErrors.OFFER_ANSWER_FAILED:
  332. APP.store.dispatch(conferenceWillLeave(room));
  333. // FIXME the conference should be stopped by the library and not by
  334. // the app. Both the errors above are unrecoverable from the library
  335. // perspective.
  336. room.leave().then(() => connection.disconnect());
  337. break;
  338. case JitsiConferenceErrors.CONFERENCE_MAX_USERS:
  339. connection.disconnect();
  340. APP.UI.notifyMaxUsersLimitReached();
  341. break;
  342. case JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  343. APP.store.dispatch(reloadWithStoredParams());
  344. break;
  345. default:
  346. this._handleConferenceFailed(err, ...params);
  347. }
  348. }
  349. /**
  350. *
  351. */
  352. _unsubscribe() {
  353. room.off(
  354. JitsiConferenceEvents.CONFERENCE_JOINED,
  355. this._handleConferenceJoined);
  356. room.off(
  357. JitsiConferenceEvents.CONFERENCE_FAILED,
  358. this._onConferenceFailed);
  359. if (this.reconnectTimeout !== null) {
  360. clearTimeout(this.reconnectTimeout);
  361. }
  362. }
  363. /**
  364. *
  365. */
  366. _handleConferenceJoined() {
  367. this._unsubscribe();
  368. this._resolve();
  369. }
  370. /**
  371. *
  372. */
  373. connect() {
  374. const replaceParticipant = getReplaceParticipant(APP.store.getState());
  375. // the local storage overrides here and in connection.js can be used by jibri
  376. room.join(jitsiLocalStorage.getItem('xmpp_conference_password_override'), replaceParticipant);
  377. }
  378. }
  379. /**
  380. * Disconnects the connection.
  381. * @returns resolved Promise. We need this in order to make the Promise.all
  382. * call in hangup() to resolve when all operations are finished.
  383. */
  384. function disconnect() {
  385. const onDisconnected = () => {
  386. APP.API.notifyConferenceLeft(APP.conference.roomName);
  387. return Promise.resolve();
  388. };
  389. if (!connection) {
  390. return onDisconnected();
  391. }
  392. return connection.disconnect().then(onDisconnected, onDisconnected);
  393. }
  394. /**
  395. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  396. *
  397. * @param {JitsiConnectionError} error - The reported error.
  398. * @returns {void}
  399. * @private
  400. */
  401. function _connectionFailedHandler(error) {
  402. if (isFatalJitsiConnectionError(error)) {
  403. APP.connection.removeEventListener(
  404. JitsiConnectionEvents.CONNECTION_FAILED,
  405. _connectionFailedHandler);
  406. if (room) {
  407. APP.store.dispatch(conferenceWillLeave(room));
  408. room.leave();
  409. }
  410. }
  411. }
  412. export default {
  413. /**
  414. * Flag used to delay modification of the muted status of local media tracks
  415. * until those are created (or not, but at that point it's certain that
  416. * the tracks won't exist).
  417. */
  418. _localTracksInitialized: false,
  419. isSharingScreen: false,
  420. /**
  421. * The local presenter video track (if any).
  422. * @type {JitsiLocalTrack|null}
  423. */
  424. localPresenterVideo: null,
  425. /**
  426. * Returns an object containing a promise which resolves with the created tracks &
  427. * the errors resulting from that process.
  428. *
  429. * @returns {Promise<JitsiLocalTrack[]>, Object}
  430. */
  431. createInitialLocalTracks(options = {}) {
  432. const errors = {};
  433. // Always get a handle on the audio input device so that we have statistics (such as "No audio input" or
  434. // "Are you trying to speak?" ) even if the user joins the conference muted.
  435. const initialDevices = config.disableInitialGUM ? [] : [ 'audio' ];
  436. const requestedAudio = !config.disableInitialGUM;
  437. let requestedVideo = false;
  438. if (!config.disableInitialGUM
  439. && !options.startWithVideoMuted
  440. && !options.startAudioOnly
  441. && !options.startScreenSharing) {
  442. initialDevices.push('video');
  443. requestedVideo = true;
  444. }
  445. if (!config.disableInitialGUM) {
  446. JitsiMeetJS.mediaDevices.addEventListener(
  447. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  448. browserName =>
  449. APP.store.dispatch(
  450. mediaPermissionPromptVisibilityChanged(true, browserName))
  451. );
  452. }
  453. JitsiMeetJS.mediaDevices.addEventListener(
  454. JitsiMediaDevicesEvents.SLOW_GET_USER_MEDIA,
  455. () => APP.store.dispatch(toggleSlowGUMOverlay(true))
  456. );
  457. let tryCreateLocalTracks;
  458. // On Electron there is no permission prompt for granting permissions. That's why we don't need to
  459. // spend much time displaying the overlay screen. If GUM is not resolved within 15 seconds it will
  460. // probably never resolve.
  461. const timeout = browser.isElectron() ? 15000 : 60000;
  462. // FIXME is there any simpler way to rewrite this spaghetti below ?
  463. if (options.startScreenSharing) {
  464. tryCreateLocalTracks = this._createDesktopTrack()
  465. .then(([ desktopStream ]) => {
  466. if (!requestedAudio) {
  467. return [ desktopStream ];
  468. }
  469. return createLocalTracksF({
  470. devices: [ 'audio' ],
  471. timeout,
  472. firePermissionPromptIsShownEvent: true,
  473. fireSlowPromiseEvent: true
  474. })
  475. .then(([ audioStream ]) =>
  476. [ desktopStream, audioStream ])
  477. .catch(error => {
  478. errors.audioOnlyError = error;
  479. return [ desktopStream ];
  480. });
  481. })
  482. .catch(error => {
  483. logger.error('Failed to obtain desktop stream', error);
  484. errors.screenSharingError = error;
  485. return requestedAudio
  486. ? createLocalTracksF({
  487. devices: [ 'audio' ],
  488. timeout,
  489. firePermissionPromptIsShownEvent: true,
  490. fireSlowPromiseEvent: true
  491. })
  492. : [];
  493. })
  494. .catch(error => {
  495. errors.audioOnlyError = error;
  496. return [];
  497. });
  498. } else if (!requestedAudio && !requestedVideo) {
  499. // Resolve with no tracks
  500. tryCreateLocalTracks = Promise.resolve([]);
  501. } else {
  502. tryCreateLocalTracks = createLocalTracksF({
  503. devices: initialDevices,
  504. timeout,
  505. firePermissionPromptIsShownEvent: true,
  506. fireSlowPromiseEvent: true
  507. })
  508. .catch(err => {
  509. if (requestedAudio && requestedVideo) {
  510. // Try audio only...
  511. errors.audioAndVideoError = err;
  512. if (err.name === JitsiTrackErrors.TIMEOUT && !browser.isElectron()) {
  513. // In this case we expect that the permission prompt is still visible. There is no point of
  514. // executing GUM with different source. Also at the time of writing the following
  515. // inconsistency have been noticed in some browsers - if the permissions prompt is visible
  516. // and another GUM is executed the prompt does not change its content but if the user
  517. // clicks allow the user action isassociated with the latest GUM call.
  518. errors.audioOnlyError = err;
  519. errors.videoOnlyError = err;
  520. return [];
  521. }
  522. return (
  523. createLocalTracksF({
  524. devices: [ 'audio' ],
  525. timeout,
  526. firePermissionPromptIsShownEvent: true,
  527. fireSlowPromiseEvent: true
  528. }));
  529. } else if (requestedAudio && !requestedVideo) {
  530. errors.audioOnlyError = err;
  531. return [];
  532. } else if (requestedVideo && !requestedAudio) {
  533. errors.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. errors.audioOnlyError = err;
  544. // Try video only...
  545. return requestedVideo
  546. ? createLocalTracksF({
  547. devices: [ 'video' ],
  548. firePermissionPromptIsShownEvent: true,
  549. fireSlowPromiseEvent: true
  550. })
  551. : [];
  552. })
  553. .catch(err => {
  554. // Log this just in case...
  555. if (!requestedVideo) {
  556. logger.error('The impossible just happened', err);
  557. }
  558. errors.videoOnlyError = err;
  559. return [];
  560. });
  561. }
  562. // Hide the permissions prompt/overlay as soon as the tracks are
  563. // created. Don't wait for the connection to be made, since in some
  564. // cases, when auth is required, for instance, that won't happen until
  565. // the user inputs their credentials, but the dialog would be
  566. // overshadowed by the overlay.
  567. tryCreateLocalTracks.then(tracks => {
  568. APP.store.dispatch(toggleSlowGUMOverlay(false));
  569. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false));
  570. return tracks;
  571. });
  572. return {
  573. tryCreateLocalTracks,
  574. errors
  575. };
  576. },
  577. /**
  578. * Displays error notifications according to the state carried by {@code errors} object returned
  579. * by {@link createInitialLocalTracks}.
  580. * @param {Object} errors - the errors (if any) returned by {@link createInitialLocalTracks}.
  581. *
  582. * @returns {void}
  583. * @private
  584. */
  585. _displayErrorsForCreateInitialLocalTracks(errors) {
  586. const {
  587. audioAndVideoError,
  588. audioOnlyError,
  589. screenSharingError,
  590. videoOnlyError
  591. } = errors;
  592. // FIXME If there will be microphone error it will cover any screensharing dialog, but it's still better than in
  593. // the reverse order where the screensharing dialog will sometimes be closing the microphone alert
  594. // ($.prompt.close(); is called). Need to figure out dialogs chaining to fix that.
  595. if (screenSharingError) {
  596. this._handleScreenSharingError(screenSharingError);
  597. }
  598. if (audioAndVideoError || audioOnlyError) {
  599. if (audioOnlyError || videoOnlyError) {
  600. // If both requests for 'audio' + 'video' and 'audio' only failed, we assume that there are some
  601. // problems with user's microphone and show corresponding dialog.
  602. APP.store.dispatch(notifyMicError(audioOnlyError));
  603. APP.store.dispatch(notifyCameraError(videoOnlyError));
  604. } else {
  605. // If request for 'audio' + 'video' failed, but request for 'audio' only was OK, we assume that we had
  606. // problems with camera and show corresponding dialog.
  607. APP.store.dispatch(notifyCameraError(audioAndVideoError));
  608. }
  609. }
  610. },
  611. /**
  612. * Creates local media tracks and connects to a room. Will show error
  613. * dialogs in case accessing the local microphone and/or camera failed. Will
  614. * show guidance overlay for users on how to give access to camera and/or
  615. * microphone.
  616. * @param {string} roomName
  617. * @param {object} options
  618. * @param {boolean} options.startAudioOnly=false - if <tt>true</tt> then
  619. * only audio track will be created and the audio only mode will be turned
  620. * on.
  621. * @param {boolean} options.startScreenSharing=false - if <tt>true</tt>
  622. * should start with screensharing instead of camera video.
  623. * @param {boolean} options.startWithAudioMuted - will start the conference
  624. * without any audio tracks.
  625. * @param {boolean} options.startWithVideoMuted - will start the conference
  626. * without any video tracks.
  627. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  628. */
  629. createInitialLocalTracksAndConnect(roomName, options = {}) {
  630. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(options);
  631. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  632. .then(([ tracks, con ]) => {
  633. this._displayErrorsForCreateInitialLocalTracks(errors);
  634. return [ tracks, con ];
  635. });
  636. },
  637. startConference(con, tracks) {
  638. tracks.forEach(track => {
  639. if ((track.isAudioTrack() && this.isLocalAudioMuted())
  640. || (track.isVideoTrack() && this.isLocalVideoMuted())) {
  641. const mediaType = track.getType();
  642. sendAnalytics(
  643. createTrackMutedEvent(mediaType, 'initial mute'));
  644. logger.log(`${mediaType} mute: initially muted.`);
  645. track.mute();
  646. }
  647. });
  648. con.addEventListener(JitsiConnectionEvents.CONNECTION_FAILED, _connectionFailedHandler);
  649. APP.connection = connection = con;
  650. this._createRoom(tracks);
  651. // if user didn't give access to mic or camera or doesn't have
  652. // them at all, we mark corresponding toolbar buttons as muted,
  653. // so that the user can try unmute later on and add audio/video
  654. // to the conference
  655. if (!tracks.find(t => t.isAudioTrack())) {
  656. this.setAudioMuteStatus(true);
  657. }
  658. if (!tracks.find(t => t.isVideoTrack())) {
  659. this.setVideoMuteStatus();
  660. }
  661. if (config.iAmRecorder) {
  662. this.recorder = new Recorder();
  663. }
  664. if (config.startSilent) {
  665. sendAnalytics(createStartSilentEvent());
  666. APP.store.dispatch(showNotification({
  667. descriptionKey: 'notify.startSilentDescription',
  668. titleKey: 'notify.startSilentTitle'
  669. }));
  670. }
  671. // XXX The API will take care of disconnecting from the XMPP
  672. // server (and, thus, leaving the room) on unload.
  673. return new Promise((resolve, reject) => {
  674. new ConferenceConnector(resolve, reject).connect();
  675. });
  676. },
  677. /**
  678. * Open new connection and join the conference when prejoin page is not enabled.
  679. * If prejoin page is enabled open an new connection in the background
  680. * and create local tracks.
  681. *
  682. * @param {{ roomName: string }} options
  683. * @returns {Promise}
  684. */
  685. async init({ roomName }) {
  686. const initialOptions = {
  687. startAudioOnly: config.startAudioOnly,
  688. startScreenSharing: config.startScreenSharing,
  689. startWithAudioMuted: getStartWithAudioMuted(APP.store.getState())
  690. || config.startSilent
  691. || isUserInteractionRequiredForUnmute(APP.store.getState()),
  692. startWithVideoMuted: getStartWithVideoMuted(APP.store.getState())
  693. || isUserInteractionRequiredForUnmute(APP.store.getState())
  694. };
  695. this.roomName = roomName;
  696. try {
  697. // Initialize the device list first. This way, when creating tracks
  698. // based on preferred devices, loose label matching can be done in
  699. // cases where the exact ID match is no longer available, such as
  700. // when the camera device has switched USB ports.
  701. // when in startSilent mode we want to start with audio muted
  702. await this._initDeviceList();
  703. } catch (error) {
  704. logger.warn('initial device list initialization failed', error);
  705. }
  706. if (isPrejoinPageEnabled(APP.store.getState())) {
  707. _connectionPromise = connect(roomName).then(c => {
  708. // we want to initialize it early, in case of errors to be able
  709. // to gather logs
  710. APP.connection = c;
  711. return c;
  712. });
  713. if (_onConnectionPromiseCreated) {
  714. _onConnectionPromiseCreated();
  715. }
  716. APP.store.dispatch(makePrecallTest(this._getConferenceOptions()));
  717. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(initialOptions);
  718. const tracks = await tryCreateLocalTracks;
  719. // Initialize device list a second time to ensure device labels
  720. // get populated in case of an initial gUM acceptance; otherwise
  721. // they may remain as empty strings.
  722. this._initDeviceList(true);
  723. if (isPrejoinPageVisible(APP.store.getState())) {
  724. return APP.store.dispatch(initPrejoin(tracks, errors));
  725. }
  726. logger.debug('Prejoin screen no longer displayed at the time when tracks were created');
  727. this._displayErrorsForCreateInitialLocalTracks(errors);
  728. return this._setLocalAudioVideoStreams(tracks);
  729. }
  730. const [ tracks, con ] = await this.createInitialLocalTracksAndConnect(roomName, initialOptions);
  731. let localTracks = tracks;
  732. this._initDeviceList(true);
  733. if (initialOptions.startWithAudioMuted) {
  734. // Always add the track on Safari because of a known issue where audio playout doesn't happen
  735. // if the user joins audio and video muted, i.e., if there is no local media capture.
  736. if (browser.isWebKitBased()) {
  737. this.muteAudio(true, true);
  738. } else {
  739. localTracks = localTracks.filter(track => track.getType() !== MEDIA_TYPE.AUDIO);
  740. }
  741. }
  742. return this.startConference(con, localTracks);
  743. },
  744. /**
  745. * Joins conference after the tracks have been configured in the prejoin screen.
  746. *
  747. * @param {Object[]} tracks - An array with the configured tracks
  748. * @returns {void}
  749. */
  750. async prejoinStart(tracks) {
  751. if (!_connectionPromise) {
  752. // The conference object isn't initialized yet. Wait for the promise to initialise.
  753. await new Promise(resolve => {
  754. _onConnectionPromiseCreated = resolve;
  755. });
  756. _onConnectionPromiseCreated = undefined;
  757. }
  758. let con;
  759. try {
  760. con = await _connectionPromise;
  761. this.startConference(con, tracks);
  762. } catch (error) {
  763. logger.error(`An error occurred while trying to join a meeting from the prejoin screen: ${error}`);
  764. APP.store.dispatch(setJoiningInProgress(false));
  765. }
  766. },
  767. /**
  768. * Check if id is id of the local user.
  769. * @param {string} id id to check
  770. * @returns {boolean}
  771. */
  772. isLocalId(id) {
  773. return this.getMyUserId() === id;
  774. },
  775. /**
  776. * Tells whether the local video is muted or not.
  777. * @return {boolean}
  778. */
  779. isLocalVideoMuted() {
  780. // If the tracks are not ready, read from base/media state
  781. return this._localTracksInitialized
  782. ? isLocalCameraTrackMuted(
  783. APP.store.getState()['features/base/tracks'])
  784. : isVideoMutedByUser(APP.store);
  785. },
  786. /**
  787. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  788. * @param {boolean} mute true for mute and false for unmute.
  789. * @param {boolean} [showUI] when set to false will not display any error
  790. * dialogs in case of media permissions error.
  791. */
  792. muteAudio(mute, showUI = true) {
  793. const state = APP.store.getState();
  794. if (!mute
  795. && isUserInteractionRequiredForUnmute(state)) {
  796. logger.error('Unmuting audio requires user interaction');
  797. return;
  798. }
  799. // check for A/V Moderation when trying to unmute
  800. if (!mute && shouldShowModeratedNotification(MEDIA_TYPE.AUDIO, state)) {
  801. if (!isModerationNotificationDisplayed(MEDIA_TYPE.AUDIO, state)) {
  802. APP.store.dispatch(showModeratedNotification(MEDIA_TYPE.AUDIO));
  803. }
  804. return;
  805. }
  806. // Not ready to modify track's state yet
  807. if (!this._localTracksInitialized) {
  808. // This will only modify base/media.audio.muted which is then synced
  809. // up with the track at the end of local tracks initialization.
  810. muteLocalAudio(mute);
  811. this.setAudioMuteStatus(mute);
  812. return;
  813. } else if (this.isLocalAudioMuted() === mute) {
  814. // NO-OP
  815. return;
  816. }
  817. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  818. if (!localAudio && !mute) {
  819. const maybeShowErrorDialog = error => {
  820. showUI && APP.store.dispatch(notifyMicError(error));
  821. };
  822. createLocalTracksF({ devices: [ 'audio' ] })
  823. .then(([ audioTrack ]) => audioTrack)
  824. .catch(error => {
  825. maybeShowErrorDialog(error);
  826. // Rollback the audio muted status by using null track
  827. return null;
  828. })
  829. .then(audioTrack => this.useAudioStream(audioTrack));
  830. } else {
  831. muteLocalAudio(mute);
  832. }
  833. },
  834. /**
  835. * Returns whether local audio is muted or not.
  836. * @returns {boolean}
  837. */
  838. isLocalAudioMuted() {
  839. // If the tracks are not ready, read from base/media state
  840. return this._localTracksInitialized
  841. ? isLocalTrackMuted(
  842. APP.store.getState()['features/base/tracks'],
  843. MEDIA_TYPE.AUDIO)
  844. : Boolean(
  845. APP.store.getState()['features/base/media'].audio.muted);
  846. },
  847. /**
  848. * Simulates toolbar button click for audio mute. Used by shortcuts
  849. * and API.
  850. * @param {boolean} [showUI] when set to false will not display any error
  851. * dialogs in case of media permissions error.
  852. */
  853. toggleAudioMuted(showUI = true) {
  854. this.muteAudio(!this.isLocalAudioMuted(), showUI);
  855. },
  856. /**
  857. * Simulates toolbar button click for presenter video mute. Used by
  858. * shortcuts and API.
  859. * @param mute true for mute and false for unmute.
  860. * @param {boolean} [showUI] when set to false will not display any error
  861. * dialogs in case of media permissions error.
  862. */
  863. async mutePresenter(mute, showUI = true) {
  864. const maybeShowErrorDialog = error => {
  865. showUI && APP.store.dispatch(notifyCameraError(error));
  866. };
  867. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  868. if (mute) {
  869. try {
  870. await localVideo.setEffect(undefined);
  871. } catch (err) {
  872. logger.error('Failed to remove the presenter effect', err);
  873. maybeShowErrorDialog(err);
  874. }
  875. } else {
  876. try {
  877. await localVideo.setEffect(await this._createPresenterStreamEffect());
  878. } catch (err) {
  879. logger.error('Failed to apply the presenter effect', err);
  880. maybeShowErrorDialog(err);
  881. }
  882. }
  883. },
  884. /**
  885. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  886. * @param mute true for mute and false for unmute.
  887. * @param {boolean} [showUI] when set to false will not display any error
  888. * dialogs in case of media permissions error.
  889. */
  890. muteVideo(mute, showUI = true) {
  891. if (this.videoSwitchInProgress) {
  892. // Turning the camera on while the screen sharing mode is being turned off is causing issues around
  893. // the presenter mode handling. It should be okay for the user to click the button again once that's done.
  894. console.warn('muteVideo - unable to perform operations while video switch is in progress');
  895. return;
  896. }
  897. if (!mute
  898. && isUserInteractionRequiredForUnmute(APP.store.getState())) {
  899. logger.error('Unmuting video requires user interaction');
  900. return;
  901. }
  902. if (this.isSharingScreen) {
  903. // Chain _mutePresenterVideo calls
  904. _prevMutePresenterVideo = _prevMutePresenterVideo.then(() => this._mutePresenterVideo(mute));
  905. return;
  906. }
  907. // If not ready to modify track's state yet adjust the base/media
  908. if (!this._localTracksInitialized) {
  909. // This will only modify base/media.video.muted which is then synced
  910. // up with the track at the end of local tracks initialization.
  911. muteLocalVideo(mute);
  912. this.setVideoMuteStatus();
  913. return;
  914. } else if (this.isLocalVideoMuted() === mute) {
  915. // NO-OP
  916. return;
  917. }
  918. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  919. if (!localVideo && !mute) {
  920. const maybeShowErrorDialog = error => {
  921. showUI && APP.store.dispatch(notifyCameraError(error));
  922. };
  923. // Try to create local video if there wasn't any.
  924. // This handles the case when user joined with no video
  925. // (dismissed screen sharing screen or in audio only mode), but
  926. // decided to add it later on by clicking on muted video icon or
  927. // turning off the audio only mode.
  928. //
  929. // FIXME when local track creation is moved to react/redux
  930. // it should take care of the use case described above
  931. createLocalTracksF({ devices: [ 'video' ] })
  932. .then(([ videoTrack ]) => videoTrack)
  933. .catch(error => {
  934. // FIXME should send some feedback to the API on error ?
  935. maybeShowErrorDialog(error);
  936. // Rollback the video muted status by using null track
  937. return null;
  938. })
  939. .then(videoTrack => {
  940. logger.debug(`muteVideo: calling useVideoStream for track: ${videoTrack}`);
  941. return this.useVideoStream(videoTrack);
  942. });
  943. } else {
  944. // FIXME show error dialog if it fails (should be handled by react)
  945. muteLocalVideo(mute);
  946. }
  947. },
  948. /**
  949. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  950. * @param {boolean} [showUI] when set to false will not display any error
  951. * dialogs in case of media permissions error.
  952. */
  953. toggleVideoMuted(showUI = true) {
  954. this.muteVideo(!this.isLocalVideoMuted(), showUI);
  955. },
  956. /**
  957. * Retrieve list of ids of conference participants (without local user).
  958. * @returns {string[]}
  959. */
  960. listMembersIds() {
  961. return room.getParticipants().map(p => p.getId());
  962. },
  963. /**
  964. * Checks whether the participant identified by id is a moderator.
  965. * @id id to search for participant
  966. * @return {boolean} whether the participant is moderator
  967. */
  968. isParticipantModerator(id) {
  969. const user = room.getParticipantById(id);
  970. return user && user.isModerator();
  971. },
  972. /**
  973. * Retrieve list of conference participants (without local user).
  974. * @returns {JitsiParticipant[]}
  975. *
  976. * NOTE: Used by jitsi-meet-torture!
  977. */
  978. listMembers() {
  979. return room.getParticipants();
  980. },
  981. get membersCount() {
  982. return room.getParticipants().length + 1;
  983. },
  984. /**
  985. * Returns true if the callstats integration is enabled, otherwise returns
  986. * false.
  987. *
  988. * @returns true if the callstats integration is enabled, otherwise returns
  989. * false.
  990. */
  991. isCallstatsEnabled() {
  992. return room && room.isCallstatsEnabled();
  993. },
  994. /**
  995. * Get speaker stats that track total dominant speaker time.
  996. *
  997. * @returns {object} A hash with keys being user ids and values being the
  998. * library's SpeakerStats model used for calculating time as dominant
  999. * speaker.
  1000. */
  1001. getSpeakerStats() {
  1002. return room.getSpeakerStats();
  1003. },
  1004. /**
  1005. * Returns the connection times stored in the library.
  1006. */
  1007. getConnectionTimes() {
  1008. return room.getConnectionTimes();
  1009. },
  1010. // used by torture currently
  1011. isJoined() {
  1012. return room && room.isJoined();
  1013. },
  1014. getConnectionState() {
  1015. return room && room.getConnectionState();
  1016. },
  1017. /**
  1018. * Obtains current P2P ICE connection state.
  1019. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  1020. * P2P connection
  1021. */
  1022. getP2PConnectionState() {
  1023. return room && room.getP2PConnectionState();
  1024. },
  1025. /**
  1026. * Starts P2P (for tests only)
  1027. * @private
  1028. */
  1029. _startP2P() {
  1030. try {
  1031. room && room.startP2PSession();
  1032. } catch (error) {
  1033. logger.error('Start P2P failed', error);
  1034. throw error;
  1035. }
  1036. },
  1037. /**
  1038. * Stops P2P (for tests only)
  1039. * @private
  1040. */
  1041. _stopP2P() {
  1042. try {
  1043. room && room.stopP2PSession();
  1044. } catch (error) {
  1045. logger.error('Stop P2P failed', error);
  1046. throw error;
  1047. }
  1048. },
  1049. /**
  1050. * Checks whether or not our connection is currently in interrupted and
  1051. * reconnect attempts are in progress.
  1052. *
  1053. * @returns {boolean} true if the connection is in interrupted state or
  1054. * false otherwise.
  1055. */
  1056. isConnectionInterrupted() {
  1057. return room.isConnectionInterrupted();
  1058. },
  1059. /**
  1060. * Obtains the local display name.
  1061. * @returns {string|undefined}
  1062. */
  1063. getLocalDisplayName() {
  1064. return getDisplayName(this.getMyUserId());
  1065. },
  1066. /**
  1067. * Finds JitsiParticipant for given id.
  1068. *
  1069. * @param {string} id participant's identifier(MUC nickname).
  1070. *
  1071. * @returns {JitsiParticipant|null} participant instance for given id or
  1072. * null if not found.
  1073. */
  1074. getParticipantById(id) {
  1075. return room ? room.getParticipantById(id) : null;
  1076. },
  1077. /**
  1078. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  1079. * the given <tt>id</tt>.
  1080. *
  1081. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  1082. *
  1083. * @return {string} the participant's display name or the default string if
  1084. * absent.
  1085. */
  1086. getParticipantDisplayName(id) {
  1087. const displayName = getDisplayName(id);
  1088. if (displayName) {
  1089. return displayName;
  1090. }
  1091. if (APP.conference.isLocalId(id)) {
  1092. return APP.translation.generateTranslationHTML(
  1093. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  1094. }
  1095. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  1096. },
  1097. getMyUserId() {
  1098. return room && room.myUserId();
  1099. },
  1100. /**
  1101. * Will be filled with values only when config.debug is enabled.
  1102. * Its used by torture to check audio levels.
  1103. */
  1104. audioLevelsMap: {},
  1105. /**
  1106. * Returns the stored audio level (stored only if config.debug is enabled)
  1107. * @param id the id for the user audio level to return (the id value is
  1108. * returned for the participant using getMyUserId() method)
  1109. */
  1110. getPeerSSRCAudioLevel(id) {
  1111. return this.audioLevelsMap[id];
  1112. },
  1113. /**
  1114. * @return {number} the number of participants in the conference with at
  1115. * least one track.
  1116. */
  1117. getNumberOfParticipantsWithTracks() {
  1118. return room.getParticipants()
  1119. .filter(p => p.getTracks().length > 0)
  1120. .length;
  1121. },
  1122. /**
  1123. * Returns the stats.
  1124. */
  1125. getStats() {
  1126. return room.connectionQuality.getStats();
  1127. },
  1128. // end used by torture
  1129. /**
  1130. * Download logs, a function that can be called from console while
  1131. * debugging.
  1132. * @param filename (optional) specify target filename
  1133. */
  1134. saveLogs(filename = 'meetlog.json') {
  1135. // this can be called from console and will not have reference to this
  1136. // that's why we reference the global var
  1137. const logs = APP.connection.getLogs();
  1138. downloadJSON(logs, filename);
  1139. },
  1140. /**
  1141. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  1142. * desire to keep room private to this instance and (2) the need of other
  1143. * modules to send and receive commands to and from participants.
  1144. * Eventually, this instance remains in control with respect to the
  1145. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  1146. * JitsiConference) is to be used in the implementation of the Command(s)
  1147. * API of this instance.
  1148. */
  1149. commands: {
  1150. /**
  1151. * Known custom conference commands.
  1152. */
  1153. defaults: commands,
  1154. /**
  1155. * Receives notifications from other participants about commands aka
  1156. * custom events (sent by sendCommand or sendCommandOnce methods).
  1157. * @param command {String} the name of the command
  1158. * @param handler {Function} handler for the command
  1159. */
  1160. addCommandListener() {
  1161. // eslint-disable-next-line prefer-rest-params
  1162. room.addCommandListener(...arguments);
  1163. },
  1164. /**
  1165. * Removes command.
  1166. * @param name {String} the name of the command.
  1167. */
  1168. removeCommand() {
  1169. // eslint-disable-next-line prefer-rest-params
  1170. room.removeCommand(...arguments);
  1171. },
  1172. /**
  1173. * Sends command.
  1174. * @param name {String} the name of the command.
  1175. * @param values {Object} with keys and values that will be sent.
  1176. */
  1177. sendCommand() {
  1178. // eslint-disable-next-line prefer-rest-params
  1179. room.sendCommand(...arguments);
  1180. },
  1181. /**
  1182. * Sends command one time.
  1183. * @param name {String} the name of the command.
  1184. * @param values {Object} with keys and values that will be sent.
  1185. */
  1186. sendCommandOnce() {
  1187. // eslint-disable-next-line prefer-rest-params
  1188. room.sendCommandOnce(...arguments);
  1189. }
  1190. },
  1191. /**
  1192. * Used by the Breakout Rooms feature to join a breakout room or go back to the main room.
  1193. */
  1194. async joinRoom(roomName, isBreakoutRoom = false) {
  1195. this.roomName = roomName;
  1196. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks();
  1197. const localTracks = await tryCreateLocalTracks;
  1198. this._displayErrorsForCreateInitialLocalTracks(errors);
  1199. localTracks.forEach(track => {
  1200. if ((track.isAudioTrack() && this.isLocalAudioMuted())
  1201. || (track.isVideoTrack() && this.isLocalVideoMuted())) {
  1202. track.mute();
  1203. }
  1204. });
  1205. this._createRoom(localTracks, isBreakoutRoom);
  1206. return new Promise((resolve, reject) => {
  1207. new ConferenceConnector(resolve, reject).connect();
  1208. });
  1209. },
  1210. _createRoom(localTracks, isBreakoutRoom = false) {
  1211. const extraOptions = {};
  1212. if (isBreakoutRoom) {
  1213. // We must be in a room already.
  1214. if (!room?.xmpp?.breakoutRoomsComponentAddress) {
  1215. throw new Error('Breakout Rooms not enabled');
  1216. }
  1217. // TODO: re-evaluate this. -saghul
  1218. extraOptions.customDomain = room.xmpp.breakoutRoomsComponentAddress;
  1219. }
  1220. room
  1221. = connection.initJitsiConference(
  1222. APP.conference.roomName,
  1223. {
  1224. ...this._getConferenceOptions(),
  1225. ...extraOptions
  1226. });
  1227. // Filter out the tracks that are muted (except on Safari).
  1228. const tracks = browser.isWebKitBased() ? localTracks : localTracks.filter(track => !track.isMuted());
  1229. this._setLocalAudioVideoStreams(tracks);
  1230. this._room = room; // FIXME do not use this
  1231. APP.store.dispatch(_conferenceWillJoin(room));
  1232. sendLocalParticipant(APP.store, room);
  1233. this._setupListeners();
  1234. },
  1235. /**
  1236. * Sets local video and audio streams.
  1237. * @param {JitsiLocalTrack[]} tracks=[]
  1238. * @returns {Promise[]}
  1239. * @private
  1240. */
  1241. _setLocalAudioVideoStreams(tracks = []) {
  1242. const promises = tracks.map(track => {
  1243. if (track.isAudioTrack()) {
  1244. return this.useAudioStream(track);
  1245. } else if (track.isVideoTrack()) {
  1246. logger.debug(`_setLocalAudioVideoStreams is calling useVideoStream with track: ${track}`);
  1247. return this.useVideoStream(track);
  1248. }
  1249. logger.error('Ignored not an audio nor a video track: ', track);
  1250. return Promise.resolve();
  1251. });
  1252. return Promise.allSettled(promises).then(() => {
  1253. this._localTracksInitialized = true;
  1254. logger.log(`Initialized with ${tracks.length} local tracks`);
  1255. });
  1256. },
  1257. _getConferenceOptions() {
  1258. const options = getConferenceOptions(APP.store.getState());
  1259. options.createVADProcessor = createRnnoiseProcessor;
  1260. return options;
  1261. },
  1262. /**
  1263. * Start using provided video stream.
  1264. * Stops previous video stream.
  1265. * @param {JitsiLocalTrack} newTrack - new track to use or null
  1266. * @returns {Promise}
  1267. */
  1268. useVideoStream(newTrack) {
  1269. logger.debug(`useVideoStream: ${newTrack}`);
  1270. return new Promise((resolve, reject) => {
  1271. _replaceLocalVideoTrackQueue.enqueue(onFinish => {
  1272. const oldTrack = getLocalJitsiVideoTrack(APP.store.getState());
  1273. logger.debug(`useVideoStream: Replacing ${oldTrack} with ${newTrack}`);
  1274. if (oldTrack === newTrack) {
  1275. resolve();
  1276. onFinish();
  1277. return;
  1278. }
  1279. APP.store.dispatch(
  1280. replaceLocalTrack(oldTrack, newTrack, room))
  1281. .then(() => {
  1282. this._setSharingScreen(newTrack);
  1283. this.setVideoMuteStatus();
  1284. })
  1285. .then(resolve)
  1286. .catch(error => {
  1287. logger.error(`useVideoStream failed: ${error}`);
  1288. reject(error);
  1289. })
  1290. .then(onFinish);
  1291. });
  1292. });
  1293. },
  1294. /**
  1295. * Sets `this.isSharingScreen` depending on provided video stream.
  1296. * In case new screen sharing status is not equal previous one
  1297. * it updates desktop sharing buttons in UI
  1298. * and notifies external application.
  1299. *
  1300. * @param {JitsiLocalTrack} [newStream] new stream to use or null
  1301. * @private
  1302. * @returns {void}
  1303. */
  1304. _setSharingScreen(newStream) {
  1305. const wasSharingScreen = this.isSharingScreen;
  1306. this.isSharingScreen = newStream && newStream.videoType === 'desktop';
  1307. if (wasSharingScreen !== this.isSharingScreen) {
  1308. const details = {};
  1309. if (this.isSharingScreen) {
  1310. details.sourceType = newStream.sourceType;
  1311. }
  1312. APP.API.notifyScreenSharingStatusChanged(
  1313. this.isSharingScreen, details);
  1314. }
  1315. },
  1316. /**
  1317. * Start using provided audio stream.
  1318. * Stops previous audio stream.
  1319. * @param {JitsiLocalTrack} newTrack - new track to use or null
  1320. * @returns {Promise}
  1321. */
  1322. useAudioStream(newTrack) {
  1323. return new Promise((resolve, reject) => {
  1324. _replaceLocalAudioTrackQueue.enqueue(onFinish => {
  1325. const oldTrack = getLocalJitsiAudioTrack(APP.store.getState());
  1326. if (oldTrack === newTrack) {
  1327. resolve();
  1328. onFinish();
  1329. return;
  1330. }
  1331. APP.store.dispatch(
  1332. replaceLocalTrack(oldTrack, newTrack, room))
  1333. .then(() => {
  1334. this.setAudioMuteStatus(this.isLocalAudioMuted());
  1335. })
  1336. .then(resolve)
  1337. .catch(reject)
  1338. .then(onFinish);
  1339. });
  1340. });
  1341. },
  1342. /**
  1343. * Returns whether or not the conference is currently in audio only mode.
  1344. *
  1345. * @returns {boolean}
  1346. */
  1347. isAudioOnly() {
  1348. return Boolean(APP.store.getState()['features/base/audio-only'].enabled);
  1349. },
  1350. videoSwitchInProgress: false,
  1351. /**
  1352. * This fields stores a handler which will create a Promise which turns off
  1353. * the screen sharing and restores the previous video state (was there
  1354. * any video, before switching to screen sharing ? was it muted ?).
  1355. *
  1356. * Once called this fields is cleared to <tt>null</tt>.
  1357. * @type {Function|null}
  1358. */
  1359. _untoggleScreenSharing: null,
  1360. /**
  1361. * Creates a Promise which turns off the screen sharing and restores
  1362. * the previous state described by the arguments.
  1363. *
  1364. * This method is bound to the appropriate values, after switching to screen
  1365. * sharing and stored in {@link _untoggleScreenSharing}.
  1366. *
  1367. * @param {boolean} didHaveVideo indicates if there was a camera video being
  1368. * used, before switching to screen sharing.
  1369. * @param {boolean} ignoreDidHaveVideo indicates if the camera video should be
  1370. * ignored when switching screen sharing off.
  1371. * @return {Promise} resolved after the screen sharing is turned off, or
  1372. * rejected with some error (no idea what kind of error, possible GUM error)
  1373. * in case it fails.
  1374. * @private
  1375. */
  1376. async _turnScreenSharingOff(didHaveVideo, ignoreDidHaveVideo) {
  1377. this._untoggleScreenSharing = null;
  1378. this.videoSwitchInProgress = true;
  1379. APP.store.dispatch(stopReceiver());
  1380. this._stopProxyConnection();
  1381. if (config.enableScreenshotCapture) {
  1382. APP.store.dispatch(toggleScreenshotCaptureSummary(false));
  1383. }
  1384. const tracks = APP.store.getState()['features/base/tracks'];
  1385. const duration = getLocalVideoTrack(tracks)?.jitsiTrack.getDuration() ?? 0;
  1386. // It can happen that presenter GUM is in progress while screensharing is being turned off. Here it needs to
  1387. // wait for that GUM to be resolved in order to prevent leaking the presenter track(this.localPresenterVideo
  1388. // will be null when SS is being turned off, but it will initialize once GUM resolves).
  1389. let promise = _prevMutePresenterVideo = _prevMutePresenterVideo.then(() => {
  1390. // mute the presenter track if it exists.
  1391. if (this.localPresenterVideo) {
  1392. APP.store.dispatch(setVideoMuted(true, MEDIA_TYPE.PRESENTER));
  1393. return this.localPresenterVideo.dispose().then(() => {
  1394. APP.store.dispatch(trackRemoved(this.localPresenterVideo));
  1395. this.localPresenterVideo = null;
  1396. });
  1397. }
  1398. });
  1399. // If system audio was also shared stop the AudioMixerEffect and dispose of the desktop audio track.
  1400. if (this._mixerEffect) {
  1401. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1402. await localAudio.setEffect(undefined);
  1403. await this._desktopAudioStream.dispose();
  1404. this._mixerEffect = undefined;
  1405. this._desktopAudioStream = undefined;
  1406. // In case there was no local audio when screen sharing was started the fact that we set the audio stream to
  1407. // null will take care of the desktop audio stream cleanup.
  1408. } else if (this._desktopAudioStream) {
  1409. await this.useAudioStream(null);
  1410. this._desktopAudioStream = undefined;
  1411. }
  1412. APP.store.dispatch(setScreenAudioShareState(false));
  1413. if (didHaveVideo && !ignoreDidHaveVideo) {
  1414. promise = promise.then(() => createLocalTracksF({ devices: [ 'video' ] }))
  1415. .then(([ stream ]) => {
  1416. logger.debug(`_turnScreenSharingOff using ${stream} for useVideoStream`);
  1417. return this.useVideoStream(stream);
  1418. })
  1419. .catch(error => {
  1420. logger.error('failed to switch back to local video', error);
  1421. return this.useVideoStream(null).then(() =>
  1422. // Still fail with the original err
  1423. Promise.reject(error)
  1424. );
  1425. });
  1426. } else {
  1427. promise = promise.then(() => {
  1428. logger.debug('_turnScreenSharingOff using null for useVideoStream');
  1429. return this.useVideoStream(null);
  1430. });
  1431. }
  1432. return promise.then(
  1433. () => {
  1434. this.videoSwitchInProgress = false;
  1435. sendAnalytics(createScreenSharingEvent('stopped',
  1436. duration === 0 ? null : duration));
  1437. logger.info('Screen sharing stopped.');
  1438. },
  1439. error => {
  1440. this.videoSwitchInProgress = false;
  1441. logger.error(`_turnScreenSharingOff failed: ${error}`);
  1442. throw error;
  1443. });
  1444. },
  1445. /**
  1446. * Toggles between screen sharing and camera video if the toggle parameter
  1447. * is not specified and starts the procedure for obtaining new screen
  1448. * sharing/video track otherwise.
  1449. *
  1450. * @param {boolean} [toggle] - If true - new screen sharing track will be
  1451. * obtained. If false - new video track will be obtain. If not specified -
  1452. * toggles between screen sharing and camera video.
  1453. * @param {Object} [options] - Screen sharing options that will be passed to
  1454. * createLocalTracks.
  1455. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  1456. * sources that have to be displayed in the desktop picker window ('screen',
  1457. * 'window', etc.).
  1458. * @param {boolean} ignoreDidHaveVideo - if true ignore if video was on when sharing started.
  1459. * @return {Promise.<T>}
  1460. */
  1461. async toggleScreenSharing(toggle = !this._untoggleScreenSharing, options = {}, ignoreDidHaveVideo) {
  1462. logger.debug(`toggleScreenSharing: ${toggle}`);
  1463. if (this.videoSwitchInProgress) {
  1464. return Promise.reject(`toggleScreenSharing: ${toggle} aborted - video switch in progress.`);
  1465. }
  1466. if (!JitsiMeetJS.isDesktopSharingEnabled()) {
  1467. return Promise.reject('Cannot toggle screen sharing: not supported.');
  1468. }
  1469. if (this.isAudioOnly()) {
  1470. return Promise.reject('No screensharing in audio only mode');
  1471. }
  1472. if (toggle) {
  1473. try {
  1474. await this._switchToScreenSharing(options);
  1475. return;
  1476. } catch (err) {
  1477. logger.error('Failed to switch to screensharing', err);
  1478. return;
  1479. }
  1480. }
  1481. return this._untoggleScreenSharing
  1482. ? this._untoggleScreenSharing(ignoreDidHaveVideo)
  1483. : Promise.resolve();
  1484. },
  1485. /**
  1486. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1487. *
  1488. * @param {Object} [options] - Screen sharing options that will be passed to
  1489. * createLocalTracks.
  1490. * @param {Object} [options.desktopSharing]
  1491. * @param {Object} [options.desktopStream] - An existing desktop stream to
  1492. * use instead of creating a new desktop stream.
  1493. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1494. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1495. * {@link JitsiTrackError}.
  1496. *
  1497. * @private
  1498. */
  1499. _createDesktopTrack(options = {}) {
  1500. const didHaveVideo = !this.isLocalVideoMuted();
  1501. const getDesktopStreamPromise = options.desktopStream
  1502. ? Promise.resolve([ options.desktopStream ])
  1503. : createLocalTracksF({
  1504. desktopSharingSourceDevice: options.desktopSharingSources
  1505. ? null : config._desktopSharingSourceDevice,
  1506. desktopSharingSources: options.desktopSharingSources,
  1507. devices: [ 'desktop' ]
  1508. });
  1509. return getDesktopStreamPromise.then(desktopStreams => {
  1510. // Stores the "untoggle" handler which remembers whether was
  1511. // there any video before and whether was it muted.
  1512. this._untoggleScreenSharing
  1513. = this._turnScreenSharingOff.bind(this, didHaveVideo);
  1514. const desktopVideoStream = desktopStreams.find(stream => stream.getType() === MEDIA_TYPE.VIDEO);
  1515. const dekstopAudioStream = desktopStreams.find(stream => stream.getType() === MEDIA_TYPE.AUDIO);
  1516. if (dekstopAudioStream) {
  1517. dekstopAudioStream.on(
  1518. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1519. () => {
  1520. logger.debug(`Local screensharing audio track stopped. ${this.isSharingScreen}`);
  1521. // Handle case where screen share was stopped from the browsers 'screen share in progress'
  1522. // window. If audio screen sharing is stopped via the normal UX flow this point shouldn't
  1523. // be reached.
  1524. isScreenAudioShared(APP.store.getState())
  1525. && this._untoggleScreenSharing
  1526. && this._untoggleScreenSharing();
  1527. }
  1528. );
  1529. }
  1530. if (desktopVideoStream) {
  1531. desktopVideoStream.on(
  1532. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1533. () => {
  1534. logger.debug(`Local screensharing track stopped. ${this.isSharingScreen}`);
  1535. // If the stream was stopped during screen sharing
  1536. // session then we should switch back to video.
  1537. this.isSharingScreen
  1538. && this._untoggleScreenSharing
  1539. && this._untoggleScreenSharing();
  1540. }
  1541. );
  1542. }
  1543. return desktopStreams;
  1544. }, error => {
  1545. throw error;
  1546. });
  1547. },
  1548. /**
  1549. * Creates a new instance of presenter effect. A new video track is created
  1550. * using the new set of constraints that are calculated based on
  1551. * the height of the desktop that is being currently shared.
  1552. *
  1553. * @param {number} height - The height of the desktop stream that is being
  1554. * currently shared.
  1555. * @param {string} cameraDeviceId - The device id of the camera to be used.
  1556. * @return {Promise<JitsiStreamPresenterEffect>} - A promise resolved with
  1557. * {@link JitsiStreamPresenterEffect} if it succeeds.
  1558. */
  1559. async _createPresenterStreamEffect(height = null, cameraDeviceId = null) {
  1560. if (!this.localPresenterVideo) {
  1561. const camera = cameraDeviceId ?? getUserSelectedCameraDeviceId(APP.store.getState());
  1562. try {
  1563. this.localPresenterVideo = await createLocalPresenterTrack({ cameraDeviceId: camera }, height);
  1564. } catch (err) {
  1565. logger.error('Failed to create a camera track for presenter', err);
  1566. return;
  1567. }
  1568. APP.store.dispatch(trackAdded(this.localPresenterVideo));
  1569. }
  1570. try {
  1571. const effect = await createPresenterEffect(this.localPresenterVideo.stream);
  1572. return effect;
  1573. } catch (err) {
  1574. logger.error('Failed to create the presenter effect', err);
  1575. }
  1576. },
  1577. /**
  1578. * Tries to turn the presenter video track on or off. If a presenter track
  1579. * doesn't exist, a new video track is created.
  1580. *
  1581. * @param mute - true for mute and false for unmute.
  1582. *
  1583. * @private
  1584. */
  1585. async _mutePresenterVideo(mute) {
  1586. const maybeShowErrorDialog = error => {
  1587. APP.store.dispatch(notifyCameraError(error));
  1588. };
  1589. // Check for NO-OP
  1590. if (mute && (!this.localPresenterVideo || this.localPresenterVideo.isMuted())) {
  1591. return;
  1592. } else if (!mute && this.localPresenterVideo && !this.localPresenterVideo.isMuted()) {
  1593. return;
  1594. }
  1595. // Create a new presenter track and apply the presenter effect.
  1596. if (!this.localPresenterVideo && !mute) {
  1597. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  1598. const { height, width } = localVideo.track.getSettings() ?? localVideo.track.getConstraints();
  1599. const isPortrait = height >= width;
  1600. const DESKTOP_STREAM_CAP = 720;
  1601. const highResolutionTrack
  1602. = (isPortrait && width > DESKTOP_STREAM_CAP) || (!isPortrait && height > DESKTOP_STREAM_CAP);
  1603. // Resizing the desktop track for presenter is causing blurriness of the desktop share on chrome.
  1604. // Disable resizing by default, enable it only when config.js setting is enabled.
  1605. const resizeDesktopStream = highResolutionTrack && config.videoQuality?.resizeDesktopForPresenter;
  1606. if (resizeDesktopStream) {
  1607. let desktopResizeConstraints = {};
  1608. if (height && width) {
  1609. const advancedConstraints = [ { aspectRatio: (width / height).toPrecision(4) } ];
  1610. const constraint = isPortrait ? { width: DESKTOP_STREAM_CAP } : { height: DESKTOP_STREAM_CAP };
  1611. advancedConstraints.push(constraint);
  1612. desktopResizeConstraints.advanced = advancedConstraints;
  1613. } else {
  1614. desktopResizeConstraints = {
  1615. width: 1280,
  1616. height: 720
  1617. };
  1618. }
  1619. // Apply the constraints on the desktop track.
  1620. try {
  1621. await localVideo.track.applyConstraints(desktopResizeConstraints);
  1622. } catch (err) {
  1623. logger.error('Failed to apply constraints on the desktop stream for presenter mode', err);
  1624. return;
  1625. }
  1626. }
  1627. const trackHeight = resizeDesktopStream
  1628. ? localVideo.track.getSettings().height ?? DESKTOP_STREAM_CAP
  1629. : height;
  1630. let effect;
  1631. try {
  1632. effect = await this._createPresenterStreamEffect(trackHeight);
  1633. } catch (err) {
  1634. logger.error('Failed to unmute Presenter Video', err);
  1635. maybeShowErrorDialog(err);
  1636. return;
  1637. }
  1638. // Replace the desktop track on the peerconnection.
  1639. try {
  1640. await localVideo.setEffect(effect);
  1641. APP.store.dispatch(setVideoMuted(mute, MEDIA_TYPE.PRESENTER));
  1642. this.setVideoMuteStatus();
  1643. } catch (err) {
  1644. logger.error('Failed to apply the Presenter effect', err);
  1645. }
  1646. } else {
  1647. APP.store.dispatch(setVideoMuted(mute, MEDIA_TYPE.PRESENTER));
  1648. }
  1649. },
  1650. /**
  1651. * Tries to switch to the screensharing mode by disposing camera stream and
  1652. * replacing it with a desktop one.
  1653. *
  1654. * @param {Object} [options] - Screen sharing options that will be passed to
  1655. * createLocalTracks.
  1656. *
  1657. * @return {Promise} - A Promise resolved if the operation succeeds or
  1658. * rejected with some unknown type of error in case it fails. Promise will
  1659. * be rejected immediately if {@link videoSwitchInProgress} is true.
  1660. *
  1661. * @private
  1662. */
  1663. _switchToScreenSharing(options = {}) {
  1664. if (this.videoSwitchInProgress) {
  1665. return Promise.reject('Switch in progress.');
  1666. }
  1667. this.videoSwitchInProgress = true;
  1668. return this._createDesktopTrack(options)
  1669. .then(async streams => {
  1670. let desktopVideoStream = streams.find(stream => stream.getType() === MEDIA_TYPE.VIDEO);
  1671. this._desktopAudioStream = streams.find(stream => stream.getType() === MEDIA_TYPE.AUDIO);
  1672. const { audioOnly = false } = options;
  1673. // If we're in audio only mode dispose of the video track otherwise the screensharing state will be
  1674. // inconsistent.
  1675. if (audioOnly) {
  1676. desktopVideoStream.dispose();
  1677. desktopVideoStream = undefined;
  1678. if (!this._desktopAudioStream) {
  1679. return Promise.reject(AUDIO_ONLY_SCREEN_SHARE_NO_TRACK);
  1680. }
  1681. }
  1682. if (desktopVideoStream) {
  1683. logger.debug(`_switchToScreenSharing is using ${desktopVideoStream} for useVideoStream`);
  1684. await this.useVideoStream(desktopVideoStream);
  1685. }
  1686. if (this._desktopAudioStream) {
  1687. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1688. // If there is a localAudio stream, mix in the desktop audio stream captured by the screen sharing
  1689. // api.
  1690. if (localAudio) {
  1691. this._mixerEffect = new AudioMixerEffect(this._desktopAudioStream);
  1692. await localAudio.setEffect(this._mixerEffect);
  1693. } else {
  1694. // If no local stream is present ( i.e. no input audio devices) we use the screen share audio
  1695. // stream as we would use a regular stream.
  1696. await this.useAudioStream(this._desktopAudioStream);
  1697. }
  1698. APP.store.dispatch(setScreenAudioShareState(true));
  1699. }
  1700. })
  1701. .then(() => {
  1702. this.videoSwitchInProgress = false;
  1703. if (config.enableScreenshotCapture) {
  1704. APP.store.dispatch(toggleScreenshotCaptureSummary(true));
  1705. }
  1706. sendAnalytics(createScreenSharingEvent('started'));
  1707. logger.log('Screen sharing started');
  1708. })
  1709. .catch(error => {
  1710. this.videoSwitchInProgress = false;
  1711. // Pawel: With this call I'm trying to preserve the original
  1712. // behaviour although it is not clear why would we "untoggle"
  1713. // on failure. I suppose it was to restore video in case there
  1714. // was some problem during "this.useVideoStream(desktopStream)".
  1715. // It's important to note that the handler will not be available
  1716. // if we fail early on trying to get desktop media (which makes
  1717. // sense, because the camera video is still being used, so
  1718. // nothing to "untoggle").
  1719. if (this._untoggleScreenSharing) {
  1720. this._untoggleScreenSharing();
  1721. }
  1722. // FIXME the code inside of _handleScreenSharingError is
  1723. // asynchronous, but does not return a Promise and is not part
  1724. // of the current Promise chain.
  1725. this._handleScreenSharingError(error);
  1726. return Promise.reject(error);
  1727. });
  1728. },
  1729. /**
  1730. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1731. * trying to create screensharing track. It will either do nothing if
  1732. * the dialog was canceled on user's request or display an error if
  1733. * screensharing couldn't be started.
  1734. * @param {JitsiTrackError} error - The error returned by
  1735. * {@link _createDesktopTrack} Promise.
  1736. * @private
  1737. */
  1738. _handleScreenSharingError(error) {
  1739. if (error.name === JitsiTrackErrors.SCREENSHARING_USER_CANCELED) {
  1740. return;
  1741. }
  1742. logger.error('failed to share local desktop', error);
  1743. // Handling:
  1744. // JitsiTrackErrors.CONSTRAINT_FAILED
  1745. // JitsiTrackErrors.PERMISSION_DENIED
  1746. // JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR
  1747. // and any other
  1748. let descriptionKey;
  1749. let titleKey;
  1750. if (error.name === JitsiTrackErrors.PERMISSION_DENIED) {
  1751. descriptionKey = 'dialog.screenSharingPermissionDeniedError';
  1752. titleKey = 'dialog.screenSharingFailedTitle';
  1753. } else if (error.name === JitsiTrackErrors.CONSTRAINT_FAILED) {
  1754. descriptionKey = 'dialog.cameraConstraintFailedError';
  1755. titleKey = 'deviceError.cameraError';
  1756. } else if (error.name === JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR) {
  1757. descriptionKey = 'dialog.screenSharingFailed';
  1758. titleKey = 'dialog.screenSharingFailedTitle';
  1759. } else if (error === AUDIO_ONLY_SCREEN_SHARE_NO_TRACK) {
  1760. descriptionKey = 'notify.screenShareNoAudio';
  1761. titleKey = 'notify.screenShareNoAudioTitle';
  1762. }
  1763. APP.UI.messageHandler.showError({
  1764. descriptionKey,
  1765. titleKey
  1766. });
  1767. },
  1768. /**
  1769. * Setup interaction between conference and UI.
  1770. */
  1771. _setupListeners() {
  1772. // add local streams when joined to the conference
  1773. room.on(JitsiConferenceEvents.CONFERENCE_JOINED, () => {
  1774. this._onConferenceJoined();
  1775. });
  1776. room.on(JitsiConferenceEvents.CONFERENCE_JOIN_IN_PROGRESS, () => {
  1777. APP.store.dispatch(setPrejoinPageVisibility(false));
  1778. });
  1779. room.on(
  1780. JitsiConferenceEvents.CONFERENCE_LEFT,
  1781. (...args) => {
  1782. APP.store.dispatch(conferenceTimestampChanged(0));
  1783. APP.store.dispatch(conferenceLeft(room, ...args));
  1784. });
  1785. room.on(
  1786. JitsiConferenceEvents.CONFERENCE_UNIQUE_ID_SET,
  1787. (...args) => {
  1788. // Preserve the sessionId so that the value is accessible even after room
  1789. // is disconnected.
  1790. room.sessionId = room.getMeetingUniqueId();
  1791. APP.store.dispatch(conferenceUniqueIdSet(room, ...args));
  1792. });
  1793. room.on(
  1794. JitsiConferenceEvents.AUTH_STATUS_CHANGED,
  1795. (authEnabled, authLogin) =>
  1796. APP.store.dispatch(authStatusChanged(authEnabled, authLogin)));
  1797. room.on(JitsiConferenceEvents.PARTCIPANT_FEATURES_CHANGED, user => {
  1798. APP.store.dispatch(updateRemoteParticipantFeatures(user));
  1799. });
  1800. room.on(JitsiConferenceEvents.USER_JOINED, (id, user) => {
  1801. // The logic shared between RN and web.
  1802. commonUserJoinedHandling(APP.store, room, user);
  1803. if (user.isHidden()) {
  1804. return;
  1805. }
  1806. APP.store.dispatch(updateRemoteParticipantFeatures(user));
  1807. logger.log(`USER ${id} connected:`, user);
  1808. APP.UI.addUser(user);
  1809. });
  1810. room.on(JitsiConferenceEvents.USER_LEFT, (id, user) => {
  1811. // The logic shared between RN and web.
  1812. commonUserLeftHandling(APP.store, room, user);
  1813. if (user.isHidden()) {
  1814. return;
  1815. }
  1816. logger.log(`USER ${id} LEFT:`, user);
  1817. });
  1818. room.on(JitsiConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1819. APP.store.dispatch(participantPresenceChanged(id, status));
  1820. const user = room.getParticipantById(id);
  1821. if (user) {
  1822. APP.UI.updateUserStatus(user, status);
  1823. }
  1824. });
  1825. room.on(JitsiConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1826. if (this.isLocalId(id)) {
  1827. logger.info(`My role changed, new role: ${role}`);
  1828. APP.store.dispatch(localParticipantRoleChanged(role));
  1829. APP.API.notifyUserRoleChanged(id, role);
  1830. } else {
  1831. APP.store.dispatch(participantRoleChanged(id, role));
  1832. }
  1833. });
  1834. room.on(JitsiConferenceEvents.TRACK_ADDED, track => {
  1835. if (!track || track.isLocal()) {
  1836. return;
  1837. }
  1838. APP.store.dispatch(trackAdded(track));
  1839. });
  1840. room.on(JitsiConferenceEvents.TRACK_REMOVED, track => {
  1841. if (!track || track.isLocal()) {
  1842. return;
  1843. }
  1844. APP.store.dispatch(trackRemoved(track));
  1845. });
  1846. room.on(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1847. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1848. let newLvl = lvl;
  1849. if (this.isLocalId(id) && localAudio?.isMuted()) {
  1850. newLvl = 0;
  1851. }
  1852. if (config.debug) {
  1853. this.audioLevelsMap[id] = newLvl;
  1854. if (config.debugAudioLevels) {
  1855. logger.log(`AudioLevel:${id}/${newLvl}`);
  1856. }
  1857. }
  1858. APP.UI.setAudioLevel(id, newLvl);
  1859. });
  1860. room.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED, (track, participantThatMutedUs) => {
  1861. if (participantThatMutedUs) {
  1862. APP.store.dispatch(participantMutedUs(participantThatMutedUs, track));
  1863. if (this.isSharingScreen && track.isVideoTrack()) {
  1864. logger.debug('TRACK_MUTE_CHANGED while screen sharing');
  1865. this._turnScreenSharingOff(false);
  1866. }
  1867. }
  1868. });
  1869. room.on(JitsiConferenceEvents.SUBJECT_CHANGED,
  1870. subject => APP.store.dispatch(conferenceSubjectChanged(subject)));
  1871. room.on(
  1872. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1873. (leavingIds, enteringIds) =>
  1874. APP.UI.handleLastNEndpoints(leavingIds, enteringIds));
  1875. room.on(
  1876. JitsiConferenceEvents.P2P_STATUS,
  1877. (jitsiConference, p2p) =>
  1878. APP.store.dispatch(p2pStatusChanged(p2p)));
  1879. room.on(
  1880. JitsiConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1881. (id, connectionStatus) => APP.store.dispatch(
  1882. participantConnectionStatusChanged(id, connectionStatus)));
  1883. room.on(
  1884. JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED,
  1885. (dominant, previous) => APP.store.dispatch(dominantSpeakerChanged(dominant, previous, room)));
  1886. room.on(
  1887. JitsiConferenceEvents.CONFERENCE_CREATED_TIMESTAMP,
  1888. conferenceTimestamp => APP.store.dispatch(conferenceTimestampChanged(conferenceTimestamp)));
  1889. room.on(JitsiConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1890. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1891. JitsiParticipantConnectionStatus.INTERRUPTED));
  1892. });
  1893. room.on(JitsiConferenceEvents.CONNECTION_RESTORED, () => {
  1894. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1895. JitsiParticipantConnectionStatus.ACTIVE));
  1896. });
  1897. room.on(
  1898. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1899. (id, displayName) => {
  1900. const formattedDisplayName
  1901. = getNormalizedDisplayName(displayName);
  1902. APP.store.dispatch(participantUpdated({
  1903. conference: room,
  1904. id,
  1905. name: formattedDisplayName
  1906. }));
  1907. APP.API.notifyDisplayNameChanged(id, {
  1908. displayName: formattedDisplayName,
  1909. formattedDisplayName:
  1910. appendSuffix(
  1911. formattedDisplayName
  1912. || interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME)
  1913. });
  1914. }
  1915. );
  1916. room.on(
  1917. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1918. (id, botType) => {
  1919. APP.store.dispatch(participantUpdated({
  1920. conference: room,
  1921. id,
  1922. botType
  1923. }));
  1924. }
  1925. );
  1926. room.on(
  1927. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1928. (...args) => {
  1929. APP.store.dispatch(endpointMessageReceived(...args));
  1930. if (args && args.length >= 2) {
  1931. const [ sender, eventData ] = args;
  1932. if (eventData.name === ENDPOINT_TEXT_MESSAGE_NAME) {
  1933. APP.API.notifyEndpointTextMessageReceived({
  1934. senderInfo: {
  1935. jid: sender._jid,
  1936. id: sender._id
  1937. },
  1938. eventData
  1939. });
  1940. }
  1941. }
  1942. });
  1943. room.on(
  1944. JitsiConferenceEvents.NON_PARTICIPANT_MESSAGE_RECEIVED,
  1945. (...args) => APP.store.dispatch(nonParticipantMessageReceived(...args)));
  1946. room.on(
  1947. JitsiConferenceEvents.LOCK_STATE_CHANGED,
  1948. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1949. room.on(JitsiConferenceEvents.KICKED, (participant, reason, isReplaced) => {
  1950. if (isReplaced) {
  1951. // this event triggers when the local participant is kicked, `participant`
  1952. // is the kicker. In replace participant case, kicker is undefined,
  1953. // as the server initiated it. We mark in store the local participant
  1954. // as being replaced based on jwt.
  1955. const localParticipant = getLocalParticipant(APP.store.getState());
  1956. APP.store.dispatch(participantUpdated({
  1957. conference: room,
  1958. id: localParticipant.id,
  1959. isReplaced
  1960. }));
  1961. // we send readyToClose when kicked participant is replace so that
  1962. // embedding app can choose to dispose the iframe API on the handler.
  1963. APP.API.notifyReadyToClose();
  1964. }
  1965. APP.store.dispatch(kickedOut(room, participant));
  1966. });
  1967. room.on(JitsiConferenceEvents.PARTICIPANT_KICKED, (kicker, kicked) => {
  1968. APP.store.dispatch(participantKicked(kicker, kicked));
  1969. });
  1970. room.on(JitsiConferenceEvents.SUSPEND_DETECTED, () => {
  1971. APP.store.dispatch(suspendDetected());
  1972. });
  1973. APP.UI.addListener(UIEvents.AUDIO_MUTED, muted => {
  1974. this.muteAudio(muted);
  1975. });
  1976. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  1977. this.muteVideo(muted);
  1978. });
  1979. room.addCommandListener(this.commands.defaults.ETHERPAD,
  1980. ({ value }) => {
  1981. APP.UI.initEtherpad(value);
  1982. }
  1983. );
  1984. APP.UI.addListener(UIEvents.EMAIL_CHANGED,
  1985. this.changeLocalEmail.bind(this));
  1986. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1987. APP.store.dispatch(participantUpdated({
  1988. conference: room,
  1989. id: from,
  1990. email: data.value
  1991. }));
  1992. });
  1993. room.addCommandListener(
  1994. this.commands.defaults.AVATAR_URL,
  1995. (data, from) => {
  1996. APP.store.dispatch(
  1997. participantUpdated({
  1998. conference: room,
  1999. id: from,
  2000. avatarURL: data.value
  2001. }));
  2002. });
  2003. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  2004. this.changeLocalDisplayName.bind(this));
  2005. room.on(
  2006. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  2007. ({ audio, video }) => {
  2008. APP.store.dispatch(
  2009. onStartMutedPolicyChanged(audio, video));
  2010. }
  2011. );
  2012. room.on(JitsiConferenceEvents.STARTED_MUTED, () => {
  2013. const audioMuted = room.isStartAudioMuted();
  2014. const videoMuted = room.isStartVideoMuted();
  2015. const localTracks = getLocalTracks(APP.store.getState()['features/base/tracks']);
  2016. const promises = [];
  2017. APP.store.dispatch(setAudioMuted(audioMuted));
  2018. APP.store.dispatch(setVideoMuted(videoMuted));
  2019. // Remove the tracks from the peerconnection.
  2020. for (const track of localTracks) {
  2021. // Always add the track on Safari because of a known issue where audio playout doesn't happen
  2022. // if the user joins audio and video muted, i.e., if there is no local media capture.
  2023. if (audioMuted && track.jitsiTrack?.getType() === MEDIA_TYPE.AUDIO && !browser.isWebKitBased()) {
  2024. promises.push(this.useAudioStream(null));
  2025. }
  2026. if (videoMuted && track.jitsiTrack?.getType() === MEDIA_TYPE.VIDEO) {
  2027. promises.push(this.useVideoStream(null));
  2028. }
  2029. }
  2030. Promise.allSettled(promises)
  2031. .then(() => APP.UI.notifyInitiallyMuted());
  2032. });
  2033. room.on(
  2034. JitsiConferenceEvents.DATA_CHANNEL_OPENED, () => {
  2035. APP.store.dispatch(dataChannelOpened());
  2036. }
  2037. );
  2038. // call hangup
  2039. APP.UI.addListener(UIEvents.HANGUP, () => {
  2040. this.hangup(true);
  2041. });
  2042. // logout
  2043. APP.UI.addListener(UIEvents.LOGOUT, () => {
  2044. AuthHandler.logout(room).then(url => {
  2045. if (url) {
  2046. UIUtil.redirect(url);
  2047. } else {
  2048. this.hangup(true);
  2049. }
  2050. });
  2051. });
  2052. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  2053. AuthHandler.authenticate(room);
  2054. });
  2055. APP.UI.addListener(
  2056. UIEvents.VIDEO_DEVICE_CHANGED,
  2057. cameraDeviceId => {
  2058. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  2059. const videoWasMuted = this.isLocalVideoMuted();
  2060. sendAnalytics(createDeviceChangedEvent('video', 'input'));
  2061. // If both screenshare and video are in progress, restart the
  2062. // presenter mode with the new camera device.
  2063. if (this.isSharingScreen && !videoWasMuted) {
  2064. const { height } = localVideo.track.getSettings();
  2065. // dispose the existing presenter track and create a new
  2066. // camera track.
  2067. // FIXME JitsiLocalTrack.dispose is async and should be waited for
  2068. this.localPresenterVideo && this.localPresenterVideo.dispose();
  2069. this.localPresenterVideo = null;
  2070. return this._createPresenterStreamEffect(height, cameraDeviceId)
  2071. .then(effect => localVideo.setEffect(effect))
  2072. .then(() => {
  2073. this.setVideoMuteStatus();
  2074. logger.log('Switched local video device while screen sharing and the video is unmuted');
  2075. this._updateVideoDeviceId();
  2076. })
  2077. .catch(err => APP.store.dispatch(notifyCameraError(err)));
  2078. // If screenshare is in progress but video is muted, update the default device
  2079. // id for video, dispose the existing presenter track and create a new effect
  2080. // that can be applied on un-mute.
  2081. } else if (this.isSharingScreen && videoWasMuted) {
  2082. logger.log('Switched local video device: while screen sharing and the video is muted');
  2083. const { height } = localVideo.track.getSettings();
  2084. this._updateVideoDeviceId();
  2085. // FIXME JitsiLocalTrack.dispose is async and should be waited for
  2086. this.localPresenterVideo && this.localPresenterVideo.dispose();
  2087. this.localPresenterVideo = null;
  2088. this._createPresenterStreamEffect(height, cameraDeviceId);
  2089. // if there is only video, switch to the new camera stream.
  2090. } else {
  2091. createLocalTracksF({
  2092. devices: [ 'video' ],
  2093. cameraDeviceId,
  2094. micDeviceId: null
  2095. })
  2096. .then(([ stream ]) => {
  2097. // if we are in audio only mode or video was muted before
  2098. // changing device, then mute
  2099. if (this.isAudioOnly() || videoWasMuted) {
  2100. return stream.mute()
  2101. .then(() => stream);
  2102. }
  2103. return stream;
  2104. })
  2105. .then(stream => {
  2106. logger.log('Switching the local video device.');
  2107. return this.useVideoStream(stream);
  2108. })
  2109. .then(() => {
  2110. logger.log('Switched local video device.');
  2111. this._updateVideoDeviceId();
  2112. })
  2113. .catch(error => {
  2114. logger.error(`Switching the local video device failed: ${error}`);
  2115. return APP.store.dispatch(notifyCameraError(error));
  2116. });
  2117. }
  2118. }
  2119. );
  2120. APP.UI.addListener(
  2121. UIEvents.AUDIO_DEVICE_CHANGED,
  2122. micDeviceId => {
  2123. const audioWasMuted = this.isLocalAudioMuted();
  2124. // When the 'default' mic needs to be selected, we need to
  2125. // pass the real device id to gUM instead of 'default' in order
  2126. // to get the correct MediaStreamTrack from chrome because of the
  2127. // following bug.
  2128. // https://bugs.chromium.org/p/chromium/issues/detail?id=997689
  2129. const hasDefaultMicChanged = micDeviceId === 'default';
  2130. sendAnalytics(createDeviceChangedEvent('audio', 'input'));
  2131. createLocalTracksF({
  2132. devices: [ 'audio' ],
  2133. cameraDeviceId: null,
  2134. micDeviceId: hasDefaultMicChanged
  2135. ? getDefaultDeviceId(APP.store.getState(), 'audioInput')
  2136. : micDeviceId
  2137. })
  2138. .then(([ stream ]) => {
  2139. // if audio was muted before changing the device, mute
  2140. // with the new device
  2141. if (audioWasMuted) {
  2142. return stream.mute()
  2143. .then(() => stream);
  2144. }
  2145. return stream;
  2146. })
  2147. .then(async stream => {
  2148. // In case screen sharing audio is also shared we mix it with new input stream. The old _mixerEffect
  2149. // will be cleaned up when the existing track is replaced.
  2150. if (this._mixerEffect) {
  2151. this._mixerEffect = new AudioMixerEffect(this._desktopAudioStream);
  2152. await stream.setEffect(this._mixerEffect);
  2153. }
  2154. return this.useAudioStream(stream);
  2155. })
  2156. .then(() => {
  2157. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  2158. if (localAudio && hasDefaultMicChanged) {
  2159. // workaround for the default device to be shown as selected in the
  2160. // settings even when the real device id was passed to gUM because of the
  2161. // above mentioned chrome bug.
  2162. localAudio._realDeviceId = localAudio.deviceId = 'default';
  2163. }
  2164. logger.log(`switched local audio device: ${localAudio?.getDeviceId()}`);
  2165. this._updateAudioDeviceId();
  2166. })
  2167. .catch(err => {
  2168. APP.store.dispatch(notifyMicError(err));
  2169. });
  2170. }
  2171. );
  2172. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  2173. // FIXME On web video track is stored both in redux and in
  2174. // 'localVideo' field, video is attempted to be unmuted twice when
  2175. // turning off the audio only mode. This will crash the app with
  2176. // 'unmute operation is already in progress'.
  2177. // Because there's no logic in redux about creating new track in
  2178. // case unmute when not track exists the things have to go through
  2179. // muteVideo logic in such case.
  2180. const tracks = APP.store.getState()['features/base/tracks'];
  2181. const isTrackInRedux
  2182. = Boolean(
  2183. tracks.find(
  2184. track => track.jitsiTrack
  2185. && track.jitsiTrack.getType() === 'video'));
  2186. if (!isTrackInRedux) {
  2187. this.muteVideo(audioOnly);
  2188. }
  2189. // Immediately update the UI by having remote videos and the large
  2190. // video update themselves instead of waiting for some other event
  2191. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  2192. // There is no guarantee another event will trigger the update
  2193. // immediately and in all situations, for example because a remote
  2194. // participant is having connection trouble so no status changes.
  2195. const displayedUserId = APP.UI.getLargeVideoID();
  2196. if (displayedUserId) {
  2197. APP.UI.updateLargeVideo(displayedUserId, true);
  2198. }
  2199. });
  2200. APP.UI.addListener(
  2201. UIEvents.TOGGLE_SCREENSHARING, ({ enabled, audioOnly, ignoreDidHaveVideo }) => {
  2202. this.toggleScreenSharing(enabled, { audioOnly }, ignoreDidHaveVideo);
  2203. }
  2204. );
  2205. },
  2206. /**
  2207. * Cleanups local conference on suspend.
  2208. */
  2209. onSuspendDetected() {
  2210. // After wake up, we will be in a state where conference is left
  2211. // there will be dialog shown to user.
  2212. // We do not want video/audio as we show an overlay and after it
  2213. // user need to rejoin or close, while waking up we can detect
  2214. // camera wakeup as a problem with device.
  2215. // We also do not care about device change, which happens
  2216. // on resume after suspending PC.
  2217. if (this.deviceChangeListener) {
  2218. JitsiMeetJS.mediaDevices.removeEventListener(
  2219. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2220. this.deviceChangeListener);
  2221. }
  2222. },
  2223. /**
  2224. * Callback invoked when the conference has been successfully joined.
  2225. * Initializes the UI and various other features.
  2226. *
  2227. * @private
  2228. * @returns {void}
  2229. */
  2230. _onConferenceJoined() {
  2231. APP.UI.initConference();
  2232. if (!config.disableShortcuts) {
  2233. APP.keyboardshortcut.init();
  2234. }
  2235. APP.store.dispatch(conferenceJoined(room));
  2236. },
  2237. /**
  2238. * Updates the list of current devices.
  2239. * @param {boolean} setDeviceListChangeHandler - Whether to add the deviceList change handlers.
  2240. * @private
  2241. * @returns {Promise}
  2242. */
  2243. _initDeviceList(setDeviceListChangeHandler = false) {
  2244. const { mediaDevices } = JitsiMeetJS;
  2245. if (mediaDevices.isDeviceListAvailable()
  2246. && mediaDevices.isDeviceChangeAvailable()) {
  2247. if (setDeviceListChangeHandler) {
  2248. this.deviceChangeListener = devices =>
  2249. window.setTimeout(() => this._onDeviceListChanged(devices), 0);
  2250. mediaDevices.addEventListener(
  2251. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2252. this.deviceChangeListener);
  2253. }
  2254. const { dispatch } = APP.store;
  2255. return dispatch(getAvailableDevices())
  2256. .then(devices => {
  2257. // Ugly way to synchronize real device IDs with local
  2258. // storage and settings menu. This is a workaround until
  2259. // getConstraints() method will be implemented in browsers.
  2260. this._updateAudioDeviceId();
  2261. this._updateVideoDeviceId();
  2262. APP.UI.onAvailableDevicesChanged(devices);
  2263. });
  2264. }
  2265. return Promise.resolve();
  2266. },
  2267. /**
  2268. * Updates the settings for the currently used video device, extracting
  2269. * the device id from the used track.
  2270. * @private
  2271. */
  2272. _updateVideoDeviceId() {
  2273. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  2274. if (localVideo && localVideo.videoType === 'camera') {
  2275. APP.store.dispatch(updateSettings({
  2276. cameraDeviceId: localVideo.getDeviceId()
  2277. }));
  2278. }
  2279. // If screenshare is in progress, get the device id from the presenter track.
  2280. if (this.localPresenterVideo) {
  2281. APP.store.dispatch(updateSettings({
  2282. cameraDeviceId: this.localPresenterVideo.getDeviceId()
  2283. }));
  2284. }
  2285. },
  2286. /**
  2287. * Updates the settings for the currently used audio device, extracting
  2288. * the device id from the used track.
  2289. * @private
  2290. */
  2291. _updateAudioDeviceId() {
  2292. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  2293. if (localAudio) {
  2294. APP.store.dispatch(updateSettings({
  2295. micDeviceId: localAudio.getDeviceId()
  2296. }));
  2297. }
  2298. },
  2299. /**
  2300. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  2301. * handle change of available media devices.
  2302. * @private
  2303. * @param {MediaDeviceInfo[]} devices
  2304. * @returns {Promise}
  2305. */
  2306. _onDeviceListChanged(devices) {
  2307. const oldDevices = APP.store.getState()['features/base/devices'].availableDevices;
  2308. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  2309. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  2310. APP.store.dispatch(updateDeviceList(devices));
  2311. // Firefox users can choose their preferred device in the gUM prompt. In that case
  2312. // we should respect that and not attempt to switch to the preferred device from
  2313. // our settings.
  2314. const newLabelsOnly = mediaDeviceHelper.newDeviceListAddedLabelsOnly(oldDevices, devices);
  2315. const newDevices
  2316. = mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  2317. devices,
  2318. this.isSharingScreen,
  2319. localVideo,
  2320. localAudio,
  2321. newLabelsOnly);
  2322. const promises = [];
  2323. const audioWasMuted = this.isLocalAudioMuted();
  2324. const videoWasMuted = this.isLocalVideoMuted();
  2325. const requestedInput = {
  2326. audio: Boolean(newDevices.audioinput),
  2327. video: Boolean(newDevices.videoinput)
  2328. };
  2329. if (typeof newDevices.audiooutput !== 'undefined') {
  2330. const { dispatch } = APP.store;
  2331. const setAudioOutputPromise
  2332. = setAudioOutputDeviceId(newDevices.audiooutput, dispatch)
  2333. .catch(); // Just ignore any errors in catch block.
  2334. promises.push(setAudioOutputPromise);
  2335. }
  2336. // Handles the use case when the default device is changed (we are always stopping the streams because it's
  2337. // simpler):
  2338. // If the default device is changed we need to first stop the local streams and then call GUM. Otherwise GUM
  2339. // will return a stream using the old default device.
  2340. if (requestedInput.audio && localAudio) {
  2341. localAudio.stopStream();
  2342. }
  2343. if (requestedInput.video && localVideo) {
  2344. localVideo.stopStream();
  2345. }
  2346. // Let's handle unknown/non-preferred devices
  2347. const newAvailDevices
  2348. = APP.store.getState()['features/base/devices'].availableDevices;
  2349. let newAudioDevices = [];
  2350. let oldAudioDevices = [];
  2351. if (typeof newDevices.audiooutput === 'undefined') {
  2352. newAudioDevices = newAvailDevices.audioOutput;
  2353. oldAudioDevices = oldDevices.audioOutput;
  2354. }
  2355. if (!requestedInput.audio) {
  2356. newAudioDevices = newAudioDevices.concat(newAvailDevices.audioInput);
  2357. oldAudioDevices = oldAudioDevices.concat(oldDevices.audioInput);
  2358. }
  2359. // check for audio
  2360. if (newAudioDevices.length > 0) {
  2361. APP.store.dispatch(
  2362. checkAndNotifyForNewDevice(newAudioDevices, oldAudioDevices));
  2363. }
  2364. // check for video
  2365. if (!requestedInput.video) {
  2366. APP.store.dispatch(
  2367. checkAndNotifyForNewDevice(newAvailDevices.videoInput, oldDevices.videoInput));
  2368. }
  2369. // When the 'default' mic needs to be selected, we need to
  2370. // pass the real device id to gUM instead of 'default' in order
  2371. // to get the correct MediaStreamTrack from chrome because of the
  2372. // following bug.
  2373. // https://bugs.chromium.org/p/chromium/issues/detail?id=997689
  2374. const hasDefaultMicChanged = newDevices.audioinput === 'default';
  2375. // This is the case when the local video is muted and a preferred device is connected.
  2376. if (requestedInput.video && this.isLocalVideoMuted()) {
  2377. // We want to avoid creating a new video track in order to prevent turning on the camera.
  2378. requestedInput.video = false;
  2379. APP.store.dispatch(updateSettings({ // Update the current selected camera for the device selection dialog.
  2380. cameraDeviceId: newDevices.videoinput
  2381. }));
  2382. delete newDevices.videoinput;
  2383. // Removing the current video track in order to force the unmute to select the preferred device.
  2384. logger.debug('_onDeviceListChanged: Removing the current video track.');
  2385. this.useVideoStream(null);
  2386. }
  2387. promises.push(
  2388. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  2389. createLocalTracksF,
  2390. newDevices.videoinput,
  2391. hasDefaultMicChanged
  2392. ? getDefaultDeviceId(APP.store.getState(), 'audioInput')
  2393. : newDevices.audioinput)
  2394. .then(tracks => {
  2395. // If audio or video muted before, or we unplugged current
  2396. // device and selected new one, then mute new track.
  2397. const muteSyncPromises = tracks.map(track => {
  2398. if ((track.isVideoTrack() && videoWasMuted)
  2399. || (track.isAudioTrack() && audioWasMuted)) {
  2400. return track.mute();
  2401. }
  2402. return Promise.resolve();
  2403. });
  2404. return Promise.all(muteSyncPromises)
  2405. .then(() =>
  2406. Promise.all(Object.keys(requestedInput).map(mediaType => {
  2407. if (requestedInput[mediaType]) {
  2408. const useStream
  2409. = mediaType === 'audio'
  2410. ? this.useAudioStream.bind(this)
  2411. : this.useVideoStream.bind(this);
  2412. const track = tracks.find(t => t.getType() === mediaType) || null;
  2413. // Use the new stream or null if we failed to obtain it.
  2414. return useStream(track)
  2415. .then(() => {
  2416. if (track?.isAudioTrack() && hasDefaultMicChanged) {
  2417. // workaround for the default device to be shown as selected in the
  2418. // settings even when the real device id was passed to gUM because of
  2419. // the above mentioned chrome bug.
  2420. track._realDeviceId = track.deviceId = 'default';
  2421. }
  2422. mediaType === 'audio'
  2423. ? this._updateAudioDeviceId()
  2424. : this._updateVideoDeviceId();
  2425. });
  2426. }
  2427. return Promise.resolve();
  2428. })));
  2429. })
  2430. .then(() => {
  2431. // Log and sync known mute state.
  2432. if (audioWasMuted) {
  2433. sendAnalytics(createTrackMutedEvent(
  2434. 'audio',
  2435. 'device list changed'));
  2436. logger.log('Audio mute: device list changed');
  2437. muteLocalAudio(true);
  2438. }
  2439. if (!this.isSharingScreen && videoWasMuted) {
  2440. sendAnalytics(createTrackMutedEvent(
  2441. 'video',
  2442. 'device list changed'));
  2443. logger.log('Video mute: device list changed');
  2444. muteLocalVideo(true);
  2445. }
  2446. }));
  2447. return Promise.all(promises)
  2448. .then(() => {
  2449. APP.UI.onAvailableDevicesChanged(devices);
  2450. });
  2451. },
  2452. /**
  2453. * Determines whether or not the audio button should be enabled.
  2454. */
  2455. updateAudioIconEnabled() {
  2456. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  2457. const audioMediaDevices = APP.store.getState()['features/base/devices'].availableDevices.audioInput;
  2458. const audioDeviceCount = audioMediaDevices ? audioMediaDevices.length : 0;
  2459. // The audio functionality is considered available if there are any
  2460. // audio devices detected or if the local audio stream already exists.
  2461. const available = audioDeviceCount > 0 || Boolean(localAudio);
  2462. APP.store.dispatch(setAudioAvailable(available));
  2463. APP.API.notifyAudioAvailabilityChanged(available);
  2464. },
  2465. /**
  2466. * Determines whether or not the video button should be enabled.
  2467. */
  2468. updateVideoIconEnabled() {
  2469. const videoMediaDevices
  2470. = APP.store.getState()['features/base/devices'].availableDevices.videoInput;
  2471. const videoDeviceCount
  2472. = videoMediaDevices ? videoMediaDevices.length : 0;
  2473. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  2474. // The video functionality is considered available if there are any
  2475. // video devices detected or if there is local video stream already
  2476. // active which could be either screensharing stream or a video track
  2477. // created before the permissions were rejected (through browser
  2478. // config).
  2479. const available = videoDeviceCount > 0 || Boolean(localVideo);
  2480. APP.store.dispatch(setVideoAvailable(available));
  2481. APP.API.notifyVideoAvailabilityChanged(available);
  2482. },
  2483. /**
  2484. * Disconnect from the conference and optionally request user feedback.
  2485. * @param {boolean} [requestFeedback=false] if user feedback should be
  2486. * requested
  2487. */
  2488. hangup(requestFeedback = false) {
  2489. APP.store.dispatch(disableReceiver());
  2490. this._stopProxyConnection();
  2491. APP.store.dispatch(destroyLocalTracks());
  2492. this._localTracksInitialized = false;
  2493. // Remove unnecessary event listeners from firing callbacks.
  2494. if (this.deviceChangeListener) {
  2495. JitsiMeetJS.mediaDevices.removeEventListener(
  2496. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2497. this.deviceChangeListener);
  2498. }
  2499. APP.UI.removeAllListeners();
  2500. let requestFeedbackPromise;
  2501. if (requestFeedback) {
  2502. requestFeedbackPromise
  2503. = APP.store.dispatch(maybeOpenFeedbackDialog(room))
  2504. // false because the thank you dialog shouldn't be displayed
  2505. .catch(() => Promise.resolve(false));
  2506. } else {
  2507. requestFeedbackPromise = Promise.resolve(true);
  2508. }
  2509. Promise.all([
  2510. requestFeedbackPromise,
  2511. this.leaveRoomAndDisconnect()
  2512. ])
  2513. .then(values => {
  2514. this._room = undefined;
  2515. room = undefined;
  2516. /**
  2517. * Don't call {@code notifyReadyToClose} if the promotional page flag is set
  2518. * and let the page take care of sending the message, since there will be
  2519. * a redirect to the page regardlessly.
  2520. */
  2521. if (!interfaceConfig.SHOW_PROMOTIONAL_CLOSE_PAGE) {
  2522. APP.API.notifyReadyToClose();
  2523. }
  2524. APP.store.dispatch(maybeRedirectToWelcomePage(values[0]));
  2525. });
  2526. },
  2527. /**
  2528. * Leaves the room.
  2529. *
  2530. * @returns {Promise}
  2531. */
  2532. leaveRoom() {
  2533. if (room && room.isJoined()) {
  2534. return room.leave();
  2535. }
  2536. },
  2537. /**
  2538. * Leaves the room and calls JitsiConnection.disconnect.
  2539. *
  2540. * @returns {Promise}
  2541. */
  2542. leaveRoomAndDisconnect() {
  2543. APP.store.dispatch(conferenceWillLeave(room));
  2544. if (room && room.isJoined()) {
  2545. return room.leave().then(disconnect, disconnect);
  2546. }
  2547. return disconnect();
  2548. },
  2549. /**
  2550. * Changes the email for the local user
  2551. * @param email {string} the new email
  2552. */
  2553. changeLocalEmail(email = '') {
  2554. const localParticipant = getLocalParticipant(APP.store.getState());
  2555. const formattedEmail = String(email).trim();
  2556. if (formattedEmail === localParticipant.email) {
  2557. return;
  2558. }
  2559. const localId = localParticipant.id;
  2560. APP.store.dispatch(participantUpdated({
  2561. // XXX Only the local participant is allowed to update without
  2562. // stating the JitsiConference instance (i.e. participant property
  2563. // `conference` for a remote participant) because the local
  2564. // participant is uniquely identified by the very fact that there is
  2565. // only one local participant.
  2566. id: localId,
  2567. local: true,
  2568. email: formattedEmail
  2569. }));
  2570. APP.store.dispatch(updateSettings({
  2571. email: formattedEmail
  2572. }));
  2573. APP.API.notifyEmailChanged(localId, {
  2574. email: formattedEmail
  2575. });
  2576. sendData(commands.EMAIL, formattedEmail);
  2577. },
  2578. /**
  2579. * Changes the avatar url for the local user
  2580. * @param url {string} the new url
  2581. */
  2582. changeLocalAvatarUrl(url = '') {
  2583. const { avatarURL, id } = getLocalParticipant(APP.store.getState());
  2584. const formattedUrl = String(url).trim();
  2585. if (formattedUrl === avatarURL) {
  2586. return;
  2587. }
  2588. APP.store.dispatch(participantUpdated({
  2589. // XXX Only the local participant is allowed to update without
  2590. // stating the JitsiConference instance (i.e. participant property
  2591. // `conference` for a remote participant) because the local
  2592. // participant is uniquely identified by the very fact that there is
  2593. // only one local participant.
  2594. id,
  2595. local: true,
  2596. avatarURL: formattedUrl
  2597. }));
  2598. APP.store.dispatch(updateSettings({
  2599. avatarURL: formattedUrl
  2600. }));
  2601. sendData(commands.AVATAR_URL, url);
  2602. },
  2603. /**
  2604. * Sends a message via the data channel.
  2605. * @param {string} to the id of the endpoint that should receive the
  2606. * message. If "" - the message will be sent to all participants.
  2607. * @param {object} payload the payload of the message.
  2608. * @throws NetworkError or InvalidStateError or Error if the operation
  2609. * fails.
  2610. */
  2611. sendEndpointMessage(to, payload) {
  2612. room.sendEndpointMessage(to, payload);
  2613. },
  2614. /**
  2615. * Sends a facial expression as a string and its duration as a number
  2616. * @param {object} payload - Object containing the {string} facialExpression
  2617. * and {number} duration
  2618. */
  2619. sendFacialExpression(payload) {
  2620. room.sendFacialExpression(payload);
  2621. },
  2622. /**
  2623. * Adds new listener.
  2624. * @param {String} eventName the name of the event
  2625. * @param {Function} listener the listener.
  2626. */
  2627. addListener(eventName, listener) {
  2628. eventEmitter.addListener(eventName, listener);
  2629. },
  2630. /**
  2631. * Removes listener.
  2632. * @param {String} eventName the name of the event that triggers the
  2633. * listener
  2634. * @param {Function} listener the listener.
  2635. */
  2636. removeListener(eventName, listener) {
  2637. eventEmitter.removeListener(eventName, listener);
  2638. },
  2639. /**
  2640. * Changes the display name for the local user
  2641. * @param nickname {string} the new display name
  2642. */
  2643. changeLocalDisplayName(nickname = '') {
  2644. const formattedNickname = getNormalizedDisplayName(nickname);
  2645. const { id, name } = getLocalParticipant(APP.store.getState());
  2646. if (formattedNickname === name) {
  2647. return;
  2648. }
  2649. APP.store.dispatch(participantUpdated({
  2650. // XXX Only the local participant is allowed to update without
  2651. // stating the JitsiConference instance (i.e. participant property
  2652. // `conference` for a remote participant) because the local
  2653. // participant is uniquely identified by the very fact that there is
  2654. // only one local participant.
  2655. id,
  2656. local: true,
  2657. name: formattedNickname
  2658. }));
  2659. APP.store.dispatch(updateSettings({
  2660. displayName: formattedNickname
  2661. }));
  2662. },
  2663. /**
  2664. * Callback invoked by the external api create or update a direct connection
  2665. * from the local client to an external client.
  2666. *
  2667. * @param {Object} event - The object containing information that should be
  2668. * passed to the {@code ProxyConnectionService}.
  2669. * @returns {void}
  2670. */
  2671. onProxyConnectionEvent(event) {
  2672. if (!this._proxyConnection) {
  2673. this._proxyConnection = new JitsiMeetJS.ProxyConnectionService({
  2674. /**
  2675. * Pass the {@code JitsiConnection} instance which will be used
  2676. * to fetch TURN credentials.
  2677. */
  2678. jitsiConnection: APP.connection,
  2679. /**
  2680. * The proxy connection feature is currently tailored towards
  2681. * taking a proxied video stream and showing it as a local
  2682. * desktop screen.
  2683. */
  2684. convertVideoToDesktop: true,
  2685. /**
  2686. * Callback invoked when the connection has been closed
  2687. * automatically. Triggers cleanup of screensharing if active.
  2688. *
  2689. * @returns {void}
  2690. */
  2691. onConnectionClosed: () => {
  2692. if (this._untoggleScreenSharing) {
  2693. this._untoggleScreenSharing();
  2694. }
  2695. },
  2696. /**
  2697. * Callback invoked to pass messages from the local client back
  2698. * out to the external client.
  2699. *
  2700. * @param {string} peerJid - The jid of the intended recipient
  2701. * of the message.
  2702. * @param {Object} data - The message that should be sent. For
  2703. * screensharing this is an iq.
  2704. * @returns {void}
  2705. */
  2706. onSendMessage: (peerJid, data) =>
  2707. APP.API.sendProxyConnectionEvent({
  2708. data,
  2709. to: peerJid
  2710. }),
  2711. /**
  2712. * Callback invoked when the remote peer of the proxy connection
  2713. * has provided a video stream, intended to be used as a local
  2714. * desktop stream.
  2715. *
  2716. * @param {JitsiLocalTrack} remoteProxyStream - The media
  2717. * stream to use as a local desktop stream.
  2718. * @returns {void}
  2719. */
  2720. onRemoteStream: desktopStream => {
  2721. if (desktopStream.videoType !== 'desktop') {
  2722. logger.warn('Received a non-desktop stream to proxy.');
  2723. desktopStream.dispose();
  2724. return;
  2725. }
  2726. this.toggleScreenSharing(undefined, { desktopStream });
  2727. }
  2728. });
  2729. }
  2730. this._proxyConnection.processMessage(event);
  2731. },
  2732. /**
  2733. * Sets the video muted status.
  2734. */
  2735. setVideoMuteStatus() {
  2736. APP.UI.setVideoMuted(this.getMyUserId());
  2737. },
  2738. /**
  2739. * Sets the audio muted status.
  2740. *
  2741. * @param {boolean} muted - New muted status.
  2742. */
  2743. setAudioMuteStatus(muted) {
  2744. APP.UI.setAudioMuted(this.getMyUserId(), muted);
  2745. APP.API.notifyAudioMutedStatusChanged(muted);
  2746. },
  2747. /**
  2748. * Dispatches the passed in feedback for submission. The submitted score
  2749. * should be a number inclusively between 1 through 5, or -1 for no score.
  2750. *
  2751. * @param {number} score - a number between 1 and 5 (inclusive) or -1 for no
  2752. * score.
  2753. * @param {string} message - An optional message to attach to the feedback
  2754. * in addition to the score.
  2755. * @returns {void}
  2756. */
  2757. submitFeedback(score = -1, message = '') {
  2758. if (score === -1 || (score >= 1 && score <= 5)) {
  2759. APP.store.dispatch(submitFeedback(score, message, room));
  2760. }
  2761. },
  2762. /**
  2763. * Terminates any proxy screensharing connection that is active.
  2764. *
  2765. * @private
  2766. * @returns {void}
  2767. */
  2768. _stopProxyConnection() {
  2769. if (this._proxyConnection) {
  2770. this._proxyConnection.stop();
  2771. }
  2772. this._proxyConnection = null;
  2773. }
  2774. };