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

conference.js 109KB

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