Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

conference.js 58KB

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