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

conference.js 111KB

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