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

conference.js 53KB

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