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.

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