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

conference.js 117KB

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