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

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