Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

conference.js 115KB

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