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

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