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

conference.js 54KB

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