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

conference.js 61KB

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