Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

conference.js 60KB

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