Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conference.js 104KB

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