This repository has been archived by the owner on May 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
overtime.ts
169 lines (149 loc) · 5.22 KB
/
overtime.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import axios from 'axios';
import { ChartData } from 'chart.js';
import type { NextApiRequest, NextApiResponse } from 'next';
import { withSessionRoute } from '@lib/AuthSession';
import logger from '@utils/logger';
import { UpstreamApiUrl } from '@utils/url/upstream';
import { IOverTimeData10minutes } from '@utils/url/upstream.types';
import { getQueriesOvertimeUrl as apiUrl } from '@utils/url/api';
/**
* Error message to return to the Requester
*/
interface ErrorMessage {
message: string;
}
export interface IGetRequestData {
/**
* Return formatted data that is compatible with ChartJS
*
* @see {@link https://www.chartjs.org/docs/latest/general/data-structures.html}
* @see {@link https://www.chartjs.org/docs/latest/charts/bar.html#example-dataset-configuration}
*
* @defaultValue `false`
*/
formatted?: string | 'false';
}
/**
* `overTimeData10mins` data format obtained from Pi-hole
*/
export type IGetQueriesOvertimeResponseData = IOverTimeData10minutes;
export type IGetQueriesOvertimeFormatted = ChartData<'bar', number[], number>;
/**
* GET endpoint for `/api/queries/overtime`
*
* @param req - HTTP request provided by NextJS
* @param res - HTTP response provided by NextJS
*/
const handleGetQueriesOvertimeRaw = (
req: NextApiRequest,
res: NextApiResponse<IGetQueriesOvertimeResponseData | ErrorMessage>,
) => {
const getLogger = logger.scope(apiUrl, 'GET');
const { ipAddress, port, password } = req.session.authSession;
const requestUrl = new UpstreamApiUrl(ipAddress, port, password).overTimeData10mins();
axios
.get<IOverTimeData10minutes>(requestUrl)
.then((response) => {
getLogger.info('data obtained from upstream');
res.status(200).json(response.data);
getLogger.complete(`sending response`);
getLogger.debug('response data: ', response.data);
})
.catch((error) => {
getLogger.error(`error returned when sending HTTP request to '${requestUrl}'`);
res.status(500).json({ message: JSON.stringify(error) });
});
};
/**
* GET endpoint for `/api/queries/overtime`
*
* returns formatted data for ChartJS and react-chartjs-2
*
* @see {@link https://github.com/pi-hole/AdminLTE/blob/master/scripts/pi-hole/js/index.js#L219-L286 | Code inspired by Pi-hole Admin portal}
*
* @param req - HTTP request provided by NextJS
* @param res - HTTP response provided by NextJS
*/
const handleGetQueriesOvertimeFormatted = (
req: NextApiRequest,
res: NextApiResponse<IGetQueriesOvertimeFormatted | ErrorMessage>,
) => {
const getLogger = logger.scope(apiUrl, 'GET');
const { ipAddress, port, password } = req.session.authSession;
const requestUrl = new UpstreamApiUrl(ipAddress, port, password).overTimeData10mins();
const responseData: IGetQueriesOvertimeFormatted = {
labels: [], // unix time
datasets: [],
};
axios
.get<IOverTimeData10minutes>(requestUrl)
.then((response) => {
getLogger.info('data obtained from upstream');
const domainsOvertime = Object.entries(response.data.domains_over_time);
const adsOvertime = Object.entries(response.data.ads_over_time);
// add blocked datasets group
responseData.datasets.push({
data: [],
backgroundColor: '#f56954',
label: 'Blocked DNS Queries',
});
// add permitted datasets group
responseData.datasets.push({
data: [],
backgroundColor: '#00a65a',
label: 'Permitted DNS Queries',
});
for (let i = 0; i < domainsOvertime.length; i += 1) {
const time = +domainsOvertime[i][0]; // convert domainOvertime to type `number`
const blocked = adsOvertime[i][1];
const allowed = domainsOvertime[i][1] - adsOvertime[i][1];
const hour = // set date/time in UNIX format
time < 1200
? new Date().setHours(Math.floor(time / 6), 10 * (time % 6), 0, 0)
: new Date(1000 * time).getTime();
responseData.labels?.push(hour);
responseData.datasets[0].data.push(blocked);
responseData.datasets[1].data.push(allowed);
}
res.status(200).json(responseData);
getLogger.complete(`sending response`);
getLogger.debug('response data: ', responseData);
})
.catch((error) => {
getLogger.error(`error returned when sending HTTP request to '${requestUrl}'`);
res.status(500).json({ message: JSON.stringify(error) });
});
};
/**
* Default method to run when executing this http api endpoint
*
* @remarks
* HTTP API endpoint `/api/queries/overtime`
*
* @remarks
* HTTP method allowed: `GET`
*/
const requestHandler = (req: NextApiRequest, res: NextApiResponse) => {
const { method = '' } = req;
// limit which HTTP methods are allowed
switch (method) {
case 'GET': {
const { formatted = 'false' } = req.query as IGetRequestData;
if (formatted === 'true') {
handleGetQueriesOvertimeFormatted(req, res);
} else {
handleGetQueriesOvertimeRaw(req, res);
}
break;
}
default: {
logger.error({
prefix: apiUrl,
message: `invalid HTTP method type '${method}'`,
});
res.setHeader('Allow', ['GET']);
res.status(405).end(`Method ${method} Not Allowed`);
}
}
};
export default withSessionRoute(requestHandler);