Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

conference.js 95KB

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