Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

conference.js 63KB

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