Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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