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

conference.js 55KB

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