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

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