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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. const logger = require("jitsi-meet-logger").getLogger(__filename);
  3. import {openConnection} from './connection';
  4. import ContactList from './modules/UI/side_pannels/contactlist/ContactList';
  5. import AuthHandler from './modules/UI/authentication/AuthHandler';
  6. import Recorder from './modules/recorder/Recorder';
  7. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  8. import { reload, reportError } from './modules/util/helpers';
  9. import UIEvents from './service/UI/UIEvents';
  10. import UIUtil from './modules/UI/util/UIUtil';
  11. import * as JitsiMeetConferenceEvents from './ConferenceEvents';
  12. import analytics from './modules/analytics/analytics';
  13. import EventEmitter from "events";
  14. import { getLocationContextRoot } from './react/features/app';
  15. import {
  16. AVATAR_ID_COMMAND,
  17. AVATAR_URL_COMMAND,
  18. conferenceFailed,
  19. conferenceJoined,
  20. conferenceLeft,
  21. EMAIL_COMMAND,
  22. lockStateChanged
  23. } from './react/features/base/conference';
  24. import {
  25. updateDeviceList
  26. } from './react/features/base/devices';
  27. import {
  28. isFatalJitsiConnectionError
  29. } from './react/features/base/lib-jitsi-meet';
  30. import {
  31. localParticipantRoleChanged,
  32. participantJoined,
  33. participantLeft,
  34. participantRoleChanged,
  35. participantUpdated
  36. } from './react/features/base/participants';
  37. import {
  38. replaceLocalTrack,
  39. trackAdded,
  40. trackRemoved
  41. } from './react/features/base/tracks';
  42. import {
  43. showDesktopPicker
  44. } from './react/features/desktop-picker';
  45. import {
  46. mediaPermissionPromptVisibilityChanged,
  47. suspendDetected
  48. } from './react/features/overlay';
  49. import { showDesktopSharingButton } from './react/features/toolbox';
  50. const ConnectionEvents = JitsiMeetJS.events.connection;
  51. const ConnectionErrors = JitsiMeetJS.errors.connection;
  52. const ConferenceEvents = JitsiMeetJS.events.conference;
  53. const ConferenceErrors = JitsiMeetJS.errors.conference;
  54. const TrackEvents = JitsiMeetJS.events.track;
  55. const TrackErrors = JitsiMeetJS.errors.track;
  56. const ConnectionQualityEvents = JitsiMeetJS.events.connectionQuality;
  57. const eventEmitter = new EventEmitter();
  58. let room;
  59. let connection;
  60. let localAudio, localVideo;
  61. let initialAudioMutedState = false, initialVideoMutedState = false;
  62. /**
  63. * Indicates whether extension external installation is in progress or not.
  64. */
  65. let DSExternalInstallationInProgress = false;
  66. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/VideoContainer";
  67. /*
  68. * Logic to open a desktop picker put on the window global for
  69. * lib-jitsi-meet to detect and invoke
  70. */
  71. window.JitsiMeetScreenObtainer = {
  72. openDesktopPicker(onSourceChoose) {
  73. APP.store.dispatch(showDesktopPicker(onSourceChoose));
  74. }
  75. };
  76. /**
  77. * Known custom conference commands.
  78. */
  79. const commands = {
  80. AVATAR_ID: AVATAR_ID_COMMAND,
  81. AVATAR_URL: AVATAR_URL_COMMAND,
  82. CUSTOM_ROLE: "custom-role",
  83. EMAIL: EMAIL_COMMAND,
  84. ETHERPAD: "etherpad",
  85. SHARED_VIDEO: "shared-video"
  86. };
  87. /**
  88. * Max length of the display names. If we receive longer display name the
  89. * additional chars are going to be cut.
  90. */
  91. const MAX_DISPLAY_NAME_LENGTH = 50;
  92. /**
  93. * Open Connection. When authentication failed it shows auth dialog.
  94. * @param roomName the room name to use
  95. * @returns Promise<JitsiConnection>
  96. */
  97. function connect(roomName) {
  98. return openConnection({retry: true, roomName: roomName})
  99. .catch(function (err) {
  100. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  101. APP.UI.notifyTokenAuthFailed();
  102. } else {
  103. APP.UI.notifyConnectionFailed(err);
  104. }
  105. throw err;
  106. });
  107. }
  108. /**
  109. * Creates local media tracks and connects to room. Will show error
  110. * dialogs in case if accessing local microphone and/or camera failed. Will
  111. * show guidance overlay for users on how to give access to camera and/or
  112. * microphone,
  113. * @param {string} roomName
  114. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  115. */
  116. function createInitialLocalTracksAndConnect(roomName) {
  117. let audioAndVideoError,
  118. audioOnlyError;
  119. JitsiMeetJS.mediaDevices.addEventListener(
  120. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  121. browser =>
  122. APP.store.dispatch(
  123. mediaPermissionPromptVisibilityChanged(true, browser))
  124. );
  125. // First try to retrieve both audio and video.
  126. let tryCreateLocalTracks = createLocalTracks(
  127. { devices: ['audio', 'video'] }, true)
  128. .catch(err => {
  129. // If failed then try to retrieve only audio.
  130. audioAndVideoError = err;
  131. return createLocalTracks({ devices: ['audio'] }, true);
  132. })
  133. .catch(err => {
  134. // If audio failed too then just return empty array for tracks.
  135. audioOnlyError = err;
  136. return [];
  137. });
  138. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  139. .then(([tracks, con]) => {
  140. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false));
  141. if (audioAndVideoError) {
  142. if (audioOnlyError) {
  143. // If both requests for 'audio' + 'video' and 'audio' only
  144. // failed, we assume that there is some problems with user's
  145. // microphone and show corresponding dialog.
  146. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  147. } else {
  148. // If request for 'audio' + 'video' failed, but request for
  149. // 'audio' only was OK, we assume that we had problems with
  150. // camera and show corresponding dialog.
  151. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  152. }
  153. }
  154. return [tracks, con];
  155. });
  156. }
  157. /**
  158. * Share data to other users.
  159. * @param command the command
  160. * @param {string} value new value
  161. */
  162. function sendData(command, value) {
  163. if(!room) {
  164. return;
  165. }
  166. room.removeCommand(command);
  167. room.sendCommand(command, {value: value});
  168. }
  169. /**
  170. * Sets up initially the properties of the local participant - email, avatarID,
  171. * avatarURL, displayName, etc.
  172. */
  173. function _setupLocalParticipantProperties() {
  174. const email = APP.settings.getEmail();
  175. email && sendData(commands.EMAIL, email);
  176. const avatarUrl = APP.settings.getAvatarUrl();
  177. avatarUrl && sendData(commands.AVATAR_URL, avatarUrl);
  178. if (!email && !avatarUrl) {
  179. sendData(commands.AVATAR_ID, APP.settings.getAvatarId());
  180. }
  181. let nick = APP.settings.getDisplayName();
  182. if (config.useNicks && !nick) {
  183. nick = APP.UI.askForNickname();
  184. APP.settings.setDisplayName(nick);
  185. }
  186. nick && room.setDisplayName(nick);
  187. }
  188. /**
  189. * Get user nickname by user id.
  190. * @param {string} id user id
  191. * @returns {string?} user nickname or undefined if user is unknown.
  192. */
  193. function getDisplayName(id) {
  194. if (APP.conference.isLocalId(id)) {
  195. return APP.settings.getDisplayName();
  196. }
  197. let participant = room.getParticipantById(id);
  198. if (participant && participant.getDisplayName()) {
  199. return participant.getDisplayName();
  200. }
  201. }
  202. /**
  203. * Mute or unmute local audio stream if it exists.
  204. * @param {boolean} muted - if audio stream should be muted or unmuted.
  205. * @param {boolean} userInteraction - indicates if this local audio mute was a
  206. * result of user interaction
  207. */
  208. function muteLocalAudio(muted) {
  209. muteLocalMedia(localAudio, muted, 'Audio');
  210. }
  211. function muteLocalMedia(localMedia, muted, localMediaTypeString) {
  212. if (!localMedia) {
  213. return;
  214. }
  215. const method = muted ? 'mute' : 'unmute';
  216. localMedia[method]().catch(reason => {
  217. logger.warn(`${localMediaTypeString} ${method} was rejected:`, reason);
  218. });
  219. }
  220. /**
  221. * Mute or unmute local video stream if it exists.
  222. * @param {boolean} muted if video stream should be muted or unmuted.
  223. */
  224. function muteLocalVideo(muted) {
  225. muteLocalMedia(localVideo, muted, 'Video');
  226. }
  227. /**
  228. * Check if the welcome page is enabled and redirects to it.
  229. * If requested show a thank you dialog before that.
  230. * If we have a close page enabled, redirect to it without
  231. * showing any other dialog.
  232. *
  233. * @param {object} options used to decide which particular close page to show
  234. * or if close page is disabled, whether we should show the thankyou dialog
  235. * @param {boolean} options.thankYouDialogVisible - whether we should
  236. * show thank you dialog
  237. * @param {boolean} options.feedbackSubmitted - whether feedback was submitted
  238. */
  239. function maybeRedirectToWelcomePage(options) {
  240. // if close page is enabled redirect to it, without further action
  241. if (config.enableClosePage) {
  242. const { isGuest } = APP.store.getState()['features/jwt'];
  243. // save whether current user is guest or not, before navigating
  244. // to close page
  245. window.sessionStorage.setItem('guest', isGuest);
  246. assignWindowLocationPathname('static/'
  247. + (options.feedbackSubmitted ? "close.html" : "close2.html"));
  248. return;
  249. }
  250. // else: show thankYou dialog only if there is no feedback
  251. if (options.thankYouDialogVisible)
  252. APP.UI.messageHandler.openMessageDialog(
  253. null, "dialog.thankYou", {appName:interfaceConfig.APP_NAME});
  254. // if Welcome page is enabled redirect to welcome page after 3 sec.
  255. if (config.enableWelcomePage) {
  256. setTimeout(() => {
  257. APP.settings.setWelcomePageEnabled(true);
  258. assignWindowLocationPathname('./');
  259. }, 3000);
  260. }
  261. }
  262. /**
  263. * Assigns a specific pathname to window.location.pathname taking into account
  264. * the context root of the Web app.
  265. *
  266. * @param {string} pathname - The pathname to assign to
  267. * window.location.pathname. If the specified pathname is relative, the context
  268. * root of the Web app will be prepended to the specified pathname before
  269. * assigning it to window.location.pathname.
  270. * @return {void}
  271. */
  272. function assignWindowLocationPathname(pathname) {
  273. const windowLocation = window.location;
  274. if (!pathname.startsWith('/')) {
  275. // A pathname equal to ./ specifies the current directory. It will be
  276. // fine but pointless to include it because contextRoot is the current
  277. // directory.
  278. pathname.startsWith('./') && (pathname = pathname.substring(2));
  279. pathname = getLocationContextRoot(windowLocation) + pathname;
  280. }
  281. windowLocation.pathname = pathname;
  282. }
  283. /**
  284. * Create local tracks of specified types.
  285. * @param {Object} options
  286. * @param {string[]} options.devices - required track types
  287. * ('audio', 'video' etc.)
  288. * @param {string|null} (options.cameraDeviceId) - camera device id, if
  289. * undefined - one from settings will be used
  290. * @param {string|null} (options.micDeviceId) - microphone device id, if
  291. * undefined - one from settings will be used
  292. * @param {boolean} (checkForPermissionPrompt) - if lib-jitsi-meet should check
  293. * for gUM permission prompt
  294. * @returns {Promise<JitsiLocalTrack[]>}
  295. */
  296. function createLocalTracks(options, checkForPermissionPrompt) {
  297. options || (options = {});
  298. return JitsiMeetJS
  299. .createLocalTracks({
  300. // copy array to avoid mutations inside library
  301. devices: options.devices.slice(0),
  302. resolution: config.resolution,
  303. cameraDeviceId: typeof options.cameraDeviceId === 'undefined' ||
  304. options.cameraDeviceId === null
  305. ? APP.settings.getCameraDeviceId()
  306. : options.cameraDeviceId,
  307. micDeviceId: typeof options.micDeviceId === 'undefined' ||
  308. options.micDeviceId === null
  309. ? APP.settings.getMicDeviceId()
  310. : options.micDeviceId,
  311. // adds any ff fake device settings if any
  312. firefox_fake_device: config.firefox_fake_device,
  313. desktopSharingExtensionExternalInstallation:
  314. options.desktopSharingExtensionExternalInstallation
  315. }, checkForPermissionPrompt).then( (tracks) => {
  316. tracks.forEach((track) => {
  317. track.on(TrackEvents.NO_DATA_FROM_SOURCE,
  318. APP.UI.showTrackNotWorkingDialog.bind(null, track));
  319. });
  320. return tracks;
  321. }).catch(function (err) {
  322. logger.error(
  323. 'failed to create local tracks', options.devices, err);
  324. return Promise.reject(err);
  325. });
  326. }
  327. class ConferenceConnector {
  328. constructor(resolve, reject) {
  329. this._resolve = resolve;
  330. this._reject = reject;
  331. this.reconnectTimeout = null;
  332. room.on(ConferenceEvents.CONFERENCE_JOINED,
  333. this._handleConferenceJoined.bind(this));
  334. room.on(ConferenceEvents.CONFERENCE_FAILED,
  335. this._onConferenceFailed.bind(this));
  336. room.on(ConferenceEvents.CONFERENCE_ERROR,
  337. this._onConferenceError.bind(this));
  338. }
  339. _handleConferenceFailed(err) {
  340. this._unsubscribe();
  341. this._reject(err);
  342. }
  343. _onConferenceFailed(err, ...params) {
  344. APP.store.dispatch(conferenceFailed(room, err, ...params));
  345. logger.error('CONFERENCE FAILED:', err, ...params);
  346. switch (err) {
  347. case ConferenceErrors.CONNECTION_ERROR:
  348. {
  349. let [msg] = params;
  350. APP.UI.notifyConnectionFailed(msg);
  351. }
  352. break;
  353. case ConferenceErrors.NOT_ALLOWED_ERROR:
  354. {
  355. // let's show some auth not allowed page
  356. assignWindowLocationPathname('static/authError.html');
  357. }
  358. break;
  359. // not enough rights to create conference
  360. case ConferenceErrors.AUTHENTICATION_REQUIRED: {
  361. // Schedule reconnect to check if someone else created the room.
  362. this.reconnectTimeout = setTimeout(() => room.join(), 5000);
  363. const { password }
  364. = APP.store.getState()['features/base/conference'];
  365. AuthHandler.requireAuth(room, password);
  366. }
  367. break;
  368. case ConferenceErrors.RESERVATION_ERROR:
  369. {
  370. let [code, msg] = params;
  371. APP.UI.notifyReservationError(code, msg);
  372. }
  373. break;
  374. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  375. APP.UI.notifyGracefulShutdown();
  376. break;
  377. case ConferenceErrors.JINGLE_FATAL_ERROR:
  378. APP.UI.notifyInternalError();
  379. break;
  380. case ConferenceErrors.CONFERENCE_DESTROYED:
  381. {
  382. let [reason] = params;
  383. APP.UI.hideStats();
  384. APP.UI.notifyConferenceDestroyed(reason);
  385. }
  386. break;
  387. // FIXME FOCUS_DISCONNECTED is confusing event name.
  388. // What really happens there is that the library is not ready yet,
  389. // because Jicofo is not available, but it is going to give
  390. // it another try.
  391. case ConferenceErrors.FOCUS_DISCONNECTED:
  392. {
  393. let [focus, retrySec] = params;
  394. APP.UI.notifyFocusDisconnected(focus, retrySec);
  395. }
  396. break;
  397. case ConferenceErrors.FOCUS_LEFT:
  398. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  399. // FIXME the conference should be stopped by the library and not by
  400. // the app. Both the errors above are unrecoverable from the library
  401. // perspective.
  402. room.leave().then(() => connection.disconnect());
  403. break;
  404. case ConferenceErrors.CONFERENCE_MAX_USERS:
  405. connection.disconnect();
  406. APP.UI.notifyMaxUsersLimitReached();
  407. break;
  408. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  409. reload();
  410. break;
  411. default:
  412. this._handleConferenceFailed(err, ...params);
  413. }
  414. }
  415. _onConferenceError(err, ...params) {
  416. logger.error('CONFERENCE Error:', err, params);
  417. switch (err) {
  418. case ConferenceErrors.CHAT_ERROR:
  419. {
  420. let [code, msg] = params;
  421. APP.UI.showChatError(code, msg);
  422. }
  423. break;
  424. default:
  425. logger.error("Unknown error.", err);
  426. }
  427. }
  428. _unsubscribe() {
  429. room.off(
  430. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  431. room.off(
  432. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  433. if (this.reconnectTimeout !== null) {
  434. clearTimeout(this.reconnectTimeout);
  435. }
  436. AuthHandler.closeAuth();
  437. }
  438. _handleConferenceJoined() {
  439. this._unsubscribe();
  440. this._resolve();
  441. }
  442. connect() {
  443. room.join();
  444. }
  445. }
  446. /**
  447. * Disconnects the connection.
  448. * @returns resolved Promise. We need this in order to make the Promise.all
  449. * call in hangup() to resolve when all operations are finished.
  450. */
  451. function disconnect() {
  452. connection.disconnect();
  453. APP.API.notifyConferenceLeft(APP.conference.roomName);
  454. return Promise.resolve();
  455. }
  456. /**
  457. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  458. *
  459. * @param {JitsiMeetJS.connection.error} error - The reported error.
  460. * @returns {void}
  461. * @private
  462. */
  463. function _connectionFailedHandler(error) {
  464. if (isFatalJitsiConnectionError(error)) {
  465. APP.connection.removeEventListener(
  466. ConnectionEvents.CONNECTION_FAILED,
  467. _connectionFailedHandler);
  468. if (room)
  469. room.leave();
  470. }
  471. }
  472. export default {
  473. isModerator: false,
  474. audioMuted: false,
  475. videoMuted: false,
  476. isSharingScreen: false,
  477. isDesktopSharingEnabled: false,
  478. /*
  479. * Whether the local "raisedHand" flag is on.
  480. */
  481. isHandRaised: false,
  482. /*
  483. * Whether the local participant is the dominant speaker in the conference.
  484. */
  485. isDominantSpeaker: false,
  486. /**
  487. * Open new connection and join to the conference.
  488. * @param {object} options
  489. * @param {string} roomName name of the conference
  490. * @returns {Promise}
  491. */
  492. init(options) {
  493. this.roomName = options.roomName;
  494. // attaches global error handler, if there is already one, respect it
  495. if(JitsiMeetJS.getGlobalOnErrorHandler){
  496. var oldOnErrorHandler = window.onerror;
  497. window.onerror = function (message, source, lineno, colno, error) {
  498. JitsiMeetJS.getGlobalOnErrorHandler(
  499. message, source, lineno, colno, error);
  500. if(oldOnErrorHandler)
  501. oldOnErrorHandler(message, source, lineno, colno, error);
  502. };
  503. var oldOnUnhandledRejection = window.onunhandledrejection;
  504. window.onunhandledrejection = function(event) {
  505. JitsiMeetJS.getGlobalOnErrorHandler(
  506. null, null, null, null, event.reason);
  507. if(oldOnUnhandledRejection)
  508. oldOnUnhandledRejection(event);
  509. };
  510. }
  511. return JitsiMeetJS.init(
  512. Object.assign(
  513. {enableAnalyticsLogging: analytics.isEnabled()}, config)
  514. ).then(() => {
  515. analytics.init();
  516. return createInitialLocalTracksAndConnect(options.roomName);
  517. }).then(([tracks, con]) => {
  518. tracks.forEach(track => {
  519. if((track.isAudioTrack() && initialAudioMutedState)
  520. || (track.isVideoTrack() && initialVideoMutedState)) {
  521. track.mute();
  522. }
  523. });
  524. logger.log('initialized with %s local tracks', tracks.length);
  525. con.addEventListener(
  526. ConnectionEvents.CONNECTION_FAILED,
  527. _connectionFailedHandler);
  528. APP.connection = connection = con;
  529. this.isDesktopSharingEnabled =
  530. JitsiMeetJS.isDesktopSharingEnabled();
  531. eventEmitter.emit(
  532. JitsiMeetConferenceEvents.DESKTOP_SHARING_ENABLED_CHANGED,
  533. this.isDesktopSharingEnabled);
  534. APP.store.dispatch(showDesktopSharingButton());
  535. this._createRoom(tracks);
  536. APP.remoteControl.init();
  537. if (UIUtil.isButtonEnabled('contacts')
  538. && !interfaceConfig.filmStripOnly) {
  539. APP.UI.ContactList = new ContactList(room);
  540. }
  541. // if user didn't give access to mic or camera or doesn't have
  542. // them at all, we disable corresponding toolbar buttons
  543. if (!tracks.find((t) => t.isAudioTrack())) {
  544. APP.UI.setMicrophoneButtonEnabled(false);
  545. }
  546. if (!tracks.find((t) => t.isVideoTrack())) {
  547. APP.UI.setCameraButtonEnabled(false);
  548. }
  549. this._initDeviceList();
  550. if (config.iAmRecorder)
  551. this.recorder = new Recorder();
  552. // XXX The API will take care of disconnecting from the XMPP
  553. // server (and, thus, leaving the room) on unload.
  554. return new Promise((resolve, reject) => {
  555. (new ConferenceConnector(resolve, reject)).connect();
  556. });
  557. });
  558. },
  559. /**
  560. * Check if id is id of the local user.
  561. * @param {string} id id to check
  562. * @returns {boolean}
  563. */
  564. isLocalId(id) {
  565. return this.getMyUserId() === id;
  566. },
  567. /**
  568. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  569. * @param mute true for mute and false for unmute.
  570. */
  571. muteAudio(mute) {
  572. muteLocalAudio(mute);
  573. },
  574. /**
  575. * Returns whether local audio is muted or not.
  576. * @returns {boolean}
  577. */
  578. isLocalAudioMuted() {
  579. return this.audioMuted;
  580. },
  581. /**
  582. * Simulates toolbar button click for audio mute. Used by shortcuts
  583. * and API.
  584. * @param {boolean} force - If the track is not created, the operation
  585. * will be executed after the track is created. Otherwise the operation
  586. * will be ignored.
  587. */
  588. toggleAudioMuted(force = false) {
  589. if(!localAudio && force) {
  590. initialAudioMutedState = !initialAudioMutedState;
  591. return;
  592. }
  593. this.muteAudio(!this.audioMuted);
  594. },
  595. /**
  596. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  597. * @param mute true for mute and false for unmute.
  598. */
  599. muteVideo(mute) {
  600. muteLocalVideo(mute);
  601. },
  602. /**
  603. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  604. * @param {boolean} force - If the track is not created, the operation
  605. * will be executed after the track is created. Otherwise the operation
  606. * will be ignored.
  607. */
  608. toggleVideoMuted(force = false) {
  609. if(!localVideo && force) {
  610. initialVideoMutedState = !initialVideoMutedState;
  611. return;
  612. }
  613. this.muteVideo(!this.videoMuted);
  614. },
  615. /**
  616. * Retrieve list of conference participants (without local user).
  617. * @returns {JitsiParticipant[]}
  618. */
  619. listMembers() {
  620. return room.getParticipants();
  621. },
  622. /**
  623. * Retrieve list of ids of conference participants (without local user).
  624. * @returns {string[]}
  625. */
  626. listMembersIds() {
  627. return room.getParticipants().map(p => p.getId());
  628. },
  629. /**
  630. * Checks whether the participant identified by id is a moderator.
  631. * @id id to search for participant
  632. * @return {boolean} whether the participant is moderator
  633. */
  634. isParticipantModerator(id) {
  635. let user = room.getParticipantById(id);
  636. return user && user.isModerator();
  637. },
  638. /**
  639. * Check if SIP is supported.
  640. * @returns {boolean}
  641. */
  642. sipGatewayEnabled() {
  643. return room.isSIPCallingSupported();
  644. },
  645. get membersCount() {
  646. return room.getParticipants().length + 1;
  647. },
  648. /**
  649. * Returns true if the callstats integration is enabled, otherwise returns
  650. * false.
  651. *
  652. * @returns true if the callstats integration is enabled, otherwise returns
  653. * false.
  654. */
  655. isCallstatsEnabled() {
  656. return room && room.isCallstatsEnabled();
  657. },
  658. /**
  659. * Sends the given feedback through CallStats if enabled.
  660. *
  661. * @param overallFeedback an integer between 1 and 5 indicating the
  662. * user feedback
  663. * @param detailedFeedback detailed feedback from the user. Not yet used
  664. */
  665. sendFeedback(overallFeedback, detailedFeedback) {
  666. return room.sendFeedback (overallFeedback, detailedFeedback);
  667. },
  668. /**
  669. * Get speaker stats that track total dominant speaker time.
  670. *
  671. * @returns {object} A hash with keys being user ids and values being the
  672. * library's SpeakerStats model used for calculating time as dominant
  673. * speaker.
  674. */
  675. getSpeakerStats() {
  676. return room.getSpeakerStats();
  677. },
  678. /**
  679. * Returns the connection times stored in the library.
  680. */
  681. getConnectionTimes() {
  682. return this._room.getConnectionTimes();
  683. },
  684. // used by torture currently
  685. isJoined() {
  686. return this._room
  687. && this._room.isJoined();
  688. },
  689. getConnectionState() {
  690. return this._room
  691. && this._room.getConnectionState();
  692. },
  693. /**
  694. * Obtains current P2P ICE connection state.
  695. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  696. * P2P connection
  697. */
  698. getP2PConnectionState() {
  699. return this._room
  700. && this._room.getP2PConnectionState();
  701. },
  702. /**
  703. * Starts P2P (for tests only)
  704. * @private
  705. */
  706. _startP2P() {
  707. try {
  708. this._room && this._room.startP2PSession();
  709. } catch (error) {
  710. logger.error("Start P2P failed", error);
  711. throw error;
  712. }
  713. },
  714. /**
  715. * Stops P2P (for tests only)
  716. * @private
  717. */
  718. _stopP2P() {
  719. try {
  720. this._room && this._room.stopP2PSession();
  721. } catch (error) {
  722. logger.error("Stop P2P failed", error);
  723. throw error;
  724. }
  725. },
  726. /**
  727. * Checks whether or not our connection is currently in interrupted and
  728. * reconnect attempts are in progress.
  729. *
  730. * @returns {boolean} true if the connection is in interrupted state or
  731. * false otherwise.
  732. */
  733. isConnectionInterrupted() {
  734. return this._room.isConnectionInterrupted();
  735. },
  736. /**
  737. * Finds JitsiParticipant for given id.
  738. *
  739. * @param {string} id participant's identifier(MUC nickname).
  740. *
  741. * @returns {JitsiParticipant|null} participant instance for given id or
  742. * null if not found.
  743. */
  744. getParticipantById(id) {
  745. return room ? room.getParticipantById(id) : null;
  746. },
  747. /**
  748. * Get participant connection status for the participant.
  749. *
  750. * @param {string} id participant's identifier(MUC nickname)
  751. *
  752. * @returns {ParticipantConnectionStatus|null} the status of the participant
  753. * or null if no such participant is found or participant is the local user.
  754. */
  755. getParticipantConnectionStatus(id) {
  756. let participant = this.getParticipantById(id);
  757. return participant ? participant.getConnectionStatus() : null;
  758. },
  759. /**
  760. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  761. * the given <tt>id</tt>.
  762. *
  763. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  764. *
  765. * @return {string} the participant's display name or the default string if
  766. * absent.
  767. */
  768. getParticipantDisplayName(id) {
  769. let displayName = getDisplayName(id);
  770. if (displayName) {
  771. return displayName;
  772. } else {
  773. if (APP.conference.isLocalId(id)) {
  774. return APP.translation.generateTranslationHTML(
  775. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  776. } else {
  777. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  778. }
  779. }
  780. },
  781. getMyUserId() {
  782. return this._room
  783. && this._room.myUserId();
  784. },
  785. /**
  786. * Indicates if recording is supported in this conference.
  787. */
  788. isRecordingSupported() {
  789. return this._room && this._room.isRecordingSupported();
  790. },
  791. /**
  792. * Returns the recording state or undefined if the room is not defined.
  793. */
  794. getRecordingState() {
  795. return (this._room) ? this._room.getRecordingState() : undefined;
  796. },
  797. /**
  798. * Will be filled with values only when config.debug is enabled.
  799. * Its used by torture to check audio levels.
  800. */
  801. audioLevelsMap: {},
  802. /**
  803. * Returns the stored audio level (stored only if config.debug is enabled)
  804. * @param id the id for the user audio level to return (the id value is
  805. * returned for the participant using getMyUserId() method)
  806. */
  807. getPeerSSRCAudioLevel(id) {
  808. return this.audioLevelsMap[id];
  809. },
  810. /**
  811. * @return {number} the number of participants in the conference with at
  812. * least one track.
  813. */
  814. getNumberOfParticipantsWithTracks() {
  815. return this._room.getParticipants()
  816. .filter((p) => p.getTracks().length > 0)
  817. .length;
  818. },
  819. /**
  820. * Returns the stats.
  821. */
  822. getStats() {
  823. return room.connectionQuality.getStats();
  824. },
  825. // end used by torture
  826. getLogs() {
  827. return room.getLogs();
  828. },
  829. /**
  830. * Download logs, a function that can be called from console while
  831. * debugging.
  832. * @param filename (optional) specify target filename
  833. */
  834. saveLogs(filename = 'meetlog.json') {
  835. // this can be called from console and will not have reference to this
  836. // that's why we reference the global var
  837. let logs = APP.conference.getLogs();
  838. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  839. let elem = document.createElement('a');
  840. elem.download = filename;
  841. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  842. elem.dataset.downloadurl
  843. = ['text/json', elem.download, elem.href].join(':');
  844. elem.dispatchEvent(new MouseEvent('click', {
  845. view: window,
  846. bubbles: true,
  847. cancelable: false
  848. }));
  849. },
  850. /**
  851. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  852. * desire to keep room private to this instance and (2) the need of other
  853. * modules to send and receive commands to and from participants.
  854. * Eventually, this instance remains in control with respect to the
  855. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  856. * JitsiConference) is to be used in the implementation of the Command(s)
  857. * API of this instance.
  858. */
  859. commands: {
  860. /**
  861. * Known custom conference commands.
  862. */
  863. defaults: commands,
  864. /**
  865. * Receives notifications from other participants about commands aka
  866. * custom events (sent by sendCommand or sendCommandOnce methods).
  867. * @param command {String} the name of the command
  868. * @param handler {Function} handler for the command
  869. */
  870. addCommandListener () {
  871. room.addCommandListener.apply(room, arguments);
  872. },
  873. /**
  874. * Removes command.
  875. * @param name {String} the name of the command.
  876. */
  877. removeCommand () {
  878. room.removeCommand.apply(room, arguments);
  879. },
  880. /**
  881. * Sends command.
  882. * @param name {String} the name of the command.
  883. * @param values {Object} with keys and values that will be sent.
  884. */
  885. sendCommand () {
  886. room.sendCommand.apply(room, arguments);
  887. },
  888. /**
  889. * Sends command one time.
  890. * @param name {String} the name of the command.
  891. * @param values {Object} with keys and values that will be sent.
  892. */
  893. sendCommandOnce () {
  894. room.sendCommandOnce.apply(room, arguments);
  895. }
  896. },
  897. _createRoom (localTracks) {
  898. room = connection.initJitsiConference(APP.conference.roomName,
  899. this._getConferenceOptions());
  900. this._setLocalAudioVideoStreams(localTracks);
  901. this._room = room; // FIXME do not use this
  902. _setupLocalParticipantProperties();
  903. this._setupListeners();
  904. },
  905. /**
  906. * Sets local video and audio streams.
  907. * @param {JitsiLocalTrack[]} tracks=[]
  908. * @returns {Promise[]}
  909. * @private
  910. */
  911. _setLocalAudioVideoStreams(tracks = []) {
  912. return tracks.map(track => {
  913. if (track.isAudioTrack()) {
  914. return this.useAudioStream(track);
  915. } else if (track.isVideoTrack()) {
  916. return this.useVideoStream(track);
  917. } else {
  918. logger.error(
  919. "Ignored not an audio nor a video track: ", track);
  920. return Promise.resolve();
  921. }
  922. });
  923. },
  924. _getConferenceOptions() {
  925. let options = config;
  926. if(config.enableRecording && !config.recordingType) {
  927. options.recordingType = (config.hosts &&
  928. (typeof config.hosts.jirecon != "undefined"))?
  929. "jirecon" : "colibri";
  930. }
  931. return options;
  932. },
  933. /**
  934. * Start using provided video stream.
  935. * Stops previous video stream.
  936. * @param {JitsiLocalTrack} [stream] new stream to use or null
  937. * @returns {Promise}
  938. */
  939. useVideoStream(newStream) {
  940. return APP.store.dispatch(
  941. replaceLocalTrack(localVideo, newStream, room))
  942. .then(() => {
  943. localVideo = newStream;
  944. if (newStream) {
  945. this.videoMuted = newStream.isMuted();
  946. this.isSharingScreen = newStream.videoType === 'desktop';
  947. APP.UI.addLocalStream(newStream);
  948. newStream.videoType === 'camera'
  949. && APP.UI.setCameraButtonEnabled(true);
  950. } else {
  951. this.videoMuted = false;
  952. this.isSharingScreen = false;
  953. }
  954. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  955. APP.UI.updateDesktopSharingButtons();
  956. });
  957. },
  958. /**
  959. * Start using provided audio stream.
  960. * Stops previous audio stream.
  961. * @param {JitsiLocalTrack} [stream] new stream to use or null
  962. * @returns {Promise}
  963. */
  964. useAudioStream(newStream) {
  965. return APP.store.dispatch(
  966. replaceLocalTrack(localAudio, newStream, room))
  967. .then(() => {
  968. localAudio = newStream;
  969. if (newStream) {
  970. this.audioMuted = newStream.isMuted();
  971. APP.UI.addLocalStream(newStream);
  972. } else {
  973. this.audioMuted = false;
  974. }
  975. APP.UI.setMicrophoneButtonEnabled(true);
  976. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  977. });
  978. },
  979. /**
  980. * Triggers a tooltip to display when a feature was attempted to be used
  981. * while in audio only mode.
  982. *
  983. * @param {string} featureName - The name of the feature that attempted to
  984. * toggle.
  985. * @private
  986. * @returns {void}
  987. */
  988. _displayAudioOnlyTooltip(featureName) {
  989. let tooltipElementId = null;
  990. switch (featureName) {
  991. case 'screenShare':
  992. tooltipElementId = '#screenshareWhileAudioOnly';
  993. break;
  994. case 'videoMute':
  995. tooltipElementId = '#unmuteWhileAudioOnly';
  996. break;
  997. }
  998. if (tooltipElementId) {
  999. APP.UI.showToolbar(6000);
  1000. APP.UI.showCustomToolbarPopup(
  1001. tooltipElementId, true, 5000);
  1002. }
  1003. },
  1004. /**
  1005. * Returns whether or not the conference is currently in audio only mode.
  1006. *
  1007. * @returns {boolean}
  1008. */
  1009. isAudioOnly() {
  1010. return Boolean(
  1011. APP.store.getState()['features/base/conference'].audioOnly);
  1012. },
  1013. videoSwitchInProgress: false,
  1014. /**
  1015. * Toggles between screensharing and camera video.
  1016. * @param {boolean} [shareScreen]
  1017. * @return {Promise.<T>}
  1018. */
  1019. toggleScreenSharing(shareScreen = !this.isSharingScreen) {
  1020. if (this.videoSwitchInProgress) {
  1021. return Promise.reject('Switch in progress.');
  1022. }
  1023. if (!this.isDesktopSharingEnabled) {
  1024. return Promise.reject(
  1025. 'Cannot toggle screen sharing: not supported.');
  1026. }
  1027. if (this.isAudioOnly()) {
  1028. this._displayAudioOnlyTooltip('screenShare');
  1029. return Promise.reject('No screensharing in audio only mode');
  1030. }
  1031. this.videoSwitchInProgress = true;
  1032. let externalInstallation = false;
  1033. if (shareScreen) {
  1034. return createLocalTracks({
  1035. devices: ['desktop'],
  1036. desktopSharingExtensionExternalInstallation: {
  1037. interval: 500,
  1038. checkAgain: () => {
  1039. return DSExternalInstallationInProgress;
  1040. },
  1041. listener: (status, url) => {
  1042. switch(status) {
  1043. case "waitingForExtension":
  1044. DSExternalInstallationInProgress = true;
  1045. externalInstallation = true;
  1046. APP.UI.showExtensionExternalInstallationDialog(
  1047. url);
  1048. break;
  1049. case "extensionFound":
  1050. if(externalInstallation) //close the dialog
  1051. $.prompt.close();
  1052. break;
  1053. default:
  1054. //Unknown status
  1055. }
  1056. }
  1057. }
  1058. }).then(([stream]) => {
  1059. DSExternalInstallationInProgress = false;
  1060. // close external installation dialog on success.
  1061. if(externalInstallation)
  1062. $.prompt.close();
  1063. stream.on(
  1064. TrackEvents.LOCAL_TRACK_STOPPED,
  1065. () => {
  1066. // if stream was stopped during screensharing session
  1067. // then we should switch to video
  1068. // otherwise we stopped it because we already switched
  1069. // to video, so nothing to do here
  1070. if (this.isSharingScreen) {
  1071. this.toggleScreenSharing(false);
  1072. }
  1073. }
  1074. );
  1075. return this.useVideoStream(stream);
  1076. }).then(() => {
  1077. this.videoSwitchInProgress = false;
  1078. JitsiMeetJS.analytics.sendEvent(
  1079. 'conference.sharingDesktop.start');
  1080. logger.log('sharing local desktop');
  1081. }).catch((err) => {
  1082. // close external installation dialog to show the error.
  1083. if(externalInstallation)
  1084. $.prompt.close();
  1085. this.videoSwitchInProgress = false;
  1086. this.toggleScreenSharing(false);
  1087. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1088. return;
  1089. }
  1090. logger.error('failed to share local desktop', err);
  1091. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  1092. APP.UI.showExtensionRequiredDialog(
  1093. config.desktopSharingFirefoxExtensionURL
  1094. );
  1095. return;
  1096. }
  1097. // Handling:
  1098. // TrackErrors.PERMISSION_DENIED
  1099. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1100. // TrackErrors.GENERAL
  1101. // and any other
  1102. let dialogTxt;
  1103. let dialogTitleKey;
  1104. if (err.name === TrackErrors.PERMISSION_DENIED) {
  1105. dialogTxt = APP.translation.generateTranslationHTML(
  1106. "dialog.screenSharingPermissionDeniedError");
  1107. dialogTitleKey = "dialog.error";
  1108. } else {
  1109. dialogTxt = APP.translation.generateTranslationHTML(
  1110. "dialog.failtoinstall");
  1111. dialogTitleKey = "dialog.permissionDenied";
  1112. }
  1113. APP.UI.messageHandler.openDialog(
  1114. dialogTitleKey, dialogTxt, false);
  1115. });
  1116. } else {
  1117. APP.remoteControl.receiver.stop();
  1118. return createLocalTracks(
  1119. { devices: ['video'] })
  1120. .then(
  1121. ([stream]) => this.useVideoStream(stream)
  1122. ).then(() => {
  1123. this.videoSwitchInProgress = false;
  1124. JitsiMeetJS.analytics.sendEvent(
  1125. 'conference.sharingDesktop.stop');
  1126. logger.log('sharing local video');
  1127. }).catch((err) => {
  1128. this.useVideoStream(null);
  1129. this.videoSwitchInProgress = false;
  1130. logger.error('failed to share local video', err);
  1131. });
  1132. }
  1133. },
  1134. /**
  1135. * Setup interaction between conference and UI.
  1136. */
  1137. _setupListeners() {
  1138. // add local streams when joined to the conference
  1139. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1140. APP.store.dispatch(conferenceJoined(room));
  1141. APP.UI.mucJoined();
  1142. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1143. APP.UI.markVideoInterrupted(false);
  1144. });
  1145. room.on(
  1146. ConferenceEvents.CONFERENCE_LEFT,
  1147. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1148. room.on(
  1149. ConferenceEvents.AUTH_STATUS_CHANGED,
  1150. (authEnabled, authLogin) =>
  1151. APP.UI.updateAuthInfo(authEnabled, authLogin));
  1152. room.on(ConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1153. user => APP.UI.onUserFeaturesChanged(user));
  1154. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1155. if (user.isHidden())
  1156. return;
  1157. APP.store.dispatch(participantJoined({
  1158. id,
  1159. name: user.getDisplayName(),
  1160. role: user.getRole()
  1161. }));
  1162. logger.log('USER %s connnected', id, user);
  1163. APP.API.notifyUserJoined(id);
  1164. APP.UI.addUser(user);
  1165. // check the roles for the new user and reflect them
  1166. APP.UI.updateUserRole(user);
  1167. updateRemoteThumbnailsVisibility();
  1168. });
  1169. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1170. APP.store.dispatch(participantLeft(id, user));
  1171. logger.log('USER %s LEFT', id, user);
  1172. APP.API.notifyUserLeft(id);
  1173. APP.UI.removeUser(id, user.getDisplayName());
  1174. APP.UI.onSharedVideoStop(id);
  1175. updateRemoteThumbnailsVisibility();
  1176. });
  1177. room.on(ConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1178. let user = room.getParticipantById(id);
  1179. if (user) {
  1180. APP.UI.updateUserStatus(user, status);
  1181. }
  1182. });
  1183. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1184. if (this.isLocalId(id)) {
  1185. logger.info(`My role changed, new role: ${role}`);
  1186. APP.store.dispatch(localParticipantRoleChanged(role));
  1187. if (this.isModerator !== room.isModerator()) {
  1188. this.isModerator = room.isModerator();
  1189. APP.UI.updateLocalRole(room.isModerator());
  1190. }
  1191. } else {
  1192. APP.store.dispatch(participantRoleChanged(id, role));
  1193. let user = room.getParticipantById(id);
  1194. if (user) {
  1195. APP.UI.updateUserRole(user);
  1196. }
  1197. }
  1198. });
  1199. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1200. if(!track || track.isLocal())
  1201. return;
  1202. APP.store.dispatch(trackAdded(track));
  1203. });
  1204. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1205. if(!track || track.isLocal())
  1206. return;
  1207. APP.store.dispatch(trackRemoved(track));
  1208. });
  1209. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1210. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1211. lvl = 0;
  1212. }
  1213. if(config.debug)
  1214. {
  1215. this.audioLevelsMap[id] = lvl;
  1216. if(config.debugAudioLevels)
  1217. logger.log("AudioLevel:" + id + "/" + lvl);
  1218. }
  1219. APP.UI.setAudioLevel(id, lvl);
  1220. });
  1221. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1222. APP.UI.showToolbar(6000);
  1223. APP.UI.showCustomToolbarPopup('#talkWhileMutedPopup', true, 5000);
  1224. });
  1225. room.on(
  1226. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1227. (leavingIds, enteringIds) => {
  1228. APP.UI.handleLastNEndpoints(leavingIds, enteringIds);
  1229. });
  1230. room.on(
  1231. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1232. id => {
  1233. APP.UI.participantConnectionStatusChanged(id);
  1234. });
  1235. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1236. if (this.isLocalId(id)) {
  1237. this.isDominantSpeaker = true;
  1238. this.setRaisedHand(false);
  1239. } else {
  1240. this.isDominantSpeaker = false;
  1241. var participant = room.getParticipantById(id);
  1242. if (participant) {
  1243. APP.UI.setRaisedHandStatus(participant, false);
  1244. }
  1245. }
  1246. APP.UI.markDominantSpeaker(id);
  1247. });
  1248. if (!interfaceConfig.filmStripOnly) {
  1249. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1250. APP.UI.markVideoInterrupted(true);
  1251. });
  1252. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1253. APP.UI.markVideoInterrupted(false);
  1254. });
  1255. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, body, ts) => {
  1256. let nick = getDisplayName(id);
  1257. APP.API.notifyReceivedChatMessage({
  1258. id,
  1259. nick,
  1260. body,
  1261. ts
  1262. });
  1263. APP.UI.addMessage(id, nick, body, ts);
  1264. });
  1265. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1266. APP.API.notifySendingChatMessage(message);
  1267. room.sendTextMessage(message);
  1268. });
  1269. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1270. try {
  1271. // do not try to select participant if there is none (we
  1272. // are alone in the room), otherwise an error will be
  1273. // thrown cause reporting mechanism is not available
  1274. // (datachannels currently)
  1275. if (room.getParticipants().length === 0)
  1276. return;
  1277. room.selectParticipant(id);
  1278. } catch (e) {
  1279. JitsiMeetJS.analytics.sendEvent(
  1280. 'selectParticipant.failed');
  1281. reportError(e);
  1282. }
  1283. });
  1284. APP.UI.addListener(
  1285. UIEvents.VIDEO_UNMUTING_WHILE_AUDIO_ONLY,
  1286. () => this._displayAudioOnlyTooltip('videoMute'));
  1287. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1288. (smallVideo, isPinned) => {
  1289. let smallVideoId = smallVideo.getId();
  1290. let isLocal = APP.conference.isLocalId(smallVideoId);
  1291. let eventName
  1292. = (isPinned ? "pinned" : "unpinned") + "." +
  1293. (isLocal ? "local" : "remote");
  1294. let participantCount = room.getParticipantCount();
  1295. JitsiMeetJS.analytics.sendEvent(
  1296. eventName,
  1297. { value: participantCount });
  1298. // FIXME why VIDEO_CONTAINER_TYPE instead of checking if
  1299. // the participant is on the large video ?
  1300. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1301. && !isLocal) {
  1302. // When the library starts supporting multiple pins we
  1303. // would pass the isPinned parameter together with the
  1304. // identifier, but currently we send null to indicate that
  1305. // we unpin the last pinned.
  1306. try {
  1307. room.pinParticipant(isPinned ? smallVideoId : null);
  1308. } catch (e) {
  1309. reportError(e);
  1310. }
  1311. }
  1312. updateRemoteThumbnailsVisibility();
  1313. });
  1314. }
  1315. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1316. APP.UI.showLocalConnectionInterrupted(true);
  1317. });
  1318. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1319. APP.UI.showLocalConnectionInterrupted(false);
  1320. });
  1321. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1322. const formattedDisplayName
  1323. = displayName.substr(0, MAX_DISPLAY_NAME_LENGTH);
  1324. APP.store.dispatch(participantUpdated({
  1325. id,
  1326. name: formattedDisplayName
  1327. }));
  1328. APP.API.notifyDisplayNameChanged(id, formattedDisplayName);
  1329. APP.UI.changeDisplayName(id, formattedDisplayName);
  1330. });
  1331. room.on(
  1332. ConferenceEvents.LOCK_STATE_CHANGED,
  1333. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1334. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1335. (participant, name, oldValue, newValue) => {
  1336. if (name === "raisedHand") {
  1337. APP.UI.setRaisedHandStatus(participant, newValue);
  1338. }
  1339. });
  1340. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1341. logger.log("Received recorder status change: ", status, error);
  1342. APP.UI.updateRecordingState(status);
  1343. });
  1344. room.on(ConferenceEvents.KICKED, () => {
  1345. APP.UI.hideStats();
  1346. APP.UI.notifyKicked();
  1347. // FIXME close
  1348. });
  1349. room.on(ConferenceEvents.SUSPEND_DETECTED, () => {
  1350. APP.store.dispatch(suspendDetected());
  1351. // After wake up, we will be in a state where conference is left
  1352. // there will be dialog shown to user.
  1353. // We do not want video/audio as we show an overlay and after it
  1354. // user need to rejoin or close, while waking up we can detect
  1355. // camera wakeup as a problem with device.
  1356. // We also do not care about device change, which happens
  1357. // on resume after suspending PC.
  1358. if (this.deviceChangeListener)
  1359. JitsiMeetJS.mediaDevices.removeEventListener(
  1360. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1361. this.deviceChangeListener);
  1362. // stop local video
  1363. if (localVideo) {
  1364. localVideo.dispose();
  1365. }
  1366. // stop local audio
  1367. if (localAudio) {
  1368. localAudio.dispose();
  1369. }
  1370. });
  1371. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1372. APP.UI.updateDTMFSupport(isDTMFSupported);
  1373. });
  1374. APP.UI.addListener(UIEvents.EXTERNAL_INSTALLATION_CANCELED, () => {
  1375. // Wait a little bit more just to be sure that we won't miss the
  1376. // extension installation
  1377. setTimeout(() => DSExternalInstallationInProgress = false, 500);
  1378. });
  1379. APP.UI.addListener(UIEvents.OPEN_EXTENSION_STORE, (url) => {
  1380. window.open(
  1381. url, "extension_store_window",
  1382. "resizable,scrollbars=yes,status=1");
  1383. });
  1384. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1385. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  1386. if (this.isAudioOnly() && !muted) {
  1387. this._displayAudioOnlyTooltip('videoMute');
  1388. return;
  1389. }
  1390. muteLocalVideo(muted);
  1391. });
  1392. room.on(ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  1393. (stats) => {
  1394. APP.UI.updateLocalStats(stats.connectionQuality, stats);
  1395. });
  1396. room.on(ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  1397. (id, stats) => {
  1398. APP.UI.updateRemoteStats(id, stats.connectionQuality, stats);
  1399. });
  1400. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1401. APP.UI.initEtherpad(value);
  1402. });
  1403. APP.UI.addListener(UIEvents.EMAIL_CHANGED, this.changeLocalEmail);
  1404. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1405. APP.store.dispatch(participantUpdated({
  1406. id: from,
  1407. email: data.value
  1408. }));
  1409. APP.UI.setUserEmail(from, data.value);
  1410. });
  1411. room.addCommandListener(
  1412. this.commands.defaults.AVATAR_URL,
  1413. (data, from) => {
  1414. APP.store.dispatch(
  1415. participantUpdated({
  1416. id: from,
  1417. avatarURL: data.value
  1418. }));
  1419. APP.UI.setUserAvatarUrl(from, data.value);
  1420. });
  1421. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1422. (data, from) => {
  1423. APP.store.dispatch(
  1424. participantUpdated({
  1425. id: from,
  1426. avatarID: data.value
  1427. }));
  1428. APP.UI.setUserAvatarID(from, data.value);
  1429. });
  1430. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1431. this.changeLocalDisplayName.bind(this));
  1432. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1433. (startAudioMuted, startVideoMuted) => {
  1434. room.setStartMutedPolicy({
  1435. audio: startAudioMuted,
  1436. video: startVideoMuted
  1437. });
  1438. }
  1439. );
  1440. room.on(
  1441. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1442. ({ audio, video }) => {
  1443. APP.UI.onStartMutedChanged(audio, video);
  1444. }
  1445. );
  1446. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1447. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1448. && APP.UI.notifyInitiallyMuted();
  1449. });
  1450. room.on(
  1451. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1452. APP.UI.updateDevicesAvailability(id, devices);
  1453. }
  1454. );
  1455. // call hangup
  1456. APP.UI.addListener(UIEvents.HANGUP, () => {
  1457. this.hangup(true);
  1458. });
  1459. // logout
  1460. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1461. AuthHandler.logout(room).then(url => {
  1462. if (url) {
  1463. UIUtil.redirect(url);
  1464. } else {
  1465. this.hangup(true);
  1466. }
  1467. });
  1468. });
  1469. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1470. (id, oldResolution, newResolution, delay) => {
  1471. var logObject = {
  1472. id: "resolution_change",
  1473. participant: id,
  1474. oldValue: oldResolution,
  1475. newValue: newResolution,
  1476. delay: delay
  1477. };
  1478. room.sendApplicationLog(JSON.stringify(logObject));
  1479. // We only care about the delay between simulcast streams.
  1480. // Longer delays will be caused by something else and will just
  1481. // poison the data.
  1482. if (delay < 2000) {
  1483. JitsiMeetJS.analytics.sendEvent('stream.switch.delay',
  1484. {value: delay});
  1485. }
  1486. });
  1487. // Starts or stops the recording for the conference.
  1488. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1489. room.toggleRecording(options);
  1490. });
  1491. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1492. room.setSubject(topic);
  1493. });
  1494. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1495. APP.UI.setSubject(subject);
  1496. });
  1497. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1498. room.kickParticipant(id);
  1499. });
  1500. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1501. room.muteParticipant(id);
  1502. });
  1503. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1504. AuthHandler.authenticate(room);
  1505. });
  1506. APP.UI.addListener(
  1507. UIEvents.VIDEO_DEVICE_CHANGED,
  1508. (cameraDeviceId) => {
  1509. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1510. createLocalTracks({
  1511. devices: ['video'],
  1512. cameraDeviceId: cameraDeviceId,
  1513. micDeviceId: null
  1514. })
  1515. .then(([stream]) => {
  1516. if (this.isAudioOnly()) {
  1517. return stream.mute()
  1518. .then(() => stream);
  1519. }
  1520. return stream;
  1521. })
  1522. .then(stream => {
  1523. this.useVideoStream(stream);
  1524. logger.log('switched local video device');
  1525. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1526. })
  1527. .catch((err) => {
  1528. APP.UI.showDeviceErrorDialog(null, err);
  1529. });
  1530. }
  1531. );
  1532. APP.UI.addListener(
  1533. UIEvents.AUDIO_DEVICE_CHANGED,
  1534. (micDeviceId) => {
  1535. JitsiMeetJS.analytics.sendEvent(
  1536. 'settings.changeDevice.audioIn');
  1537. createLocalTracks({
  1538. devices: ['audio'],
  1539. cameraDeviceId: null,
  1540. micDeviceId: micDeviceId
  1541. })
  1542. .then(([stream]) => {
  1543. this.useAudioStream(stream);
  1544. logger.log('switched local audio device');
  1545. APP.settings.setMicDeviceId(micDeviceId, true);
  1546. })
  1547. .catch((err) => {
  1548. APP.UI.showDeviceErrorDialog(err, null);
  1549. });
  1550. }
  1551. );
  1552. APP.UI.addListener(
  1553. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1554. (audioOutputDeviceId) => {
  1555. JitsiMeetJS.analytics.sendEvent(
  1556. 'settings.changeDevice.audioOut');
  1557. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1558. .then(() => logger.log('changed audio output device'))
  1559. .catch((err) => {
  1560. logger.warn('Failed to change audio output device. ' +
  1561. 'Default or previously set audio output device ' +
  1562. 'will be used instead.', err);
  1563. });
  1564. }
  1565. );
  1566. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  1567. muteLocalVideo(audioOnly);
  1568. // Immediately update the UI by having remote videos and the large
  1569. // video update themselves instead of waiting for some other event
  1570. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  1571. // There is no guarantee another event will trigger the update
  1572. // immediately and in all situations, for example because a remote
  1573. // participant is having connection trouble so no status changes.
  1574. APP.UI.updateAllVideos();
  1575. });
  1576. APP.UI.addListener(
  1577. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1578. );
  1579. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1580. (url, state, time, isMuted, volume) => {
  1581. // send start and stop commands once, and remove any updates
  1582. // that had left
  1583. if (state === 'stop' || state === 'start' || state === 'playing') {
  1584. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1585. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1586. value: url,
  1587. attributes: {
  1588. state: state,
  1589. time: time,
  1590. muted: isMuted,
  1591. volume: volume
  1592. }
  1593. });
  1594. }
  1595. else {
  1596. // in case of paused, in order to allow late users to join
  1597. // paused
  1598. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1599. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1600. value: url,
  1601. attributes: {
  1602. state: state,
  1603. time: time,
  1604. muted: isMuted,
  1605. volume: volume
  1606. }
  1607. });
  1608. }
  1609. updateRemoteThumbnailsVisibility();
  1610. });
  1611. room.addCommandListener(
  1612. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1613. if (attributes.state === 'stop') {
  1614. APP.UI.onSharedVideoStop(id, attributes);
  1615. }
  1616. else if (attributes.state === 'start') {
  1617. APP.UI.onSharedVideoStart(id, value, attributes);
  1618. }
  1619. else if (attributes.state === 'playing'
  1620. || attributes.state === 'pause') {
  1621. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1622. }
  1623. });
  1624. function updateRemoteThumbnailsVisibility() {
  1625. const localUserId = APP.conference.getMyUserId();
  1626. const remoteParticipantsCount = room.getParticipantCount() - 1;
  1627. // Get the remote thumbnail count for cases where there are
  1628. // non-participants displaying video, such as with video sharing.
  1629. const remoteVideosCount = APP.UI.getRemoteVideosCount();
  1630. const shouldShowRemoteThumbnails = interfaceConfig.filmStripOnly
  1631. || (APP.UI.isPinned(localUserId) && remoteVideosCount)
  1632. || remoteVideosCount > 1
  1633. || remoteParticipantsCount !== remoteVideosCount;
  1634. APP.UI.setRemoteThumbnailsVisibility(
  1635. Boolean(shouldShowRemoteThumbnails));
  1636. }
  1637. },
  1638. /**
  1639. * Adds any room listener.
  1640. * @param {string} eventName one of the ConferenceEvents
  1641. * @param {Function} listener the function to be called when the event
  1642. * occurs
  1643. */
  1644. addConferenceListener(eventName, listener) {
  1645. room.on(eventName, listener);
  1646. },
  1647. /**
  1648. * Removes any room listener.
  1649. * @param {string} eventName one of the ConferenceEvents
  1650. * @param {Function} listener the listener to be removed.
  1651. */
  1652. removeConferenceListener(eventName, listener) {
  1653. room.off(eventName, listener);
  1654. },
  1655. /**
  1656. * Inits list of current devices and event listener for device change.
  1657. * @private
  1658. */
  1659. _initDeviceList() {
  1660. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1661. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1662. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1663. // Ugly way to synchronize real device IDs with local
  1664. // storage and settings menu. This is a workaround until
  1665. // getConstraints() method will be implemented in browsers.
  1666. if (localAudio) {
  1667. APP.settings.setMicDeviceId(
  1668. localAudio.getDeviceId(), false);
  1669. }
  1670. if (localVideo) {
  1671. APP.settings.setCameraDeviceId(
  1672. localVideo.getDeviceId(), false);
  1673. }
  1674. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1675. APP.UI.onAvailableDevicesChanged(devices);
  1676. APP.store.dispatch(updateDeviceList(devices));
  1677. });
  1678. this.deviceChangeListener = (devices) =>
  1679. window.setTimeout(
  1680. () => this._onDeviceListChanged(devices), 0);
  1681. JitsiMeetJS.mediaDevices.addEventListener(
  1682. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1683. this.deviceChangeListener);
  1684. }
  1685. },
  1686. /**
  1687. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1688. * handle change of available media devices.
  1689. * @private
  1690. * @param {MediaDeviceInfo[]} devices
  1691. * @returns {Promise}
  1692. */
  1693. _onDeviceListChanged(devices) {
  1694. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1695. // Event handler can be fired before direct
  1696. // enumerateDevices() call, so handle this situation here.
  1697. if (!currentDevices.audioinput &&
  1698. !currentDevices.videoinput &&
  1699. !currentDevices.audiooutput) {
  1700. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1701. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1702. }
  1703. let newDevices =
  1704. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1705. devices, this.isSharingScreen, localVideo, localAudio);
  1706. let promises = [];
  1707. let audioWasMuted = this.audioMuted;
  1708. let videoWasMuted = this.videoMuted;
  1709. let availableAudioInputDevices =
  1710. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1711. let availableVideoInputDevices =
  1712. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1713. if (typeof newDevices.audiooutput !== 'undefined') {
  1714. // Just ignore any errors in catch block.
  1715. promises.push(APP.settings
  1716. .setAudioOutputDeviceId(newDevices.audiooutput)
  1717. .catch());
  1718. }
  1719. promises.push(
  1720. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1721. createLocalTracks,
  1722. newDevices.videoinput,
  1723. newDevices.audioinput)
  1724. .then(tracks =>
  1725. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1726. .then(() => {
  1727. // If audio was muted before, or we unplugged current device
  1728. // and selected new one, then mute new audio track.
  1729. if (audioWasMuted ||
  1730. currentDevices.audioinput.length >
  1731. availableAudioInputDevices.length) {
  1732. muteLocalAudio(true);
  1733. }
  1734. // If video was muted before, or we unplugged current device
  1735. // and selected new one, then mute new video track.
  1736. if (videoWasMuted ||
  1737. currentDevices.videoinput.length >
  1738. availableVideoInputDevices.length) {
  1739. muteLocalVideo(true);
  1740. }
  1741. }));
  1742. return Promise.all(promises)
  1743. .then(() => {
  1744. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1745. APP.UI.onAvailableDevicesChanged(devices);
  1746. });
  1747. },
  1748. /**
  1749. * Toggles the local "raised hand" status.
  1750. */
  1751. maybeToggleRaisedHand() {
  1752. this.setRaisedHand(!this.isHandRaised);
  1753. },
  1754. /**
  1755. * Sets the local "raised hand" status to a particular value.
  1756. */
  1757. setRaisedHand(raisedHand) {
  1758. if (raisedHand !== this.isHandRaised)
  1759. {
  1760. APP.UI.onLocalRaiseHandChanged(raisedHand);
  1761. this.isHandRaised = raisedHand;
  1762. // Advertise the updated status
  1763. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1764. // Update the view
  1765. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1766. }
  1767. },
  1768. /**
  1769. * Log event to callstats and analytics.
  1770. * @param {string} name the event name
  1771. * @param {int} value the value (it's int because google analytics supports
  1772. * only int).
  1773. * @param {string} label short text which provides more info about the event
  1774. * which allows to distinguish between few event cases of the same name
  1775. * NOTE: Should be used after conference.init
  1776. */
  1777. logEvent(name, value, label) {
  1778. if(JitsiMeetJS.analytics) {
  1779. JitsiMeetJS.analytics.sendEvent(name, {value, label});
  1780. }
  1781. if(room) {
  1782. room.sendApplicationLog(JSON.stringify({name, value, label}));
  1783. }
  1784. },
  1785. /**
  1786. * Methods logs an application event given in the JSON format.
  1787. * @param {string} logJSON an event to be logged in JSON format
  1788. */
  1789. logJSON(logJSON) {
  1790. if (room) {
  1791. room.sendApplicationLog(logJSON);
  1792. }
  1793. },
  1794. /**
  1795. * Disconnect from the conference and optionally request user feedback.
  1796. * @param {boolean} [requestFeedback=false] if user feedback should be
  1797. * requested
  1798. */
  1799. hangup(requestFeedback = false) {
  1800. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  1801. let requestFeedbackPromise = requestFeedback
  1802. ? APP.UI.requestFeedbackOnHangup()
  1803. // false - because the thank you dialog shouldn't be displayed
  1804. .catch(() => Promise.resolve(false))
  1805. : Promise.resolve(true);// true - because the thank you dialog
  1806. //should be displayed
  1807. // All promises are returning Promise.resolve to make Promise.all to
  1808. // be resolved when both Promises are finished. Otherwise Promise.all
  1809. // will reject on first rejected Promise and we can redirect the page
  1810. // before all operations are done.
  1811. Promise.all([
  1812. requestFeedbackPromise,
  1813. room.leave().then(disconnect, disconnect)
  1814. ]).then(values => {
  1815. APP.API.notifyReadyToClose();
  1816. maybeRedirectToWelcomePage(values[0]);
  1817. });
  1818. },
  1819. /**
  1820. * Changes the email for the local user
  1821. * @param email {string} the new email
  1822. */
  1823. changeLocalEmail(email = '') {
  1824. email = String(email).trim();
  1825. if (email === APP.settings.getEmail()) {
  1826. return;
  1827. }
  1828. const localId = room ? room.myUserId() : undefined;
  1829. APP.store.dispatch(participantUpdated({
  1830. id: localId,
  1831. local: true,
  1832. email
  1833. }));
  1834. APP.settings.setEmail(email);
  1835. APP.UI.setUserEmail(localId, email);
  1836. sendData(commands.EMAIL, email);
  1837. },
  1838. /**
  1839. * Changes the avatar url for the local user
  1840. * @param url {string} the new url
  1841. */
  1842. changeLocalAvatarUrl(url = '') {
  1843. url = String(url).trim();
  1844. if (url === APP.settings.getAvatarUrl()) {
  1845. return;
  1846. }
  1847. const localId = room ? room.myUserId() : undefined;
  1848. APP.store.dispatch(participantUpdated({
  1849. id: localId,
  1850. local: true,
  1851. avatarURL: url
  1852. }));
  1853. APP.settings.setAvatarUrl(url);
  1854. APP.UI.setUserAvatarUrl(localId, url);
  1855. sendData(commands.AVATAR_URL, url);
  1856. },
  1857. /**
  1858. * Sends a message via the data channel.
  1859. * @param {string} to the id of the endpoint that should receive the
  1860. * message. If "" - the message will be sent to all participants.
  1861. * @param {object} payload the payload of the message.
  1862. * @throws NetworkError or InvalidStateError or Error if the operation
  1863. * fails.
  1864. */
  1865. sendEndpointMessage(to, payload) {
  1866. room.sendEndpointMessage(to, payload);
  1867. },
  1868. /**
  1869. * Adds new listener.
  1870. * @param {String} eventName the name of the event
  1871. * @param {Function} listener the listener.
  1872. */
  1873. addListener(eventName, listener) {
  1874. eventEmitter.addListener(eventName, listener);
  1875. },
  1876. /**
  1877. * Removes listener.
  1878. * @param {String} eventName the name of the event that triggers the
  1879. * listener
  1880. * @param {Function} listener the listener.
  1881. */
  1882. removeListener(eventName, listener) {
  1883. eventEmitter.removeListener(eventName, listener);
  1884. },
  1885. /**
  1886. * Changes the display name for the local user
  1887. * @param nickname {string} the new display name
  1888. */
  1889. changeLocalDisplayName(nickname = '') {
  1890. const formattedNickname
  1891. = nickname.trim().substr(0, MAX_DISPLAY_NAME_LENGTH);
  1892. if (formattedNickname === APP.settings.getDisplayName()) {
  1893. return;
  1894. }
  1895. APP.store.dispatch(participantUpdated({
  1896. id: this.getMyUserId(),
  1897. local: true,
  1898. name: formattedNickname
  1899. }));
  1900. APP.settings.setDisplayName(formattedNickname);
  1901. if (room) {
  1902. room.setDisplayName(formattedNickname);
  1903. APP.UI.changeDisplayName(this.getMyUserId(), formattedNickname);
  1904. }
  1905. }
  1906. };