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

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