您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 99KB

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