You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 102KB

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