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