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

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