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

conference.js 65KB

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