選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

conference.js 106KB

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