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

conference.js 109KB

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