📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
implemented live visitors feature
Blue Mouse653ec550813a
diff --git a/package.json b/package.jsonindex e8886c9f9..1d9cc4f77 100644--- a/package.json+++ b/package.json@@ -41,7 +41,7 @@"redux": "^4.1.1","redux-auth-wrapper": "^3.0.0","redux-saga": "^1.1.3",- "swetrix": "^1.1.0"+ "swetrix": "^1.2.0"},"scripts": {"start": "craco start",diff --git a/src/api/index.js b/src/api/index.jsindex ffb1712ab..20d2a4b32 100644--- a/src/api/index.js+++ b/src/api/index.js@@ -7,7 +7,7 @@ import { authActions } from 'redux/actions/auth'import { getAccessToken, removeAccessToken } from 'utils/accessToken'-const debug = Debug('analytics:api')+const debug = Debug('swetrix:api')const api = axios.create({baseURL: process.env.REACT_APP_API_URL,@@ -213,3 +213,12 @@ export const getOverallStats = (pids) =>debug('%s', error)throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})++export const getLiveVisitors = (pids) =>+ api+ .get(`log/hb?pids=[${_map(pids, (pid) => `"${pid}"`).join(',')}]`)+ .then(response => response.data)+ .catch(error => {+ debug('%s', error)+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })diff --git a/src/index.js b/src/index.jsindex 749eaaff4..cb81f06ed 100644--- a/src/index.js+++ b/src/index.js@@ -23,6 +23,7 @@ console.log('%cWelcome, hacker, glad you opened your console, you seem serious aSwetrix.init(SWETRIX_PID)Swetrix.trackViews({ignore: [/^\/projects/i, /^\/verify/i],+ heartbeatOnBackground: true,})Sentry.init({diff --git a/src/pages/Dashboard/Dashboard.jsx b/src/pages/Dashboard/Dashboard.jsxindex 573141e50..9cff63b56 100644--- a/src/pages/Dashboard/Dashboard.jsx+++ b/src/pages/Dashboard/Dashboard.jsx@@ -4,10 +4,10 @@ import cx from 'classnames'import dayjs from 'dayjs'import PropTypes from 'prop-types'import _isEmpty from 'lodash/isEmpty'+import _isNumber from 'lodash/isNumber'import _map from 'lodash/map'import { useTranslation } from 'react-i18next'import { EyeIcon } from '@heroicons/react/outline'-// import { ChartBarIcon } from '@heroicons/react/outline'import { CalendarIcon } from '@heroicons/react/outline'import { ArrowSmUpIcon } from '@heroicons/react/solid'import { ArrowSmDownIcon } from '@heroicons/react/solid'@@ -18,9 +18,12 @@ import { isAuthenticated } from 'hoc/protected'import Title from 'components/Title'import Loader from 'ui/Loader'import { ActivePin, InactivePin } from 'ui/Pin'+import PulsatingCircle from 'ui/icons/PulsatingCircle'import routes from 'routes'-const ProjectCart = ({ name, url, created, active, overall, t, language }) => {+const ProjectCart = ({+ name, url, created, active, overall, t, language, live,+}) => {const statsDidGrowUp = overall?.percChange >= 0return (@@ -47,7 +50,7 @@ const ProjectCart = ({ name, url, created, active, overall, t, language }) => {: <dd className='flex items-baseline'>- <p className='h-5 mr-1 text-gray-500'>+ <p className='h-5 mr-1'>{overall?.thisWeek}</p><p className={cx('flex text-xs -ml-1 items-baseline', {@@ -73,10 +76,12 @@ const ProjectCart = ({ name, url, created, active, overall, t, language }) => {</p></dd></div>- {/* <p className='mt-2 flex items-center text-sm text-gray-500 sm:mt-0'>- <ChartBarIcon className='flex-shrink-0 mr-1.5 h-5 w-5 text-gray-400' />- Average load time- </p> */}+ <div className='mt-2 flex items-center text-sm text-gray-500 sm:mt-0'>+ <PulsatingCircle className='flex-shrink-0 mr-3 ml-1' />+ Live visitors:+ + {live}+ </div></div><div className='mt-2 flex items-center text-sm text-gray-500'><CalendarIcon className='flex-shrink-0 mr-1.5 h-5 w-5 text-gray-400' />@@ -158,7 +163,7 @@ const Dashboard = ({ projects, isLoading, error, user }) => {) : (<div className='bg-white shadow overflow-hidden sm:rounded-md mt-10'><ul className='divide-y divide-gray-200'>- {_map(projects, ({ name, id, created, active, overall }) => (+ {_map(projects, ({ name, id, created, active, overall, live }) => (<ProjectCartkey={id}t={t}@@ -167,6 +172,7 @@ const Dashboard = ({ projects, isLoading, error, user }) => {created={created}active={active}overall={overall}+ live={_isNumber(live) ? live : 'N/A'}url={routes.project.replace(':id', id)}/>))}diff --git a/src/pages/Docs/Docs.jsx b/src/pages/Docs/Docs.jsxindex 70b8e17eb..61ac2deb0 100644--- a/src/pages/Docs/Docs.jsx+++ b/src/pages/Docs/Docs.jsx@@ -184,11 +184,17 @@ const Docs = () => {<hr className='mt-10 mb-4' /><p className='text-lg text-gray-900 tracking-tight'>- <i>Last updated: October 24, 2021.</i><br />+ <i>Last updated: November 30, 2021. (v1.2.0)</i><br /><div>- - Updated - <a className='hover:underline text-gray-700' href='#docs-umd'>UMD Build</a>- script URL.+ - Added a heartbeat mechanism to track realtime visitors.+ <br />+ New params noHeartbeat and heartbeatOnBackground have been introduced to the + <a className='hover:underline text-gray-700' href='#docs-tv'>trackViews</a>+ function.+ <br />+ - Using XMLHttpRequest instead of Fetch API for better browser compatibility.+ <br />+ - Other minor improvements and optimisations.</div></p></div>diff --git a/src/pages/Docs/examples.js b/src/pages/Docs/examples.jsindex 381532573..9392efa25 100644--- a/src/pages/Docs/examples.js+++ b/src/pages/Docs/examples.js@@ -66,9 +66,20 @@ export const trackPVAPI = `swetrix.trackViews({// This param is useful when tracking single-page landing websites.unique: false,- // A list of regular expressions or string pathes to ignore+ // A list of regular expressions or string pathes to ignore.// for example: ['/dashboard', /^\/projects/i] setting will force// script to ignore all pathes which start with /projects or equal to /dashboard// Please pay attention, that the pathes always start with /ignore: [],++ // Do not send Heartbeat requests to the server.+ // By setting this to true you will not be able to see the realtime amount of+ // users on your website.+ noHeartbeat?: boolean++ // Send Heartbeat requests when the website tab is not active in the browser.+ // Setting this to true means that users who opened your website in inactive+ // browser tab or window will not be counted into users realtime statistics.+ // Setting this to true is usually useful for services like Spotify or Youtube+ heartbeatOnBackground?: boolean})`diff --git a/src/pages/Project/View/Panels.jsx b/src/pages/Project/View/Panels.jsxindex 2dd93bb69..fa6f6e61c 100644--- a/src/pages/Project/View/Panels.jsx+++ b/src/pages/Project/View/Panels.jsx@@ -15,6 +15,7 @@ import _slice from 'lodash/slice'import _sum from 'lodash/sum'import Progress from 'ui/Progress'+import PulsatingCircle from 'ui/icons/PulsatingCircle'const ENTRIES_PER_PANEL = 5@@ -35,7 +36,7 @@ PanelContainer.propTypes = {}const Overview = ({- overall, chartData, activePeriod, t,+ overall, chartData, activePeriod, t, live,}) => {const pageviewsDidGrowUp = overall.percChange >= 0const uniqueDidGrowUp = overall.percChangeUnique >= 0@@ -44,6 +45,15 @@ const Overview = ({return (<PanelContainer name={t('project.overview')}>+ <div className='flex text-lg justify-between'>+ <div className='flex items-center'>+ <PulsatingCircle className='mr-1.5' type='big' />+ Live visitors:+ </div>+ <p className='h-5 mr-2 text-gray-900 text-xl'>+ {live}+ </p>+ </div>{!_isEmpty(chartData) && (<><p className='text-lg font-semibold'>diff --git a/src/pages/Project/View/ViewProject.jsx b/src/pages/Project/View/ViewProject.jsxindex 5e5072953..3f2e5f08d 100644--- a/src/pages/Project/View/ViewProject.jsx+++ b/src/pages/Project/View/ViewProject.jsx@@ -338,6 +338,7 @@ const ViewProject = ({overall={project.overall}chartData={chartData}activePeriod={activePeriod}+ live={project.live}/>)}{_map(panelsData.types, type => {diff --git a/src/redux/actions/ui/index.js b/src/redux/actions/ui/index.jsindex c67fa610a..352c0921a 100644--- a/src/redux/actions/ui/index.js+++ b/src/redux/actions/ui/index.js@@ -11,6 +11,13 @@ const setProjects = (projects) => ({},})+const setLiveStats = (data) => ({+ type: types.SET_LIVE_STATS,+ payload: {+ data,+ },+})+const setProject = (project) => ({type: types.SET_PROJECT,payload: {@@ -70,6 +77,7 @@ const UIActions = {deleteProjectCache,setProjectViewPrefs,setProject,+ setLiveStats,}export default UIActionsdiff --git a/src/redux/actions/ui/types.js b/src/redux/actions/ui/types.jsindex 107f70ee8..9d12ba5e0 100644--- a/src/redux/actions/ui/types.js+++ b/src/redux/actions/ui/types.js@@ -1,11 +1,12 @@export const types = {- LOAD_PROJECTS: 'LOAD_PROJECTS',- SET_PROJECTS_ERROR: 'SET_PROJECTS_ERROR',- SET_PROJECTS_LOADING: 'SET_PROJECTS_LOADING',- REMOVE_PROJECT: 'REMOVE_PROJECT',- SET_PROJECT_CACHE: 'SET_PROJECT_CACHE',- DELETE_PROJECT_CACHE: 'DELETE_PROJECT_CACHE',- SET_PROJECT_VIEW_PREFS: 'SET_PROJECT_VIEW_PREFS',- SET_PROJECTS: 'SET_PROJECTS',- SET_PROJECT: 'SET_PROJECT',+ LOAD_PROJECTS: 'UI_LOAD_PROJECTS',+ SET_PROJECTS_ERROR: 'UI_SET_PROJECTS_ERROR',+ SET_PROJECTS_LOADING: 'UI_SET_PROJECTS_LOADING',+ REMOVE_PROJECT: 'UI_REMOVE_PROJECT',+ SET_PROJECT_CACHE: 'UI_SET_PROJECT_CACHE',+ DELETE_PROJECT_CACHE: 'UI_DELETE_PROJECT_CACHE',+ SET_PROJECT_VIEW_PREFS: 'UI_SET_PROJECT_VIEW_PREFS',+ SET_PROJECTS: 'UI_SET_PROJECTS',+ SET_LIVE_STATS: 'UI_SET_LIVE_STATS',+ SET_PROJECT: 'UI_SET_PROJECT',}diff --git a/src/redux/reducers/ui/projects.js b/src/redux/reducers/ui/projects.jsindex 9869c6ece..3c2b11aea 100644--- a/src/redux/reducers/ui/projects.js+++ b/src/redux/reducers/ui/projects.js@@ -1,6 +1,7 @@import { types } from 'redux/actions/ui/types'import _filter from 'lodash/filter'import _findIndex from 'lodash/findIndex'+import _map from 'lodash/map'const getInitialState = () => {return {@@ -21,6 +22,18 @@ const projectsReducer = (state = getInitialState(), { type, payload }) => {}}+ case types.SET_LIVE_STATS: {+ const { data } = payload++ return {+ ...state,+ projects: _map(state.projects, res => ({+ ...res,+ live: data[res.id],+ }))+ }+ }+case types.SET_PROJECT: {const { project } = payloadreturn {diff --git a/src/redux/sagas/ui/index.js b/src/redux/sagas/ui/index.jsindex 628d757c0..6b01dc2ca 100644--- a/src/redux/sagas/ui/index.js+++ b/src/redux/sagas/ui/index.js@@ -4,10 +4,12 @@ import { types as authTypes } from '../../actions/auth/types'import loadProjects from './load_projects'import initialise from './initialise'+import liveVisitors from './worker_live_visitors'import logout from './logout'function* mainUISaga() {yield fork(initialise)+ yield fork(liveVisitors)yield takeEvery(types.LOAD_PROJECTS, loadProjects)yield takeEvery(authTypes.LOGOUT, logout)}diff --git a/src/redux/sagas/ui/initialise.js b/src/redux/sagas/ui/initialise.jsindex 046b4d7d8..059718c2d 100644--- a/src/redux/sagas/ui/initialise.js+++ b/src/redux/sagas/ui/initialise.js@@ -4,7 +4,7 @@ import Debug from 'debug'import { getAccessToken } from 'utils/accessToken'import UIActions from 'redux/actions/ui'-const debug = Debug('analytics:rx:s:initialise')+const debug = Debug('swetrix:rx:s:initialise')export default function* initialise() {try {diff --git a/src/redux/sagas/ui/load_projects.js b/src/redux/sagas/ui/load_projects.jsindex 3bb6a268e..8d7012f9d 100644--- a/src/redux/sagas/ui/load_projects.js+++ b/src/redux/sagas/ui/load_projects.js@@ -6,7 +6,7 @@ import Debug from 'debug'import { getProjects, getOverallStats } from '../../../api'import UIActions from 'redux/actions/ui'-const debug = Debug('analytics:rx:s:load-projects')+const debug = Debug('swetrix:rx:s:load-projects')export default function* loadProjects() {try {diff --git a/src/redux/sagas/ui/worker_live_visitors.js b/src/redux/sagas/ui/worker_live_visitors.jsnew file mode 100644index 000000000..ac857715f--- /dev/null+++ b/src/redux/sagas/ui/worker_live_visitors.js@@ -0,0 +1,20 @@+import { put, call, delay, select } from 'redux-saga/effects'+import _map from 'lodash/map'++import { getLiveVisitors } from 'api'+import UIActions from 'redux/actions/ui'++const LIVE_VISITORS_UPDATE_INTERVAL = 58000++export default function* liveVisitors() {+ while (true) {+ yield delay(2000)++ let projects = yield select(state => state.ui.projects.projects)+ const pids = _map(projects, project => project.id)+ const liveStats = yield call(getLiveVisitors, pids)++ yield put(UIActions.setLiveStats(liveStats))+ yield delay(LIVE_VISITORS_UPDATE_INTERVAL)+ }+}diff --git a/src/ui/icons/PulsatingCircle.jsx b/src/ui/icons/PulsatingCircle.jsxnew file mode 100644index 000000000..040e2e65b--- /dev/null+++ b/src/ui/icons/PulsatingCircle.jsx@@ -0,0 +1,33 @@+import React from 'react'+import cx from 'classnames'+import PropTypes from 'prop-types'++const types = {+ small: {+ pulse: 'h-2.5 w-2.5',+ base: 'h-2 w-2',+ },+ big: {+ pulse: 'h-3 w-3',+ base: 'h-2.5 w-2.5',+ },+}++const PulsatingCircle = ({ className, type }) => (+ <span className={cx('flex justify-center items-center', types[type]?.pulse, className)}>+ <span className={cx('animate-ping-slow absolute inline-flex rounded-full bg-green-400', types[type]?.pulse)}></span>+ <span className={cx('relative inline-flex rounded-full bg-green-500', types[type]?.base)}></span>+ </span>+)++PulsatingCircle.propTypes = {+ className: PropTypes.string,+ type: PropTypes.oneOf(['small', 'big']),+}++PulsatingCircle.defaultProps = {+ className: '',+ type: 'small',+}++export default PulsatingCirclediff --git a/tailwind.config.js b/tailwind.config.jsindex 30bc6ff50..a3b20f178 100644--- a/tailwind.config.js+++ b/tailwind.config.js@@ -7,13 +7,27 @@ module.exports = {extend: {width: {'card-toggle': 'calc(100% - 3rem)',- }+ },+ animation: {+ 'ping-slow': 'ping-op 3s cubic-bezier(0, 0, 0.2, 1) infinite',+ },+ keyframes: {+ 'ping-op': {+ '0%': {+ opacity: 0.75,+ },+ '75%, 100%': {+ transform: 'scale(2)',+ opacity: 0,+ },+ },+ },},minHeight: {'72': '18rem','page': 'calc(100vh - 74px)', // header height -> 74px'min-footer': 'calc(100vh - 162px)', // 74px + 88px footer height- }+ },},variants: {extend: {},@@ -21,5 +35,5 @@ module.exports = {},plugins: [require('@tailwindcss/forms'),- ]+ ],}