Skip to content

armgit / umami

Public Imported from GitHub
0

Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.

More updates to realtime.

Mike Cao93b77672f334
diff --git a/components/common/DateFilter.js b/components/input/DateFilter.js
similarity index 100%
rename from components/common/DateFilter.js
rename to components/input/DateFilter.js
diff --git a/components/input/WebsiteSelect.js b/components/input/WebsiteSelect.js
new file mode 100644
index 000000000..82f516e82
--- /dev/null
+++ b/components/input/WebsiteSelect.js
@@ -0,0 +1,28 @@
+import { useIntl } from 'react-intl';
+import { Dropdown, Item } from 'react-basics';
+import { labels } from 'components/messages';
+import useApi from 'hooks/useApi';
+
+export default function WebsiteSelect({ websiteId, onSelect }) {
+ const { formatMessage } = useIntl();
+ const { get, useQuery } = useApi();
+ const { data } = useQuery(['websites:me'], () => get('/me/websites'));
+
+ const renderValue = value => {
+ return data?.find(({ id }) => id === value)?.name;
+ };
+
+ return (
+ <Dropdown
+ items={data}
+ value={websiteId}
+ renderValue={renderValue}
+ onChange={onSelect}
+ alignment="end"
+ placeholder={formatMessage(labels.selectWebsite)}
+ style={{ width: 200 }}
+ >
+ {item => <Item key={item.id}>{item.name}</Item>}
+ </Dropdown>
+ );
+}
diff --git a/components/layout/PageHeader.module.css b/components/layout/PageHeader.module.css
index c48749f7b..511f10913 100644
--- a/components/layout/PageHeader.module.css
+++ b/components/layout/PageHeader.module.css
@@ -19,7 +19,7 @@
.title {
display: flex;
align-items: center;
- font-size: 18px;
- font-weight: bold;
+ font-size: 24px;
+ font-weight: 700;
gap: 20px;
}
diff --git a/components/messages.js b/components/messages.js
index ce506fd12..28f5bf18d 100644
--- a/components/messages.js
+++ b/components/messages.js
@@ -96,6 +96,7 @@ export const labels = defineMessages({
selectWebsite: { id: 'label.select-website', defaultMessage: 'Select website' },
all: { id: 'label.all', defaultMessage: 'All' },
sessions: { id: 'label.sessions', defaultMessage: 'Sessions' },
+ pageNotFound: { id: 'message.page-not-found', defaultMessage: 'Page not found' },
});
export const messages = defineMessages({
diff --git a/components/metrics/DataTable.js b/components/metrics/DataTable.js
index 9a2de075f..76272808e 100644
--- a/components/metrics/DataTable.js
+++ b/components/metrics/DataTable.js
@@ -8,7 +8,7 @@ import { formatNumber, formatLongNumber } from 'lib/format';
import styles from './DataTable.module.css';
export default function DataTable({
- data,
+ data = [],
title,
metric,
className,
diff --git a/components/metrics/EventDataForm.js b/components/metrics/EventDataForm.js
index dbcc59179..aa3504152 100644
--- a/components/metrics/EventDataForm.js
+++ b/components/metrics/EventDataForm.js
@@ -1,6 +1,6 @@
import { useMutation } from '@tanstack/react-query';
import classNames from 'classnames';
-import DateFilter from 'components/common/DateFilter';
+import DateFilter from 'components/input/DateFilter';
import DataTable from 'components/metrics/DataTable';
import FilterTags from 'components/metrics/FilterTags';
import useApi from 'hooks/useApi';
diff --git a/components/metrics/WebsiteChart.js b/components/metrics/WebsiteChart.js
index 2f495a371..52132fd76 100644
--- a/components/metrics/WebsiteChart.js
+++ b/components/metrics/WebsiteChart.js
@@ -5,7 +5,7 @@ import Link from 'next/link';
import PageviewsChart from './PageviewsChart';
import MetricsBar from './MetricsBar';
import WebsiteHeader from './WebsiteHeader';
-import DateFilter from 'components/common/DateFilter';
+import DateFilter from 'components/input/DateFilter';
import StickyHeader from 'components/helpers/StickyHeader';
import ErrorMessage from 'components/common/ErrorMessage';
import FilterTags from 'components/metrics/FilterTags';
diff --git a/components/pages/console/TestConsole.js b/components/pages/console/TestConsole.js
index a0c562c87..0f9c144e2 100644
--- a/components/pages/console/TestConsole.js
+++ b/components/pages/console/TestConsole.js
@@ -6,12 +6,13 @@ import Page from 'components/layout/Page';
import PageHeader from 'components/layout/PageHeader';
import EventsChart from 'components/metrics/EventsChart';
import WebsiteChart from 'components/metrics/WebsiteChart';
+import WebsiteSelect from 'components/input/WebsiteSelect';
import useApi from 'hooks/useApi';
import styles from './TestConsole.module.css';
export default function TestConsole() {
const { get, useQuery } = useApi();
- const { data, isLoading, error } = useQuery(['websites:test-console'], () => get('/websites'));
+ const { data, isLoading, error } = useQuery(['websites:me'], () => get('/me/websites'));
const router = useRouter();
const {
basePath,
@@ -50,15 +51,7 @@ export default function TestConsole() {
)}
</Head>
<PageHeader title="Test console">
- <Dropdown
- items={data}
- renderValue={() => website?.name || 'Select website'}
- value={website?.id}
- onChange={handleChange}
- style={{ width: 300 }}
- >
- {({ id, name }) => <Item key={id}>{name}</Item>}
- </Dropdown>
+ <WebsiteSelect websiteId={website?.id} onSelect={handleChange} />
</PageHeader>
{website && (
<>
diff --git a/components/pages/realtime/RealtimeDashboard.js b/components/pages/realtime/RealtimeDashboard.js
index 8a9b77b4f..b45d85d25 100644
--- a/components/pages/realtime/RealtimeDashboard.js
+++ b/components/pages/realtime/RealtimeDashboard.js
@@ -7,43 +7,38 @@ import Page from 'components/layout/Page';
import RealtimeChart from 'components/metrics/RealtimeChart';
import RealtimeLog from 'components/pages/realtime/RealtimeLog';
import RealtimeHeader from 'components/pages/realtime/RealtimeHeader';
+import StickyHeader from 'components/helpers/StickyHeader';
+import PageHeader from 'components/layout/PageHeader';
import WorldMap from 'components/common/WorldMap';
import DataTable from 'components/metrics/DataTable';
-import RealtimeViews from 'components/pages/realtime/RealtimeViews';
+import RealtimeUrls from 'components/pages/realtime/RealtimeUrls';
import useApi from 'hooks/useApi';
import useLocale from 'hooks/useLocale';
import useCountryNames from 'hooks/useCountryNames';
import { percentFilter } from 'lib/filters';
import { labels } from 'components/messages';
-import { SHARE_TOKEN_HEADER, REALTIME_RANGE, REALTIME_INTERVAL } from 'lib/constants';
+import { REALTIME_RANGE, REALTIME_INTERVAL } from 'lib/constants';
import styles from './RealtimeDashboard.module.css';
-import StickyHeader from 'components/helpers/StickyHeader';
-import PageHeader from 'components/layout/PageHeader';
-import ActiveUsers from 'components/metrics/ActiveUsers';
+import WebsiteSelect from '../../input/WebsiteSelect';
+import { useRouter } from 'next/router';
-function mergeData(state, data, time) {
+function mergeData(state = [], data, time) {
const ids = state.map(({ __id }) => __id);
return state
.concat(data.filter(({ __id }) => !ids.includes(__id)))
.filter(({ createdAt }) => new Date(createdAt).getTime() >= time);
}
-function filterWebsite(data, id) {
- return data.filter(({ websiteId }) => websiteId === id);
-}
-
-export default function RealtimeDashboard() {
+export default function RealtimeDashboard({ websiteId }) {
const { formatMessage } = useIntl();
const { locale } = useLocale();
+ const router = useRouter();
const countryNames = useCountryNames(locale);
- const [data, setData] = useState();
- const [websiteId, setWebsiteId] = useState();
+ const [currentData, setCurrentData] = useState();
const { get, useQuery } = useApi();
- const { data: websites, isLoading } = useQuery(['websites:me'], () => get('/me/websites'));
-
- const { data: updates } = useQuery(
- ['realtime:updates'],
- () => get('/realtime/update', { startAt: data?.timestamp }),
+ const { data, isLoading, error } = useQuery(
+ ['realtime', websiteId],
+ () => get(`/realtime/${websiteId}`, { startAt: currentData?.timestamp }),
{
enabled: !!websiteId,
retryInterval: REALTIME_INTERVAL,
@@ -55,91 +50,67 @@ export default function RealtimeDashboard() {
[countryNames],
);
- const realtimeData = useMemo(() => {
+ useEffect(() => {
if (data) {
- const { pageviews, sessions, events } = data;
+ const { pageviews, sessions, events, timestamp } = data;
+ const time = subMinutes(startOfMinute(new Date()), REALTIME_RANGE).getTime();
- if (websiteId) {
- const { id } = websites.find(n => n.id === websiteId);
- return {
- pageviews: filterWebsite(pageviews, id),
- sessions: filterWebsite(sessions, id),
- events: filterWebsite(events, id),
- };
- }
+ setCurrentData(state => ({
+ ...state,
+ pageviews: mergeData(state?.pageviews, pageviews, time),
+ sessions: mergeData(state?.sessions, sessions, time),
+ events: mergeData(state?.events, events, time),
+ timestamp,
+ }));
}
+ }, [data]);
- return data;
- }, [data, websiteId]);
-
- const count = useMemo(() => {
- if (data) {
- const { sessions } = data;
- return sessions.filter(
- ({ createdAt }) => differenceInMinutes(new Date(), new Date(createdAt)) <= 5,
- ).length;
+ const realtimeData = useMemo(() => {
+ if (!currentData) {
+ return { pageviews: [], sessions: [], events: [], countries: [] };
}
- }, [data, websiteId]);
- const countries = useMemo(() => {
- if (realtimeData?.sessions) {
- return percentFilter(
- realtimeData.sessions
- .reduce((arr, { country }) => {
- if (country) {
- const row = arr.find(({ x }) => x === country);
+ currentData.countries = percentFilter(
+ currentData.sessions
+ .reduce((arr, { country }) => {
+ if (country) {
+ const row = arr.find(({ x }) => x === country);
- if (!row) {
- arr.push({ x: country, y: 1 });
- } else {
- row.y += 1;
- }
+ if (!row) {
+ arr.push({ x: country, y: 1 });
+ } else {
+ row.y += 1;
}
- return arr;
- }, [])
- .sort(firstBy('y', -1)),
- );
- }
- return [];
- }, [realtimeData?.sessions]);
+ }
+ return arr;
+ }, [])
+ .sort(firstBy('y', -1)),
+ );
- useEffect(() => {
- if (updates) {
- const { pageviews, sessions, events, timestamp } = updates;
- const time = subMinutes(startOfMinute(new Date()), REALTIME_RANGE).getTime();
+ return currentData;
+ }, [currentData]);
- setData(state => ({
- ...state,
- pageviews: mergeData(state.pageviews, pageviews, time),
- sessions: mergeData(state.sessions, sessions, time),
- events: mergeData(state.events, events, time),
- timestamp,
- }));
- }
- }, [updates]);
+ const handleSelect = id => {
+ router.push(`/realtime/${id}`);
+ };
return (
- <Page loading={isLoading || !websites}>
+ <Page loading={isLoading} error={error}>
<PageHeader title={formatMessage(labels.realtime)}>
- <ActiveUsers value={count} />
+ <WebsiteSelect websiteId={websiteId} onSelect={handleSelect} />
</PageHeader>
<StickyHeader stickyClassName={styles.sticky}>
- <RealtimeHeader
- websites={websites}
- websiteId={websiteId}
- data={{ ...realtimeData, countries }}
- onSelect={setWebsiteId}
- />
+ <RealtimeHeader websiteId={websiteId} data={currentData} />
</StickyHeader>
<div className={styles.chart}>
<RealtimeChart data={realtimeData} unit="minute" records={REALTIME_RANGE} />
</div>
<GridRow>
<GridColumn xs={12} sm={12} md={12} lg={4} xl={4}>
- <RealtimeViews websiteId={websiteId} data={realtimeData} websites={websites} />
+ <RealtimeUrls websiteId={websiteId} data={realtimeData} />
</GridColumn>
<GridColumn xs={12} sm={12} md={12} lg={8} xl={8}>
- <RealtimeLog websiteId={websiteId} data={realtimeData} websites={websites} />
+ <RealtimeLog websiteId={websiteId} data={realtimeData} />
</GridColumn>
</GridRow>
<GridRow>
@@ -147,12 +118,12 @@ export default function RealtimeDashboard() {
<DataTable
title={formatMessage(labels.countries)}
metric={formatMessage(labels.visitors)}
- data={countries}
+ data={realtimeData?.countries}
renderLabel={renderCountryName}
/>
</GridColumn>
<GridColumn xs={12} lg={8}>
- <WorldMap data={countries} />
+ <WorldMap data={realtimeData?.countries} />
</GridColumn>
</GridRow>
</Page>
diff --git a/components/pages/realtime/RealtimeHeader.js b/components/pages/realtime/RealtimeHeader.js
index 69013a700..2f34e766a 100644
--- a/components/pages/realtime/RealtimeHeader.js
+++ b/components/pages/realtime/RealtimeHeader.js
@@ -1,18 +1,12 @@
import { useIntl } from 'react-intl';
-import { Dropdown, Item } from 'react-basics';
import MetricCard from 'components/metrics/MetricCard';
import { labels } from 'components/messages';
import styles from './RealtimeHeader.module.css';
-export default function RealtimeHeader({ data, websiteId, websites, onSelect }) {
+export default function RealtimeHeader({ data = {} }) {
const { formatMessage } = useIntl();
-
const { pageviews, sessions, events, countries } = data;
- const renderValue = value => {
- return websites?.find(({ id }) => id === value)?.name;
- };
-
return (
<div className={styles.header}>
<div className={styles.metrics}>
@@ -25,20 +19,10 @@ export default function RealtimeHeader({ data, websiteId, websites, onSelect })
<MetricCard label={formatMessage(labels.events)} value={events?.length} hideComparison />
<MetricCard
label={formatMessage(labels.countries)}
- value={countries.length}
+ value={countries?.length}
hideComparison
/>
</div>
- <Dropdown
- items={websites}
- value={websiteId}
- renderValue={renderValue}
- onChange={onSelect}
- alignment="end"
- placeholder={formatMessage(labels.selectWebsite)}
- >
- {item => <Item key={item.id}>{item.name}</Item>}
- </Dropdown>
</div>
);
}
diff --git a/components/pages/realtime/RealtimeHome.js b/components/pages/realtime/RealtimeHome.js
new file mode 100644
index 000000000..f54ed4dee
--- /dev/null
+++ b/components/pages/realtime/RealtimeHome.js
@@ -0,0 +1,28 @@
+import { useEffect } from 'react';
+import { useRouter } from 'next/router';
+import { useIntl } from 'react-intl';
+import Page from 'components/layout/Page';
+import PageHeader from 'components/layout/PageHeader';
+import useApi from 'hooks/useApi';
+import { labels, messages } from 'components/messages';
+import EmptyPlaceholder from 'components/common/EmptyPlaceholder';
+
+export default function RealtimeHome() {
+ const { formatMessage } = useIntl();
+ const { get, useQuery } = useApi();
+ const router = useRouter();
+ const { data, isLoading, error } = useQuery(['websites:me'], () => get('/me/websites'));
+
+ useEffect(() => {
+ if (data?.length) {
+ router.push(`realtime/${data[0].id}`);
+ }
+ }, [data]);
+
+ return (
+ <Page loading={isLoading || !data} error={error}>
+ <PageHeader title={formatMessage(labels.realtime)} />
+ {data?.length === 0 && <EmptyPlaceholder message={formatMessage(messages.noWebsites)} />}
+ </Page>
+ );
+}
diff --git a/components/pages/realtime/RealtimeLog.js b/components/pages/realtime/RealtimeLog.js
index 8d293e37c..25fba487b 100644
--- a/components/pages/realtime/RealtimeLog.js
+++ b/components/pages/realtime/RealtimeLog.js
@@ -26,7 +26,7 @@ const TYPE_ICONS = {
[TYPE_EVENT]: <Icons.Bolt />,
};
-export default function RealtimeLog({ data, websites, websiteId }) {
+export default function RealtimeLog({ data, websiteDomain }) {
const { formatMessage } = useIntl();
const { locale } = useLocale();
const countryNames = useCountryNames(locale);
@@ -92,10 +92,6 @@ export default function RealtimeLog({ data, websites, websiteId }) {
return TYPE_ICONS[getType(row)];
}
- function getWebsite({ websiteId }) {
- return websites.find(n => n.id === websiteId);
- }
-
function getDetail({
eventName,
pageviewId,
@@ -111,11 +107,10 @@ export default function RealtimeLog({ data, websites, websiteId }) {
return <div>{eventName}</div>;
}
if (pageviewId) {
- const domain = getWebsite({ websiteId })?.domain;
return (
<a
className={styles.link}
- href={`//${domain}${url}`}
+ href={`//${websiteDomain}${url}`}
target="_blank"
rel="noreferrer noopener"
>
@@ -146,7 +141,7 @@ export default function RealtimeLog({ data, websites, websiteId }) {
function getColor(row) {
const { sessionId } = row;
- return stringToColor(uuids[sessionId] || `${sessionId}${getWebsite(row)}`);
+ return stringToColor(uuids[sessionId] || `${sessionId}}`);
}
const Row = ({ index, style }) => {
@@ -161,9 +156,6 @@ export default function RealtimeLog({ data, websites, websiteId }) {
<Icon className={styles.icon} icon={getIcon(row)} />
{getDetail(row)}
</div>
- {!websiteId && websites.length > 1 && (
- <div className={styles.website}>{getWebsite(row)?.domain}</div>
- )}
</div>
);
};
diff --git a/components/pages/realtime/RealtimeViews.js b/components/pages/realtime/RealtimeUrls.js
similarity index 71%
rename from components/pages/realtime/RealtimeViews.js
rename to components/pages/realtime/RealtimeUrls.js
index c1f93be1d..8437af40f 100644
--- a/components/pages/realtime/RealtimeViews.js
+++ b/components/pages/realtime/RealtimeUrls.js
@@ -1,5 +1,5 @@
-import { useMemo, useState, useCallback } from 'react';
-import { ButtonGroup, Button } from 'react-basics';
+import { useMemo, useState } from 'react';
+import { ButtonGroup, Button, Flexbox } from 'react-basics';
import { useIntl } from 'react-intl';
import firstBy from 'thenby';
import { percentFilter } from 'lib/filters';
@@ -7,18 +7,10 @@ import DataTable from 'components/metrics/DataTable';
import { FILTER_PAGES, FILTER_REFERRERS } from 'lib/constants';
import { labels } from 'components/messages';
-export default function RealtimeViews({ websiteId, data = {}, websites }) {
+export default function RealtimeUrls({ websiteDomain, data = {} }) {
const { formatMessage } = useIntl();
const { pageviews } = data;
const [filter, setFilter] = useState(FILTER_REFERRERS);
- const domains = useMemo(() => websites.map(({ domain }) => domain), [websites]);
- const getDomain = useCallback(
- id =>
- websites.length === 1
- ? websites[0]?.domain
- : websites.find(({ websiteId }) => websiteId === id)?.domain,
- [websites],
- );
const buttons = [
{
@@ -32,7 +24,7 @@ export default function RealtimeViews({ websiteId, data = {}, websites }) {
];
const renderLink = ({ x }) => {
- const domain = x.startsWith('/') ? getDomain(websiteId) : '';
+ const domain = x.startsWith('/') ? websiteDomain : '';
return (
<a href={`//${domain}${x}`} target="_blank" rel="noreferrer noopener">
{x}
@@ -48,7 +40,7 @@ export default function RealtimeViews({ websiteId, data = {}, websites }) {
if (referrer?.startsWith('http')) {
const hostname = new URL(referrer).hostname.replace(/^www\./, '');
- if (hostname && !domains.includes(hostname)) {
+ if (hostname) {
const row = arr.find(({ x }) => x === hostname);
if (!row) {
@@ -65,11 +57,8 @@ export default function RealtimeViews({ websiteId, data = {}, websites }) {
const pages = percentFilter(
pageviews
- .reduce((arr, { url, websiteId }) => {
+ .reduce((arr, { url }) => {
if (url?.startsWith('/')) {
- if (!websiteId && websites.length > 1) {
- url = `${getDomain(websiteId)}${url}`;
- }
const row = arr.find(({ x }) => x === url);
if (!row) {
@@ -91,9 +80,11 @@ export default function RealtimeViews({ websiteId, data = {}, websites }) {
return (
<>
- <ButtonGroup items={buttons} selectedKey={filter} onSelect={setFilter}>
- {({ key, label }) => <Button key={key}>{label}</Button>}
- </ButtonGroup>
+ <Flexbox justifyContent="center">
+ <ButtonGroup items={buttons} selectedKey={filter} onSelect={setFilter}>
+ {({ key, label }) => <Button key={key}>{label}</Button>}
+ </ButtonGroup>
+ </Flexbox>
{filter === FILTER_REFERRERS && (
<DataTable
title={formatMessage(labels.referrers)}
diff --git a/components/pages/settings/profile/DateRangeSetting.js b/components/pages/settings/profile/DateRangeSetting.js
index a5139cb38..5eca8cc5f 100644
--- a/components/pages/settings/profile/DateRangeSetting.js
+++ b/components/pages/settings/profile/DateRangeSetting.js
@@ -1,5 +1,5 @@
import { useIntl } from 'react-intl';
-import DateFilter from 'components/common/DateFilter';
+import DateFilter from 'components/input/DateFilter';
import { Button, Flexbox } from 'react-basics';
import useDateRange from 'hooks/useDateRange';
import { DEFAULT_DATE_RANGE } from 'lib/constants';
diff --git a/hooks/useLocale.js b/hooks/useLocale.js
index bcb2b4fd9..5cece3470 100644
--- a/hooks/useLocale.js
+++ b/hooks/useLocale.js
@@ -51,7 +51,7 @@ export default function useLocale() {
}, [locale]);
useEffect(() => {
- const url = new URL(window.location.href);
+ const url = new URL(window?.location?.href);
const locale = url.searchParams.get('locale');
if (locale) {
diff --git a/hooks/useTheme.js b/hooks/useTheme.js
index 5c21bf1ce..c50f442f0 100644
--- a/hooks/useTheme.js
+++ b/hooks/useTheme.js
@@ -24,7 +24,7 @@ export default function useTheme() {
}, [theme]);
useEffect(() => {
- const url = new URL(window.location.href);
+ const url = new URL(window?.location?.href);
const theme = url.searchParams.get('theme');
if (['light', 'dark'].includes(theme)) {
diff --git a/next.config.js b/next.config.js
index eac47415f..c654b086f 100644
--- a/next.config.js
+++ b/next.config.js
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-var-requires */
require('dotenv').config();
const pkg = require('./package.json');
diff --git a/pages/404.js b/pages/404.js
index 9f13a5455..12cb41133 100644
--- a/pages/404.js
+++ b/pages/404.js
@@ -1,18 +1,20 @@
+import { Row, Column, Flexbox } from 'react-basics';
+import { useIntl } from 'react-intl';
import AppLayout from 'components/layout/AppLayout';
-import { useIntl, defineMessages } from 'react-intl';
-
-const messages = defineMessages({
- notFound: { id: 'message.page-not-found', defaultMessage: 'Page not found' },
-});
+import { labels } from 'components/messages';
export default function Custom404() {
const { formatMessage } = useIntl();
return (
<AppLayout>
- <div className="row justify-content-center">
- <h1 style={{ textAlign: 'center' }}>{formatMessage(messages.notFound)}</h1>
- </div>
+ <Row>
+ <Column>
+ <Flexbox alignItems="center" justifyContent="center" flex={1} style={{ minHeight: 600 }}>
+ <h1>{formatMessage(labels.pageNotFound)}</h1>
+ </Flexbox>
+ </Column>
+ </Row>
</AppLayout>
);
}
diff --git a/pages/api/realtime/[id].ts b/pages/api/realtime/[id].ts
new file mode 100644
index 000000000..d8e6ad623
--- /dev/null
+++ b/pages/api/realtime/[id].ts
@@ -0,0 +1,20 @@
+import { subMinutes } from 'date-fns';
+import { RealtimeInit, NextApiRequestAuth } from 'lib/types';
+import { useAuth } from 'lib/middleware';
+import { NextApiResponse } from 'next';
+import { methodNotAllowed, ok } from 'next-basics';
+import { getRealtimeData } from 'queries';
+
+export default async (req: NextApiRequestAuth, res: NextApiResponse<RealtimeInit>) => {
+ await useAuth(req, res);
+
+ if (req.method === 'GET') {
+ const { id } = req.query;
+
+ const data = await getRealtimeData(id, subMinutes(new Date(), 30));
+
+ return ok(res, data);
+ }
+
+ return methodNotAllowed(res);
+};
diff --git a/pages/api/realtime/init.ts b/pages/api/realtime/init.ts
deleted file mode 100644
index 1cb5746fb..000000000
--- a/pages/api/realtime/init.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { subMinutes } from 'date-fns';
-import { RealtimeInit, NextApiRequestAuth } from 'lib/types';
-import { secret } from 'lib/crypto';
-import { useAuth } from 'lib/middleware';
-import { NextApiResponse } from 'next';
-import { createToken, methodNotAllowed, ok } from 'next-basics';
-import { getRealtimeData, getUserWebsites } from 'queries';
-
-export default async (req: NextApiRequestAuth, res: NextApiResponse<RealtimeInit>) => {
- await useAuth(req, res);
-
- if (req.method === 'GET') {
- const { id: userId } = req.auth.user;
-
- const websites = await getUserWebsites(userId);
- const ids = websites.map(({ id }) => id);
- const token = createToken({ websites: ids }, secret());
- const data = await getRealtimeData(ids, subMinutes(new Date(), 30));
-
- return ok(res, {
- websites,
- token,
- data,
- });
- }
-
- return methodNotAllowed(res);
-};
diff --git a/pages/api/realtime/update.ts b/pages/api/realtime/update.ts
deleted file mode 100644
index 8125d02d5..000000000
--- a/pages/api/realtime/update.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { ok, methodNotAllowed, badRequest, parseToken } from 'next-basics';
-import { useAuth } from 'lib/middleware';
-import { getRealtimeData } from 'queries';
-import { SHARE_TOKEN_HEADER } from 'lib/constants';
-import { secret } from 'lib/crypto';
-import { NextApiRequestQueryBody, RealtimeUpdate } from 'lib/types';
-import { NextApiResponse } from 'next';
-
-export interface InitUpdateRequestQuery {
- startAt: string;
-}
-
-export default async (
- req: NextApiRequestQueryBody<InitUpdateRequestQuery>,
- res: NextApiResponse<RealtimeUpdate>,
-) => {
- await useAuth(req, res);
-
- if (req.method === 'GET') {
- const { startAt } = req.query;
-
- const token = req.headers[SHARE_TOKEN_HEADER];
-
- if (!token) {
- return badRequest(res);
- }
-
- const { websites } = parseToken(token, secret());
-
- const data = await getRealtimeData(websites, new Date(+startAt));
-
- return ok(res, data);
- }
-
- return methodNotAllowed(res);
-};
diff --git a/pages/dashboard/[[...id]].js b/pages/dashboard/index.js
similarity index 100%
rename from pages/dashboard/[[...id]].js
rename to pages/dashboard/index.js
diff --git a/pages/realtime/[id]/index.js b/pages/realtime/[id]/index.js
new file mode 100644
index 000000000..3ef556be5
--- /dev/null
+++ b/pages/realtime/[id]/index.js
@@ -0,0 +1,18 @@
+import { useRouter } from 'next/router';
+import AppLayout from 'components/layout/AppLayout';
+import RealtimeDashboard from 'components/pages/realtime/RealtimeDashboard';
+
+export default function RealtimeDetailsPage() {
+ const router = useRouter();
+ const { id: websiteId } = router.query;
+
+ if (!websiteId) {
+ return null;
+ }
+
+ return (
+ <AppLayout>
+ <RealtimeDashboard websiteId={websiteId} />
+ </AppLayout>
+ );
+}
diff --git a/pages/realtime.js b/pages/realtime/index.js
similarity index 58%
rename from pages/realtime.js
rename to pages/realtime/index.js
index 008255e6b..fa0d86d63 100644
--- a/pages/realtime.js
+++ b/pages/realtime/index.js
@@ -1,10 +1,10 @@
import AppLayout from 'components/layout/AppLayout';
-import RealtimeDashboard from 'components/pages/realtime/RealtimeDashboard';
+import RealtimeHome from 'components/pages/realtime/RealtimeHome';
export default function RealtimePage() {
return (
<AppLayout>
- <RealtimeDashboard />
+ <RealtimeHome />
</AppLayout>
);
}
diff --git a/queries/analytics/event/getEvents.ts b/queries/analytics/event/getEvents.ts
index 5d01824c3..953b1a287 100644
--- a/queries/analytics/event/getEvents.ts
+++ b/queries/analytics/event/getEvents.ts
@@ -3,19 +3,17 @@ import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
import { EVENT_TYPE } from 'lib/constants';
-export function getEvents(...args: [websites: string[], startAt: Date]) {
+export function getEvents(...args: [websiteId: string, startAt: Date]) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
-function relationalQuery(websites: string[], startAt: Date) {
- return prisma.client.event.findMany({
+function relationalQuery(websiteId: string, startAt: Date) {
+ return prisma.client.websiteEvent.findMany({
where: {
- websiteId: {
- in: websites,
- },
+ websiteId,
createdAt: {
gte: startAt,
},
@@ -23,7 +21,7 @@ function relationalQuery(websites: string[], startAt: Date) {
});
}
-function clickhouseQuery(websites: string[], startAt: Date) {
+function clickhouseQuery(websiteId: string, startAt: Date) {
const { rawQuery } = clickhouse;
return rawQuery(
@@ -36,10 +34,10 @@ function clickhouseQuery(websites: string[], startAt: Date) {
event_name
from event
where event_type = ${EVENT_TYPE.customEvent}
- and ${websites && websites.length > 0 ? `website_id in {websites:Array(UUID)}` : '0 = 0'}
+ and website_id = {websiteId:UUID}
and created_at >= {startAt:DateTime('UTC')}`,
{
- websites,
+ websiteId,
startAt,
},
);
diff --git a/queries/analytics/pageview/getPageviews.ts b/queries/analytics/pageview/getPageviews.ts
index eb60a1f52..c37f23c1a 100644
--- a/queries/analytics/pageview/getPageviews.ts
+++ b/queries/analytics/pageview/getPageviews.ts
@@ -3,19 +3,17 @@ import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
import { EVENT_TYPE } from 'lib/constants';
-export async function getPageviews(...args: [websites: string[], startAt: Date]) {
+export async function getPageviews(...args: [websiteId: string, startAt: Date]) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
-async function relationalQuery(websites: string[], startAt: Date) {
- return prisma.client.pageview.findMany({
+async function relationalQuery(websiteId: string, startAt: Date) {
+ return prisma.client.websiteEvent.findMany({
where: {
- websiteId: {
- in: websites,
- },
+ websiteId,
createdAt: {
gte: startAt,
},
@@ -23,21 +21,21 @@ async function relationalQuery(websites: string[], startAt: Date) {
});
}
-async function clickhouseQuery(websites: string[], startAt: Date) {
+async function clickhouseQuery(websiteId: string, startAt: Date) {
const { rawQuery } = clickhouse;
return rawQuery(
`select
- website_id,
- session_id,
- created_at,
+ website_id as websiteId,
+ session_id as sessionId,
+ created_at as createdAt,
url
from event
where event_type = ${EVENT_TYPE.pageView}
- and ${websites && websites.length > 0 ? `website_id in {websites:Array(UUID)}` : '0 = 0'}
+ and website_id = {websiteId:UUID}
and created_at >= {startAt:DateTime('UTC')}`,
{
- websites,
+ websiteId,
startAt,
},
);
diff --git a/queries/analytics/session/getSessions.ts b/queries/analytics/session/getSessions.ts
index 460572778..1f28333b9 100644
--- a/queries/analytics/session/getSessions.ts
+++ b/queries/analytics/session/getSessions.ts
@@ -2,23 +2,17 @@ import prisma from 'lib/prisma';
import clickhouse from 'lib/clickhouse';
import { runQuery, PRISMA, CLICKHOUSE } from 'lib/db';
-export async function getSessions(...args: [websites: string[], startAt: Date]) {
+export async function getSessions(...args: [websiteId: string, startAt: Date]) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
-async function relationalQuery(websites: string[], startAt: Date) {
+async function relationalQuery(websiteId: string, startAt: Date) {
return prisma.client.session.findMany({
where: {
- ...(websites && websites.length > 0
- ? {
- websiteId: {
- in: websites,
- },
- }
- : {}),
+ websiteId,
createdAt: {
gte: startAt,
},
@@ -26,7 +20,7 @@ async function relationalQuery(websites: string[], startAt: Date) {
});
}
-async function clickhouseQuery(websites: string[], startAt: Date) {
+async function clickhouseQuery(websiteId: string, startAt: Date) {
const { rawQuery } = clickhouse;
return rawQuery(
@@ -42,10 +36,10 @@ async function clickhouseQuery(websites: string[], startAt: Date) {
language,
country
from event
- where ${websites && websites.length > 0 ? `website_id in {websites:Array(UUID)}` : '0 = 0'}
+ where website_id = {websiteId:UUID}
and created_at >= {startAt:DateTime('UTC')}`,
{
- websites,
+ websiteId,
startAt,
},
);
diff --git a/queries/analytics/stats/getRealtimeData.ts b/queries/analytics/stats/getRealtimeData.ts
index 659f61455..46cb67462 100644
--- a/queries/analytics/stats/getRealtimeData.ts
+++ b/queries/analytics/stats/getRealtimeData.ts
@@ -2,11 +2,11 @@ import { getPageviews } from '../pageview/getPageviews';
import { getSessions } from '../session/getSessions';
import { getEvents } from '../event/getEvents';
-export async function getRealtimeData(websites, time) {
+export async function getRealtimeData(websiteId, time) {
const [pageviews, sessions, events] = await Promise.all([
- getPageviews(websites, time),
- getSessions(websites, time),
- getEvents(websites, time),
+ getPageviews(websiteId, time),
+ getSessions(websiteId, time),
+ getEvents(websiteId, time),
]);
return {