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

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