You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 113KB

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