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

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