Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

conference.js 95KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645
  1. /* global APP, JitsiMeetJS, config, interfaceConfig */
  2. import { jitsiLocalStorage } from '@jitsi/js-utils';
  3. import Logger from '@jitsi/logger';
  4. import EventEmitter from 'events';
  5. import { ENDPOINT_TEXT_MESSAGE_NAME } from './modules/API/constants';
  6. import { AUDIO_ONLY_SCREEN_SHARE_NO_TRACK } from './modules/UI/UIErrors';
  7. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  8. import Recorder from './modules/recorder/Recorder';
  9. import { createTaskQueue } from './modules/util/helpers';
  10. import {
  11. createDeviceChangedEvent,
  12. createScreenSharingEvent,
  13. createStartSilentEvent,
  14. createTrackMutedEvent
  15. } from './react/features/analytics/AnalyticsEvents';
  16. import { sendAnalytics } from './react/features/analytics/functions';
  17. import {
  18. maybeRedirectToWelcomePage,
  19. redirectToStaticPage,
  20. reloadWithStoredParams
  21. } from './react/features/app/actions';
  22. import { showModeratedNotification } from './react/features/av-moderation/actions';
  23. import { shouldShowModeratedNotification } from './react/features/av-moderation/functions';
  24. import {
  25. _conferenceWillJoin,
  26. authStatusChanged,
  27. conferenceFailed,
  28. conferenceJoinInProgress,
  29. conferenceJoined,
  30. conferenceLeft,
  31. conferenceSubjectChanged,
  32. conferenceTimestampChanged,
  33. conferenceUniqueIdSet,
  34. conferenceWillInit,
  35. conferenceWillLeave,
  36. dataChannelClosed,
  37. dataChannelOpened,
  38. e2eRttChanged,
  39. endpointMessageReceived,
  40. kickedOut,
  41. lockStateChanged,
  42. nonParticipantMessageReceived,
  43. onStartMutedPolicyChanged,
  44. p2pStatusChanged
  45. } from './react/features/base/conference/actions';
  46. import {
  47. AVATAR_URL_COMMAND,
  48. CONFERENCE_LEAVE_REASONS,
  49. EMAIL_COMMAND
  50. } from './react/features/base/conference/constants';
  51. import {
  52. commonUserJoinedHandling,
  53. commonUserLeftHandling,
  54. getConferenceOptions,
  55. sendLocalParticipant
  56. } from './react/features/base/conference/functions';
  57. import { getReplaceParticipant } from './react/features/base/config/functions';
  58. import { connect } from './react/features/base/connection/actions.web';
  59. import {
  60. checkAndNotifyForNewDevice,
  61. getAvailableDevices,
  62. notifyCameraError,
  63. notifyMicError,
  64. updateDeviceList
  65. } from './react/features/base/devices/actions.web';
  66. import {
  67. areDevicesDifferent,
  68. filterIgnoredDevices,
  69. flattenAvailableDevices,
  70. getDefaultDeviceId,
  71. logDevices,
  72. setAudioOutputDeviceId
  73. } from './react/features/base/devices/functions.web';
  74. import {
  75. JitsiConferenceErrors,
  76. JitsiConferenceEvents,
  77. JitsiE2ePingEvents,
  78. JitsiMediaDevicesEvents,
  79. JitsiTrackErrors,
  80. JitsiTrackEvents,
  81. browser
  82. } from './react/features/base/lib-jitsi-meet';
  83. import {
  84. gumPending,
  85. setAudioAvailable,
  86. setAudioMuted,
  87. setAudioUnmutePermissions,
  88. setVideoAvailable,
  89. setVideoMuted,
  90. setVideoUnmutePermissions
  91. } from './react/features/base/media/actions';
  92. import { MEDIA_TYPE } from './react/features/base/media/constants';
  93. import {
  94. getStartWithAudioMuted,
  95. getStartWithVideoMuted,
  96. isVideoMutedByUser
  97. } from './react/features/base/media/functions';
  98. import { IGUMPendingState } from './react/features/base/media/types';
  99. import {
  100. dominantSpeakerChanged,
  101. localParticipantAudioLevelChanged,
  102. localParticipantRoleChanged,
  103. participantKicked,
  104. participantMutedUs,
  105. participantPresenceChanged,
  106. participantRoleChanged,
  107. participantSourcesUpdated,
  108. participantUpdated,
  109. screenshareParticipantDisplayNameChanged,
  110. updateRemoteParticipantFeatures
  111. } from './react/features/base/participants/actions';
  112. import {
  113. getLocalParticipant,
  114. getNormalizedDisplayName,
  115. getVirtualScreenshareParticipantByOwnerId
  116. } from './react/features/base/participants/functions';
  117. import { updateSettings } from './react/features/base/settings/actions';
  118. import {
  119. addLocalTrack,
  120. destroyLocalTracks,
  121. replaceLocalTrack,
  122. toggleScreensharing as toggleScreensharingA,
  123. trackAdded,
  124. trackRemoved
  125. } from './react/features/base/tracks/actions';
  126. import {
  127. createLocalTracksF,
  128. getLocalJitsiAudioTrack,
  129. getLocalJitsiVideoTrack,
  130. getLocalTracks,
  131. getLocalVideoTrack,
  132. isLocalTrackMuted,
  133. isUserInteractionRequiredForUnmute
  134. } from './react/features/base/tracks/functions';
  135. import { downloadJSON } from './react/features/base/util/downloadJSON';
  136. import { openLeaveReasonDialog } from './react/features/conference/actions.web';
  137. import { showDesktopPicker } from './react/features/desktop-picker/actions';
  138. import { appendSuffix } from './react/features/display-name/functions';
  139. import { maybeOpenFeedbackDialog, submitFeedback } from './react/features/feedback/actions';
  140. import { initKeyboardShortcuts } from './react/features/keyboard-shortcuts/actions';
  141. import { maybeSetLobbyChatMessageListener } from './react/features/lobby/actions.any';
  142. import { setNoiseSuppressionEnabled } from './react/features/noise-suppression/actions';
  143. import {
  144. hideNotification,
  145. showErrorNotification,
  146. showNotification,
  147. showWarningNotification
  148. } from './react/features/notifications/actions';
  149. import {
  150. DATA_CHANNEL_CLOSED_NOTIFICATION_ID,
  151. NOTIFICATION_TIMEOUT_TYPE
  152. } from './react/features/notifications/constants';
  153. import { isModerationNotificationDisplayed } from './react/features/notifications/functions';
  154. import { mediaPermissionPromptVisibilityChanged } from './react/features/overlay/actions';
  155. import { suspendDetected } from './react/features/power-monitor/actions';
  156. import { initPrejoin } from './react/features/prejoin/actions';
  157. import { isPrejoinPageVisible } from './react/features/prejoin/functions';
  158. import { disableReceiver, stopReceiver } from './react/features/remote-control/actions';
  159. import { setScreenAudioShareState } from './react/features/screen-share/actions.web';
  160. import { isScreenAudioShared } from './react/features/screen-share/functions';
  161. import { toggleScreenshotCaptureSummary } from './react/features/screenshot-capture/actions';
  162. import { AudioMixerEffect } from './react/features/stream-effects/audio-mixer/AudioMixerEffect';
  163. import { createRnnoiseProcessor } from './react/features/stream-effects/rnnoise';
  164. import { handleToggleVideoMuted } from './react/features/toolbox/actions.any';
  165. import { muteLocal } from './react/features/video-menu/actions.any';
  166. import { iAmVisitor } from './react/features/visitors/functions';
  167. import UIEvents from './service/UI/UIEvents';
  168. const logger = Logger.getLogger(__filename);
  169. const eventEmitter = new EventEmitter();
  170. let room;
  171. /*
  172. * Logic to open a desktop picker put on the window global for
  173. * lib-jitsi-meet to detect and invoke
  174. */
  175. window.JitsiMeetScreenObtainer = {
  176. openDesktopPicker(options, onSourceChoose) {
  177. APP.store.dispatch(showDesktopPicker(options, onSourceChoose));
  178. }
  179. };
  180. /**
  181. * Known custom conference commands.
  182. */
  183. const commands = {
  184. AVATAR_URL: AVATAR_URL_COMMAND,
  185. CUSTOM_ROLE: 'custom-role',
  186. EMAIL: EMAIL_COMMAND,
  187. ETHERPAD: 'etherpad'
  188. };
  189. /**
  190. * Share data to other users.
  191. * @param command the command
  192. * @param {string} value new value
  193. */
  194. function sendData(command, value) {
  195. if (!room) {
  196. return;
  197. }
  198. room.removeCommand(command);
  199. room.sendCommand(command, { value });
  200. }
  201. /**
  202. * Mute or unmute local audio stream if it exists.
  203. * @param {boolean} muted - if audio stream should be muted or unmuted.
  204. */
  205. function muteLocalAudio(muted) {
  206. APP.store.dispatch(setAudioMuted(muted));
  207. }
  208. /**
  209. * Mute or unmute local video stream if it exists.
  210. * @param {boolean} muted if video stream should be muted or unmuted.
  211. *
  212. */
  213. function muteLocalVideo(muted) {
  214. APP.store.dispatch(setVideoMuted(muted));
  215. }
  216. /**
  217. * A queue for the async replaceLocalTrack action so that multiple audio
  218. * replacements cannot happen simultaneously. This solves the issue where
  219. * replaceLocalTrack is called multiple times with an oldTrack of null, causing
  220. * multiple local tracks of the same type to be used.
  221. *
  222. * @private
  223. * @type {Object}
  224. */
  225. const _replaceLocalAudioTrackQueue = createTaskQueue();
  226. /**
  227. * A task queue for replacement local video tracks. This separate queue exists
  228. * so video replacement is not blocked by audio replacement tasks in the queue
  229. * {@link _replaceLocalAudioTrackQueue}.
  230. *
  231. * @private
  232. * @type {Object}
  233. */
  234. const _replaceLocalVideoTrackQueue = createTaskQueue();
  235. /**
  236. *
  237. */
  238. class ConferenceConnector {
  239. /**
  240. *
  241. */
  242. constructor(resolve, reject, conference) {
  243. this._conference = conference;
  244. this._resolve = resolve;
  245. this._reject = reject;
  246. this.reconnectTimeout = null;
  247. room.on(JitsiConferenceEvents.CONFERENCE_JOINED,
  248. this._handleConferenceJoined.bind(this));
  249. room.on(JitsiConferenceEvents.CONFERENCE_FAILED,
  250. this._onConferenceFailed.bind(this));
  251. }
  252. /**
  253. *
  254. */
  255. _handleConferenceFailed(err) {
  256. this._unsubscribe();
  257. this._reject(err);
  258. }
  259. /**
  260. *
  261. */
  262. _onConferenceFailed(err, ...params) {
  263. APP.store.dispatch(conferenceFailed(room, err, ...params));
  264. logger.error('CONFERENCE FAILED:', err, ...params);
  265. switch (err) {
  266. case JitsiConferenceErrors.NOT_ALLOWED_ERROR: {
  267. // let's show some auth not allowed page
  268. APP.store.dispatch(redirectToStaticPage('static/authError.html'));
  269. break;
  270. }
  271. case JitsiConferenceErrors.RESERVATION_ERROR: {
  272. const [ code, msg ] = params;
  273. APP.store.dispatch(showErrorNotification({
  274. descriptionArguments: {
  275. code,
  276. msg
  277. },
  278. descriptionKey: 'dialog.reservationErrorMsg',
  279. titleKey: 'dialog.reservationError'
  280. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  281. break;
  282. }
  283. case JitsiConferenceErrors.GRACEFUL_SHUTDOWN:
  284. APP.store.dispatch(showErrorNotification({
  285. descriptionKey: 'dialog.gracefulShutdown',
  286. titleKey: 'dialog.serviceUnavailable'
  287. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  288. break;
  289. // FIXME FOCUS_DISCONNECTED is a confusing event name.
  290. // What really happens there is that the library is not ready yet,
  291. // because Jicofo is not available, but it is going to give it another
  292. // try.
  293. case JitsiConferenceErrors.FOCUS_DISCONNECTED: {
  294. const [ focus, retrySec ] = params;
  295. APP.store.dispatch(showNotification({
  296. descriptionKey: focus,
  297. titleKey: retrySec
  298. }, NOTIFICATION_TIMEOUT_TYPE.SHORT));
  299. break;
  300. }
  301. case JitsiConferenceErrors.FOCUS_LEFT:
  302. case JitsiConferenceErrors.ICE_FAILED:
  303. case JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  304. case JitsiConferenceErrors.OFFER_ANSWER_FAILED:
  305. APP.store.dispatch(conferenceWillLeave(room));
  306. // FIXME the conference should be stopped by the library and not by
  307. // the app. Both the errors above are unrecoverable from the library
  308. // perspective.
  309. room.leave(CONFERENCE_LEAVE_REASONS.UNRECOVERABLE_ERROR).then(() => APP.connection.disconnect());
  310. break;
  311. case JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  312. APP.store.dispatch(reloadWithStoredParams());
  313. break;
  314. default:
  315. this._handleConferenceFailed(err, ...params);
  316. }
  317. }
  318. /**
  319. *
  320. */
  321. _unsubscribe() {
  322. room.off(
  323. JitsiConferenceEvents.CONFERENCE_JOINED,
  324. this._handleConferenceJoined);
  325. room.off(
  326. JitsiConferenceEvents.CONFERENCE_FAILED,
  327. this._onConferenceFailed);
  328. if (this.reconnectTimeout !== null) {
  329. clearTimeout(this.reconnectTimeout);
  330. }
  331. }
  332. /**
  333. *
  334. */
  335. _handleConferenceJoined() {
  336. this._unsubscribe();
  337. this._resolve();
  338. }
  339. /**
  340. *
  341. */
  342. connect() {
  343. const replaceParticipant = getReplaceParticipant(APP.store.getState());
  344. // the local storage overrides here and in connection.js can be used by jibri
  345. room.join(jitsiLocalStorage.getItem('xmpp_conference_password_override'), replaceParticipant);
  346. }
  347. }
  348. /**
  349. * Disconnects the connection.
  350. * @returns resolved Promise. We need this in order to make the Promise.all
  351. * call in hangup() to resolve when all operations are finished.
  352. */
  353. function disconnect() {
  354. const onDisconnected = () => {
  355. APP.API.notifyConferenceLeft(APP.conference.roomName);
  356. return Promise.resolve();
  357. };
  358. if (!APP.connection) {
  359. return onDisconnected();
  360. }
  361. return APP.connection.disconnect().then(onDisconnected, onDisconnected);
  362. }
  363. /**
  364. * Sets the GUM pending state for the tracks that have failed.
  365. *
  366. * NOTE: Some of the track that we will be setting to GUM pending state NONE may not have failed but they may have
  367. * been requested. This won't be a problem because their current GUM pending state will be NONE anyway.
  368. * @param {JitsiLocalTrack} tracks - The tracks that have been created.
  369. * @returns {void}
  370. */
  371. function setGUMPendingStateOnFailedTracks(tracks) {
  372. const tracksTypes = tracks.map(track => track.getType());
  373. const nonPendingTracks = [ MEDIA_TYPE.AUDIO, MEDIA_TYPE.VIDEO ].filter(type => !tracksTypes.includes(type));
  374. APP.store.dispatch(gumPending(nonPendingTracks, IGUMPendingState.NONE));
  375. }
  376. export default {
  377. /**
  378. * Flag used to delay modification of the muted status of local media tracks
  379. * until those are created (or not, but at that point it's certain that
  380. * the tracks won't exist).
  381. */
  382. _localTracksInitialized: false,
  383. /**
  384. * Flag used to prevent the creation of another local video track in this.muteVideo if one is already in progress.
  385. */
  386. isCreatingLocalTrack: false,
  387. isSharingScreen: false,
  388. /**
  389. * Returns an object containing a promise which resolves with the created tracks &
  390. * the errors resulting from that process.
  391. * @param {object} options
  392. * @param {boolean} options.startAudioOnly=false - if <tt>true</tt> then
  393. * only audio track will be created and the audio only mode will be turned
  394. * on.
  395. * @param {boolean} options.startScreenSharing=false - if <tt>true</tt>
  396. * should start with screensharing instead of camera video.
  397. * @param {boolean} options.startWithAudioMuted - will start the conference
  398. * without any audio tracks.
  399. * @param {boolean} options.startWithVideoMuted - will start the conference
  400. * without any video tracks.
  401. * @returns {Promise<JitsiLocalTrack[]>, Object}
  402. */
  403. createInitialLocalTracks(options = {}) {
  404. const errors = {};
  405. // Always get a handle on the audio input device so that we have statistics (such as "No audio input" or
  406. // "Are you trying to speak?" ) even if the user joins the conference muted.
  407. const initialDevices = config.startSilent || config.disableInitialGUM ? [] : [ MEDIA_TYPE.AUDIO ];
  408. const requestedAudio = !config.disableInitialGUM;
  409. let requestedVideo = false;
  410. if (!config.disableInitialGUM
  411. && !options.startWithVideoMuted
  412. && !options.startAudioOnly
  413. && !options.startScreenSharing) {
  414. initialDevices.push(MEDIA_TYPE.VIDEO);
  415. requestedVideo = true;
  416. }
  417. if (!config.disableInitialGUM) {
  418. JitsiMeetJS.mediaDevices.addEventListener(
  419. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  420. browserName =>
  421. APP.store.dispatch(
  422. mediaPermissionPromptVisibilityChanged(true, browserName))
  423. );
  424. }
  425. let tryCreateLocalTracks = Promise.resolve([]);
  426. // On Electron there is no permission prompt for granting permissions. That's why we don't need to
  427. // spend much time displaying the overlay screen. If GUM is not resolved within 15 seconds it will
  428. // probably never resolve.
  429. const timeout = browser.isElectron() ? 15000 : 60000;
  430. const audioOptions = {
  431. devices: [ MEDIA_TYPE.AUDIO ],
  432. timeout,
  433. firePermissionPromptIsShownEvent: true
  434. };
  435. // Spot uses the _desktopSharingSourceDevice config option to use an external video input device label as
  436. // screenshare and calls getUserMedia instead of getDisplayMedia for capturing the media.
  437. if (options.startScreenSharing && config._desktopSharingSourceDevice) {
  438. tryCreateLocalTracks = this._createDesktopTrack()
  439. .then(([ desktopStream ]) => {
  440. if (!requestedAudio) {
  441. return [ desktopStream ];
  442. }
  443. return createLocalTracksF(audioOptions)
  444. .then(([ audioStream ]) =>
  445. [ desktopStream, audioStream ])
  446. .catch(error => {
  447. errors.audioOnlyError = error;
  448. return [ desktopStream ];
  449. });
  450. })
  451. .catch(error => {
  452. logger.error('Failed to obtain desktop stream', error);
  453. errors.screenSharingError = error;
  454. return requestedAudio ? createLocalTracksF(audioOptions) : [];
  455. })
  456. .catch(error => {
  457. errors.audioOnlyError = error;
  458. return [];
  459. });
  460. } else if (requestedAudio || requestedVideo) {
  461. APP.store.dispatch(gumPending(initialDevices, IGUMPendingState.PENDING_UNMUTE));
  462. tryCreateLocalTracks = createLocalTracksF({
  463. devices: initialDevices,
  464. timeout,
  465. firePermissionPromptIsShownEvent: true
  466. })
  467. .catch(async error => {
  468. if (error.name === JitsiTrackErrors.TIMEOUT && !browser.isElectron()) {
  469. errors.audioAndVideoError = error;
  470. return [];
  471. }
  472. // Retry with separate gUM calls.
  473. const gUMPromises = [];
  474. const tracks = [];
  475. if (requestedAudio) {
  476. gUMPromises.push(createLocalTracksF(audioOptions));
  477. }
  478. if (requestedVideo) {
  479. gUMPromises.push(createLocalTracksF({
  480. devices: [ MEDIA_TYPE.VIDEO ],
  481. timeout,
  482. firePermissionPromptIsShownEvent: true
  483. }));
  484. }
  485. const results = await Promise.allSettled(gUMPromises);
  486. let errorMsg;
  487. results.forEach((result, idx) => {
  488. if (result.status === 'fulfilled') {
  489. tracks.push(result.value[0]);
  490. } else {
  491. errorMsg = result.reason;
  492. const isAudio = idx === 0;
  493. logger.error(`${isAudio ? 'Audio' : 'Video'} track creation failed with error ${errorMsg}`);
  494. if (isAudio) {
  495. errors.audioOnlyError = errorMsg;
  496. } else {
  497. errors.videoOnlyError = errorMsg;
  498. }
  499. }
  500. });
  501. if (errors.audioOnlyError && errors.videoOnlyError) {
  502. errors.audioAndVideoError = errorMsg;
  503. }
  504. return tracks;
  505. });
  506. }
  507. // Hide the permissions prompt/overlay as soon as the tracks are created. Don't wait for the connection to
  508. // be established, as in some cases like when auth is required, connection won't be established until the user
  509. // inputs their credentials, but the dialog would be overshadowed by the overlay.
  510. tryCreateLocalTracks.then(tracks => {
  511. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false));
  512. return tracks;
  513. });
  514. return {
  515. tryCreateLocalTracks,
  516. errors
  517. };
  518. },
  519. /**
  520. * Displays error notifications according to the state carried by {@code errors} object returned
  521. * by {@link createInitialLocalTracks}.
  522. * @param {Object} errors - the errors (if any) returned by {@link createInitialLocalTracks}.
  523. *
  524. * @returns {void}
  525. * @private
  526. */
  527. _displayErrorsForCreateInitialLocalTracks(errors) {
  528. const {
  529. audioAndVideoError,
  530. audioOnlyError,
  531. screenSharingError,
  532. videoOnlyError
  533. } = errors;
  534. // FIXME If there will be microphone error it will cover any screensharing dialog, but it's still better than in
  535. // the reverse order where the screensharing dialog will sometimes be closing the microphone alert
  536. // ($.prompt.close(); is called). Need to figure out dialogs chaining to fix that.
  537. if (screenSharingError) {
  538. this._handleScreenSharingError(screenSharingError);
  539. }
  540. if (audioAndVideoError || audioOnlyError) {
  541. if (audioOnlyError || videoOnlyError) {
  542. // If both requests for 'audio' + 'video' and 'audio' only failed, we assume that there are some
  543. // problems with user's microphone and show corresponding dialog.
  544. APP.store.dispatch(notifyMicError(audioOnlyError));
  545. APP.store.dispatch(notifyCameraError(videoOnlyError));
  546. } else {
  547. // If request for 'audio' + 'video' failed, but request for 'audio' only was OK, we assume that we had
  548. // problems with camera and show corresponding dialog.
  549. APP.store.dispatch(notifyCameraError(audioAndVideoError));
  550. }
  551. }
  552. },
  553. startConference(tracks) {
  554. tracks.forEach(track => {
  555. if ((track.isAudioTrack() && this.isLocalAudioMuted())
  556. || (track.isVideoTrack() && this.isLocalVideoMuted())) {
  557. const mediaType = track.getType();
  558. sendAnalytics(
  559. createTrackMutedEvent(mediaType, 'initial mute'));
  560. logger.log(`${mediaType} mute: initially muted.`);
  561. track.mute();
  562. }
  563. });
  564. this._createRoom(tracks);
  565. // if user didn't give access to mic or camera or doesn't have
  566. // them at all, we mark corresponding toolbar buttons as muted,
  567. // so that the user can try unmute later on and add audio/video
  568. // to the conference
  569. if (!tracks.find(t => t.isAudioTrack())) {
  570. this.updateAudioIconEnabled();
  571. }
  572. if (!tracks.find(t => t.isVideoTrack())) {
  573. this.setVideoMuteStatus();
  574. }
  575. if (config.iAmRecorder) {
  576. this.recorder = new Recorder();
  577. }
  578. if (config.startSilent) {
  579. sendAnalytics(createStartSilentEvent());
  580. APP.store.dispatch(showNotification({
  581. descriptionKey: 'notify.startSilentDescription',
  582. titleKey: 'notify.startSilentTitle'
  583. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  584. }
  585. // XXX The API will take care of disconnecting from the XMPP
  586. // server (and, thus, leaving the room) on unload.
  587. return new Promise((resolve, reject) => {
  588. new ConferenceConnector(resolve, reject, this).connect();
  589. });
  590. },
  591. /**
  592. * Open new connection and join the conference when prejoin page is not enabled.
  593. * If prejoin page is enabled open an new connection in the background
  594. * and create local tracks.
  595. *
  596. * @param {{ roomName: string }} options
  597. * @returns {Promise}
  598. */
  599. async init({ roomName }) {
  600. const state = APP.store.getState();
  601. const initialOptions = {
  602. startAudioOnly: config.startAudioOnly,
  603. startScreenSharing: config.startScreenSharing,
  604. startWithAudioMuted: getStartWithAudioMuted(state) || isUserInteractionRequiredForUnmute(state),
  605. startWithVideoMuted: getStartWithVideoMuted(state) || isUserInteractionRequiredForUnmute(state)
  606. };
  607. this.roomName = roomName;
  608. try {
  609. // Initialize the device list first. This way, when creating tracks based on preferred devices, loose label
  610. // matching can be done in cases where the exact ID match is no longer available, such as -
  611. // 1. When the camera device has switched USB ports.
  612. // 2. When in startSilent mode we want to start with audio muted
  613. await this._initDeviceList();
  614. } catch (error) {
  615. logger.warn('initial device list initialization failed', error);
  616. }
  617. // Filter out the local tracks based on various config options, i.e., when user joins muted or is muted by
  618. // focus. However, audio track will always be created even though it is not added to the conference since we
  619. // want audio related features (noisy mic, talk while muted, etc.) to work even if the mic is muted.
  620. const handleInitialTracks = (options, tracks) => {
  621. let localTracks = tracks;
  622. // No local tracks are added when user joins as a visitor.
  623. if (iAmVisitor(state)) {
  624. return [];
  625. }
  626. if (options.startWithAudioMuted || room?.isStartAudioMuted()) {
  627. // Always add the track on Safari because of a known issue where audio playout doesn't happen
  628. // if the user joins audio and video muted, i.e., if there is no local media capture.
  629. if (browser.isWebKitBased()) {
  630. this.muteAudio(true, true);
  631. } else {
  632. localTracks = localTracks.filter(track => track.getType() !== MEDIA_TYPE.AUDIO);
  633. }
  634. }
  635. if (room?.isStartVideoMuted()) {
  636. localTracks = localTracks.filter(track => track.getType() !== MEDIA_TYPE.VIDEO);
  637. }
  638. return localTracks;
  639. };
  640. if (isPrejoinPageVisible(state)) {
  641. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(initialOptions);
  642. const localTracks = await tryCreateLocalTracks;
  643. // Initialize device list a second time to ensure device labels get populated in case of an initial gUM
  644. // acceptance; otherwise they may remain as empty strings.
  645. this._initDeviceList(true);
  646. if (isPrejoinPageVisible(state)) {
  647. APP.store.dispatch(gumPending([ MEDIA_TYPE.AUDIO, MEDIA_TYPE.VIDEO ], IGUMPendingState.NONE));
  648. return APP.store.dispatch(initPrejoin(localTracks, errors));
  649. }
  650. logger.debug('Prejoin screen no longer displayed at the time when tracks were created');
  651. this._displayErrorsForCreateInitialLocalTracks(errors);
  652. const tracks = handleInitialTracks(initialOptions, localTracks);
  653. setGUMPendingStateOnFailedTracks(tracks);
  654. return this._setLocalAudioVideoStreams(tracks);
  655. }
  656. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(initialOptions);
  657. return Promise.all([
  658. tryCreateLocalTracks.then(tr => {
  659. this._displayErrorsForCreateInitialLocalTracks(errors);
  660. return tr;
  661. }).then(tr => {
  662. this._initDeviceList(true);
  663. const filteredTracks = handleInitialTracks(initialOptions, tr);
  664. setGUMPendingStateOnFailedTracks(filteredTracks);
  665. return filteredTracks;
  666. }),
  667. APP.store.dispatch(connect())
  668. ]).then(([ tracks, _ ]) => {
  669. this.startConference(tracks).catch(logger.error);
  670. });
  671. },
  672. /**
  673. * Check if id is id of the local user.
  674. * @param {string} id id to check
  675. * @returns {boolean}
  676. */
  677. isLocalId(id) {
  678. return this.getMyUserId() === id;
  679. },
  680. /**
  681. * Tells whether the local video is muted or not.
  682. * @return {boolean}
  683. */
  684. isLocalVideoMuted() {
  685. // If the tracks are not ready, read from base/media state
  686. return this._localTracksInitialized
  687. ? isLocalTrackMuted(APP.store.getState()['features/base/tracks'], MEDIA_TYPE.VIDEO)
  688. : isVideoMutedByUser(APP.store);
  689. },
  690. /**
  691. * Verify if there is an ongoing system audio sharing session and apply to the provided track
  692. * as a AudioMixer effect.
  693. *
  694. * @param {*} localAudioTrack - track to which system audio track will be applied as an effect, most likely
  695. * microphone local audio track.
  696. */
  697. async _maybeApplyAudioMixerEffect(localAudioTrack) {
  698. // At the time of writing this comment there were two separate flows for toggling screen-sharing
  699. // and system audio sharing, the first is the legacy method using the functionality from conference.js
  700. // the second is used when both sendMultipleVideoStreams and sourceNameSignaling flags are set to true.
  701. // The second flow uses functionality from base/conference/middleware.web.js.
  702. // We check if system audio sharing was done using the first flow by verifying this._desktopAudioStream and
  703. // for the second by checking 'features/screen-share' state.
  704. const { desktopAudioTrack } = APP.store.getState()['features/screen-share'];
  705. const currentDesktopAudioTrack = this._desktopAudioStream || desktopAudioTrack;
  706. // If system audio is already being sent, mix it with the provided audio track.
  707. if (currentDesktopAudioTrack) {
  708. // In case system audio sharing was done in the absence of an initial mic audio track, there is no
  709. // AudioMixerEffect so we have to remove system audio track from the room before setting it as an effect.
  710. await room.replaceTrack(currentDesktopAudioTrack, null);
  711. this._mixerEffect = new AudioMixerEffect(currentDesktopAudioTrack);
  712. logger.debug('Mixing new audio track with existing screen audio track.');
  713. await localAudioTrack.setEffect(this._mixerEffect);
  714. }
  715. },
  716. /**
  717. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  718. * @param {boolean} mute true for mute and false for unmute.
  719. * @param {boolean} [showUI] when set to false will not display any error
  720. * dialogs in case of media permissions error.
  721. */
  722. muteAudio(mute, showUI = true) {
  723. const state = APP.store.getState();
  724. if (!mute
  725. && isUserInteractionRequiredForUnmute(state)) {
  726. logger.error('Unmuting audio requires user interaction');
  727. return;
  728. }
  729. // check for A/V Moderation when trying to unmute
  730. if (!mute && shouldShowModeratedNotification(MEDIA_TYPE.AUDIO, state)) {
  731. if (!isModerationNotificationDisplayed(MEDIA_TYPE.AUDIO, state)) {
  732. APP.store.dispatch(showModeratedNotification(MEDIA_TYPE.AUDIO));
  733. }
  734. return;
  735. }
  736. // Not ready to modify track's state yet
  737. if (!this._localTracksInitialized) {
  738. // This will only modify base/media.audio.muted which is then synced
  739. // up with the track at the end of local tracks initialization.
  740. muteLocalAudio(mute);
  741. this.updateAudioIconEnabled();
  742. return;
  743. } else if (this.isLocalAudioMuted() === mute) {
  744. // NO-OP
  745. return;
  746. }
  747. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  748. if (!localAudio && !mute) {
  749. const maybeShowErrorDialog = error => {
  750. showUI && APP.store.dispatch(notifyMicError(error));
  751. };
  752. APP.store.dispatch(gumPending([ MEDIA_TYPE.AUDIO ], IGUMPendingState.PENDING_UNMUTE));
  753. createLocalTracksF({ devices: [ 'audio' ] })
  754. .then(([ audioTrack ]) => audioTrack)
  755. .catch(error => {
  756. maybeShowErrorDialog(error);
  757. // Rollback the audio muted status by using null track
  758. return null;
  759. })
  760. .then(async audioTrack => {
  761. await this._maybeApplyAudioMixerEffect(audioTrack);
  762. return this.useAudioStream(audioTrack);
  763. })
  764. .finally(() => {
  765. APP.store.dispatch(gumPending([ MEDIA_TYPE.AUDIO ], IGUMPendingState.NONE));
  766. });
  767. } else {
  768. muteLocalAudio(mute);
  769. }
  770. },
  771. /**
  772. * Returns whether local audio is muted or not.
  773. * @returns {boolean}
  774. */
  775. isLocalAudioMuted() {
  776. // If the tracks are not ready, read from base/media state
  777. return this._localTracksInitialized
  778. ? isLocalTrackMuted(
  779. APP.store.getState()['features/base/tracks'],
  780. MEDIA_TYPE.AUDIO)
  781. : Boolean(
  782. APP.store.getState()['features/base/media'].audio.muted);
  783. },
  784. /**
  785. * Simulates toolbar button click for audio mute. Used by shortcuts
  786. * and API.
  787. * @param {boolean} [showUI] when set to false will not display any error
  788. * dialogs in case of media permissions error.
  789. */
  790. toggleAudioMuted(showUI = true) {
  791. this.muteAudio(!this.isLocalAudioMuted(), showUI);
  792. },
  793. /**
  794. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  795. * @param mute true for mute and false for unmute.
  796. * @param {boolean} [showUI] when set to false will not display any error
  797. * dialogs in case of media permissions error.
  798. */
  799. muteVideo(mute, showUI = true) {
  800. if (this.videoSwitchInProgress) {
  801. logger.warn('muteVideo - unable to perform operations while video switch is in progress');
  802. return;
  803. }
  804. const state = APP.store.getState();
  805. if (!mute
  806. && isUserInteractionRequiredForUnmute(state)) {
  807. logger.error('Unmuting video requires user interaction');
  808. return;
  809. }
  810. // check for A/V Moderation when trying to unmute and return early
  811. if (!mute && shouldShowModeratedNotification(MEDIA_TYPE.VIDEO, state)) {
  812. return;
  813. }
  814. // If not ready to modify track's state yet adjust the base/media
  815. if (!this._localTracksInitialized) {
  816. // This will only modify base/media.video.muted which is then synced
  817. // up with the track at the end of local tracks initialization.
  818. muteLocalVideo(mute);
  819. this.setVideoMuteStatus();
  820. return;
  821. } else if (this.isLocalVideoMuted() === mute) {
  822. // NO-OP
  823. return;
  824. }
  825. const localVideo = getLocalJitsiVideoTrack(state);
  826. if (!localVideo && !mute && !this.isCreatingLocalTrack) {
  827. const maybeShowErrorDialog = error => {
  828. showUI && APP.store.dispatch(notifyCameraError(error));
  829. };
  830. this.isCreatingLocalTrack = true;
  831. APP.store.dispatch(gumPending([ MEDIA_TYPE.VIDEO ], IGUMPendingState.PENDING_UNMUTE));
  832. // Try to create local video if there wasn't any.
  833. // This handles the case when user joined with no video
  834. // (dismissed screen sharing screen or in audio only mode), but
  835. // decided to add it later on by clicking on muted video icon or
  836. // turning off the audio only mode.
  837. //
  838. // FIXME when local track creation is moved to react/redux
  839. // it should take care of the use case described above
  840. createLocalTracksF({ devices: [ 'video' ] })
  841. .then(([ videoTrack ]) => videoTrack)
  842. .catch(error => {
  843. // FIXME should send some feedback to the API on error ?
  844. maybeShowErrorDialog(error);
  845. // Rollback the video muted status by using null track
  846. return null;
  847. })
  848. .then(videoTrack => {
  849. logger.debug(`muteVideo: calling useVideoStream for track: ${videoTrack}`);
  850. return this.useVideoStream(videoTrack);
  851. })
  852. .finally(() => {
  853. this.isCreatingLocalTrack = false;
  854. APP.store.dispatch(gumPending([ MEDIA_TYPE.VIDEO ], IGUMPendingState.NONE));
  855. });
  856. } else {
  857. // FIXME show error dialog if it fails (should be handled by react)
  858. muteLocalVideo(mute);
  859. }
  860. },
  861. /**
  862. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  863. * @param {boolean} [showUI] when set to false will not display any error
  864. * dialogs in case of media permissions error.
  865. * @param {boolean} ensureTrack - True if we want to ensure that a new track is
  866. * created if missing.
  867. */
  868. toggleVideoMuted(showUI = true, ensureTrack = false) {
  869. const mute = !this.isLocalVideoMuted();
  870. APP.store.dispatch(handleToggleVideoMuted(mute, showUI, ensureTrack));
  871. },
  872. /**
  873. * Retrieve list of ids of conference participants (without local user).
  874. * @returns {string[]}
  875. */
  876. listMembersIds() {
  877. return room.getParticipants().map(p => p.getId());
  878. },
  879. /**
  880. * Checks whether the participant identified by id is a moderator.
  881. * @id id to search for participant
  882. * @return {boolean} whether the participant is moderator
  883. */
  884. isParticipantModerator(id) {
  885. const user = room.getParticipantById(id);
  886. return user && user.isModerator();
  887. },
  888. /**
  889. * Retrieve list of conference participants (without local user).
  890. * @returns {JitsiParticipant[]}
  891. *
  892. * NOTE: Used by jitsi-meet-torture!
  893. */
  894. listMembers() {
  895. return room.getParticipants();
  896. },
  897. /**
  898. * Used by Jibri to detect when it's alone and the meeting should be terminated.
  899. */
  900. get membersCount() {
  901. return room.getParticipants()
  902. .filter(p => !p.isHidden() || !(config.iAmRecorder && p.isHiddenFromRecorder())).length + 1;
  903. },
  904. /**
  905. * Get speaker stats that track total dominant speaker time.
  906. *
  907. * @returns {object} A hash with keys being user ids and values being the
  908. * library's SpeakerStats model used for calculating time as dominant
  909. * speaker.
  910. */
  911. getSpeakerStats() {
  912. return room.getSpeakerStats();
  913. },
  914. // used by torture currently
  915. isJoined() {
  916. return room && room.isJoined();
  917. },
  918. getConnectionState() {
  919. return room && room.getConnectionState();
  920. },
  921. /**
  922. * Obtains current P2P ICE connection state.
  923. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  924. * P2P connection
  925. */
  926. getP2PConnectionState() {
  927. return room && room.getP2PConnectionState();
  928. },
  929. /**
  930. * Starts P2P (for tests only)
  931. * @private
  932. */
  933. _startP2P() {
  934. try {
  935. room && room.startP2PSession();
  936. } catch (error) {
  937. logger.error('Start P2P failed', error);
  938. throw error;
  939. }
  940. },
  941. /**
  942. * Stops P2P (for tests only)
  943. * @private
  944. */
  945. _stopP2P() {
  946. try {
  947. room && room.stopP2PSession();
  948. } catch (error) {
  949. logger.error('Stop P2P failed', error);
  950. throw error;
  951. }
  952. },
  953. /**
  954. * Checks whether or not our connection is currently in interrupted and
  955. * reconnect attempts are in progress.
  956. *
  957. * @returns {boolean} true if the connection is in interrupted state or
  958. * false otherwise.
  959. */
  960. isConnectionInterrupted() {
  961. return room.isConnectionInterrupted();
  962. },
  963. /**
  964. * Finds JitsiParticipant for given id.
  965. *
  966. * @param {string} id participant's identifier(MUC nickname).
  967. *
  968. * @returns {JitsiParticipant|null} participant instance for given id or
  969. * null if not found.
  970. */
  971. getParticipantById(id) {
  972. return room ? room.getParticipantById(id) : null;
  973. },
  974. getMyUserId() {
  975. return room && room.myUserId();
  976. },
  977. /**
  978. * Will be filled with values only when config.debug is enabled.
  979. * Its used by torture to check audio levels.
  980. */
  981. audioLevelsMap: {},
  982. /**
  983. * Returns the stored audio level (stored only if config.debug is enabled)
  984. * @param id the id for the user audio level to return (the id value is
  985. * returned for the participant using getMyUserId() method)
  986. */
  987. getPeerSSRCAudioLevel(id) {
  988. return this.audioLevelsMap[id];
  989. },
  990. /**
  991. * @return {number} the number of participants in the conference with at
  992. * least one track.
  993. */
  994. getNumberOfParticipantsWithTracks() {
  995. return room.getParticipants()
  996. .filter(p => p.getTracks().length > 0)
  997. .length;
  998. },
  999. /**
  1000. * Returns the stats.
  1001. */
  1002. getStats() {
  1003. return room.connectionQuality.getStats();
  1004. },
  1005. // end used by torture
  1006. /**
  1007. * Download logs, a function that can be called from console while
  1008. * debugging.
  1009. * @param filename (optional) specify target filename
  1010. */
  1011. saveLogs(filename = 'meetlog.json') {
  1012. // this can be called from console and will not have reference to this
  1013. // that's why we reference the global var
  1014. const logs = APP.connection.getLogs();
  1015. downloadJSON(logs, filename);
  1016. },
  1017. /**
  1018. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  1019. * desire to keep room private to this instance and (2) the need of other
  1020. * modules to send and receive commands to and from participants.
  1021. * Eventually, this instance remains in control with respect to the
  1022. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  1023. * JitsiConference) is to be used in the implementation of the Command(s)
  1024. * API of this instance.
  1025. */
  1026. commands: {
  1027. /**
  1028. * Known custom conference commands.
  1029. */
  1030. defaults: commands,
  1031. /**
  1032. * Receives notifications from other participants about commands aka
  1033. * custom events (sent by sendCommand or sendCommandOnce methods).
  1034. * @param command {String} the name of the command
  1035. * @param handler {Function} handler for the command
  1036. */
  1037. addCommandListener() {
  1038. // eslint-disable-next-line prefer-rest-params
  1039. room.addCommandListener(...arguments);
  1040. },
  1041. /**
  1042. * Removes command.
  1043. * @param name {String} the name of the command.
  1044. */
  1045. removeCommand() {
  1046. // eslint-disable-next-line prefer-rest-params
  1047. room.removeCommand(...arguments);
  1048. },
  1049. /**
  1050. * Sends command.
  1051. * @param name {String} the name of the command.
  1052. * @param values {Object} with keys and values that will be sent.
  1053. */
  1054. sendCommand() {
  1055. // eslint-disable-next-line prefer-rest-params
  1056. room.sendCommand(...arguments);
  1057. },
  1058. /**
  1059. * Sends command one time.
  1060. * @param name {String} the name of the command.
  1061. * @param values {Object} with keys and values that will be sent.
  1062. */
  1063. sendCommandOnce() {
  1064. // eslint-disable-next-line prefer-rest-params
  1065. room.sendCommandOnce(...arguments);
  1066. }
  1067. },
  1068. /**
  1069. * Used by the Breakout Rooms feature to join a breakout room or go back to the main room.
  1070. */
  1071. async joinRoom(roomName, options) {
  1072. APP.store.dispatch(conferenceWillInit());
  1073. // Restore initial state.
  1074. this._localTracksInitialized = false;
  1075. this.isSharingScreen = false;
  1076. this.roomName = roomName;
  1077. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(options);
  1078. const localTracks = await tryCreateLocalTracks;
  1079. this._displayErrorsForCreateInitialLocalTracks(errors);
  1080. localTracks.forEach(track => {
  1081. if ((track.isAudioTrack() && this.isLocalAudioMuted())
  1082. || (track.isVideoTrack() && this.isLocalVideoMuted())) {
  1083. track.mute();
  1084. }
  1085. });
  1086. this._createRoom(localTracks);
  1087. return new Promise((resolve, reject) => {
  1088. new ConferenceConnector(resolve, reject, this).connect();
  1089. });
  1090. },
  1091. _createRoom(localTracks) {
  1092. room = APP.connection.initJitsiConference(APP.conference.roomName, this._getConferenceOptions());
  1093. // Filter out the tracks that are muted (except on Safari).
  1094. const tracks = browser.isWebKitBased() ? localTracks : localTracks.filter(track => !track.isMuted());
  1095. this._setLocalAudioVideoStreams(tracks);
  1096. this._room = room; // FIXME do not use this
  1097. APP.store.dispatch(_conferenceWillJoin(room));
  1098. sendLocalParticipant(APP.store, room);
  1099. this._setupListeners();
  1100. },
  1101. /**
  1102. * Sets local video and audio streams.
  1103. * @param {JitsiLocalTrack[]} tracks=[]
  1104. * @returns {Promise[]}
  1105. * @private
  1106. */
  1107. _setLocalAudioVideoStreams(tracks = []) {
  1108. const { dispatch } = APP.store;
  1109. const pendingGUMDevicesToRemove = [];
  1110. const promises = tracks.map(track => {
  1111. if (track.isAudioTrack()) {
  1112. pendingGUMDevicesToRemove.push(MEDIA_TYPE.AUDIO);
  1113. return this.useAudioStream(track);
  1114. } else if (track.isVideoTrack()) {
  1115. logger.debug(`_setLocalAudioVideoStreams is calling useVideoStream with track: ${track}`);
  1116. pendingGUMDevicesToRemove.push(MEDIA_TYPE.VIDEO);
  1117. return this.useVideoStream(track);
  1118. }
  1119. logger.error('Ignored not an audio nor a video track: ', track);
  1120. return Promise.resolve();
  1121. });
  1122. return Promise.allSettled(promises).then(() => {
  1123. if (pendingGUMDevicesToRemove.length > 0) {
  1124. dispatch(gumPending(pendingGUMDevicesToRemove, IGUMPendingState.NONE));
  1125. }
  1126. this._localTracksInitialized = true;
  1127. logger.log(`Initialized with ${tracks.length} local tracks`);
  1128. });
  1129. },
  1130. _getConferenceOptions() {
  1131. const options = getConferenceOptions(APP.store.getState());
  1132. options.createVADProcessor = createRnnoiseProcessor;
  1133. return options;
  1134. },
  1135. /**
  1136. * Start using provided video stream.
  1137. * Stops previous video stream.
  1138. * @param {JitsiLocalTrack} newTrack - new track to use or null
  1139. * @returns {Promise}
  1140. */
  1141. useVideoStream(newTrack) {
  1142. const state = APP.store.getState();
  1143. logger.debug(`useVideoStream: ${newTrack}`);
  1144. return new Promise((resolve, reject) => {
  1145. _replaceLocalVideoTrackQueue.enqueue(onFinish => {
  1146. const oldTrack = getLocalJitsiVideoTrack(state);
  1147. logger.debug(`useVideoStream: Replacing ${oldTrack} with ${newTrack}`);
  1148. if (oldTrack === newTrack || (!oldTrack && !newTrack)) {
  1149. resolve();
  1150. onFinish();
  1151. return;
  1152. }
  1153. // Add the track to the conference if there is no existing track, replace it otherwise.
  1154. const trackAction = oldTrack
  1155. ? replaceLocalTrack(oldTrack, newTrack, room)
  1156. : addLocalTrack(newTrack);
  1157. APP.store.dispatch(trackAction)
  1158. .then(() => {
  1159. this.setVideoMuteStatus();
  1160. })
  1161. .then(resolve)
  1162. .catch(error => {
  1163. logger.error(`useVideoStream failed: ${error}`);
  1164. reject(error);
  1165. })
  1166. .then(onFinish);
  1167. });
  1168. });
  1169. },
  1170. /**
  1171. * Start using provided audio stream.
  1172. * Stops previous audio stream.
  1173. * @param {JitsiLocalTrack} newTrack - new track to use or null
  1174. * @returns {Promise}
  1175. */
  1176. useAudioStream(newTrack) {
  1177. return new Promise((resolve, reject) => {
  1178. _replaceLocalAudioTrackQueue.enqueue(onFinish => {
  1179. const oldTrack = getLocalJitsiAudioTrack(APP.store.getState());
  1180. if (oldTrack === newTrack) {
  1181. resolve();
  1182. onFinish();
  1183. return;
  1184. }
  1185. APP.store.dispatch(
  1186. replaceLocalTrack(oldTrack, newTrack, room))
  1187. .then(() => {
  1188. this.updateAudioIconEnabled();
  1189. })
  1190. .then(resolve)
  1191. .catch(reject)
  1192. .then(onFinish);
  1193. });
  1194. });
  1195. },
  1196. /**
  1197. * Returns whether or not the conference is currently in audio only mode.
  1198. *
  1199. * @returns {boolean}
  1200. */
  1201. isAudioOnly() {
  1202. return Boolean(APP.store.getState()['features/base/audio-only'].enabled);
  1203. },
  1204. videoSwitchInProgress: false,
  1205. /**
  1206. * This fields stores a handler which will create a Promise which turns off
  1207. * the screen sharing and restores the previous video state (was there
  1208. * any video, before switching to screen sharing ? was it muted ?).
  1209. *
  1210. * Once called this fields is cleared to <tt>null</tt>.
  1211. * @type {Function|null}
  1212. */
  1213. _untoggleScreenSharing: null,
  1214. /**
  1215. * Creates a Promise which turns off the screen sharing and restores
  1216. * the previous state described by the arguments.
  1217. *
  1218. * This method is bound to the appropriate values, after switching to screen
  1219. * sharing and stored in {@link _untoggleScreenSharing}.
  1220. *
  1221. * @param {boolean} didHaveVideo indicates if there was a camera video being
  1222. * used, before switching to screen sharing.
  1223. * @param {boolean} ignoreDidHaveVideo indicates if the camera video should be
  1224. * ignored when switching screen sharing off.
  1225. * @return {Promise} resolved after the screen sharing is turned off, or
  1226. * rejected with some error (no idea what kind of error, possible GUM error)
  1227. * in case it fails.
  1228. * @private
  1229. */
  1230. async _turnScreenSharingOff(didHaveVideo, ignoreDidHaveVideo) {
  1231. this._untoggleScreenSharing = null;
  1232. this.videoSwitchInProgress = true;
  1233. APP.store.dispatch(stopReceiver());
  1234. this._stopProxyConnection();
  1235. APP.store.dispatch(toggleScreenshotCaptureSummary(false));
  1236. const tracks = APP.store.getState()['features/base/tracks'];
  1237. const duration = getLocalVideoTrack(tracks)?.jitsiTrack.getDuration() ?? 0;
  1238. // If system audio was also shared stop the AudioMixerEffect and dispose of the desktop audio track.
  1239. if (this._mixerEffect) {
  1240. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1241. await localAudio.setEffect(undefined);
  1242. await this._desktopAudioStream.dispose();
  1243. this._mixerEffect = undefined;
  1244. this._desktopAudioStream = undefined;
  1245. // In case there was no local audio when screen sharing was started the fact that we set the audio stream to
  1246. // null will take care of the desktop audio stream cleanup.
  1247. } else if (this._desktopAudioStream) {
  1248. await room.replaceTrack(this._desktopAudioStream, null);
  1249. this._desktopAudioStream.dispose();
  1250. this._desktopAudioStream = undefined;
  1251. }
  1252. APP.store.dispatch(setScreenAudioShareState(false));
  1253. let promise;
  1254. if (didHaveVideo && !ignoreDidHaveVideo) {
  1255. promise = createLocalTracksF({ devices: [ 'video' ] })
  1256. .then(([ stream ]) => {
  1257. logger.debug(`_turnScreenSharingOff using ${stream} for useVideoStream`);
  1258. return this.useVideoStream(stream);
  1259. })
  1260. .catch(error => {
  1261. logger.error('failed to switch back to local video', error);
  1262. return this.useVideoStream(null).then(() =>
  1263. // Still fail with the original err
  1264. Promise.reject(error)
  1265. );
  1266. });
  1267. } else {
  1268. promise = this.useVideoStream(null);
  1269. }
  1270. return promise.then(
  1271. () => {
  1272. this.videoSwitchInProgress = false;
  1273. sendAnalytics(createScreenSharingEvent('stopped',
  1274. duration === 0 ? null : duration));
  1275. logger.info('Screen sharing stopped.');
  1276. },
  1277. error => {
  1278. this.videoSwitchInProgress = false;
  1279. logger.error(`_turnScreenSharingOff failed: ${error}`);
  1280. throw error;
  1281. });
  1282. },
  1283. /**
  1284. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1285. *
  1286. * @param {Object} [options] - Screen sharing options that will be passed to
  1287. * createLocalTracks.
  1288. * @param {Object} [options.desktopSharing]
  1289. * @param {Object} [options.desktopStream] - An existing desktop stream to
  1290. * use instead of creating a new desktop stream.
  1291. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1292. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1293. * {@link JitsiTrackError}.
  1294. *
  1295. * @private
  1296. */
  1297. _createDesktopTrack(options = {}) {
  1298. const didHaveVideo = !this.isLocalVideoMuted();
  1299. const getDesktopStreamPromise = options.desktopStream
  1300. ? Promise.resolve([ options.desktopStream ])
  1301. : createLocalTracksF({
  1302. desktopSharingSourceDevice: options.desktopSharingSources
  1303. ? null : config._desktopSharingSourceDevice,
  1304. desktopSharingSources: options.desktopSharingSources,
  1305. devices: [ 'desktop' ]
  1306. });
  1307. return getDesktopStreamPromise.then(desktopStreams => {
  1308. // Stores the "untoggle" handler which remembers whether was
  1309. // there any video before and whether was it muted.
  1310. this._untoggleScreenSharing
  1311. = this._turnScreenSharingOff.bind(this, didHaveVideo);
  1312. const desktopVideoStream = desktopStreams.find(stream => stream.getType() === MEDIA_TYPE.VIDEO);
  1313. const desktopAudioStream = desktopStreams.find(stream => stream.getType() === MEDIA_TYPE.AUDIO);
  1314. if (desktopAudioStream) {
  1315. desktopAudioStream.on(
  1316. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1317. () => {
  1318. logger.debug(`Local screensharing audio track stopped. ${this.isSharingScreen}`);
  1319. // Handle case where screen share was stopped from the browsers 'screen share in progress'
  1320. // window. If audio screen sharing is stopped via the normal UX flow this point shouldn't
  1321. // be reached.
  1322. isScreenAudioShared(APP.store.getState())
  1323. && this._untoggleScreenSharing
  1324. && this._untoggleScreenSharing();
  1325. }
  1326. );
  1327. }
  1328. if (desktopVideoStream) {
  1329. desktopVideoStream.on(
  1330. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1331. () => {
  1332. logger.debug(`Local screensharing track stopped. ${this.isSharingScreen}`);
  1333. // If the stream was stopped during screen sharing
  1334. // session then we should switch back to video.
  1335. this.isSharingScreen
  1336. && this._untoggleScreenSharing
  1337. && this._untoggleScreenSharing();
  1338. }
  1339. );
  1340. }
  1341. return desktopStreams;
  1342. }, error => {
  1343. throw error;
  1344. });
  1345. },
  1346. /**
  1347. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1348. * trying to create screensharing track. It will either do nothing if
  1349. * the dialog was canceled on user's request or display an error if
  1350. * screensharing couldn't be started.
  1351. * @param {JitsiTrackError} error - The error returned by
  1352. * {@link _createDesktopTrack} Promise.
  1353. * @private
  1354. */
  1355. _handleScreenSharingError(error) {
  1356. if (error.name === JitsiTrackErrors.SCREENSHARING_USER_CANCELED) {
  1357. return;
  1358. }
  1359. logger.error('failed to share local desktop', error);
  1360. // Handling:
  1361. // JitsiTrackErrors.CONSTRAINT_FAILED
  1362. // JitsiTrackErrors.PERMISSION_DENIED
  1363. // JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR
  1364. // and any other
  1365. let descriptionKey;
  1366. let titleKey;
  1367. if (error.name === JitsiTrackErrors.PERMISSION_DENIED) {
  1368. descriptionKey = 'dialog.screenSharingPermissionDeniedError';
  1369. titleKey = 'dialog.screenSharingFailedTitle';
  1370. } else if (error.name === JitsiTrackErrors.CONSTRAINT_FAILED) {
  1371. descriptionKey = 'dialog.cameraConstraintFailedError';
  1372. titleKey = 'deviceError.cameraError';
  1373. } else if (error.name === JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR) {
  1374. descriptionKey = 'dialog.screenSharingFailed';
  1375. titleKey = 'dialog.screenSharingFailedTitle';
  1376. } else if (error === AUDIO_ONLY_SCREEN_SHARE_NO_TRACK) {
  1377. descriptionKey = 'notify.screenShareNoAudio';
  1378. titleKey = 'notify.screenShareNoAudioTitle';
  1379. }
  1380. APP.store.dispatch(showErrorNotification({
  1381. descriptionKey,
  1382. titleKey
  1383. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  1384. },
  1385. /**
  1386. * Setup interaction between conference and UI.
  1387. */
  1388. _setupListeners() {
  1389. // add local streams when joined to the conference
  1390. room.on(JitsiConferenceEvents.CONFERENCE_JOINED, () => {
  1391. this._onConferenceJoined();
  1392. });
  1393. room.on(
  1394. JitsiConferenceEvents.CONFERENCE_JOIN_IN_PROGRESS,
  1395. () => APP.store.dispatch(conferenceJoinInProgress(room)));
  1396. room.on(
  1397. JitsiConferenceEvents.CONFERENCE_LEFT,
  1398. (...args) => {
  1399. APP.store.dispatch(conferenceTimestampChanged(0));
  1400. APP.store.dispatch(conferenceLeft(room, ...args));
  1401. });
  1402. room.on(
  1403. JitsiConferenceEvents.CONFERENCE_UNIQUE_ID_SET,
  1404. (...args) => {
  1405. // Preserve the sessionId so that the value is accessible even after room
  1406. // is disconnected.
  1407. room.sessionId = room.getMeetingUniqueId();
  1408. APP.store.dispatch(conferenceUniqueIdSet(room, ...args));
  1409. });
  1410. // we want to ignore this event in case of tokenAuthUrl config
  1411. // we are deprecating this and at some point will get rid of it
  1412. if (!config.tokenAuthUrl) {
  1413. room.on(
  1414. JitsiConferenceEvents.AUTH_STATUS_CHANGED,
  1415. (authEnabled, authLogin) =>
  1416. APP.store.dispatch(authStatusChanged(authEnabled, authLogin)));
  1417. }
  1418. room.on(JitsiConferenceEvents.PARTCIPANT_FEATURES_CHANGED, user => {
  1419. APP.store.dispatch(updateRemoteParticipantFeatures(user));
  1420. });
  1421. room.on(JitsiConferenceEvents.USER_JOINED, (id, user) => {
  1422. if (config.iAmRecorder && user.isHiddenFromRecorder()) {
  1423. return;
  1424. }
  1425. // The logic shared between RN and web.
  1426. commonUserJoinedHandling(APP.store, room, user);
  1427. if (user.isHidden()) {
  1428. return;
  1429. }
  1430. APP.store.dispatch(updateRemoteParticipantFeatures(user));
  1431. logger.log(`USER ${id} connected:`, user);
  1432. APP.UI.addUser(user);
  1433. });
  1434. room.on(JitsiConferenceEvents.USER_LEFT, (id, user) => {
  1435. // The logic shared between RN and web.
  1436. commonUserLeftHandling(APP.store, room, user);
  1437. if (user.isHidden()) {
  1438. return;
  1439. }
  1440. logger.log(`USER ${id} LEFT:`, user);
  1441. });
  1442. room.on(JitsiConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1443. APP.store.dispatch(participantPresenceChanged(id, status));
  1444. const user = room.getParticipantById(id);
  1445. if (user) {
  1446. APP.UI.updateUserStatus(user, status);
  1447. }
  1448. });
  1449. room.on(JitsiConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1450. if (this.isLocalId(id)) {
  1451. logger.info(`My role changed, new role: ${role}`);
  1452. if (role === 'moderator') {
  1453. APP.store.dispatch(maybeSetLobbyChatMessageListener());
  1454. }
  1455. APP.store.dispatch(localParticipantRoleChanged(role));
  1456. APP.API.notifyUserRoleChanged(id, role);
  1457. } else {
  1458. APP.store.dispatch(participantRoleChanged(id, role));
  1459. }
  1460. });
  1461. room.on(JitsiConferenceEvents.TRACK_ADDED, track => {
  1462. if (!track || track.isLocal()) {
  1463. return;
  1464. }
  1465. if (config.iAmRecorder) {
  1466. const participant = room.getParticipantById(track.getParticipantId());
  1467. if (participant.isHiddenFromRecorder()) {
  1468. return;
  1469. }
  1470. }
  1471. APP.store.dispatch(trackAdded(track));
  1472. });
  1473. room.on(JitsiConferenceEvents.TRACK_REMOVED, track => {
  1474. if (!track || track.isLocal()) {
  1475. return;
  1476. }
  1477. APP.store.dispatch(trackRemoved(track));
  1478. });
  1479. room.on(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1480. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1481. let newLvl = lvl;
  1482. if (this.isLocalId(id)) {
  1483. APP.store.dispatch(localParticipantAudioLevelChanged(lvl));
  1484. }
  1485. if (this.isLocalId(id) && localAudio?.isMuted()) {
  1486. newLvl = 0;
  1487. }
  1488. if (config.debug) {
  1489. this.audioLevelsMap[id] = newLvl;
  1490. if (config.debugAudioLevels) {
  1491. logger.log(`AudioLevel:${id}/${newLvl}`);
  1492. }
  1493. }
  1494. APP.UI.setAudioLevel(id, newLvl);
  1495. });
  1496. room.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED, (track, participantThatMutedUs) => {
  1497. if (participantThatMutedUs) {
  1498. APP.store.dispatch(participantMutedUs(participantThatMutedUs, track));
  1499. if (this.isSharingScreen && track.isVideoTrack()) {
  1500. logger.debug('TRACK_MUTE_CHANGED while screen sharing');
  1501. this._turnScreenSharingOff(false);
  1502. }
  1503. }
  1504. });
  1505. room.on(JitsiConferenceEvents.TRACK_UNMUTE_REJECTED, track => APP.store.dispatch(destroyLocalTracks(track)));
  1506. room.on(JitsiConferenceEvents.SUBJECT_CHANGED,
  1507. subject => APP.store.dispatch(conferenceSubjectChanged(subject)));
  1508. room.on(
  1509. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1510. (leavingIds, enteringIds) =>
  1511. APP.UI.handleLastNEndpoints(leavingIds, enteringIds));
  1512. room.on(
  1513. JitsiConferenceEvents.P2P_STATUS,
  1514. (jitsiConference, p2p) =>
  1515. APP.store.dispatch(p2pStatusChanged(p2p)));
  1516. room.on(
  1517. JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED,
  1518. (dominant, previous, silence) => {
  1519. APP.store.dispatch(dominantSpeakerChanged(dominant, previous, Boolean(silence), room));
  1520. });
  1521. room.on(
  1522. JitsiConferenceEvents.CONFERENCE_CREATED_TIMESTAMP,
  1523. conferenceTimestamp => APP.store.dispatch(conferenceTimestampChanged(conferenceTimestamp)));
  1524. room.on(
  1525. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1526. (id, displayName) => {
  1527. const formattedDisplayName
  1528. = getNormalizedDisplayName(displayName);
  1529. const state = APP.store.getState();
  1530. const {
  1531. defaultRemoteDisplayName
  1532. } = state['features/base/config'];
  1533. APP.store.dispatch(participantUpdated({
  1534. conference: room,
  1535. id,
  1536. name: formattedDisplayName
  1537. }));
  1538. const virtualScreenshareParticipantId = getVirtualScreenshareParticipantByOwnerId(state, id)?.id;
  1539. if (virtualScreenshareParticipantId) {
  1540. APP.store.dispatch(
  1541. screenshareParticipantDisplayNameChanged(virtualScreenshareParticipantId, formattedDisplayName)
  1542. );
  1543. }
  1544. APP.API.notifyDisplayNameChanged(id, {
  1545. displayName: formattedDisplayName,
  1546. formattedDisplayName:
  1547. appendSuffix(
  1548. formattedDisplayName
  1549. || defaultRemoteDisplayName)
  1550. });
  1551. }
  1552. );
  1553. room.on(
  1554. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1555. (id, botType) => {
  1556. APP.store.dispatch(participantUpdated({
  1557. conference: room,
  1558. id,
  1559. botType
  1560. }));
  1561. }
  1562. );
  1563. room.on(
  1564. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1565. (participant, data) => {
  1566. APP.store.dispatch(endpointMessageReceived(participant, data));
  1567. if (data?.name === ENDPOINT_TEXT_MESSAGE_NAME) {
  1568. APP.API.notifyEndpointTextMessageReceived({
  1569. senderInfo: {
  1570. jid: participant.getJid(),
  1571. id: participant.getId()
  1572. },
  1573. eventData: data
  1574. });
  1575. }
  1576. });
  1577. room.on(
  1578. JitsiConferenceEvents.NON_PARTICIPANT_MESSAGE_RECEIVED,
  1579. (id, data) => {
  1580. APP.store.dispatch(nonParticipantMessageReceived(id, data));
  1581. APP.API.notifyNonParticipantMessageReceived(id, data);
  1582. });
  1583. room.on(
  1584. JitsiConferenceEvents.LOCK_STATE_CHANGED,
  1585. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1586. room.on(JitsiConferenceEvents.KICKED, (participant, reason, isReplaced) => {
  1587. if (isReplaced) {
  1588. // this event triggers when the local participant is kicked, `participant`
  1589. // is the kicker. In replace participant case, kicker is undefined,
  1590. // as the server initiated it. We mark in store the local participant
  1591. // as being replaced based on jwt.
  1592. const localParticipant = getLocalParticipant(APP.store.getState());
  1593. APP.store.dispatch(participantUpdated({
  1594. conference: room,
  1595. id: localParticipant.id,
  1596. isReplaced
  1597. }));
  1598. // we send readyToClose when kicked participant is replace so that
  1599. // embedding app can choose to dispose the iframe API on the handler.
  1600. APP.API.notifyReadyToClose();
  1601. }
  1602. APP.store.dispatch(kickedOut(room, participant));
  1603. });
  1604. room.on(JitsiConferenceEvents.PARTICIPANT_KICKED, (kicker, kicked) => {
  1605. APP.store.dispatch(participantKicked(kicker, kicked));
  1606. });
  1607. room.on(JitsiConferenceEvents.PARTICIPANT_SOURCE_UPDATED,
  1608. jitsiParticipant => {
  1609. APP.store.dispatch(participantSourcesUpdated(jitsiParticipant));
  1610. });
  1611. room.on(JitsiConferenceEvents.SUSPEND_DETECTED, () => {
  1612. APP.store.dispatch(suspendDetected());
  1613. });
  1614. room.on(
  1615. JitsiConferenceEvents.AUDIO_UNMUTE_PERMISSIONS_CHANGED,
  1616. disableAudioMuteChange => {
  1617. APP.store.dispatch(setAudioUnmutePermissions(disableAudioMuteChange));
  1618. });
  1619. room.on(
  1620. JitsiConferenceEvents.VIDEO_UNMUTE_PERMISSIONS_CHANGED,
  1621. disableVideoMuteChange => {
  1622. APP.store.dispatch(setVideoUnmutePermissions(disableVideoMuteChange));
  1623. });
  1624. room.on(
  1625. JitsiE2ePingEvents.E2E_RTT_CHANGED,
  1626. (...args) => APP.store.dispatch(e2eRttChanged(...args)));
  1627. APP.UI.addListener(UIEvents.AUDIO_MUTED, muted => {
  1628. this.muteAudio(muted);
  1629. });
  1630. APP.UI.addListener(UIEvents.VIDEO_MUTED, (muted, showUI = false) => {
  1631. this.muteVideo(muted, showUI);
  1632. });
  1633. room.addCommandListener(this.commands.defaults.ETHERPAD,
  1634. ({ value }) => {
  1635. APP.UI.initEtherpad(value);
  1636. }
  1637. );
  1638. APP.UI.addListener(UIEvents.EMAIL_CHANGED,
  1639. this.changeLocalEmail.bind(this));
  1640. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1641. APP.store.dispatch(participantUpdated({
  1642. conference: room,
  1643. id: from,
  1644. email: data.value
  1645. }));
  1646. });
  1647. room.addCommandListener(
  1648. this.commands.defaults.AVATAR_URL,
  1649. (data, from) => {
  1650. APP.store.dispatch(
  1651. participantUpdated({
  1652. conference: room,
  1653. id: from,
  1654. avatarURL: data.value
  1655. }));
  1656. });
  1657. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1658. this.changeLocalDisplayName.bind(this));
  1659. room.on(
  1660. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  1661. ({ audio, video }) => {
  1662. APP.store.dispatch(
  1663. onStartMutedPolicyChanged(audio, video));
  1664. }
  1665. );
  1666. room.on(JitsiConferenceEvents.STARTED_MUTED, () => {
  1667. const audioMuted = room.isStartAudioMuted();
  1668. const videoMuted = room.isStartVideoMuted();
  1669. const localTracks = getLocalTracks(APP.store.getState()['features/base/tracks']);
  1670. const promises = [];
  1671. APP.store.dispatch(setAudioMuted(audioMuted));
  1672. APP.store.dispatch(setVideoMuted(videoMuted));
  1673. // Remove the tracks from the peerconnection.
  1674. for (const track of localTracks) {
  1675. // Always add the track on Safari because of a known issue where audio playout doesn't happen
  1676. // if the user joins audio and video muted, i.e., if there is no local media capture.
  1677. if (audioMuted && track.jitsiTrack?.getType() === MEDIA_TYPE.AUDIO && !browser.isWebKitBased()) {
  1678. promises.push(this.useAudioStream(null));
  1679. }
  1680. if (videoMuted && track.jitsiTrack?.getType() === MEDIA_TYPE.VIDEO) {
  1681. promises.push(this.useVideoStream(null));
  1682. }
  1683. }
  1684. Promise.allSettled(promises)
  1685. .then(() => {
  1686. APP.store.dispatch(showNotification({
  1687. titleKey: 'notify.mutedTitle',
  1688. descriptionKey: 'notify.muted'
  1689. }, NOTIFICATION_TIMEOUT_TYPE.SHORT));
  1690. });
  1691. });
  1692. room.on(
  1693. JitsiConferenceEvents.DATA_CHANNEL_OPENED, () => {
  1694. APP.store.dispatch(dataChannelOpened());
  1695. APP.store.dispatch(hideNotification(DATA_CHANNEL_CLOSED_NOTIFICATION_ID));
  1696. }
  1697. );
  1698. room.on(
  1699. JitsiConferenceEvents.DATA_CHANNEL_CLOSED, ev => {
  1700. APP.store.dispatch(dataChannelClosed(ev.code, ev.reason));
  1701. APP.store.dispatch(showWarningNotification({
  1702. descriptionKey: 'notify.dataChannelClosedDescription',
  1703. titleKey: 'notify.dataChannelClosed',
  1704. uid: DATA_CHANNEL_CLOSED_NOTIFICATION_ID
  1705. }, NOTIFICATION_TIMEOUT_TYPE.STICKY));
  1706. }
  1707. );
  1708. // call hangup
  1709. APP.UI.addListener(UIEvents.HANGUP, () => {
  1710. this.hangup(true);
  1711. });
  1712. APP.UI.addListener(
  1713. UIEvents.VIDEO_DEVICE_CHANGED,
  1714. cameraDeviceId => {
  1715. const videoWasMuted = this.isLocalVideoMuted();
  1716. const localVideoTrack = getLocalJitsiVideoTrack(APP.store.getState());
  1717. if (localVideoTrack?.getDeviceId() === cameraDeviceId) {
  1718. return;
  1719. }
  1720. sendAnalytics(createDeviceChangedEvent('video', 'input'));
  1721. createLocalTracksF({
  1722. devices: [ 'video' ],
  1723. cameraDeviceId
  1724. })
  1725. .then(([ stream ]) => {
  1726. // if we are in audio only mode or video was muted before
  1727. // changing device, then mute
  1728. if (this.isAudioOnly() || videoWasMuted) {
  1729. return stream.mute()
  1730. .then(() => stream);
  1731. }
  1732. return stream;
  1733. })
  1734. .then(stream => {
  1735. logger.info(`Switching the local video device to ${cameraDeviceId}.`);
  1736. return this.useVideoStream(stream);
  1737. })
  1738. .catch(error => {
  1739. logger.error(`Failed to switch to selected camera:${cameraDeviceId}, error:${error}`);
  1740. return APP.store.dispatch(notifyCameraError(error));
  1741. });
  1742. }
  1743. );
  1744. APP.UI.addListener(
  1745. UIEvents.AUDIO_DEVICE_CHANGED,
  1746. async micDeviceId => {
  1747. const audioWasMuted = this.isLocalAudioMuted();
  1748. // Disable noise suppression if it was enabled on the previous track.
  1749. await APP.store.dispatch(setNoiseSuppressionEnabled(false));
  1750. // When the 'default' mic needs to be selected, we need to pass the real device id to gUM instead of
  1751. // 'default' in order to get the correct MediaStreamTrack from chrome because of the following bug.
  1752. // https://bugs.chromium.org/p/chromium/issues/detail?id=997689.
  1753. const isDefaultMicSelected = micDeviceId === 'default';
  1754. const selectedDeviceId = isDefaultMicSelected
  1755. ? getDefaultDeviceId(APP.store.getState(), 'audioInput')
  1756. : micDeviceId;
  1757. logger.info(`Switching audio input device to ${selectedDeviceId}`);
  1758. sendAnalytics(createDeviceChangedEvent('audio', 'input'));
  1759. createLocalTracksF({
  1760. devices: [ 'audio' ],
  1761. micDeviceId: selectedDeviceId
  1762. })
  1763. .then(([ stream ]) => {
  1764. // if audio was muted before changing the device, mute
  1765. // with the new device
  1766. if (audioWasMuted) {
  1767. return stream.mute()
  1768. .then(() => stream);
  1769. }
  1770. return stream;
  1771. })
  1772. .then(async stream => {
  1773. await this._maybeApplyAudioMixerEffect(stream);
  1774. return this.useAudioStream(stream);
  1775. })
  1776. .then(() => {
  1777. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1778. if (localAudio && isDefaultMicSelected) {
  1779. // workaround for the default device to be shown as selected in the
  1780. // settings even when the real device id was passed to gUM because of the
  1781. // above mentioned chrome bug.
  1782. localAudio._realDeviceId = localAudio.deviceId = 'default';
  1783. }
  1784. })
  1785. .catch(err => {
  1786. logger.error(`Failed to switch to selected audio input device ${selectedDeviceId}, error=${err}`);
  1787. APP.store.dispatch(notifyMicError(err));
  1788. });
  1789. }
  1790. );
  1791. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, () => {
  1792. // Immediately update the UI by having remote videos and the large video update themselves.
  1793. const displayedUserId = APP.UI.getLargeVideoID();
  1794. if (displayedUserId) {
  1795. APP.UI.updateLargeVideo(displayedUserId, true);
  1796. }
  1797. });
  1798. },
  1799. /**
  1800. * Cleanups local conference on suspend.
  1801. */
  1802. onSuspendDetected() {
  1803. // After wake up, we will be in a state where conference is left
  1804. // there will be dialog shown to user.
  1805. // We do not want video/audio as we show an overlay and after it
  1806. // user need to rejoin or close, while waking up we can detect
  1807. // camera wakeup as a problem with device.
  1808. // We also do not care about device change, which happens
  1809. // on resume after suspending PC.
  1810. if (this.deviceChangeListener) {
  1811. JitsiMeetJS.mediaDevices.removeEventListener(
  1812. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  1813. this.deviceChangeListener);
  1814. }
  1815. },
  1816. /**
  1817. * Callback invoked when the conference has been successfully joined.
  1818. * Initializes the UI and various other features.
  1819. *
  1820. * @private
  1821. * @returns {void}
  1822. */
  1823. _onConferenceJoined() {
  1824. const { dispatch } = APP.store;
  1825. APP.UI.initConference();
  1826. dispatch(initKeyboardShortcuts());
  1827. dispatch(conferenceJoined(room));
  1828. const jwt = APP.store.getState()['features/base/jwt'];
  1829. if (jwt?.user?.hiddenFromRecorder) {
  1830. dispatch(muteLocal(true, MEDIA_TYPE.AUDIO));
  1831. dispatch(muteLocal(true, MEDIA_TYPE.VIDEO));
  1832. dispatch(setAudioUnmutePermissions(true, true));
  1833. dispatch(setVideoUnmutePermissions(true, true));
  1834. }
  1835. },
  1836. /**
  1837. * Updates the list of current devices.
  1838. * @param {boolean} setDeviceListChangeHandler - Whether to add the deviceList change handlers.
  1839. * @private
  1840. * @returns {Promise}
  1841. */
  1842. _initDeviceList(setDeviceListChangeHandler = false) {
  1843. const { mediaDevices } = JitsiMeetJS;
  1844. if (mediaDevices.isDeviceListAvailable()
  1845. && mediaDevices.isDeviceChangeAvailable()) {
  1846. if (setDeviceListChangeHandler) {
  1847. this.deviceChangeListener = devices =>
  1848. window.setTimeout(() => this._onDeviceListChanged(devices), 0);
  1849. mediaDevices.addEventListener(
  1850. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  1851. this.deviceChangeListener);
  1852. }
  1853. const { dispatch } = APP.store;
  1854. return dispatch(getAvailableDevices())
  1855. .then(devices => {
  1856. APP.UI.onAvailableDevicesChanged(devices);
  1857. });
  1858. }
  1859. return Promise.resolve();
  1860. },
  1861. /**
  1862. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1863. * handle change of available media devices.
  1864. * @private
  1865. * @param {MediaDeviceInfo[]} devices
  1866. * @returns {Promise}
  1867. */
  1868. async _onDeviceListChanged(devices) {
  1869. const state = APP.store.getState();
  1870. const { filteredDevices, ignoredDevices } = filterIgnoredDevices(devices);
  1871. const oldDevices = state['features/base/devices'].availableDevices;
  1872. if (!areDevicesDifferent(flattenAvailableDevices(oldDevices), filteredDevices)) {
  1873. return Promise.resolve();
  1874. }
  1875. logDevices(ignoredDevices, 'Ignored devices on device list changed:');
  1876. const localAudio = getLocalJitsiAudioTrack(state);
  1877. const localVideo = getLocalJitsiVideoTrack(state);
  1878. APP.store.dispatch(updateDeviceList(filteredDevices));
  1879. // Firefox users can choose their preferred device in the gUM prompt. In that case
  1880. // we should respect that and not attempt to switch to the preferred device from
  1881. // our settings.
  1882. const newLabelsOnly = mediaDeviceHelper.newDeviceListAddedLabelsOnly(oldDevices, filteredDevices);
  1883. const newDevices
  1884. = mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1885. filteredDevices,
  1886. localVideo,
  1887. localAudio,
  1888. newLabelsOnly);
  1889. const promises = [];
  1890. const requestedInput = {
  1891. audio: Boolean(newDevices.audioinput),
  1892. video: Boolean(newDevices.videoinput)
  1893. };
  1894. if (typeof newDevices.audiooutput !== 'undefined') {
  1895. const { dispatch } = APP.store;
  1896. const setAudioOutputPromise
  1897. = setAudioOutputDeviceId(newDevices.audiooutput, dispatch)
  1898. .catch(err => {
  1899. logger.error(`Failed to set the audio output device to ${newDevices.audiooutput} - ${err}`);
  1900. });
  1901. promises.push(setAudioOutputPromise);
  1902. }
  1903. // Handles the use case when the default device is changed (we are always stopping the streams because it's
  1904. // simpler):
  1905. // If the default device is changed we need to first stop the local streams and then call GUM. Otherwise GUM
  1906. // will return a stream using the old default device.
  1907. if (requestedInput.audio && localAudio) {
  1908. localAudio.stopStream();
  1909. }
  1910. if (requestedInput.video && localVideo) {
  1911. localVideo.stopStream();
  1912. }
  1913. // Let's handle unknown/non-preferred devices
  1914. const newAvailDevices = APP.store.getState()['features/base/devices'].availableDevices;
  1915. let newAudioDevices = [];
  1916. let oldAudioDevices = [];
  1917. if (typeof newDevices.audiooutput === 'undefined') {
  1918. newAudioDevices = newAvailDevices.audioOutput;
  1919. oldAudioDevices = oldDevices.audioOutput;
  1920. }
  1921. if (!requestedInput.audio) {
  1922. newAudioDevices = newAudioDevices.concat(newAvailDevices.audioInput);
  1923. oldAudioDevices = oldAudioDevices.concat(oldDevices.audioInput);
  1924. }
  1925. // check for audio
  1926. if (newAudioDevices.length > 0) {
  1927. APP.store.dispatch(checkAndNotifyForNewDevice(newAudioDevices, oldAudioDevices));
  1928. }
  1929. // check for video
  1930. if (requestedInput.video) {
  1931. APP.store.dispatch(checkAndNotifyForNewDevice(newAvailDevices.videoInput, oldDevices.videoInput));
  1932. }
  1933. // When the 'default' mic needs to be selected, we need to pass the real device id to gUM instead of 'default'
  1934. // in order to get the correct MediaStreamTrack from chrome because of the following bug.
  1935. // https://bugs.chromium.org/p/chromium/issues/detail?id=997689
  1936. const hasDefaultMicChanged = newDevices.audioinput === 'default';
  1937. // When the local video is muted and a preferred device is connected, update the settings and remove the track
  1938. // from the conference. A new track will be created and replaced when the user unmutes their camera.
  1939. if (requestedInput.video && this.isLocalVideoMuted()) {
  1940. APP.store.dispatch(updateSettings({
  1941. cameraDeviceId: newDevices.videoinput
  1942. }));
  1943. requestedInput.video = false;
  1944. delete newDevices.videoinput;
  1945. // Remove the track from the conference.
  1946. if (localVideo) {
  1947. await this.useVideoStream(null);
  1948. logger.debug('_onDeviceListChanged: Removed the current video track.');
  1949. }
  1950. }
  1951. // When the local audio is muted and a preferred device is connected, update the settings and remove the track
  1952. // from the conference. A new track will be created and replaced when the user unmutes their mic.
  1953. if (requestedInput.audio && this.isLocalAudioMuted()) {
  1954. APP.store.dispatch(updateSettings({
  1955. micDeviceId: newDevices.audioinput
  1956. }));
  1957. requestedInput.audio = false;
  1958. delete newDevices.audioinput;
  1959. // Remove the track from the conference.
  1960. if (localAudio) {
  1961. await this.useAudioStream(null);
  1962. logger.debug('_onDeviceListChanged: Removed the current audio track.');
  1963. }
  1964. }
  1965. // Create the tracks and replace them only if the user is unmuted.
  1966. if (requestedInput.audio || requestedInput.video) {
  1967. let tracks = [];
  1968. const realAudioDeviceId = hasDefaultMicChanged
  1969. ? getDefaultDeviceId(APP.store.getState(), 'audioInput') : newDevices.audioinput;
  1970. try {
  1971. tracks = await mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1972. createLocalTracksF,
  1973. requestedInput.video ? newDevices.videoinput : null,
  1974. requestedInput.audio ? realAudioDeviceId : null
  1975. );
  1976. } catch (error) {
  1977. logger.error(`Track creation failed on device change, ${error}`);
  1978. return Promise.reject(error);
  1979. }
  1980. for (const track of tracks) {
  1981. if (track.isAudioTrack()) {
  1982. promises.push(
  1983. this.useAudioStream(track)
  1984. .then(() => {
  1985. hasDefaultMicChanged && (track._realDeviceId = track.deviceId = 'default');
  1986. }));
  1987. } else {
  1988. promises.push(
  1989. this.useVideoStream(track));
  1990. }
  1991. }
  1992. }
  1993. return Promise.all(promises)
  1994. .then(() => {
  1995. APP.UI.onAvailableDevicesChanged(filteredDevices);
  1996. });
  1997. },
  1998. /**
  1999. * Determines whether or not the audio button should be enabled.
  2000. */
  2001. updateAudioIconEnabled() {
  2002. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  2003. const audioMediaDevices = APP.store.getState()['features/base/devices'].availableDevices.audioInput;
  2004. const audioDeviceCount = audioMediaDevices ? audioMediaDevices.length : 0;
  2005. // The audio functionality is considered available if there are any
  2006. // audio devices detected or if the local audio stream already exists.
  2007. const available = audioDeviceCount > 0 || Boolean(localAudio);
  2008. APP.store.dispatch(setAudioAvailable(available));
  2009. },
  2010. /**
  2011. * Determines whether or not the video button should be enabled.
  2012. */
  2013. updateVideoIconEnabled() {
  2014. const videoMediaDevices
  2015. = APP.store.getState()['features/base/devices'].availableDevices.videoInput;
  2016. const videoDeviceCount
  2017. = videoMediaDevices ? videoMediaDevices.length : 0;
  2018. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  2019. // The video functionality is considered available if there are any
  2020. // video devices detected or if there is local video stream already
  2021. // active which could be either screensharing stream or a video track
  2022. // created before the permissions were rejected (through browser
  2023. // config).
  2024. const available = videoDeviceCount > 0 || Boolean(localVideo);
  2025. APP.store.dispatch(setVideoAvailable(available));
  2026. APP.API.notifyVideoAvailabilityChanged(available);
  2027. },
  2028. /**
  2029. * Disconnect from the conference and optionally request user feedback.
  2030. * @param {boolean} [requestFeedback=false] if user feedback should be
  2031. * @param {string} [hangupReason] the reason for leaving the meeting
  2032. * requested
  2033. */
  2034. hangup(requestFeedback = false, hangupReason) {
  2035. APP.store.dispatch(disableReceiver());
  2036. this._stopProxyConnection();
  2037. APP.store.dispatch(destroyLocalTracks());
  2038. this._localTracksInitialized = false;
  2039. // Remove unnecessary event listeners from firing callbacks.
  2040. if (this.deviceChangeListener) {
  2041. JitsiMeetJS.mediaDevices.removeEventListener(
  2042. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2043. this.deviceChangeListener);
  2044. }
  2045. APP.UI.removeAllListeners();
  2046. let feedbackResultPromise = Promise.resolve({});
  2047. if (requestFeedback) {
  2048. const feedbackDialogClosed = (feedbackResult = {}) => {
  2049. if (!feedbackResult.wasDialogShown && hangupReason) {
  2050. return APP.store.dispatch(
  2051. openLeaveReasonDialog(hangupReason)).then(() => feedbackResult);
  2052. }
  2053. return Promise.resolve(feedbackResult);
  2054. };
  2055. feedbackResultPromise
  2056. = APP.store.dispatch(maybeOpenFeedbackDialog(room, hangupReason))
  2057. .then(feedbackDialogClosed, feedbackDialogClosed);
  2058. }
  2059. const leavePromise = this.leaveRoom().catch(() => Promise.resolve());
  2060. Promise.allSettled([ feedbackResultPromise, leavePromise ]).then(([ feedback, _ ]) => {
  2061. this._room = undefined;
  2062. room = undefined;
  2063. /**
  2064. * Don't call {@code notifyReadyToClose} if the promotional page flag is set
  2065. * and let the page take care of sending the message, since there will be
  2066. * a redirect to the page anyway.
  2067. */
  2068. if (!interfaceConfig.SHOW_PROMOTIONAL_CLOSE_PAGE) {
  2069. APP.API.notifyReadyToClose();
  2070. }
  2071. APP.store.dispatch(maybeRedirectToWelcomePage(feedback.value ?? {}));
  2072. });
  2073. },
  2074. /**
  2075. * Leaves the room.
  2076. *
  2077. * @param {boolean} doDisconnect - Whether leaving the room should also terminate the connection.
  2078. * @param {string} reason - reason for leaving the room.
  2079. * @returns {Promise}
  2080. */
  2081. leaveRoom(doDisconnect = true, reason = '') {
  2082. APP.store.dispatch(conferenceWillLeave(room));
  2083. const maybeDisconnect = () => {
  2084. if (doDisconnect) {
  2085. return disconnect();
  2086. }
  2087. };
  2088. if (room && room.isJoined()) {
  2089. return room.leave(reason).then(() => maybeDisconnect())
  2090. .catch(e => {
  2091. logger.error(e);
  2092. return maybeDisconnect();
  2093. });
  2094. }
  2095. return maybeDisconnect();
  2096. },
  2097. /**
  2098. * Changes the email for the local user
  2099. * @param email {string} the new email
  2100. */
  2101. changeLocalEmail(email = '') {
  2102. const formattedEmail = String(email).trim();
  2103. APP.store.dispatch(updateSettings({
  2104. email: formattedEmail
  2105. }));
  2106. sendData(commands.EMAIL, formattedEmail);
  2107. },
  2108. /**
  2109. * Changes the avatar url for the local user
  2110. * @param url {string} the new url
  2111. */
  2112. changeLocalAvatarUrl(url = '') {
  2113. const formattedUrl = String(url).trim();
  2114. APP.store.dispatch(updateSettings({
  2115. avatarURL: formattedUrl
  2116. }));
  2117. sendData(commands.AVATAR_URL, url);
  2118. },
  2119. /**
  2120. * Sends a message via the data channel.
  2121. * @param {string} to the id of the endpoint that should receive the
  2122. * message. If "" - the message will be sent to all participants.
  2123. * @param {object} payload the payload of the message.
  2124. * @throws NetworkError or InvalidStateError or Error if the operation
  2125. * fails.
  2126. */
  2127. sendEndpointMessage(to, payload) {
  2128. room.sendEndpointMessage(to, payload);
  2129. },
  2130. /**
  2131. * Adds new listener.
  2132. * @param {String} eventName the name of the event
  2133. * @param {Function} listener the listener.
  2134. */
  2135. addListener(eventName, listener) {
  2136. eventEmitter.addListener(eventName, listener);
  2137. },
  2138. /**
  2139. * Removes listener.
  2140. * @param {String} eventName the name of the event that triggers the
  2141. * listener
  2142. * @param {Function} listener the listener.
  2143. */
  2144. removeListener(eventName, listener) {
  2145. eventEmitter.removeListener(eventName, listener);
  2146. },
  2147. /**
  2148. * Changes the display name for the local user
  2149. * @param nickname {string} the new display name
  2150. */
  2151. changeLocalDisplayName(nickname = '') {
  2152. const formattedNickname = getNormalizedDisplayName(nickname);
  2153. APP.store.dispatch(updateSettings({
  2154. displayName: formattedNickname
  2155. }));
  2156. },
  2157. /**
  2158. * Callback invoked by the external api create or update a direct connection
  2159. * from the local client to an external client.
  2160. *
  2161. * @param {Object} event - The object containing information that should be
  2162. * passed to the {@code ProxyConnectionService}.
  2163. * @returns {void}
  2164. */
  2165. onProxyConnectionEvent(event) {
  2166. if (!this._proxyConnection) {
  2167. this._proxyConnection = new JitsiMeetJS.ProxyConnectionService({
  2168. /**
  2169. * Pass the {@code JitsiConnection} instance which will be used
  2170. * to fetch TURN credentials.
  2171. */
  2172. jitsiConnection: APP.connection,
  2173. /**
  2174. * The proxy connection feature is currently tailored towards
  2175. * taking a proxied video stream and showing it as a local
  2176. * desktop screen.
  2177. */
  2178. convertVideoToDesktop: true,
  2179. /**
  2180. * Callback invoked when the connection has been closed
  2181. * automatically. Triggers cleanup of screensharing if active.
  2182. *
  2183. * @returns {void}
  2184. */
  2185. onConnectionClosed: () => {
  2186. if (this._untoggleScreenSharing) {
  2187. this._untoggleScreenSharing();
  2188. }
  2189. },
  2190. /**
  2191. * Callback invoked to pass messages from the local client back
  2192. * out to the external client.
  2193. *
  2194. * @param {string} peerJid - The jid of the intended recipient
  2195. * of the message.
  2196. * @param {Object} data - The message that should be sent. For
  2197. * screensharing this is an iq.
  2198. * @returns {void}
  2199. */
  2200. onSendMessage: (peerJid, data) =>
  2201. APP.API.sendProxyConnectionEvent({
  2202. data,
  2203. to: peerJid
  2204. }),
  2205. /**
  2206. * Callback invoked when the remote peer of the proxy connection
  2207. * has provided a video stream, intended to be used as a local
  2208. * desktop stream.
  2209. *
  2210. * @param {JitsiLocalTrack} remoteProxyStream - The media
  2211. * stream to use as a local desktop stream.
  2212. * @returns {void}
  2213. */
  2214. onRemoteStream: desktopStream => {
  2215. if (desktopStream.videoType !== 'desktop') {
  2216. logger.warn('Received a non-desktop stream to proxy.');
  2217. desktopStream.dispose();
  2218. return;
  2219. }
  2220. APP.store.dispatch(toggleScreensharingA(undefined, false, { desktopStream }));
  2221. }
  2222. });
  2223. }
  2224. this._proxyConnection.processMessage(event);
  2225. },
  2226. /**
  2227. * Sets the video muted status.
  2228. */
  2229. setVideoMuteStatus() {
  2230. APP.UI.setVideoMuted(this.getMyUserId());
  2231. },
  2232. /**
  2233. * Dispatches the passed in feedback for submission. The submitted score
  2234. * should be a number inclusively between 1 through 5, or -1 for no score.
  2235. *
  2236. * @param {number} score - a number between 1 and 5 (inclusive) or -1 for no
  2237. * score.
  2238. * @param {string} message - An optional message to attach to the feedback
  2239. * in addition to the score.
  2240. * @returns {void}
  2241. */
  2242. submitFeedback(score = -1, message = '') {
  2243. if (score === -1 || (score >= 1 && score <= 5)) {
  2244. APP.store.dispatch(submitFeedback(score, message, room));
  2245. }
  2246. },
  2247. /**
  2248. * Terminates any proxy screensharing connection that is active.
  2249. *
  2250. * @private
  2251. * @returns {void}
  2252. */
  2253. _stopProxyConnection() {
  2254. if (this._proxyConnection) {
  2255. this._proxyConnection.stop();
  2256. }
  2257. this._proxyConnection = null;
  2258. }
  2259. };