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

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