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

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