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

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