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

conference.js 54KB

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