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

conference.js 60KB

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