Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

conference.js 94KB

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