You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 116KB

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