您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 63KB

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