Skip to content

Commit

Permalink
Refactored realtime API. Add dot component and colored dots in log.
Browse files Browse the repository at this point in the history
  • Loading branch information
mikecao committed Oct 10, 2020
1 parent f2cfab5 commit b72a4c0
Show file tree
Hide file tree
Showing 12 changed files with 153 additions and 86 deletions.
15 changes: 15 additions & 0 deletions components/common/Dot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import React from 'react';
import classNames from 'classnames';
import styles from './Dot.module.css';

export default function Dot({ color, size, className }) {
return (
<div
style={{ background: color }}
className={classNames(styles.dot, className, {
[styles.small]: size === 'small',
[styles.large]: size === 'large',
})}
/>
);
}
17 changes: 17 additions & 0 deletions components/common/Dot.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
.dot {
background: var(--green400);
width: 10px;
height: 10px;
border-radius: 100%;
margin-right: 10px;
}

.dot.small {
width: 8px;
height: 8px;
}

.dot.large {
width: 16px;
height: 16px;
}
3 changes: 2 additions & 1 deletion components/metrics/ActiveUsers.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React, { useMemo } from 'react';
import { FormattedMessage } from 'react-intl';
import classNames from 'classnames';
import useFetch from 'hooks/useFetch';
import Dot from 'components/common/Dot';
import styles from './ActiveUsers.module.css';

