您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 56KB

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