mirror of
https://github.com/gosticks/web.git
synced 2026-12-03 17:51:39 +00:00
Add ClientsGraph and ChartTooltip
Also trimmed the fake data script and made sure if a list needed to have unique data it didn't have duplicates. Signed-off-by: Mcat12 <newtoncat12@yahoo.com>
This commit is contained in:
+29
-65
@@ -9,16 +9,27 @@
|
||||
* Please see LICENSE file for your rights under this license. */
|
||||
|
||||
const faker = require('faker');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const mkdirp = require('mkdirp');
|
||||
const fs = require('fs-extra');
|
||||
|
||||
function unique(generator, size) {
|
||||
const data = [];
|
||||
|
||||
while(data.length !== size) {
|
||||
const item = generator();
|
||||
|
||||
if(!data.includes(item))
|
||||
data.push(item);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function list() {
|
||||
return (new Array(10)).fill(null).map(() => faker.internet.domainName());
|
||||
return unique(faker.internet.domainName, 10);
|
||||
}
|
||||
|
||||
function status() {
|
||||
return {status: "enabled"};
|
||||
return { status: "enabled" };
|
||||
}
|
||||
|
||||
function pastDate() {
|
||||
@@ -64,6 +75,7 @@ function summary() {
|
||||
function topList(length, max, fakeData) {
|
||||
const result = [];
|
||||
const numbers = [];
|
||||
const domains = unique(fakeData, length);
|
||||
|
||||
for(let i = 0; i < length; i++)
|
||||
numbers.push(faker.random.number({ max: max }));
|
||||
@@ -71,12 +83,8 @@ function topList(length, max, fakeData) {
|
||||
numbers.sort((a, b) => parseInt(a, 10) > parseInt(b, 10) ? -1 : 1);
|
||||
|
||||
for(let i = 0; i < length; i++) {
|
||||
let domain;
|
||||
|
||||
while((domain = fakeData()) in result.map(item => item.domain)) {}
|
||||
|
||||
result.push({
|
||||
domain: domain,
|
||||
domain: domains[i],
|
||||
count: numbers[i]
|
||||
});
|
||||
}
|
||||
@@ -104,9 +112,9 @@ function topDomains(length) {
|
||||
|
||||
function topClients(length) {
|
||||
const totalQueries = faker.random.number();
|
||||
|
||||
const top_clients = [];
|
||||
const numbers = [];
|
||||
const clients = unique(faker.internet.ip, length);
|
||||
|
||||
for(let i = 0; i < length; i++)
|
||||
numbers.push(faker.random.number({ max: totalQueries }));
|
||||
@@ -114,13 +122,9 @@ function topClients(length) {
|
||||
numbers.sort((a, b) => parseInt(a, 10) > parseInt(b, 10) ? -1 : 1);
|
||||
|
||||
for(let i = 0; i < length; i++) {
|
||||
let ip;
|
||||
|
||||
while((ip = faker.internet.ip()) in top_clients.map(item => item.ip)) {}
|
||||
|
||||
top_clients.push({
|
||||
name: "",
|
||||
ip: ip,
|
||||
ip: clients[i],
|
||||
count: numbers[i]
|
||||
});
|
||||
}
|
||||
@@ -131,38 +135,25 @@ function topClients(length) {
|
||||
};
|
||||
}
|
||||
|
||||
function forwardDestOverTime(range, totalDest) {
|
||||
function clientsOverTime(range, size) {
|
||||
const startDate = pastDate();
|
||||
const forwardDest = (new Array(totalDest)).fill(null).map(() => faker.internet.ip());
|
||||
const clients = unique(faker.internet.ip, size)
|
||||
.map(ip => ({ name: faker.internet.domainWord(), ip }));
|
||||
const graph = [];
|
||||
|
||||
for(let i = 0; i < range; i++) {
|
||||
graph.push({
|
||||
timestamp: startDate + 600 * i,
|
||||
data: (new Array(totalDest)).fill(null).map(() => faker.random.number())
|
||||
data: (new Array(size)).fill(null).map(() => faker.random.number())
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
"over_time": graph,
|
||||
"forward_destinations": forwardDest
|
||||
"clients": clients
|
||||
};
|
||||
}
|
||||
|
||||
function queryTypesOverTime(range) {
|
||||
const startDate = pastDate();
|
||||
const queryTypes = [];
|
||||
|
||||
for(let i = 0; i < range; i++) {
|
||||
queryTypes.push({
|
||||
timestamp: startDate + 600 * i,
|
||||
data: [faker.random.number(), faker.random.number()]
|
||||
});
|
||||
}
|
||||
|
||||
return queryTypes;
|
||||
}
|
||||
|
||||
function historyOverTime(range) {
|
||||
const startDate = pastDate();
|
||||
const domains = [];
|
||||
@@ -189,48 +180,21 @@ function historyOverTime(range) {
|
||||
};
|
||||
}
|
||||
|
||||
function remove(path) {
|
||||
try {
|
||||
fs.unlinkSync(path);
|
||||
}
|
||||
catch(e) {
|
||||
// Ignore missing file
|
||||
}
|
||||
}
|
||||
|
||||
function write(filePath, data) {
|
||||
const dir = path.dirname(filePath);
|
||||
|
||||
if(!fs.existsSync(dir))
|
||||
mkdirp.sync(dir);
|
||||
|
||||
fs.writeFileSync(filePath, JSON.stringify(data));
|
||||
fs.outputFileSync(filePath, JSON.stringify(data));
|
||||
}
|
||||
|
||||
console.log("Deleting old fake API data...");
|
||||
|
||||
remove("public/fakeAPI/dns/whitelist");
|
||||
remove("public/fakeAPI/dns/blacklist");
|
||||
remove("public/fakeAPI/dns/wildlist");
|
||||
remove("public/fakeAPI/dns/status");
|
||||
remove("public/fakeAPI/stats/overTime/history");
|
||||
remove("public/fakeAPI/stats/overTime/forward_destinations");
|
||||
remove("public/fakeAPI/stats/overTime/query_types");
|
||||
remove("public/fakeAPI/stats/summary");
|
||||
remove("public/fakeAPI/stats/history");
|
||||
remove("public/fakeAPI/stats/top_blocked");
|
||||
remove("public/fakeAPI/stats/top_domains");
|
||||
remove("public/fakeAPI/stats/top_clients");
|
||||
fs.emptyDirSync("public/fakeAPI/dns");
|
||||
fs.emptyDirSync("public/fakeAPI/stats");
|
||||
|
||||
console.log("Generating new fake API data...");
|
||||
|
||||
write("public/fakeAPI/dns/whitelist", list("white"));
|
||||
write("public/fakeAPI/dns/blacklist", list("black"));
|
||||
write("public/fakeAPI/dns/wildlist", list("wild"));
|
||||
write("public/fakeAPI/dns/status", status());
|
||||
write("public/fakeAPI/stats/overTime/history", historyOverTime(144));
|
||||
write("public/fakeAPI/stats/overTime/forward_destinations", forwardDestOverTime(144, 3));
|
||||
write("public/fakeAPI/stats/overTime/query_types", queryTypesOverTime(144));
|
||||
write("public/fakeAPI/stats/overTime/clients", clientsOverTime(144, 5));
|
||||
write("public/fakeAPI/stats/summary", summary());
|
||||
write("public/fakeAPI/stats/history", history(5000));
|
||||
write("public/fakeAPI/stats/top_blocked", topBlocked(10));
|
||||
|
||||
@@ -55,4 +55,24 @@
|
||||
|
||||
.stat-height-lock {
|
||||
height: 100px;
|
||||
}
|
||||
|
||||
.chartjs-tooltip {
|
||||
opacity: 1;
|
||||
position: absolute;
|
||||
background: rgba(0, 0, 0, .7);
|
||||
color: white;
|
||||
border-radius: 3px;
|
||||
-webkit-transition: all .1s ease;
|
||||
transition: all .1s ease;
|
||||
pointer-events: none;
|
||||
-webkit-transform: translate(-50%, 0);
|
||||
transform: translate(-50%, 0);
|
||||
}
|
||||
|
||||
.chartjs-tooltip-key {
|
||||
display: inline-block;
|
||||
width: 20px;
|
||||
height: 10px;
|
||||
margin-right: 10px;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/* Pi-hole: A black hole for Internet advertisements
|
||||
* (c) 2017 Pi-hole, LLC (https://pi-hole.net)
|
||||
* Network-wide ad blocking via your own hardware.
|
||||
*
|
||||
* Web Interface
|
||||
* Chart Tooltip component
|
||||
*
|
||||
* This file is copyright under the latest version of the EUPL.
|
||||
* Please see LICENSE file for your rights under this license. */
|
||||
|
||||
import React, { Component } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
class ChartTooltip extends Component {
|
||||
state = {
|
||||
tooltip: null
|
||||
};
|
||||
|
||||
render() {
|
||||
const { tooltip } = this.state;
|
||||
|
||||
// Override the graph's options in a hacky way to avoid redrawing the entire graph.
|
||||
// This lets the graph directly update the tooltip without going through the parent component.
|
||||
let lastTime = Date.now();
|
||||
this.props.handler.custom = tooltip => {
|
||||
// Always disable the tooltip
|
||||
if(tooltip.opacity === 0)
|
||||
this.setState({ tooltip });
|
||||
|
||||
// Limit how quickly we set state (50ms)
|
||||
const now = Date.now();
|
||||
if(now - lastTime < 50)
|
||||
return;
|
||||
|
||||
lastTime = now;
|
||||
this.setState({ tooltip });
|
||||
};
|
||||
|
||||
// Don't render anything if there is nothing to render
|
||||
if(tooltip === null || tooltip.opacity === 0 || this.props.chart.current === null)
|
||||
return null;
|
||||
|
||||
// Get the graph's position data so we can offset the tooltip
|
||||
const position = this.props.chart.current.chartInstance.canvas.getBoundingClientRect();
|
||||
let width = tooltip.caretX;
|
||||
|
||||
// Prevent compression of the tooltip at the right edge of the screen
|
||||
if(document.offsetWidth - tooltip.caretX < 400)
|
||||
width = document.offsetWidth - 400;
|
||||
|
||||
// Prevent tooltip disappearing behind the sidebar
|
||||
if(tooltip.caretX < 100)
|
||||
width = 100;
|
||||
|
||||
// Tooltip CSS styling
|
||||
const style = {
|
||||
opacity: 1,
|
||||
left: position.left + width + "px",
|
||||
top: position.top + tooltip.caretY + window.scrollY + "px",
|
||||
fontFamily: tooltip._bodyFontFamily,
|
||||
fontSize: tooltip.bodyFontSize + "px",
|
||||
fontStyle: tooltip._bodyFontStyle,
|
||||
padding: tooltip.yPadding + "px " + tooltip.xPadding + "px"
|
||||
};
|
||||
|
||||
// Transform and sort the tooltip data
|
||||
let data = [];
|
||||
if(tooltip.body) {
|
||||
data = tooltip.body
|
||||
.map(body => body.lines)
|
||||
.map((item, i) => ({
|
||||
data: item[0],
|
||||
colors: tooltip.labelColors[i]
|
||||
}));
|
||||
}
|
||||
data.sort((a, b) => a.data.split(": ")[0].localeCompare(b.data.split(": ")[0]));
|
||||
|
||||
return (
|
||||
<div className="chartjs-tooltip" style={style}>
|
||||
<table>
|
||||
<thead>
|
||||
{
|
||||
tooltip.title.map((title, i) => (
|
||||
<tr key={i}>
|
||||
<th>{title}</th>
|
||||
</tr>
|
||||
))
|
||||
}
|
||||
</thead>
|
||||
<tbody>
|
||||
{
|
||||
data.map((item, i) => (
|
||||
<tr key={i}>
|
||||
<td>
|
||||
<span className="chartjs-tooltip-key"
|
||||
style={{
|
||||
background: item.colors.backgroundColor,
|
||||
borderColor: item.colors.borderColor,
|
||||
borderWidth: "2px"
|
||||
}}/>
|
||||
{item.data}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
ChartTooltip.propTypes = {
|
||||
chart: PropTypes.object.isRequired,
|
||||
handler: PropTypes.shape({
|
||||
custom: PropTypes.func.isRequired
|
||||
}).isRequired
|
||||
};
|
||||
|
||||
export default ChartTooltip;
|
||||
@@ -0,0 +1,169 @@
|
||||
/* Pi-hole: A black hole for Internet advertisements
|
||||
* (c) 2017 Pi-hole, LLC (https://pi-hole.net)
|
||||
* Network-wide ad blocking via your own hardware.
|
||||
*
|
||||
* Web Interface
|
||||
* Clients Graph component
|
||||
*
|
||||
* This file is copyright under the latest version of the EUPL.
|
||||
* Please see LICENSE file for your rights under this license. */
|
||||
|
||||
import React, { Component } from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { Line } from 'react-chartjs-2';
|
||||
import { translate } from 'react-i18next';
|
||||
import { padNumber, api, makeCancelable, ignoreCancel } from '../utils';
|
||||
import ChartTooltip from "./ChartTooltip";
|
||||
|
||||
class ClientsGraph extends Component {
|
||||
state = {
|
||||
loading: true,
|
||||
data: {
|
||||
labels: [],
|
||||
datasets: []
|
||||
}
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.graphRef = React.createRef();
|
||||
}
|
||||
|
||||
updateGraph() {
|
||||
this.updateHandler = makeCancelable(api.getClientsGraph(), { repeat: this.updateGraph, interval: 10 * 60 * 1000 });
|
||||
this.updateHandler.promise.then(res => {
|
||||
// Remove last data point as it's not yet finished
|
||||
res.over_time.splice(-1, 1);
|
||||
|
||||
const colors = [
|
||||
"#20a8d8",
|
||||
"#f86c6b",
|
||||
"#4dbd74",
|
||||
"#f8cb00",
|
||||
"#263238",
|
||||
"#63c2de",
|
||||
"#b0bec5"
|
||||
];
|
||||
const labels = res.over_time.map(step => new Date(1000 * step.timestamp));
|
||||
const datasets = [];
|
||||
|
||||
// Fill in dataset metadata
|
||||
let i = 0;
|
||||
for(let client of res.clients) {
|
||||
datasets.push({
|
||||
label: client.name.length !== 0 ? client.name : client.ip,
|
||||
// If we ran out of colors, make a random one
|
||||
backgroundColor: i < colors.length
|
||||
? colors[i]
|
||||
: '#' + parseInt("" + Math.random() * 0xffffff, 10).toString(16),
|
||||
pointRadius: 0,
|
||||
pointHitRadius: 5,
|
||||
pointHoverRadius: 5,
|
||||
cubicInterpolationMode: "monotone",
|
||||
data: []
|
||||
});
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
// Fill in data & labels
|
||||
for(let step of res.over_time) {
|
||||
for(let destination in datasets) {
|
||||
if(datasets.hasOwnProperty(destination))
|
||||
datasets[destination].data.push(step.data[destination]);
|
||||
}
|
||||
}
|
||||
|
||||
datasets.sort((a, b) => a.label.localeCompare(b.label));
|
||||
|
||||
this.setState({ data: { labels, datasets }, loading: false });
|
||||
}).catch(ignoreCancel)
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.updateGraph();
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.updateHandler.cancel();
|
||||
}
|
||||
|
||||
render() {
|
||||
const { t } = this.props;
|
||||
|
||||
const options = {
|
||||
tooltips: {
|
||||
enabled: false,
|
||||
mode: "x-axis",
|
||||
custom: () => "placeholder",
|
||||
itemSort: function(a, b) {
|
||||
return b.yLabel - a.yLabel;
|
||||
},
|
||||
callbacks: {
|
||||
title: tooltipItem => {
|
||||
const time = tooltipItem[0].xLabel.match(/(\d?\d):?(\d?\d?)/);
|
||||
const hour = parseInt(time[1], 10);
|
||||
const minute = parseInt(time[2], 10) || 0;
|
||||
const from = padNumber(hour) + ":" + padNumber(minute - 5) + ":00";
|
||||
const to = padNumber(hour) + ":" + padNumber(minute + 4) + ":59";
|
||||
|
||||
return t("Client activity from {{from}} to {{to}}", { from, to });
|
||||
},
|
||||
label: (tooltipItems, data) => {
|
||||
return data.datasets[tooltipItems.datasetIndex].label + ": " + tooltipItems.yLabel;
|
||||
}
|
||||
}
|
||||
},
|
||||
legend: { display: false },
|
||||
scales: {
|
||||
xAxes: [{
|
||||
type: "time",
|
||||
time: {
|
||||
unit: "hour",
|
||||
displayFormats: { hour: "HH:mm" },
|
||||
tooltipFormat: "HH:mm"
|
||||
}
|
||||
}],
|
||||
yAxes: [{
|
||||
ticks: { beginAtZero: true },
|
||||
stacked: true
|
||||
}]
|
||||
},
|
||||
maintainAspectRatio: false
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="row">
|
||||
<div className="col-md-12">
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
{t("Clients Over Last 24 Hours")}
|
||||
</div>
|
||||
<div className="card-block">
|
||||
<Line width={970} height={250} data={this.state.data} options={options} ref={this.graphRef}/>
|
||||
</div>
|
||||
{
|
||||
this.state.loading
|
||||
?
|
||||
<div className="card-img-overlay" style={{ background: "rgba(255,255,255,0.7)" }}>
|
||||
<i className="fa fa-refresh fa-spin"
|
||||
style={{ position: "absolute", top: "50%", left: "50%", fontSize: "30px" }}/>
|
||||
</div>
|
||||
:
|
||||
null
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
{
|
||||
// Now you're thinking with portals!
|
||||
ReactDOM.createPortal(
|
||||
<ChartTooltip chart={this.graphRef} handler={options.tooltips}/>,
|
||||
document.body
|
||||
)
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default translate("dashboard")(ClientsGraph);
|
||||
@@ -27,7 +27,7 @@ class QueriesGraph extends Component {
|
||||
}
|
||||
|
||||
updateGraph() {
|
||||
this.updateHandler = makeCancelable(api.getHistoryGraph(), { repeat: this.updateGraph, interval: 10 * 60 * 1000});
|
||||
this.updateHandler = makeCancelable(api.getHistoryGraph(), { repeat: this.updateGraph, interval: 10 * 60 * 1000 });
|
||||
this.updateHandler.promise.then(res => {
|
||||
// Remove last data point as it's not yet finished
|
||||
res.blocked_over_time.splice(-1, 1);
|
||||
@@ -102,12 +102,12 @@ class QueriesGraph extends Component {
|
||||
return t("Queries from {{from}} to {{to}}", { from, to });
|
||||
},
|
||||
label: (tooltipItems, data) => {
|
||||
if (tooltipItems.datasetIndex === 1) {
|
||||
if(tooltipItems.datasetIndex === 1) {
|
||||
let percentage = 0.0;
|
||||
const total = parseInt(data.datasets[0].data[tooltipItems.index], 10);
|
||||
const blocked = parseInt(data.datasets[1].data[tooltipItems.index], 10);
|
||||
|
||||
if (total > 0)
|
||||
if(total > 0)
|
||||
percentage = 100.0 * blocked / total;
|
||||
|
||||
return data.datasets[tooltipItems.datasetIndex].label + ": " + tooltipItems.yLabel
|
||||
@@ -128,7 +128,7 @@ class QueriesGraph extends Component {
|
||||
tooltipFormat: "HH:mm"
|
||||
}
|
||||
}],
|
||||
yAxes: [{
|
||||
yAxes: [{
|
||||
ticks: { beginAtZero: true }
|
||||
}]
|
||||
},
|
||||
@@ -147,11 +147,12 @@ class QueriesGraph extends Component {
|
||||
</div>
|
||||
{
|
||||
this.state.loading
|
||||
?
|
||||
<div className="card-img-overlay" style={{background: "rgba(255,255,255,0.7)"}}>
|
||||
<i className="fa fa-refresh fa-spin" style={{position: "absolute", top: "50%", left: "50%", fontSize: "30px"}}/>
|
||||
?
|
||||
<div className="card-img-overlay" style={{ background: "rgba(255,255,255,0.7)" }}>
|
||||
<i className="fa fa-refresh fa-spin"
|
||||
style={{ position: "absolute", top: "50%", left: "50%", fontSize: "30px" }}/>
|
||||
</div>
|
||||
:
|
||||
:
|
||||
null
|
||||
}
|
||||
</div>
|
||||
@@ -161,4 +162,4 @@ class QueriesGraph extends Component {
|
||||
}
|
||||
}
|
||||
|
||||
export default translate(["common", "dashboard"])(QueriesGraph);
|
||||
export default translate("dashboard")(QueriesGraph);
|
||||
|
||||
+2
-2
@@ -72,8 +72,8 @@ export const api = {
|
||||
getHistoryGraph() {
|
||||
return api.get("stats/overTime/history");
|
||||
},
|
||||
getQueryTypesOverTime() {
|
||||
return api.get("stats/overTime/query_types");
|
||||
getClientsGraph() {
|
||||
return api.get("stats/overTime/clients")
|
||||
},
|
||||
getTopDomains() {
|
||||
return api.get("stats/top_domains");
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
import React, { Fragment } from 'react';
|
||||
import SummaryStats from '../components/SummaryStats';
|
||||
import QueriesGraph from '../components/QueriesGraph';
|
||||
import ClientsGraph from '../components/ClientsGraph';
|
||||
import TopDomains from '../components/TopDomains';
|
||||
import TopBlocked from '../components/TopBlocked';
|
||||
import TopClients from '../components/TopClients';
|
||||
@@ -23,9 +24,7 @@ export default () => (
|
||||
{
|
||||
api.loggedIn ?
|
||||
<Fragment>
|
||||
<div className="row">
|
||||
{/* TODO: Add clients over time */}
|
||||
</div>
|
||||
<ClientsGraph/>
|
||||
<div className="row">
|
||||
<TopDomains/>
|
||||
<TopBlocked/>
|
||||
|
||||
Reference in New Issue
Block a user