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

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