You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 62KB

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