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

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