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

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