export default function ActiveUsers({ websiteId, token, className }) {
Expand All @@ -19,7 +20,7 @@ export default function ActiveUsers({ websiteId, token, className }) {

return (
<div className={classNames(styles.container, className)}>
<div className={styles.dot} />
<Dot />
<div className={styles.text}>
<div>
<FormattedMessage
Expand Down
8 changes: 0 additions & 8 deletions components/metrics/ActiveUsers.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,3 @@
font-weight: 600;
margin-right: 4px;
}

.dot {
background: var(--green400);
width: 10px;
height: 10px;
border-radius: 100%;
margin-right: 10px;
}
8 changes: 7 additions & 1 deletion components/metrics/RealtimeHeader.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@ import styles from './RealtimeHeader.module.css';
export default function RealtimeHeader({ websites, data, websiteId, onSelect }) {
const options = [
{ label: <FormattedMessage id="label.all-websites" defaultMessage="All websites" />, value: 0 },
].concat(websites.map(({ name, website_id }) => ({ label: name, value: website_id })));
].concat(
websites.map(({ name, website_id }, index) => ({
label: name,
value: website_id,
divider: index === 0,
})),
);

const { pageviews, sessions, events, countries } = data;

Expand Down
13 changes: 13 additions & 0 deletions components/metrics/RealtimeLog.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import { BROWSERS } from 'lib/constants';
import Bolt from 'assets/bolt.svg';
import Visitor from 'assets/visitor.svg';
import Eye from 'assets/eye.svg';
import { stringToColor } from 'lib/format';
import styles from './RealtimeLog.module.css';
import Dot from '../common/Dot';

const TYPE_PAGEVIEW = 0;
const TYPE_SESSION = 1;
Expand All @@ -26,11 +28,19 @@ const TYPE_ICONS = {
export default function RealtimeLog({ data, websites }) {
const [locale] = useLocale();
const countryNames = useCountryNames(locale);

const logs = useMemo(() => {
const { pageviews, sessions, events } = data;
return [...pageviews, ...sessions, ...events].sort(firstBy('created_at', -1));
}, [data]);

const uuids = useMemo(() => {
return data.sessions.reduce((obj, { session_id, session_uuid }) => {
obj[session_id] = session_uuid;
return obj;
}, {});
}, [data]);

function getType({ view_id, session_id, event_id }) {
if (event_id) {
return TYPE_EVENT;
Expand Down Expand Up @@ -88,6 +98,9 @@ export default function RealtimeLog({ data, websites }) {
const row = logs[index];
return (
<div className={styles.row} style={style}>
<div>
<Dot color={stringToColor(uuids[row.session_id] || `${row.session_id}`)} />
</div>
<div className={styles.time}>{format(new Date(row.created_at), 'h:mm:ss')}</div>
<div className={styles.detail}>
<Icon className={styles.icon} icon={getIcon(row)} />
Expand Down
8 changes: 4 additions & 4 deletions components/pages/RealtimeDashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import useCountryNames from 'hooks/useCountryNames';
import { FormattedMessage } from 'react-intl';

const REALTIME_RANGE = 30;
const REALTIME_INTERVAL = 55000;
const REALTIME_INTERVAL = 3000;

function mergeData(state, data, time) {
const ids = state.map(({ __id }) => __id);
Expand All @@ -34,9 +34,9 @@ export default function RealtimeDashboard() {
const countryNames = useCountryNames(locale);
const [data, setData] = useState();
const [websiteId, setWebsiteId] = useState(0);
const { data: init, loading } = useFetch('/api/realtime', { params: { type: 'init' } });
const { data: updates } = useFetch('/api/realtime', {
params: { type: 'update', start_at: data?.timestamp },
const { data: init, loading } = useFetch('/api/realtime/init');
const { data: updates } = useFetch('/api/realtime/update', {
params: { start_at: data?.timestamp },
disabled: !init?.websites?.length || !data,
interval: REALTIME_INTERVAL,
headers: { 'x-umami-token': init?.token },
Expand Down
16 changes: 16 additions & 0 deletions lib/format.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,19 @@ export function formatLongNumber(value) {

return formatNumber(n);
}

export function stringToColor(str) {
if (!str) {
return '#ffffff';
}
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
let color = '#';
for (let i = 0; i < 3; i++) {
let value = (hash >> (i * 8)) & 0xff;
color += ('00' + value.toString(16)).substr(-2);
}
return color;
}
27 changes: 27 additions & 0 deletions lib/queries.js
Original file line number Diff line number Diff line change
Expand Up @@ -500,3 +500,30 @@ export function getEventMetrics(
params,
);
}

export async function getRealtimeData(websites, time) {
const [pageviews, sessions, events] = await Promise.all([
getPageviews(websites, time),
getSessions(websites, time),
getEvents(websites, time),
]);

return {
pageviews: pageviews.map(({ view_id, ...props }) => ({
__id: `p${view_id}`,
view_id,
...props,
})),
sessions: sessions.map(({ session_id, ...props }) => ({
__id: `s${session_id}`,
session_id,
...props,
})),
events: events.map(({ event_id, ...props }) => ({
__id: `e${event_id}`,
event_id,
...props,
})),
timestamp: Date.now(),
};
}
72 changes: 0 additions & 72 deletions pages/api/realtime.js

This file was deleted.

26 changes: 26 additions & 0 deletions pages/api/realtime/init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { subMinutes } from 'date-fns';
import { useAuth } from 'lib/middleware';
import { ok, methodNotAllowed } from 'lib/response';
import { getUserWebsites, getRealtimeData } from 'lib/queries';
import { createToken } from 'lib/crypto';

export default async (req, res) => {
await useAuth(req, res);

if (req.method === 'GET') {
const { user_id } = req.auth;

const websites = await getUserWebsites(user_id);
const ids = websites.map(({ website_id }) => website_id);
const token = await createToken({ websites: ids });
const data = await getRealtimeData(ids, subMinutes(new Date(), 30));

return ok(res, {
websites,
token,
data,
});
}

return methodNotAllowed(res);
};
26 changes: 26 additions & 0 deletions pages/api/realtime/update.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useAuth } from 'lib/middleware';
import { ok, methodNotAllowed, badRequest } from 'lib/response';
import { getRealtimeData } from 'lib/queries';
import { parseToken } from 'lib/crypto';

export default async (req, res) => {
await useAuth(req, res);

if (req.method === 'GET') {
const { start_at } = req.query;

const token = req.headers['x-umami-token'];

if (!token) {
return badRequest(res);
}

const { websites } = await parseToken(token);

const data = await getRealtimeData(websites, new Date(+start_at));

return ok(res, data);
}

return methodNotAllowed(res);
};

0 comments on commit b72a4c0

Please sign in to comment.