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

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