From cf8c6f0b88d10e577d69df5c065c217d8ddd5bc6 Mon Sep 17 00:00:00 2001 From: Mcat12 Date: Sat, 9 Jun 2018 12:58:13 -0400 Subject: [PATCH 1/3] Center data in 10 minute slot This change was made on the PHP web interface already. Also renamed some temporary variables for better readability Signed-off-by: Mcat12 --- src/components/QueriesGraph.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/components/QueriesGraph.js b/src/components/QueriesGraph.js index 1497dbd..424bc26 100644 --- a/src/components/QueriesGraph.js +++ b/src/components/QueriesGraph.js @@ -94,10 +94,10 @@ class QueriesGraph extends Component { callbacks: { title: tooltipItem => { const time = tooltipItem[0].xLabel.match(/(\d?\d):?(\d?\d?)/); - const h = parseInt(time[1], 10); - const m = parseInt(time[2], 10) || 0; - const from = padNumber(h) + ":" + padNumber(m) + ":00"; - const to = padNumber(h) + ":" + padNumber(m + 9) + ":59"; + 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("Queries from {{from}} to {{to}}", { from, to }); }, From 41b95293be5334e3eadb84f7014de8747b8dca2d Mon Sep 17 00:00:00 2001 From: Mcat12 Date: Sat, 9 Jun 2018 18:04:30 -0400 Subject: [PATCH 2/3] 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 --- make-fake-data.js | 94 ++++++------------ scss/_custom.scss | 20 ++++ src/components/ChartTooltip.js | 120 +++++++++++++++++++++++ src/components/ClientsGraph.js | 169 +++++++++++++++++++++++++++++++++ src/components/QueriesGraph.js | 19 ++-- src/utils.js | 4 +- src/views/Dashboard.js | 5 +- 7 files changed, 352 insertions(+), 79 deletions(-) create mode 100644 src/components/ChartTooltip.js create mode 100644 src/components/ClientsGraph.js diff --git a/make-fake-data.js b/make-fake-data.js index 0bae6b5..54acef5 100644 --- a/make-fake-data.js +++ b/make-fake-data.js @@ -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)); diff --git a/scss/_custom.scss b/scss/_custom.scss index e9e2c9c..25545ee 100644 --- a/scss/_custom.scss +++ b/scss/_custom.scss @@ -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; } \ No newline at end of file diff --git a/src/components/ChartTooltip.js b/src/components/ChartTooltip.js new file mode 100644 index 0000000..a4bb2fc --- /dev/null +++ b/src/components/ChartTooltip.js @@ -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 ( +
+ + + { + tooltip.title.map((title, i) => ( + + + + )) + } + + + { + data.map((item, i) => ( + + + + )) + } + +
{title}
+ + {item.data} +
+
+ ); + } +} + +ChartTooltip.propTypes = { + chart: PropTypes.object.isRequired, + handler: PropTypes.shape({ + custom: PropTypes.func.isRequired + }).isRequired +}; + +export default ChartTooltip; diff --git a/src/components/ClientsGraph.js b/src/components/ClientsGraph.js new file mode 100644 index 0000000..7977982 --- /dev/null +++ b/src/components/ClientsGraph.js @@ -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 ( +
+
+
+
+ {t("Clients Over Last 24 Hours")} +
+
+ +
+ { + this.state.loading + ? +
+ +
+ : + null + } +
+
+ { + // Now you're thinking with portals! + ReactDOM.createPortal( + , + document.body + ) + } +
+ ); + } +} + +export default translate("dashboard")(ClientsGraph); \ No newline at end of file diff --git a/src/components/QueriesGraph.js b/src/components/QueriesGraph.js index 424bc26..99a16ad 100644 --- a/src/components/QueriesGraph.js +++ b/src/components/QueriesGraph.js @@ -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 { { this.state.loading - ? -
- + ? +
+
- : + : null }
@@ -161,4 +162,4 @@ class QueriesGraph extends Component { } } -export default translate(["common", "dashboard"])(QueriesGraph); +export default translate("dashboard")(QueriesGraph); diff --git a/src/utils.js b/src/utils.js index 1942f0d..9ec28f8 100644 --- a/src/utils.js +++ b/src/utils.js @@ -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"); diff --git a/src/views/Dashboard.js b/src/views/Dashboard.js index 6183ad0..7bb144f 100644 --- a/src/views/Dashboard.js +++ b/src/views/Dashboard.js @@ -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 ? -
- {/* TODO: Add clients over time */} -
+
From 4e8bd32c0b5c6b018290e7a36603d2c4548dd7ba Mon Sep 17 00:00:00 2001 From: Mcat12 Date: Sat, 9 Jun 2018 18:17:47 -0400 Subject: [PATCH 3/3] Bind updateGraph to the correct "this" Signed-off-by: Mcat12 --- src/components/ClientsGraph.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/components/ClientsGraph.js b/src/components/ClientsGraph.js index 7977982..e539d45 100644 --- a/src/components/ClientsGraph.js +++ b/src/components/ClientsGraph.js @@ -27,6 +27,7 @@ class ClientsGraph extends Component { constructor(props) { super(props); this.graphRef = React.createRef(); + this.updateGraph = this.updateGraph.bind(this); } updateGraph() {