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

conference.js 109KB

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