Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conference.js 119KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290
  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. promise = promise.then(() => createLocalTracksF({ devices: [ 'video' ] }))
  1417. .then(([ stream ]) => {
  1418. logger.debug(`_turnScreenSharingOff using ${stream} for useVideoStream`);
  1419. return this.useVideoStream(stream);
  1420. })
  1421. .catch(error => {
  1422. logger.error('failed to switch back to local video', error);
  1423. return this.useVideoStream(null).then(() =>
  1424. // Still fail with the original err
  1425. Promise.reject(error)
  1426. );
  1427. });
  1428. return promise.then(
  1429. () => {
  1430. // Mute the video if camera video needs to be ignored or if video was muted before switching to screen
  1431. // share.
  1432. if (ignoreDidHaveVideo || !didHaveVideo) {
  1433. APP.store.dispatch(setVideoMuted(true, MEDIA_TYPE.VIDEO));
  1434. }
  1435. this.videoSwitchInProgress = false;
  1436. sendAnalytics(createScreenSharingEvent('stopped',
  1437. duration === 0 ? null : duration));
  1438. logger.info('Screen sharing stopped.');
  1439. },
  1440. error => {
  1441. this.videoSwitchInProgress = false;
  1442. logger.error(`_turnScreenSharingOff failed: ${error}`);
  1443. throw error;
  1444. });
  1445. },
  1446. /**
  1447. * Toggles between screen sharing and camera video if the toggle parameter
  1448. * is not specified and starts the procedure for obtaining new screen
  1449. * sharing/video track otherwise.
  1450. *
  1451. * @param {boolean} [toggle] - If true - new screen sharing track will be
  1452. * obtained. If false - new video track will be obtain. If not specified -
  1453. * toggles between screen sharing and camera video.
  1454. * @param {Object} [options] - Screen sharing options that will be passed to
  1455. * createLocalTracks.
  1456. * @param {boolean} [options.audioOnly] - Whether or not audioOnly is enabled.
  1457. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  1458. * sources that have to be displayed in the desktop picker window ('screen',
  1459. * 'window', etc.).
  1460. * @param {Object} [options.desktopStream] - An existing desktop stream to
  1461. * use instead of creating a new desktop stream.
  1462. * @param {boolean} ignoreDidHaveVideo - if true ignore if video was on when sharing started.
  1463. * @return {Promise.<T>}
  1464. */
  1465. async toggleScreenSharing(toggle = !this._untoggleScreenSharing, options = {}, ignoreDidHaveVideo) {
  1466. logger.debug(`toggleScreenSharing: ${toggle}`);
  1467. if (this.videoSwitchInProgress) {
  1468. return Promise.reject(`toggleScreenSharing: ${toggle} aborted - video switch in progress.`);
  1469. }
  1470. if (!JitsiMeetJS.isDesktopSharingEnabled()) {
  1471. return Promise.reject('Cannot toggle screen sharing: not supported.');
  1472. }
  1473. if (this.isAudioOnly()) {
  1474. APP.store.dispatch(setAudioOnly(false));
  1475. }
  1476. if (toggle) {
  1477. try {
  1478. await this._switchToScreenSharing(options);
  1479. return;
  1480. } catch (err) {
  1481. logger.error('Failed to switch to screensharing', err);
  1482. return;
  1483. }
  1484. }
  1485. return this._untoggleScreenSharing
  1486. ? this._untoggleScreenSharing(ignoreDidHaveVideo)
  1487. : Promise.resolve();
  1488. },
  1489. /**
  1490. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1491. *
  1492. * @param {Object} [options] - Screen sharing options that will be passed to
  1493. * createLocalTracks.
  1494. * @param {Object} [options.desktopSharing]
  1495. * @param {Object} [options.desktopStream] - An existing desktop stream to
  1496. * use instead of creating a new desktop stream.
  1497. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1498. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1499. * {@link JitsiTrackError}.
  1500. *
  1501. * @private
  1502. */
  1503. _createDesktopTrack(options = {}) {
  1504. const didHaveVideo = !this.isLocalVideoMuted();
  1505. const getDesktopStreamPromise = options.desktopStream
  1506. ? Promise.resolve([ options.desktopStream ])
  1507. : createLocalTracksF({
  1508. desktopSharingSourceDevice: options.desktopSharingSources
  1509. ? null : config._desktopSharingSourceDevice,
  1510. desktopSharingSources: options.desktopSharingSources,
  1511. devices: [ 'desktop' ]
  1512. });
  1513. return getDesktopStreamPromise.then(desktopStreams => {
  1514. // Stores the "untoggle" handler which remembers whether was
  1515. // there any video before and whether was it muted.
  1516. this._untoggleScreenSharing
  1517. = this._turnScreenSharingOff.bind(this, didHaveVideo);
  1518. const desktopVideoStream = desktopStreams.find(stream => stream.getType() === MEDIA_TYPE.VIDEO);
  1519. const desktopAudioStream = desktopStreams.find(stream => stream.getType() === MEDIA_TYPE.AUDIO);
  1520. if (desktopAudioStream) {
  1521. desktopAudioStream.on(
  1522. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1523. () => {
  1524. logger.debug(`Local screensharing audio track stopped. ${this.isSharingScreen}`);
  1525. // Handle case where screen share was stopped from the browsers 'screen share in progress'
  1526. // window. If audio screen sharing is stopped via the normal UX flow this point shouldn't
  1527. // be reached.
  1528. isScreenAudioShared(APP.store.getState())
  1529. && this._untoggleScreenSharing
  1530. && this._untoggleScreenSharing();
  1531. }
  1532. );
  1533. }
  1534. if (desktopVideoStream) {
  1535. desktopVideoStream.on(
  1536. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1537. () => {
  1538. logger.debug(`Local screensharing track stopped. ${this.isSharingScreen}`);
  1539. // If the stream was stopped during screen sharing
  1540. // session then we should switch back to video.
  1541. this.isSharingScreen
  1542. && this._untoggleScreenSharing
  1543. && this._untoggleScreenSharing();
  1544. }
  1545. );
  1546. }
  1547. return desktopStreams;
  1548. }, error => {
  1549. throw error;
  1550. });
  1551. },
  1552. /**
  1553. * Creates a new instance of presenter effect. A new video track is created
  1554. * using the new set of constraints that are calculated based on
  1555. * the height of the desktop that is being currently shared.
  1556. *
  1557. * @param {number} height - The height of the desktop stream that is being
  1558. * currently shared.
  1559. * @param {string} cameraDeviceId - The device id of the camera to be used.
  1560. * @return {Promise<JitsiStreamPresenterEffect>} - A promise resolved with
  1561. * {@link JitsiStreamPresenterEffect} if it succeeds.
  1562. */
  1563. async _createPresenterStreamEffect(height = null, cameraDeviceId = null) {
  1564. if (!this.localPresenterVideo) {
  1565. const camera = cameraDeviceId ?? getUserSelectedCameraDeviceId(APP.store.getState());
  1566. try {
  1567. this.localPresenterVideo = await createLocalPresenterTrack({ cameraDeviceId: camera }, height);
  1568. } catch (err) {
  1569. logger.error('Failed to create a camera track for presenter', err);
  1570. return;
  1571. }
  1572. APP.store.dispatch(trackAdded(this.localPresenterVideo));
  1573. }
  1574. try {
  1575. const effect = await createPresenterEffect(this.localPresenterVideo.stream);
  1576. return effect;
  1577. } catch (err) {
  1578. logger.error('Failed to create the presenter effect', err);
  1579. }
  1580. },
  1581. /**
  1582. * Tries to turn the presenter video track on or off. If a presenter track
  1583. * doesn't exist, a new video track is created.
  1584. *
  1585. * @param mute - true for mute and false for unmute.
  1586. *
  1587. * @private
  1588. */
  1589. async _mutePresenterVideo(mute) {
  1590. const maybeShowErrorDialog = error => {
  1591. APP.store.dispatch(notifyCameraError(error));
  1592. };
  1593. // Check for NO-OP
  1594. if (mute && (!this.localPresenterVideo || this.localPresenterVideo.isMuted())) {
  1595. return;
  1596. } else if (!mute && this.localPresenterVideo && !this.localPresenterVideo.isMuted()) {
  1597. return;
  1598. }
  1599. // Create a new presenter track and apply the presenter effect.
  1600. if (!this.localPresenterVideo && !mute) {
  1601. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  1602. const { height, width } = localVideo.track.getSettings() ?? localVideo.track.getConstraints();
  1603. const isPortrait = height >= width;
  1604. const DESKTOP_STREAM_CAP = 720;
  1605. const highResolutionTrack
  1606. = (isPortrait && width > DESKTOP_STREAM_CAP) || (!isPortrait && height > DESKTOP_STREAM_CAP);
  1607. // Resizing the desktop track for presenter is causing blurriness of the desktop share on chrome.
  1608. // Disable resizing by default, enable it only when config.js setting is enabled.
  1609. const resizeDesktopStream = highResolutionTrack && config.videoQuality?.resizeDesktopForPresenter;
  1610. if (resizeDesktopStream) {
  1611. let desktopResizeConstraints = {};
  1612. if (height && width) {
  1613. const advancedConstraints = [ { aspectRatio: (width / height).toPrecision(4) } ];
  1614. const constraint = isPortrait ? { width: DESKTOP_STREAM_CAP } : { height: DESKTOP_STREAM_CAP };
  1615. advancedConstraints.push(constraint);
  1616. desktopResizeConstraints.advanced = advancedConstraints;
  1617. } else {
  1618. desktopResizeConstraints = {
  1619. width: 1280,
  1620. height: 720
  1621. };
  1622. }
  1623. // Apply the constraints on the desktop track.
  1624. try {
  1625. await localVideo.track.applyConstraints(desktopResizeConstraints);
  1626. } catch (err) {
  1627. logger.error('Failed to apply constraints on the desktop stream for presenter mode', err);
  1628. return;
  1629. }
  1630. }
  1631. const trackHeight = resizeDesktopStream
  1632. ? localVideo.track.getSettings().height ?? DESKTOP_STREAM_CAP
  1633. : height;
  1634. let effect;
  1635. try {
  1636. effect = await this._createPresenterStreamEffect(trackHeight);
  1637. } catch (err) {
  1638. logger.error('Failed to unmute Presenter Video', err);
  1639. maybeShowErrorDialog(err);
  1640. return;
  1641. }
  1642. // Replace the desktop track on the peerconnection.
  1643. try {
  1644. await localVideo.setEffect(effect);
  1645. APP.store.dispatch(setVideoMuted(mute, MEDIA_TYPE.PRESENTER));
  1646. this.setVideoMuteStatus();
  1647. } catch (err) {
  1648. logger.error('Failed to apply the Presenter effect', err);
  1649. }
  1650. } else {
  1651. APP.store.dispatch(setVideoMuted(mute, MEDIA_TYPE.PRESENTER));
  1652. }
  1653. },
  1654. /**
  1655. * Tries to switch to the screensharing mode by disposing camera stream and
  1656. * replacing it with a desktop one.
  1657. *
  1658. * @param {Object} [options] - Screen sharing options that will be passed to
  1659. * createLocalTracks.
  1660. *
  1661. * @return {Promise} - A Promise resolved if the operation succeeds or
  1662. * rejected with some unknown type of error in case it fails. Promise will
  1663. * be rejected immediately if {@link videoSwitchInProgress} is true.
  1664. *
  1665. * @private
  1666. */
  1667. _switchToScreenSharing(options = {}) {
  1668. if (this.videoSwitchInProgress) {
  1669. return Promise.reject('Switch in progress.');
  1670. }
  1671. this.videoSwitchInProgress = true;
  1672. return this._createDesktopTrack(options)
  1673. .then(async streams => {
  1674. let desktopVideoStream = streams.find(stream => stream.getType() === MEDIA_TYPE.VIDEO);
  1675. this._desktopAudioStream = streams.find(stream => stream.getType() === MEDIA_TYPE.AUDIO);
  1676. const { audioOnly = false } = options;
  1677. // If we're in audio only mode dispose of the video track otherwise the screensharing state will be
  1678. // inconsistent.
  1679. if (audioOnly) {
  1680. desktopVideoStream.dispose();
  1681. desktopVideoStream = undefined;
  1682. if (!this._desktopAudioStream) {
  1683. return Promise.reject(AUDIO_ONLY_SCREEN_SHARE_NO_TRACK);
  1684. }
  1685. }
  1686. if (desktopVideoStream) {
  1687. logger.debug(`_switchToScreenSharing is using ${desktopVideoStream} for useVideoStream`);
  1688. await this.useVideoStream(desktopVideoStream);
  1689. }
  1690. if (this._desktopAudioStream) {
  1691. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1692. // If there is a localAudio stream, mix in the desktop audio stream captured by the screen sharing
  1693. // api.
  1694. if (localAudio) {
  1695. this._mixerEffect = new AudioMixerEffect(this._desktopAudioStream);
  1696. logger.debug(`_switchToScreenSharing is mixing ${this._desktopAudioStream} and ${localAudio}`
  1697. + ' as a single audio stream');
  1698. await localAudio.setEffect(this._mixerEffect);
  1699. } else {
  1700. // If no local stream is present ( i.e. no input audio devices) we use the screen share audio
  1701. // stream as we would use a regular stream.
  1702. logger.debug(`_switchToScreenSharing is using ${this._desktopAudioStream} for useAudioStream`);
  1703. await this.useAudioStream(this._desktopAudioStream);
  1704. }
  1705. APP.store.dispatch(setScreenAudioShareState(true));
  1706. }
  1707. })
  1708. .then(() => {
  1709. this.videoSwitchInProgress = false;
  1710. if (isScreenshotCaptureEnabled(APP.store.getState(), false, true)) {
  1711. APP.store.dispatch(toggleScreenshotCaptureSummary(true));
  1712. }
  1713. sendAnalytics(createScreenSharingEvent('started'));
  1714. logger.log('Screen sharing started');
  1715. })
  1716. .catch(error => {
  1717. this.videoSwitchInProgress = false;
  1718. // Pawel: With this call I'm trying to preserve the original
  1719. // behaviour although it is not clear why would we "untoggle"
  1720. // on failure. I suppose it was to restore video in case there
  1721. // was some problem during "this.useVideoStream(desktopStream)".
  1722. // It's important to note that the handler will not be available
  1723. // if we fail early on trying to get desktop media (which makes
  1724. // sense, because the camera video is still being used, so
  1725. // nothing to "untoggle").
  1726. if (this._untoggleScreenSharing) {
  1727. this._untoggleScreenSharing();
  1728. }
  1729. // FIXME the code inside of _handleScreenSharingError is
  1730. // asynchronous, but does not return a Promise and is not part
  1731. // of the current Promise chain.
  1732. this._handleScreenSharingError(error);
  1733. return Promise.reject(error);
  1734. });
  1735. },
  1736. /**
  1737. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1738. * trying to create screensharing track. It will either do nothing if
  1739. * the dialog was canceled on user's request or display an error if
  1740. * screensharing couldn't be started.
  1741. * @param {JitsiTrackError} error - The error returned by
  1742. * {@link _createDesktopTrack} Promise.
  1743. * @private
  1744. */
  1745. _handleScreenSharingError(error) {
  1746. if (error.name === JitsiTrackErrors.SCREENSHARING_USER_CANCELED) {
  1747. return;
  1748. }
  1749. logger.error('failed to share local desktop', error);
  1750. // Handling:
  1751. // JitsiTrackErrors.CONSTRAINT_FAILED
  1752. // JitsiTrackErrors.PERMISSION_DENIED
  1753. // JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR
  1754. // and any other
  1755. let descriptionKey;
  1756. let titleKey;
  1757. if (error.name === JitsiTrackErrors.PERMISSION_DENIED) {
  1758. descriptionKey = 'dialog.screenSharingPermissionDeniedError';
  1759. titleKey = 'dialog.screenSharingFailedTitle';
  1760. } else if (error.name === JitsiTrackErrors.CONSTRAINT_FAILED) {
  1761. descriptionKey = 'dialog.cameraConstraintFailedError';
  1762. titleKey = 'deviceError.cameraError';
  1763. } else if (error.name === JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR) {
  1764. descriptionKey = 'dialog.screenSharingFailed';
  1765. titleKey = 'dialog.screenSharingFailedTitle';
  1766. } else if (error === AUDIO_ONLY_SCREEN_SHARE_NO_TRACK) {
  1767. descriptionKey = 'notify.screenShareNoAudio';
  1768. titleKey = 'notify.screenShareNoAudioTitle';
  1769. }
  1770. APP.UI.messageHandler.showError({
  1771. descriptionKey,
  1772. titleKey
  1773. });
  1774. },
  1775. /**
  1776. * Setup interaction between conference and UI.
  1777. */
  1778. _setupListeners() {
  1779. // add local streams when joined to the conference
  1780. room.on(JitsiConferenceEvents.CONFERENCE_JOINED, () => {
  1781. this._onConferenceJoined();
  1782. });
  1783. room.on(JitsiConferenceEvents.CONFERENCE_JOIN_IN_PROGRESS, () => {
  1784. APP.store.dispatch(setPrejoinPageVisibility(false));
  1785. });
  1786. room.on(
  1787. JitsiConferenceEvents.CONFERENCE_LEFT,
  1788. (...args) => {
  1789. APP.store.dispatch(conferenceTimestampChanged(0));
  1790. APP.store.dispatch(conferenceLeft(room, ...args));
  1791. });
  1792. room.on(
  1793. JitsiConferenceEvents.CONFERENCE_UNIQUE_ID_SET,
  1794. (...args) => {
  1795. // Preserve the sessionId so that the value is accessible even after room
  1796. // is disconnected.
  1797. room.sessionId = room.getMeetingUniqueId();
  1798. APP.store.dispatch(conferenceUniqueIdSet(room, ...args));
  1799. });
  1800. room.on(
  1801. JitsiConferenceEvents.AUTH_STATUS_CHANGED,
  1802. (authEnabled, authLogin) =>
  1803. APP.store.dispatch(authStatusChanged(authEnabled, authLogin)));
  1804. room.on(JitsiConferenceEvents.PARTCIPANT_FEATURES_CHANGED, user => {
  1805. APP.store.dispatch(updateRemoteParticipantFeatures(user));
  1806. });
  1807. room.on(JitsiConferenceEvents.USER_JOINED, (id, user) => {
  1808. if (config.iAmRecorder && user.isHiddenFromRecorder()) {
  1809. return;
  1810. }
  1811. // The logic shared between RN and web.
  1812. commonUserJoinedHandling(APP.store, room, user);
  1813. if (user.isHidden()) {
  1814. return;
  1815. }
  1816. APP.store.dispatch(updateRemoteParticipantFeatures(user));
  1817. logger.log(`USER ${id} connected:`, user);
  1818. APP.UI.addUser(user);
  1819. });
  1820. room.on(JitsiConferenceEvents.USER_LEFT, (id, user) => {
  1821. // The logic shared between RN and web.
  1822. commonUserLeftHandling(APP.store, room, user);
  1823. if (user.isHidden()) {
  1824. return;
  1825. }
  1826. logger.log(`USER ${id} LEFT:`, user);
  1827. });
  1828. room.on(JitsiConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1829. APP.store.dispatch(participantPresenceChanged(id, status));
  1830. const user = room.getParticipantById(id);
  1831. if (user) {
  1832. APP.UI.updateUserStatus(user, status);
  1833. }
  1834. });
  1835. room.on(JitsiConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1836. if (this.isLocalId(id)) {
  1837. logger.info(`My role changed, new role: ${role}`);
  1838. if (role === 'moderator') {
  1839. APP.store.dispatch(maybeSetLobbyChatMessageListener());
  1840. }
  1841. APP.store.dispatch(localParticipantRoleChanged(role));
  1842. APP.API.notifyUserRoleChanged(id, role);
  1843. } else {
  1844. APP.store.dispatch(participantRoleChanged(id, role));
  1845. }
  1846. });
  1847. room.on(JitsiConferenceEvents.TRACK_ADDED, track => {
  1848. if (!track || track.isLocal()) {
  1849. return;
  1850. }
  1851. if (config.iAmRecorder) {
  1852. const participant = room.getParticipantById(track.getParticipantId());
  1853. if (participant.isHiddenFromRecorder()) {
  1854. return;
  1855. }
  1856. }
  1857. APP.store.dispatch(trackAdded(track));
  1858. });
  1859. room.on(JitsiConferenceEvents.TRACK_REMOVED, track => {
  1860. if (!track || track.isLocal()) {
  1861. return;
  1862. }
  1863. APP.store.dispatch(trackRemoved(track));
  1864. });
  1865. room.on(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1866. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1867. let newLvl = lvl;
  1868. if (this.isLocalId(id)) {
  1869. APP.store.dispatch(localParticipantAudioLevelChanged(lvl));
  1870. }
  1871. if (this.isLocalId(id) && localAudio?.isMuted()) {
  1872. newLvl = 0;
  1873. }
  1874. if (config.debug) {
  1875. this.audioLevelsMap[id] = newLvl;
  1876. if (config.debugAudioLevels) {
  1877. logger.log(`AudioLevel:${id}/${newLvl}`);
  1878. }
  1879. }
  1880. APP.UI.setAudioLevel(id, newLvl);
  1881. });
  1882. room.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED, (track, participantThatMutedUs) => {
  1883. if (participantThatMutedUs) {
  1884. APP.store.dispatch(participantMutedUs(participantThatMutedUs, track));
  1885. if (this.isSharingScreen && track.isVideoTrack()) {
  1886. logger.debug('TRACK_MUTE_CHANGED while screen sharing');
  1887. this._turnScreenSharingOff(false);
  1888. }
  1889. }
  1890. });
  1891. room.on(JitsiConferenceEvents.TRACK_UNMUTE_REJECTED, track => APP.store.dispatch(destroyLocalTracks(track)));
  1892. room.on(JitsiConferenceEvents.SUBJECT_CHANGED,
  1893. subject => APP.store.dispatch(conferenceSubjectChanged(subject)));
  1894. room.on(
  1895. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1896. (leavingIds, enteringIds) =>
  1897. APP.UI.handleLastNEndpoints(leavingIds, enteringIds));
  1898. room.on(
  1899. JitsiConferenceEvents.P2P_STATUS,
  1900. (jitsiConference, p2p) =>
  1901. APP.store.dispatch(p2pStatusChanged(p2p)));
  1902. room.on(
  1903. JitsiConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1904. (id, connectionStatus) => APP.store.dispatch(
  1905. participantConnectionStatusChanged(id, connectionStatus)));
  1906. room.on(
  1907. JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED,
  1908. (dominant, previous) => APP.store.dispatch(dominantSpeakerChanged(dominant, previous, room)));
  1909. room.on(
  1910. JitsiConferenceEvents.CONFERENCE_CREATED_TIMESTAMP,
  1911. conferenceTimestamp => APP.store.dispatch(conferenceTimestampChanged(conferenceTimestamp)));
  1912. room.on(JitsiConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1913. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1914. JitsiParticipantConnectionStatus.INTERRUPTED));
  1915. });
  1916. room.on(JitsiConferenceEvents.CONNECTION_RESTORED, () => {
  1917. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1918. JitsiParticipantConnectionStatus.ACTIVE));
  1919. });
  1920. room.on(
  1921. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1922. (id, displayName) => {
  1923. const formattedDisplayName
  1924. = getNormalizedDisplayName(displayName);
  1925. const state = APP.store.getState();
  1926. const {
  1927. defaultRemoteDisplayName
  1928. } = state['features/base/config'];
  1929. APP.store.dispatch(participantUpdated({
  1930. conference: room,
  1931. id,
  1932. name: formattedDisplayName
  1933. }));
  1934. APP.API.notifyDisplayNameChanged(id, {
  1935. displayName: formattedDisplayName,
  1936. formattedDisplayName:
  1937. appendSuffix(
  1938. formattedDisplayName
  1939. || defaultRemoteDisplayName)
  1940. });
  1941. }
  1942. );
  1943. room.on(
  1944. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1945. (id, botType) => {
  1946. APP.store.dispatch(participantUpdated({
  1947. conference: room,
  1948. id,
  1949. botType
  1950. }));
  1951. }
  1952. );
  1953. room.on(
  1954. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1955. (...args) => {
  1956. APP.store.dispatch(endpointMessageReceived(...args));
  1957. if (args && args.length >= 2) {
  1958. const [ sender, eventData ] = args;
  1959. if (eventData.name === ENDPOINT_TEXT_MESSAGE_NAME) {
  1960. APP.API.notifyEndpointTextMessageReceived({
  1961. senderInfo: {
  1962. jid: sender._jid,
  1963. id: sender._id
  1964. },
  1965. eventData
  1966. });
  1967. }
  1968. }
  1969. });
  1970. room.on(
  1971. JitsiConferenceEvents.NON_PARTICIPANT_MESSAGE_RECEIVED,
  1972. (...args) => APP.store.dispatch(nonParticipantMessageReceived(...args)));
  1973. room.on(
  1974. JitsiConferenceEvents.LOCK_STATE_CHANGED,
  1975. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1976. room.on(JitsiConferenceEvents.KICKED, (participant, reason, isReplaced) => {
  1977. if (isReplaced) {
  1978. // this event triggers when the local participant is kicked, `participant`
  1979. // is the kicker. In replace participant case, kicker is undefined,
  1980. // as the server initiated it. We mark in store the local participant
  1981. // as being replaced based on jwt.
  1982. const localParticipant = getLocalParticipant(APP.store.getState());
  1983. APP.store.dispatch(participantUpdated({
  1984. conference: room,
  1985. id: localParticipant.id,
  1986. isReplaced
  1987. }));
  1988. // we send readyToClose when kicked participant is replace so that
  1989. // embedding app can choose to dispose the iframe API on the handler.
  1990. APP.API.notifyReadyToClose();
  1991. }
  1992. APP.store.dispatch(kickedOut(room, participant));
  1993. });
  1994. room.on(JitsiConferenceEvents.PARTICIPANT_KICKED, (kicker, kicked) => {
  1995. APP.store.dispatch(participantKicked(kicker, kicked));
  1996. });
  1997. room.on(JitsiConferenceEvents.SUSPEND_DETECTED, () => {
  1998. APP.store.dispatch(suspendDetected());
  1999. });
  2000. room.on(
  2001. JitsiConferenceEvents.AUDIO_UNMUTE_PERMISSIONS_CHANGED,
  2002. disableAudioMuteChange => {
  2003. APP.store.dispatch(setAudioUnmutePermissions(disableAudioMuteChange));
  2004. });
  2005. room.on(
  2006. JitsiConferenceEvents.VIDEO_UNMUTE_PERMISSIONS_CHANGED,
  2007. disableVideoMuteChange => {
  2008. APP.store.dispatch(setVideoUnmutePermissions(disableVideoMuteChange));
  2009. });
  2010. APP.UI.addListener(UIEvents.AUDIO_MUTED, muted => {
  2011. this.muteAudio(muted);
  2012. });
  2013. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  2014. this.muteVideo(muted);
  2015. });
  2016. room.addCommandListener(this.commands.defaults.ETHERPAD,
  2017. ({ value }) => {
  2018. APP.UI.initEtherpad(value);
  2019. }
  2020. );
  2021. APP.UI.addListener(UIEvents.EMAIL_CHANGED,
  2022. this.changeLocalEmail.bind(this));
  2023. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  2024. APP.store.dispatch(participantUpdated({
  2025. conference: room,
  2026. id: from,
  2027. email: data.value
  2028. }));
  2029. });
  2030. room.addCommandListener(
  2031. this.commands.defaults.AVATAR_URL,
  2032. (data, from) => {
  2033. APP.store.dispatch(
  2034. participantUpdated({
  2035. conference: room,
  2036. id: from,
  2037. avatarURL: data.value
  2038. }));
  2039. });
  2040. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  2041. this.changeLocalDisplayName.bind(this));
  2042. room.on(
  2043. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  2044. ({ audio, video }) => {
  2045. APP.store.dispatch(
  2046. onStartMutedPolicyChanged(audio, video));
  2047. }
  2048. );
  2049. room.on(JitsiConferenceEvents.STARTED_MUTED, () => {
  2050. const audioMuted = room.isStartAudioMuted();
  2051. const videoMuted = room.isStartVideoMuted();
  2052. const localTracks = getLocalTracks(APP.store.getState()['features/base/tracks']);
  2053. const promises = [];
  2054. APP.store.dispatch(setAudioMuted(audioMuted));
  2055. APP.store.dispatch(setVideoMuted(videoMuted));
  2056. // Remove the tracks from the peerconnection.
  2057. for (const track of localTracks) {
  2058. // Always add the track on Safari because of a known issue where audio playout doesn't happen
  2059. // if the user joins audio and video muted, i.e., if there is no local media capture.
  2060. if (audioMuted && track.jitsiTrack?.getType() === MEDIA_TYPE.AUDIO && !browser.isWebKitBased()) {
  2061. promises.push(this.useAudioStream(null));
  2062. }
  2063. if (videoMuted && track.jitsiTrack?.getType() === MEDIA_TYPE.VIDEO) {
  2064. promises.push(this.useVideoStream(null));
  2065. }
  2066. }
  2067. Promise.allSettled(promises)
  2068. .then(() => {
  2069. APP.store.dispatch(showNotification({
  2070. titleKey: 'notify.mutedTitle',
  2071. descriptionKey: 'notify.muted'
  2072. }, NOTIFICATION_TIMEOUT_TYPE.SHORT));
  2073. });
  2074. });
  2075. room.on(
  2076. JitsiConferenceEvents.DATA_CHANNEL_OPENED, () => {
  2077. APP.store.dispatch(dataChannelOpened());
  2078. }
  2079. );
  2080. // call hangup
  2081. APP.UI.addListener(UIEvents.HANGUP, () => {
  2082. this.hangup(true);
  2083. });
  2084. // logout
  2085. APP.UI.addListener(UIEvents.LOGOUT, () => {
  2086. AuthHandler.logout(room).then(url => {
  2087. if (url) {
  2088. UIUtil.redirect(url);
  2089. } else {
  2090. this.hangup(true);
  2091. }
  2092. });
  2093. });
  2094. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  2095. AuthHandler.authenticate(room);
  2096. });
  2097. APP.UI.addListener(
  2098. UIEvents.VIDEO_DEVICE_CHANGED,
  2099. cameraDeviceId => {
  2100. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  2101. const videoWasMuted = this.isLocalVideoMuted();
  2102. sendAnalytics(createDeviceChangedEvent('video', 'input'));
  2103. // If both screenshare and video are in progress, restart the
  2104. // presenter mode with the new camera device.
  2105. if (this.isSharingScreen && !videoWasMuted) {
  2106. const { height } = localVideo.track.getSettings();
  2107. // dispose the existing presenter track and create a new
  2108. // camera track.
  2109. // FIXME JitsiLocalTrack.dispose is async and should be waited for
  2110. this.localPresenterVideo && this.localPresenterVideo.dispose();
  2111. this.localPresenterVideo = null;
  2112. return this._createPresenterStreamEffect(height, cameraDeviceId)
  2113. .then(effect => localVideo.setEffect(effect))
  2114. .then(() => {
  2115. this.setVideoMuteStatus();
  2116. logger.log('Switched local video device while screen sharing and the video is unmuted');
  2117. this._updateVideoDeviceId();
  2118. })
  2119. .catch(err => APP.store.dispatch(notifyCameraError(err)));
  2120. // If screenshare is in progress but video is muted, update the default device
  2121. // id for video, dispose the existing presenter track and create a new effect
  2122. // that can be applied on un-mute.
  2123. } else if (this.isSharingScreen && videoWasMuted) {
  2124. logger.log('Switched local video device: while screen sharing and the video is muted');
  2125. const { height } = localVideo.track.getSettings();
  2126. this._updateVideoDeviceId();
  2127. // FIXME JitsiLocalTrack.dispose is async and should be waited for
  2128. this.localPresenterVideo && this.localPresenterVideo.dispose();
  2129. this.localPresenterVideo = null;
  2130. this._createPresenterStreamEffect(height, cameraDeviceId);
  2131. // if there is only video, switch to the new camera stream.
  2132. } else {
  2133. createLocalTracksF({
  2134. devices: [ 'video' ],
  2135. cameraDeviceId,
  2136. micDeviceId: null
  2137. })
  2138. .then(([ stream ]) => {
  2139. // if we are in audio only mode or video was muted before
  2140. // changing device, then mute
  2141. if (this.isAudioOnly() || videoWasMuted) {
  2142. return stream.mute()
  2143. .then(() => stream);
  2144. }
  2145. return stream;
  2146. })
  2147. .then(stream => {
  2148. logger.log('Switching the local video device.');
  2149. return this.useVideoStream(stream);
  2150. })
  2151. .then(() => {
  2152. logger.log('Switched local video device.');
  2153. this._updateVideoDeviceId();
  2154. })
  2155. .catch(error => {
  2156. logger.error(`Switching the local video device failed: ${error}`);
  2157. return APP.store.dispatch(notifyCameraError(error));
  2158. });
  2159. }
  2160. }
  2161. );
  2162. APP.UI.addListener(
  2163. UIEvents.AUDIO_DEVICE_CHANGED,
  2164. micDeviceId => {
  2165. const audioWasMuted = this.isLocalAudioMuted();
  2166. // When the 'default' mic needs to be selected, we need to
  2167. // pass the real device id to gUM instead of 'default' in order
  2168. // to get the correct MediaStreamTrack from chrome because of the
  2169. // following bug.
  2170. // https://bugs.chromium.org/p/chromium/issues/detail?id=997689
  2171. const hasDefaultMicChanged = micDeviceId === 'default';
  2172. sendAnalytics(createDeviceChangedEvent('audio', 'input'));
  2173. createLocalTracksF({
  2174. devices: [ 'audio' ],
  2175. cameraDeviceId: null,
  2176. micDeviceId: hasDefaultMicChanged
  2177. ? getDefaultDeviceId(APP.store.getState(), 'audioInput')
  2178. : micDeviceId
  2179. })
  2180. .then(([ stream ]) => {
  2181. // if audio was muted before changing the device, mute
  2182. // with the new device
  2183. if (audioWasMuted) {
  2184. return stream.mute()
  2185. .then(() => stream);
  2186. }
  2187. return stream;
  2188. })
  2189. .then(async stream => {
  2190. // In case screen sharing audio is also shared we mix it with new input stream. The old _mixerEffect
  2191. // will be cleaned up when the existing track is replaced.
  2192. if (this._mixerEffect) {
  2193. this._mixerEffect = new AudioMixerEffect(this._desktopAudioStream);
  2194. await stream.setEffect(this._mixerEffect);
  2195. }
  2196. return this.useAudioStream(stream);
  2197. })
  2198. .then(() => {
  2199. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  2200. if (localAudio && hasDefaultMicChanged) {
  2201. // workaround for the default device to be shown as selected in the
  2202. // settings even when the real device id was passed to gUM because of the
  2203. // above mentioned chrome bug.
  2204. localAudio._realDeviceId = localAudio.deviceId = 'default';
  2205. }
  2206. logger.log(`switched local audio device: ${localAudio?.getDeviceId()}`);
  2207. this._updateAudioDeviceId();
  2208. })
  2209. .catch(err => {
  2210. APP.store.dispatch(notifyMicError(err));
  2211. });
  2212. }
  2213. );
  2214. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  2215. // FIXME On web video track is stored both in redux and in
  2216. // 'localVideo' field, video is attempted to be unmuted twice when
  2217. // turning off the audio only mode. This will crash the app with
  2218. // 'unmute operation is already in progress'.
  2219. // Because there's no logic in redux about creating new track in
  2220. // case unmute when not track exists the things have to go through
  2221. // muteVideo logic in such case.
  2222. const tracks = APP.store.getState()['features/base/tracks'];
  2223. const isTrackInRedux
  2224. = Boolean(
  2225. tracks.find(
  2226. track => track.jitsiTrack
  2227. && track.jitsiTrack.getType() === 'video'));
  2228. if (!isTrackInRedux) {
  2229. this.muteVideo(audioOnly);
  2230. }
  2231. // Immediately update the UI by having remote videos and the large
  2232. // video update themselves instead of waiting for some other event
  2233. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  2234. // There is no guarantee another event will trigger the update
  2235. // immediately and in all situations, for example because a remote
  2236. // participant is having connection trouble so no status changes.
  2237. const displayedUserId = APP.UI.getLargeVideoID();
  2238. if (displayedUserId) {
  2239. APP.UI.updateLargeVideo(displayedUserId, true);
  2240. }
  2241. });
  2242. APP.UI.addListener(
  2243. UIEvents.TOGGLE_SCREENSHARING, ({ enabled, audioOnly, ignoreDidHaveVideo }) => {
  2244. this.toggleScreenSharing(enabled, { audioOnly }, ignoreDidHaveVideo);
  2245. }
  2246. );
  2247. },
  2248. /**
  2249. * Cleanups local conference on suspend.
  2250. */
  2251. onSuspendDetected() {
  2252. // After wake up, we will be in a state where conference is left
  2253. // there will be dialog shown to user.
  2254. // We do not want video/audio as we show an overlay and after it
  2255. // user need to rejoin or close, while waking up we can detect
  2256. // camera wakeup as a problem with device.
  2257. // We also do not care about device change, which happens
  2258. // on resume after suspending PC.
  2259. if (this.deviceChangeListener) {
  2260. JitsiMeetJS.mediaDevices.removeEventListener(
  2261. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2262. this.deviceChangeListener);
  2263. }
  2264. },
  2265. /**
  2266. * Callback invoked when the conference has been successfully joined.
  2267. * Initializes the UI and various other features.
  2268. *
  2269. * @private
  2270. * @returns {void}
  2271. */
  2272. _onConferenceJoined() {
  2273. const { dispatch } = APP.store;
  2274. APP.UI.initConference();
  2275. if (!config.disableShortcuts) {
  2276. APP.keyboardshortcut.init();
  2277. }
  2278. dispatch(conferenceJoined(room));
  2279. const jwt = APP.store.getState()['features/base/jwt'];
  2280. if (jwt?.user?.hiddenFromRecorder) {
  2281. dispatch(muteLocal(true, MEDIA_TYPE.AUDIO));
  2282. dispatch(muteLocal(true, MEDIA_TYPE.VIDEO));
  2283. dispatch(setAudioUnmutePermissions(true, true));
  2284. dispatch(setVideoUnmutePermissions(true, true));
  2285. }
  2286. },
  2287. /**
  2288. * Updates the list of current devices.
  2289. * @param {boolean} setDeviceListChangeHandler - Whether to add the deviceList change handlers.
  2290. * @private
  2291. * @returns {Promise}
  2292. */
  2293. _initDeviceList(setDeviceListChangeHandler = false) {
  2294. const { mediaDevices } = JitsiMeetJS;
  2295. if (mediaDevices.isDeviceListAvailable()
  2296. && mediaDevices.isDeviceChangeAvailable()) {
  2297. if (setDeviceListChangeHandler) {
  2298. this.deviceChangeListener = devices =>
  2299. window.setTimeout(() => this._onDeviceListChanged(devices), 0);
  2300. mediaDevices.addEventListener(
  2301. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2302. this.deviceChangeListener);
  2303. }
  2304. const { dispatch } = APP.store;
  2305. return dispatch(getAvailableDevices())
  2306. .then(devices => {
  2307. // Ugly way to synchronize real device IDs with local
  2308. // storage and settings menu. This is a workaround until
  2309. // getConstraints() method will be implemented in browsers.
  2310. this._updateAudioDeviceId();
  2311. this._updateVideoDeviceId();
  2312. APP.UI.onAvailableDevicesChanged(devices);
  2313. });
  2314. }
  2315. return Promise.resolve();
  2316. },
  2317. /**
  2318. * Updates the settings for the currently used video device, extracting
  2319. * the device id from the used track.
  2320. * @private
  2321. */
  2322. _updateVideoDeviceId() {
  2323. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  2324. if (localVideo && localVideo.videoType === 'camera') {
  2325. APP.store.dispatch(updateSettings({
  2326. cameraDeviceId: localVideo.getDeviceId()
  2327. }));
  2328. }
  2329. // If screenshare is in progress, get the device id from the presenter track.
  2330. if (this.localPresenterVideo) {
  2331. APP.store.dispatch(updateSettings({
  2332. cameraDeviceId: this.localPresenterVideo.getDeviceId()
  2333. }));
  2334. }
  2335. },
  2336. /**
  2337. * Updates the settings for the currently used audio device, extracting
  2338. * the device id from the used track.
  2339. * @private
  2340. */
  2341. _updateAudioDeviceId() {
  2342. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  2343. if (localAudio) {
  2344. APP.store.dispatch(updateSettings({
  2345. micDeviceId: localAudio.getDeviceId()
  2346. }));
  2347. }
  2348. },
  2349. /**
  2350. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  2351. * handle change of available media devices.
  2352. * @private
  2353. * @param {MediaDeviceInfo[]} devices
  2354. * @returns {Promise}
  2355. */
  2356. _onDeviceListChanged(devices) {
  2357. const oldDevices = APP.store.getState()['features/base/devices'].availableDevices;
  2358. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  2359. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  2360. APP.store.dispatch(updateDeviceList(devices));
  2361. // Firefox users can choose their preferred device in the gUM prompt. In that case
  2362. // we should respect that and not attempt to switch to the preferred device from
  2363. // our settings.
  2364. const newLabelsOnly = mediaDeviceHelper.newDeviceListAddedLabelsOnly(oldDevices, devices);
  2365. const newDevices
  2366. = mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  2367. devices,
  2368. this.isSharingScreen,
  2369. localVideo,
  2370. localAudio,
  2371. newLabelsOnly);
  2372. const promises = [];
  2373. const audioWasMuted = this.isLocalAudioMuted();
  2374. const videoWasMuted = this.isLocalVideoMuted();
  2375. const requestedInput = {
  2376. audio: Boolean(newDevices.audioinput),
  2377. video: Boolean(newDevices.videoinput)
  2378. };
  2379. if (typeof newDevices.audiooutput !== 'undefined') {
  2380. const { dispatch } = APP.store;
  2381. const setAudioOutputPromise
  2382. = setAudioOutputDeviceId(newDevices.audiooutput, dispatch)
  2383. .catch(); // Just ignore any errors in catch block.
  2384. promises.push(setAudioOutputPromise);
  2385. }
  2386. // Handles the use case when the default device is changed (we are always stopping the streams because it's
  2387. // simpler):
  2388. // If the default device is changed we need to first stop the local streams and then call GUM. Otherwise GUM
  2389. // will return a stream using the old default device.
  2390. if (requestedInput.audio && localAudio) {
  2391. localAudio.stopStream();
  2392. }
  2393. if (requestedInput.video && localVideo) {
  2394. localVideo.stopStream();
  2395. }
  2396. // Let's handle unknown/non-preferred devices
  2397. const newAvailDevices
  2398. = APP.store.getState()['features/base/devices'].availableDevices;
  2399. let newAudioDevices = [];
  2400. let oldAudioDevices = [];
  2401. if (typeof newDevices.audiooutput === 'undefined') {
  2402. newAudioDevices = newAvailDevices.audioOutput;
  2403. oldAudioDevices = oldDevices.audioOutput;
  2404. }
  2405. if (!requestedInput.audio) {
  2406. newAudioDevices = newAudioDevices.concat(newAvailDevices.audioInput);
  2407. oldAudioDevices = oldAudioDevices.concat(oldDevices.audioInput);
  2408. }
  2409. // check for audio
  2410. if (newAudioDevices.length > 0) {
  2411. APP.store.dispatch(
  2412. checkAndNotifyForNewDevice(newAudioDevices, oldAudioDevices));
  2413. }
  2414. // check for video
  2415. if (!requestedInput.video) {
  2416. APP.store.dispatch(
  2417. checkAndNotifyForNewDevice(newAvailDevices.videoInput, oldDevices.videoInput));
  2418. }
  2419. // When the 'default' mic needs to be selected, we need to
  2420. // pass the real device id to gUM instead of 'default' in order
  2421. // to get the correct MediaStreamTrack from chrome because of the
  2422. // following bug.
  2423. // https://bugs.chromium.org/p/chromium/issues/detail?id=997689
  2424. const hasDefaultMicChanged = newDevices.audioinput === 'default';
  2425. // This is the case when the local video is muted and a preferred device is connected.
  2426. if (requestedInput.video && this.isLocalVideoMuted()) {
  2427. // We want to avoid creating a new video track in order to prevent turning on the camera.
  2428. requestedInput.video = false;
  2429. APP.store.dispatch(updateSettings({ // Update the current selected camera for the device selection dialog.
  2430. cameraDeviceId: newDevices.videoinput
  2431. }));
  2432. delete newDevices.videoinput;
  2433. // Removing the current video track in order to force the unmute to select the preferred device.
  2434. logger.debug('_onDeviceListChanged: Removing the current video track.');
  2435. this.useVideoStream(null);
  2436. }
  2437. promises.push(
  2438. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  2439. createLocalTracksF,
  2440. newDevices.videoinput,
  2441. hasDefaultMicChanged
  2442. ? getDefaultDeviceId(APP.store.getState(), 'audioInput')
  2443. : newDevices.audioinput)
  2444. .then(tracks => {
  2445. // If audio or video muted before, or we unplugged current
  2446. // device and selected new one, then mute new track.
  2447. const muteSyncPromises = tracks.map(track => {
  2448. if ((track.isVideoTrack() && videoWasMuted)
  2449. || (track.isAudioTrack() && audioWasMuted)) {
  2450. return track.mute();
  2451. }
  2452. return Promise.resolve();
  2453. });
  2454. return Promise.all(muteSyncPromises)
  2455. .then(() =>
  2456. Promise.all(Object.keys(requestedInput).map(mediaType => {
  2457. if (requestedInput[mediaType]) {
  2458. const useStream
  2459. = mediaType === 'audio'
  2460. ? this.useAudioStream.bind(this)
  2461. : this.useVideoStream.bind(this);
  2462. const track = tracks.find(t => t.getType() === mediaType) || null;
  2463. // Use the new stream or null if we failed to obtain it.
  2464. return useStream(track)
  2465. .then(() => {
  2466. if (track?.isAudioTrack() && hasDefaultMicChanged) {
  2467. // workaround for the default device to be shown as selected in the
  2468. // settings even when the real device id was passed to gUM because of
  2469. // the above mentioned chrome bug.
  2470. track._realDeviceId = track.deviceId = 'default';
  2471. }
  2472. mediaType === 'audio'
  2473. ? this._updateAudioDeviceId()
  2474. : this._updateVideoDeviceId();
  2475. });
  2476. }
  2477. return Promise.resolve();
  2478. })));
  2479. })
  2480. .then(() => {
  2481. // Log and sync known mute state.
  2482. if (audioWasMuted) {
  2483. sendAnalytics(createTrackMutedEvent(
  2484. 'audio',
  2485. 'device list changed'));
  2486. logger.log('Audio mute: device list changed');
  2487. muteLocalAudio(true);
  2488. }
  2489. if (!this.isSharingScreen && videoWasMuted) {
  2490. sendAnalytics(createTrackMutedEvent(
  2491. 'video',
  2492. 'device list changed'));
  2493. logger.log('Video mute: device list changed');
  2494. muteLocalVideo(true);
  2495. }
  2496. }));
  2497. return Promise.all(promises)
  2498. .then(() => {
  2499. APP.UI.onAvailableDevicesChanged(devices);
  2500. });
  2501. },
  2502. /**
  2503. * Determines whether or not the audio button should be enabled.
  2504. */
  2505. updateAudioIconEnabled() {
  2506. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  2507. const audioMediaDevices = APP.store.getState()['features/base/devices'].availableDevices.audioInput;
  2508. const audioDeviceCount = audioMediaDevices ? audioMediaDevices.length : 0;
  2509. // The audio functionality is considered available if there are any
  2510. // audio devices detected or if the local audio stream already exists.
  2511. const available = audioDeviceCount > 0 || Boolean(localAudio);
  2512. APP.store.dispatch(setAudioAvailable(available));
  2513. APP.API.notifyAudioAvailabilityChanged(available);
  2514. },
  2515. /**
  2516. * Determines whether or not the video button should be enabled.
  2517. */
  2518. updateVideoIconEnabled() {
  2519. const videoMediaDevices
  2520. = APP.store.getState()['features/base/devices'].availableDevices.videoInput;
  2521. const videoDeviceCount
  2522. = videoMediaDevices ? videoMediaDevices.length : 0;
  2523. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  2524. // The video functionality is considered available if there are any
  2525. // video devices detected or if there is local video stream already
  2526. // active which could be either screensharing stream or a video track
  2527. // created before the permissions were rejected (through browser
  2528. // config).
  2529. const available = videoDeviceCount > 0 || Boolean(localVideo);
  2530. APP.store.dispatch(setVideoAvailable(available));
  2531. APP.API.notifyVideoAvailabilityChanged(available);
  2532. },
  2533. /**
  2534. * Disconnect from the conference and optionally request user feedback.
  2535. * @param {boolean} [requestFeedback=false] if user feedback should be
  2536. * requested
  2537. */
  2538. hangup(requestFeedback = false) {
  2539. APP.store.dispatch(disableReceiver());
  2540. this._stopProxyConnection();
  2541. APP.store.dispatch(destroyLocalTracks());
  2542. this._localTracksInitialized = false;
  2543. // Remove unnecessary event listeners from firing callbacks.
  2544. if (this.deviceChangeListener) {
  2545. JitsiMeetJS.mediaDevices.removeEventListener(
  2546. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2547. this.deviceChangeListener);
  2548. }
  2549. APP.UI.removeAllListeners();
  2550. let requestFeedbackPromise;
  2551. if (requestFeedback) {
  2552. requestFeedbackPromise
  2553. = APP.store.dispatch(maybeOpenFeedbackDialog(room))
  2554. // false because the thank you dialog shouldn't be displayed
  2555. .catch(() => Promise.resolve(false));
  2556. } else {
  2557. requestFeedbackPromise = Promise.resolve(true);
  2558. }
  2559. Promise.all([
  2560. requestFeedbackPromise,
  2561. this.leaveRoom()
  2562. ])
  2563. .then(values => {
  2564. this._room = undefined;
  2565. room = undefined;
  2566. /**
  2567. * Don't call {@code notifyReadyToClose} if the promotional page flag is set
  2568. * and let the page take care of sending the message, since there will be
  2569. * a redirect to the page regardlessly.
  2570. */
  2571. if (!interfaceConfig.SHOW_PROMOTIONAL_CLOSE_PAGE) {
  2572. APP.API.notifyReadyToClose();
  2573. }
  2574. APP.store.dispatch(maybeRedirectToWelcomePage(values[0]));
  2575. });
  2576. },
  2577. /**
  2578. * Leaves the room.
  2579. *
  2580. * @param {boolean} doDisconnect - Wether leaving the room should also terminate the connection.
  2581. * @returns {Promise}
  2582. */
  2583. async leaveRoom(doDisconnect = true) {
  2584. APP.store.dispatch(conferenceWillLeave(room));
  2585. if (room && room.isJoined()) {
  2586. return room.leave().finally(() => {
  2587. if (doDisconnect) {
  2588. return disconnect();
  2589. }
  2590. });
  2591. }
  2592. if (doDisconnect) {
  2593. return disconnect();
  2594. }
  2595. },
  2596. /**
  2597. * Changes the email for the local user
  2598. * @param email {string} the new email
  2599. */
  2600. changeLocalEmail(email = '') {
  2601. const localParticipant = getLocalParticipant(APP.store.getState());
  2602. const formattedEmail = String(email).trim();
  2603. if (formattedEmail === localParticipant.email) {
  2604. return;
  2605. }
  2606. const localId = localParticipant.id;
  2607. APP.store.dispatch(participantUpdated({
  2608. // XXX Only the local participant is allowed to update without
  2609. // stating the JitsiConference instance (i.e. participant property
  2610. // `conference` for a remote participant) because the local
  2611. // participant is uniquely identified by the very fact that there is
  2612. // only one local participant.
  2613. id: localId,
  2614. local: true,
  2615. email: formattedEmail
  2616. }));
  2617. APP.store.dispatch(updateSettings({
  2618. email: formattedEmail
  2619. }));
  2620. APP.API.notifyEmailChanged(localId, {
  2621. email: formattedEmail
  2622. });
  2623. sendData(commands.EMAIL, formattedEmail);
  2624. },
  2625. /**
  2626. * Changes the avatar url for the local user
  2627. * @param url {string} the new url
  2628. */
  2629. changeLocalAvatarUrl(url = '') {
  2630. const { avatarURL, id } = getLocalParticipant(APP.store.getState());
  2631. const formattedUrl = String(url).trim();
  2632. if (formattedUrl === avatarURL) {
  2633. return;
  2634. }
  2635. APP.store.dispatch(participantUpdated({
  2636. // XXX Only the local participant is allowed to update without
  2637. // stating the JitsiConference instance (i.e. participant property
  2638. // `conference` for a remote participant) because the local
  2639. // participant is uniquely identified by the very fact that there is
  2640. // only one local participant.
  2641. id,
  2642. local: true,
  2643. avatarURL: formattedUrl
  2644. }));
  2645. APP.store.dispatch(updateSettings({
  2646. avatarURL: formattedUrl
  2647. }));
  2648. sendData(commands.AVATAR_URL, url);
  2649. },
  2650. /**
  2651. * Sends a message via the data channel.
  2652. * @param {string} to the id of the endpoint that should receive the
  2653. * message. If "" - the message will be sent to all participants.
  2654. * @param {object} payload the payload of the message.
  2655. * @throws NetworkError or InvalidStateError or Error if the operation
  2656. * fails.
  2657. */
  2658. sendEndpointMessage(to, payload) {
  2659. room.sendEndpointMessage(to, payload);
  2660. },
  2661. /**
  2662. * Sends a facial expression as a string and its duration as a number
  2663. * @param {object} payload - Object containing the {string} facialExpression
  2664. * and {number} duration
  2665. */
  2666. sendFacialExpression(payload) {
  2667. room.sendFacialExpression(payload);
  2668. },
  2669. /**
  2670. * Adds new listener.
  2671. * @param {String} eventName the name of the event
  2672. * @param {Function} listener the listener.
  2673. */
  2674. addListener(eventName, listener) {
  2675. eventEmitter.addListener(eventName, listener);
  2676. },
  2677. /**
  2678. * Removes listener.
  2679. * @param {String} eventName the name of the event that triggers the
  2680. * listener
  2681. * @param {Function} listener the listener.
  2682. */
  2683. removeListener(eventName, listener) {
  2684. eventEmitter.removeListener(eventName, listener);
  2685. },
  2686. /**
  2687. * Changes the display name for the local user
  2688. * @param nickname {string} the new display name
  2689. */
  2690. changeLocalDisplayName(nickname = '') {
  2691. const formattedNickname = getNormalizedDisplayName(nickname);
  2692. const { id, name } = getLocalParticipant(APP.store.getState());
  2693. if (formattedNickname === name) {
  2694. return;
  2695. }
  2696. APP.store.dispatch(participantUpdated({
  2697. // XXX Only the local participant is allowed to update without
  2698. // stating the JitsiConference instance (i.e. participant property
  2699. // `conference` for a remote participant) because the local
  2700. // participant is uniquely identified by the very fact that there is
  2701. // only one local participant.
  2702. id,
  2703. local: true,
  2704. name: formattedNickname
  2705. }));
  2706. APP.store.dispatch(updateSettings({
  2707. displayName: formattedNickname
  2708. }));
  2709. },
  2710. /**
  2711. * Callback invoked by the external api create or update a direct connection
  2712. * from the local client to an external client.
  2713. *
  2714. * @param {Object} event - The object containing information that should be
  2715. * passed to the {@code ProxyConnectionService}.
  2716. * @returns {void}
  2717. */
  2718. onProxyConnectionEvent(event) {
  2719. if (!this._proxyConnection) {
  2720. this._proxyConnection = new JitsiMeetJS.ProxyConnectionService({
  2721. /**
  2722. * Pass the {@code JitsiConnection} instance which will be used
  2723. * to fetch TURN credentials.
  2724. */
  2725. jitsiConnection: APP.connection,
  2726. /**
  2727. * The proxy connection feature is currently tailored towards
  2728. * taking a proxied video stream and showing it as a local
  2729. * desktop screen.
  2730. */
  2731. convertVideoToDesktop: true,
  2732. /**
  2733. * Callback invoked when the connection has been closed
  2734. * automatically. Triggers cleanup of screensharing if active.
  2735. *
  2736. * @returns {void}
  2737. */
  2738. onConnectionClosed: () => {
  2739. if (this._untoggleScreenSharing) {
  2740. this._untoggleScreenSharing();
  2741. }
  2742. },
  2743. /**
  2744. * Callback invoked to pass messages from the local client back
  2745. * out to the external client.
  2746. *
  2747. * @param {string} peerJid - The jid of the intended recipient
  2748. * of the message.
  2749. * @param {Object} data - The message that should be sent. For
  2750. * screensharing this is an iq.
  2751. * @returns {void}
  2752. */
  2753. onSendMessage: (peerJid, data) =>
  2754. APP.API.sendProxyConnectionEvent({
  2755. data,
  2756. to: peerJid
  2757. }),
  2758. /**
  2759. * Callback invoked when the remote peer of the proxy connection
  2760. * has provided a video stream, intended to be used as a local
  2761. * desktop stream.
  2762. *
  2763. * @param {JitsiLocalTrack} remoteProxyStream - The media
  2764. * stream to use as a local desktop stream.
  2765. * @returns {void}
  2766. */
  2767. onRemoteStream: desktopStream => {
  2768. if (desktopStream.videoType !== 'desktop') {
  2769. logger.warn('Received a non-desktop stream to proxy.');
  2770. desktopStream.dispose();
  2771. return;
  2772. }
  2773. this.toggleScreenSharing(undefined, { desktopStream });
  2774. }
  2775. });
  2776. }
  2777. this._proxyConnection.processMessage(event);
  2778. },
  2779. /**
  2780. * Sets the video muted status.
  2781. */
  2782. setVideoMuteStatus() {
  2783. APP.UI.setVideoMuted(this.getMyUserId());
  2784. },
  2785. /**
  2786. * Sets the audio muted status.
  2787. *
  2788. * @param {boolean} muted - New muted status.
  2789. */
  2790. setAudioMuteStatus(muted) {
  2791. APP.UI.setAudioMuted(this.getMyUserId(), muted);
  2792. APP.API.notifyAudioMutedStatusChanged(muted);
  2793. },
  2794. /**
  2795. * Dispatches the passed in feedback for submission. The submitted score
  2796. * should be a number inclusively between 1 through 5, or -1 for no score.
  2797. *
  2798. * @param {number} score - a number between 1 and 5 (inclusive) or -1 for no
  2799. * score.
  2800. * @param {string} message - An optional message to attach to the feedback
  2801. * in addition to the score.
  2802. * @returns {void}
  2803. */
  2804. submitFeedback(score = -1, message = '') {
  2805. if (score === -1 || (score >= 1 && score <= 5)) {
  2806. APP.store.dispatch(submitFeedback(score, message, room));
  2807. }
  2808. },
  2809. /**
  2810. * Terminates any proxy screensharing connection that is active.
  2811. *
  2812. * @private
  2813. * @returns {void}
  2814. */
  2815. _stopProxyConnection() {
  2816. if (this._proxyConnection) {
  2817. this._proxyConnection.stop();
  2818. }
  2819. this._proxyConnection = null;
  2820. }
  2821. };