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 96KB

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