Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conference.js 51KB

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