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 123KB

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