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 61KB

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