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

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