+ ) : null}
);
diff --git a/src/components/common/LanguageApplier.tsx b/src/components/common/LanguageApplier.tsx
index b5da269..9c73f13 100644
--- a/src/components/common/LanguageApplier.tsx
+++ b/src/components/common/LanguageApplier.tsx
@@ -9,7 +9,7 @@
* Please see LICENSE file for your rights under this license. */
import React from "react";
-import { PreferencesContext } from "./context";
+import { PreferencesContext } from "./context/PreferencesContext";
import i18n from "i18next";
const applyLanguage = (language: string) => {
diff --git a/src/components/common/LayoutApplier.tsx b/src/components/common/LayoutApplier.tsx
index 9d5d0d6..fee8d08 100644
--- a/src/components/common/LayoutApplier.tsx
+++ b/src/components/common/LayoutApplier.tsx
@@ -9,7 +9,7 @@
* Please see LICENSE file for your rights under this license. */
import React from "react";
-import { PreferencesContext } from "./context";
+import { PreferencesContext } from "./context/PreferencesContext";
/**
* Update the web interface layout
diff --git a/src/components/common/StatusBadge.tsx b/src/components/common/StatusBadge.tsx
index 32fab2e..f5da351 100644
--- a/src/components/common/StatusBadge.tsx
+++ b/src/components/common/StatusBadge.tsx
@@ -10,7 +10,7 @@
import React, { Component } from "react";
import { WithNamespaces, withNamespaces } from "react-i18next";
-import { StatusContext } from "./context";
+import { StatusContext } from "./context/StatusContext";
export interface StatusBadgeProps extends WithNamespaces {
status: string;
diff --git a/src/components/common/WithAPIData.tsx b/src/components/common/WithAPIData.tsx
index 3ca175c..3e72e0a 100644
--- a/src/components/common/WithAPIData.tsx
+++ b/src/components/common/WithAPIData.tsx
@@ -19,6 +19,11 @@ export interface WithAPIDataProps {
interval: number;
};
+ /**
+ * If the data should be cleared when the props update. Defaults to true.
+ */
+ flushOnUpdate: boolean;
+
/**
* Render the children before the first API request is done
*/
@@ -61,7 +66,8 @@ export class WithAPIData extends Component<
repeatOptions: {
ignoreCancel: true,
interval: 0
- }
+ },
+ flushOnUpdate: true
};
state: WithAPIDataState = {
@@ -132,6 +138,24 @@ export class WithAPIData extends Component<
}
}
+ componentDidUpdate(
+ prevProps: Readonly>,
+ prevState: Readonly>,
+ snapshot?: any
+ ): void {
+ if (prevProps === this.props) {
+ // Don't do anything if the props didn't change
+ return;
+ }
+
+ if (this.props.flushOnUpdate) {
+ // The props changed, so trigger a full reload of the data. Current data is
+ // cleared so that loading indicators are shown.
+ this.setState({ apiResult: null });
+ this.loadData();
+ }
+ }
+
render() {
if (!this.state.apiResult) {
return this.props.renderInitial();
diff --git a/src/components/common/context.tsx b/src/components/common/context/PreferencesContext.tsx
similarity index 54%
rename from src/components/common/context.tsx
rename to src/components/common/context/PreferencesContext.tsx
index 03cc533..617fffe 100644
--- a/src/components/common/context.tsx
+++ b/src/components/common/context/PreferencesContext.tsx
@@ -3,32 +3,32 @@
* Network-wide ad blocking via your own hardware.
*
* Web Interface
- * React context objects
+ * Preferences context
*
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
import React, { ReactNode } from "react";
-import { WithAPIData } from "./WithAPIData";
-import api from "../../util/api";
-
-export interface StatusContextType {
- status: Status;
- refresh: (data?: ApiStatus) => void;
-}
+import { WithAPIData } from "../WithAPIData";
+import api from "../../../util/api";
+/**
+ * The data shared by the preferences context
+ */
export interface PreferencesContextType {
settings: ApiPreferences;
refresh: (data?: ApiPreferences) => void;
}
+/**
+ * The key used to store preferences in local storage
+ */
export const WEB_PREFERENCES_STORAGE_KEY = "webPreferences";
-const initialStatus: StatusContextType = {
- status: "unknown",
- refresh: () => {}
-};
-
+/**
+ * The default preferences. These preferences are used until the API responds
+ * with the real preferences, unless there are cached preferences available.
+ */
export const defaultPreferences: ApiPreferences = {
layout: "boxed",
language: "en"
@@ -55,62 +55,19 @@ export const loadInitialPreferences = (): ApiPreferences => {
}
};
-const initialPreferences: PreferencesContextType = {
+/**
+ * The context which will be used initially, until the API responds with the
+ * real preferences. These preferences are loaded from cache if available.
+ */
+const initialContext: PreferencesContextType = {
settings: loadInitialPreferences(),
refresh: () => {}
};
-export const StatusContext = React.createContext(initialStatus);
-export const PreferencesContext = React.createContext(initialPreferences);
-
/**
- * Provide all of the necessary context needed at the root level to its
- * children. Currently, this includes status and preferences.
+ * The React context which provides the preferences to consumers
*/
-export const GlobalContextProvider = ({
- children
-}: {
- children: ReactNode;
-}) => (
-
- {children}
-
-);
-
-/**
- * Provide the blocking status via React context.
- * Sub-components can use the `StatusContext.Consumer` component to get the
- * status.
- */
-export const StatusProvider = ({
- children,
- ...props
-}: {
- children: ReactNode;
-}) => (
- (
-
- {children}
-
- )}
- renderOk={(data, refresh) => (
-
- {children}
-
- )}
- renderErr={(_, refresh) => (
-
- {children}
-
- )}
- />
-);
+export const PreferencesContext = React.createContext(initialContext);
/**
* Provide the web interface preferences via React context.
@@ -126,7 +83,7 @@ export const PreferencesProvider = ({
(
-
+
{children}
)}
@@ -145,7 +102,9 @@ export const PreferencesProvider = ({
}}
renderErr={(_, refresh) => (
{children}
diff --git a/src/components/common/context/StatusContext.tsx b/src/components/common/context/StatusContext.tsx
new file mode 100644
index 0000000..a28b2e8
--- /dev/null
+++ b/src/components/common/context/StatusContext.tsx
@@ -0,0 +1,74 @@
+/* Pi-hole: A black hole for Internet advertisements
+ * (c) 2019 Pi-hole, LLC (https://pi-hole.net)
+ * Network-wide ad blocking via your own hardware.
+ *
+ * Web Interface
+ * Status context
+ *
+ * This file is copyright under the latest version of the EUPL.
+ * Please see LICENSE file for your rights under this license. */
+
+import React, { ReactNode } from "react";
+import { WithAPIData } from "../WithAPIData";
+import api from "../../../util/api";
+
+/**
+ * The data shared by the status context
+ */
+export interface StatusContextType {
+ status: Status;
+ refresh: (data?: ApiStatus) => void;
+}
+
+/**
+ * The status data which will be used initially, until the API responds with the
+ * real status data.
+ */
+const initialContext: StatusContextType = {
+ status: "unknown",
+ refresh: () => {}
+};
+
+/**
+ * The React context which provides the status data to consumers
+ */
+export const StatusContext = React.createContext(initialContext);
+
+/**
+ * Provide the blocking status via React context.
+ * Sub-components can use the `StatusContext.Consumer` component to get the
+ * status.
+ */
+export const StatusProvider = ({
+ children,
+ ...props
+}: {
+ children: ReactNode;
+}) => (
+ (
+
+ {children}
+
+ )}
+ renderOk={(data, refresh) => (
+
+ {children}
+
+ )}
+ renderErr={(_, refresh) => (
+
+ {children}
+
+ )}
+ />
+);
diff --git a/src/components/common/context/TimeRangeContext.tsx b/src/components/common/context/TimeRangeContext.tsx
new file mode 100644
index 0000000..64d9b69
--- /dev/null
+++ b/src/components/common/context/TimeRangeContext.tsx
@@ -0,0 +1,63 @@
+/* Pi-hole: A black hole for Internet advertisements
+ * (c) 2019 Pi-hole, LLC (https://pi-hole.net)
+ * Network-wide ad blocking via your own hardware.
+ *
+ * Web Interface
+ * Context used for sharing a time range
+ *
+ * This file is copyright under the latest version of the EUPL.
+ * Please see LICENSE file for your rights under this license. */
+
+import { Moment } from "moment";
+import React, { ReactNode, useState } from "react";
+
+/**
+ * Represents a range of time
+ */
+export interface TimeRange {
+ from: Moment;
+ until: Moment;
+ name: string;
+}
+
+/**
+ * The type of the data shared by the time range context
+ */
+export interface TimeRangeContextType {
+ range: TimeRange | null;
+
+ /**
+ * Update the time range
+ *
+ * @param range The new time range
+ */
+ update: (range: TimeRange | null) => void;
+}
+
+/**
+ * The initial data shared by the time range context
+ */
+const initialContext: TimeRangeContextType = {
+ range: null,
+ update: () => {}
+};
+
+/**
+ * The React context which provides the time range to consumers
+ */
+export const TimeRangeContext = React.createContext(initialContext);
+
+/**
+ * Provide the time range via React context.
+ * Sub-components can use the `TimeRangeContext.Consumer` component to get the
+ * time range.
+ */
+export const TimeRangeProvider = ({ children }: { children: ReactNode }) => {
+ const [range, setRange] = useState(initialContext.range);
+
+ return (
+
+ {children}
+
+ );
+};
diff --git a/src/components/common/__tests__/context.test.tsx b/src/components/common/context/__tests__/PreferencesContext.test.tsx
similarity index 96%
rename from src/components/common/__tests__/context.test.tsx
rename to src/components/common/context/__tests__/PreferencesContext.test.tsx
index b44c9f1..44191d8 100644
--- a/src/components/common/__tests__/context.test.tsx
+++ b/src/components/common/context/__tests__/PreferencesContext.test.tsx
@@ -12,7 +12,7 @@ import {
defaultPreferences,
loadInitialPreferences,
WEB_PREFERENCES_STORAGE_KEY
-} from "../context";
+} from "../PreferencesContext";
it("loads the default preferences if none are cached", () => {
const preferences = loadInitialPreferences();
diff --git a/src/components/common/context/index.tsx b/src/components/common/context/index.tsx
new file mode 100644
index 0000000..6cd2871
--- /dev/null
+++ b/src/components/common/context/index.tsx
@@ -0,0 +1,31 @@
+/* Pi-hole: A black hole for Internet advertisements
+ * (c) 2019 Pi-hole, LLC (https://pi-hole.net)
+ * Network-wide ad blocking via your own hardware.
+ *
+ * Web Interface
+ * React context objects
+ *
+ * This file is copyright under the latest version of the EUPL.
+ * Please see LICENSE file for your rights under this license. */
+
+import React, { ReactNode } from "react";
+import { StatusProvider } from "./StatusContext";
+import { PreferencesProvider } from "./PreferencesContext";
+import { TimeRangeProvider } from "./TimeRangeContext";
+
+/**
+ * Provide all of the necessary context needed at the root level to the
+ * children. Currently, this includes status, preferences, and time range (for
+ * the dashboard).
+ */
+export const GlobalContextProvider = ({
+ children
+}: {
+ children: ReactNode;
+}) => (
+
+
+ {children}
+
+
+);
diff --git a/src/components/dashboard/ClientsGraph.tsx b/src/components/dashboard/ClientsGraph.tsx
index ccbc786..17837ae 100644
--- a/src/components/dashboard/ClientsGraph.tsx
+++ b/src/components/dashboard/ClientsGraph.tsx
@@ -12,15 +12,21 @@ import React, { Component, RefObject } from "react";
import ReactDOM from "react-dom";
import { Line } from "react-chartjs-2";
import { WithNamespaces, withNamespaces } from "react-i18next";
-import { padNumber } from "../../util";
+import { getIntervalForRange, padNumber } from "../../util";
import api from "../../util/api";
import ChartTooltip from "./ChartTooltip";
import { WithAPIData } from "../common/WithAPIData";
-import { ChartDataSets, ChartOptions } from "chart.js";
+import { ChartDataSets, ChartOptions, TimeUnit } from "chart.js";
+import {
+ TimeRange,
+ TimeRangeContext
+} from "../common/context/TimeRangeContext";
export interface ClientsGraphProps {
loading: boolean;
labels: Array;
+ timeUnit: TimeUnit;
+ rangeName?: string;
datasets: Array;
}
@@ -69,7 +75,7 @@ class ClientsGraph extends Component {
{
type: "time",
time: {
- unit: "hour",
+ unit: this.props.timeUnit,
displayFormats: { hour: "HH:mm" },
tooltipFormat: "HH:mm"
}
@@ -85,9 +91,15 @@ class ClientsGraph extends Component {
maintainAspectRatio: false
};
+ const range = this.props.rangeName
+ ? this.props.rangeName
+ : t("Last 24 Hours");
+
return (
-
{t("Clients Over Last 24 Hours")}
+
+ {t("Clients Over {{range}}", { range })}
+
{
/**
* Transform the API data into props for ClientsGraph
*
- * @param data the API data
+ * @param data The API data
+ * @param range The time range to use
* @returns {{labels: Date[], datasets: Array, loading: boolean}} ClientsGraph
* props
*/
-export const transformData = (data: ApiClientsGraph) => {
- // Remove last data point as it's not yet finished
- const overTime = data.over_time.slice(0, -1);
+export const transformData = (
+ data: ApiClientsGraph,
+ range: TimeRange | null
+) => {
+ let timeUnit: TimeUnit = "hour";
+ let overTime = data.over_time;
+
+ if (range) {
+ if (range.until.diff(range.from, "day") > 1) {
+ timeUnit = "day";
+ }
+ } else {
+ // Remove last data point as it's not yet finished
+ overTime = data.over_time.slice(0, -1);
+ }
const colors = [
"#20a8d8",
@@ -186,33 +211,64 @@ export const transformData = (data: ApiClientsGraph) => {
datasets.sort((a, b) => a.label!.localeCompare(b.label!));
- return { labels, datasets, loading: false };
+ return {
+ labels,
+ datasets,
+ loading: false,
+ timeUnit,
+ rangeName: range ? range.name : undefined
+ };
};
/**
* The props used to show a loading state (either initial load or error)
*/
-export const loadingProps = {
+export const loadingProps: ClientsGraphProps = {
loading: true,
labels: [],
+ timeUnit: "hour",
+ rangeName: "---",
datasets: []
};
-export const TranslatedClientsGraph = withNamespaces("dashboard")(ClientsGraph);
+export const TranslatedClientsGraph = withNamespaces([
+ "dashboard",
+ "time-ranges"
+])(ClientsGraph);
export default (props: any) => (
- (
-
+
+ {context => (
+
+ context.range
+ ? api.getClientsGraphDb(
+ context.range,
+ getIntervalForRange(context.range)
+ )
+ : api.getClientsGraph()
+ }
+ repeatOptions={
+ context.range
+ ? undefined
+ : {
+ interval: 10 * 60 * 1000,
+ ignoreCancel: true
+ }
+ }
+ renderInitial={() => (
+
+ )}
+ renderOk={data => (
+
+ )}
+ renderErr={() => (
+
+ )}
+ />
)}
- renderOk={data => (
-
- )}
- renderErr={() => }
- />
+
);
diff --git a/src/components/dashboard/QueriesGraph.tsx b/src/components/dashboard/QueriesGraph.tsx
index 1640c24..e321bb2 100644
--- a/src/components/dashboard/QueriesGraph.tsx
+++ b/src/components/dashboard/QueriesGraph.tsx
@@ -10,15 +10,21 @@
import React, { Component } from "react";
import { WithNamespaces, withNamespaces } from "react-i18next";
-import { padNumber } from "../../util";
+import { getIntervalForRange, padNumber } from "../../util";
import api from "../../util/api";
import { WithAPIData } from "../common/WithAPIData";
-import { ChartData, ChartOptions } from "chart.js";
+import { ChartData, ChartOptions, TimeUnit } from "chart.js";
import { Line } from "react-chartjs-2";
+import {
+ TimeRange,
+ TimeRangeContext
+} from "../common/context/TimeRangeContext";
export interface QueriesGraphProps {
loading: boolean;
labels: Array;
+ timeUnit: TimeUnit;
+ rangeName?: string;
domains_over_time: Array;
blocked_over_time: Array;
}
@@ -107,7 +113,7 @@ class QueriesGraph extends Component {
{
type: "time",
time: {
- unit: "hour",
+ unit: this.props.timeUnit,
displayFormats: { hour: "HH:mm" },
tooltipFormat: "HH:mm"
}
@@ -122,9 +128,15 @@ class QueriesGraph extends Component {
maintainAspectRatio: false
};
+ const range = this.props.rangeName
+ ? this.props.rangeName
+ : t("Last 24 Hours");
+
return (
-
{t("Queries Over Last 24 Hours")}
+
+ {t("Queries Over {{range}}", { range })}
+
@@ -152,15 +164,24 @@ class QueriesGraph extends Component {
/**
* Transform the API data into props for QueriesGraph
*
- * @param data the API data
- * @returns {{loading: boolean, labels: Date[], domains_over_time: *,
- * blocked_over_time: any[]}} QueriesGraph props
+ * @param data The API data
+ * @param range The time range to use
+ * @returns QueriesGraphProps QueriesGraph props
*/
export const transformData = (
- data: Array
+ data: Array,
+ range: TimeRange | null
): QueriesGraphProps => {
- // Remove last data point as it's not yet finished
- data = data.slice(0, -1);
+ let timeUnit: TimeUnit = "hour";
+
+ if (range) {
+ if (range.until.diff(range.from, "day") > 1) {
+ timeUnit = "day";
+ }
+ } else {
+ // Remove last data point as it's not yet finished
+ data = data.slice(0, -1);
+ }
const labels = data.map(step => new Date(1000 * step.timestamp));
const domains_over_time = data.map(step => step.total_queries);
@@ -169,6 +190,8 @@ export const transformData = (
return {
loading: false,
labels,
+ timeUnit,
+ rangeName: range ? range.name : undefined,
domains_over_time,
blocked_over_time
};
@@ -177,28 +200,53 @@ export const transformData = (
/**
* The props used to show a loading state (either initial load or error)
*/
-export const loadingProps = {
+export const loadingProps: QueriesGraphProps = {
loading: true,
labels: [],
+ timeUnit: "hour",
+ rangeName: "---",
domains_over_time: [],
blocked_over_time: []
};
-export const TranslatedQueriesGraph = withNamespaces("dashboard")(QueriesGraph);
+export const TranslatedQueriesGraph = withNamespaces([
+ "dashboard",
+ "time-ranges"
+])(QueriesGraph);
export default (props: any) => (
- (
-
+
+ {context => (
+
+ context.range
+ ? api.getHistoryGraphDb(
+ context.range,
+ getIntervalForRange(context.range)
+ )
+ : api.getHistoryGraph()
+ }
+ repeatOptions={
+ context.range
+ ? undefined
+ : {
+ interval: 10 * 60 * 1000,
+ ignoreCancel: true
+ }
+ }
+ renderInitial={() => (
+
+ )}
+ renderOk={data => (
+
+ )}
+ renderErr={() => (
+
+ )}
+ />
)}
- renderOk={data => (
-
- )}
- renderErr={() => }
- />
+
);
diff --git a/src/components/dashboard/QueryTypesChart.tsx b/src/components/dashboard/QueryTypesChart.tsx
index 05e2e10..61f75a1 100644
--- a/src/components/dashboard/QueryTypesChart.tsx
+++ b/src/components/dashboard/QueryTypesChart.tsx
@@ -12,11 +12,15 @@ import React from "react";
import { WithNamespaces, withNamespaces } from "react-i18next";
import api from "../../util/api";
import GenericDoughnutChart from "./GenericDoughnutChart";
+import { TimeRangeContext } from "../common/context/TimeRangeContext";
-const QueryTypesChart = ({ t }: WithNamespaces) => (
+const QueryTypesChart = ({
+ t,
+ apiCall
+}: WithNamespaces & { apiCall: () => Promise> }) => (
{
const total = data.reduce(
(previous, current) => previous + current.count,
@@ -31,4 +35,19 @@ const QueryTypesChart = ({ t }: WithNamespaces) => (
/>
);
-export default withNamespaces("dashboard")(QueryTypesChart);
+export const QueryTypesChartContainer = (props: WithNamespaces) => (
+
+ {context => (
+
+ context.range
+ ? api.getQueryTypesDb(context.range)
+ : api.getQueryTypes()
+ }
+ />
+ )}
+
+);
+
+export default withNamespaces("dashboard")(QueryTypesChartContainer);
diff --git a/src/components/dashboard/SummaryStats.tsx b/src/components/dashboard/SummaryStats.tsx
index 3bbfe86..abb3634 100644
--- a/src/components/dashboard/SummaryStats.tsx
+++ b/src/components/dashboard/SummaryStats.tsx
@@ -12,6 +12,7 @@ import React, { Component, Fragment } from "react";
import { WithNamespaces, withNamespaces } from "react-i18next";
import { WithAPIData } from "../common/WithAPIData";
import api from "../../util/api";
+import { TimeRangeContext } from "../common/context/TimeRangeContext";
export interface SummaryStatsProps {
totalQueries: string;
@@ -132,15 +133,23 @@ export const TranslatedSummaryStats = withNamespaces(["common", "dashboard"])(
);
export default (props: any) => (
- (
-
+
+ {context => (
+
+ context.range ? api.getSummaryDb(context.range) : api.getSummary()
+ }
+ repeatOptions={
+ context.range ? undefined : { interval: 5000, ignoreCancel: true }
+ }
+ renderInitial={() => (
+
+ )}
+ renderOk={data => (
+
+ )}
+ renderErr={() => }
+ />
)}
- renderOk={data => (
-
- )}
- renderErr={() => }
- />
+
);
diff --git a/src/components/dashboard/TimeRangeSelector.tsx b/src/components/dashboard/TimeRangeSelector.tsx
new file mode 100644
index 0000000..53e73ea
--- /dev/null
+++ b/src/components/dashboard/TimeRangeSelector.tsx
@@ -0,0 +1,136 @@
+/* Pi-hole: A black hole for Internet advertisements
+ * (c) 2019 Pi-hole, LLC (https://pi-hole.net)
+ * Network-wide ad blocking via your own hardware.
+ *
+ * Web Interface
+ * Selector For Time Range Context
+ *
+ * This file is copyright under the latest version of the EUPL.
+ * Please see LICENSE file for your rights under this license. */
+
+import React, { Fragment } from "react";
+import DateRangePicker from "react-bootstrap-daterangepicker";
+import { Button } from "reactstrap";
+import {
+ TimeRange,
+ TimeRangeContext
+} from "../common/context/TimeRangeContext";
+import "bootstrap-daterangepicker/daterangepicker.css";
+import { WithNamespaces, withNamespaces } from "react-i18next";
+import { dateRanges } from "../../util/dateRanges";
+
+export interface TimeRangeSelectorProps {
+ /**
+ * The range to show
+ */
+ range: TimeRange | null;
+
+ /**
+ * Called when a new range is selected
+ *
+ * @param range The new range, or null if "Last 24 Hours" is selected
+ */
+ onSelect: (range: TimeRange | null) => void;
+
+ /**
+ * If the chosen label should be shown outside of the selector
+ */
+ showLabel: boolean;
+}
+
+/**
+ * Get the label to be shown next to the selector button
+ *
+ * @param props The selector props
+ */
+const renderLabel = (
+ props: TimeRangeSelectorProps & WithNamespaces
+): string | null => {
+ const { t } = props;
+
+ if (!props.showLabel) {
+ return null;
+ }
+
+ if (!props.range) {
+ return t("Last 24 Hours");
+ }
+
+ if (props.range.name === "Custom Range") {
+ return (
+ props.range.from.toDate().toLocaleString() +
+ " - " +
+ props.range.until.toDate().toLocaleString()
+ );
+ }
+
+ return props.range.name;
+};
+
+/**
+ * A time range selector which shows the selected time range (label if
+ * predefined, or time range if custom)
+ */
+export const TimeRangeSelector = (
+ props: TimeRangeSelectorProps & WithNamespaces
+) => {
+ const { range, onSelect, t } = props;
+
+ const translatedDateRanges = dateRanges(t);
+ const last24Hours = t("Last 24 Hours");
+ const today = t("Today");
+ const label = renderLabel(props);
+
+ return (
+ {
+ if (
+ picker.startDate.isSame(translatedDateRanges[last24Hours][0]) &&
+ picker.endDate.isSame(translatedDateRanges[last24Hours][1])
+ ) {
+ // Set to null so we fetch data from FTL instead of the database
+ onSelect(null);
+ } else {
+ // Set the time range so we fetch from the database
+ onSelect({
+ from: picker.startDate,
+ until: picker.endDate,
+ name: picker.chosenLabel
+ });
+ }
+ }}
+ timePicker={true}
+ showDropdowns={true}
+ ranges={translatedDateRanges}
+ >
+
+
+ );
+};
+
+export const TranslatedTimeRangeSelector = withNamespaces("time-ranges")(
+ TimeRangeSelector
+);
+
+export const TimeRangeSelectorContainer = () => (
+
+ {context => (
+
+ )}
+
+);
diff --git a/src/components/dashboard/TopBlocked.tsx b/src/components/dashboard/TopBlocked.tsx
index b0acfd0..5e57c63 100644
--- a/src/components/dashboard/TopBlocked.tsx
+++ b/src/components/dashboard/TopBlocked.tsx
@@ -13,6 +13,7 @@ import { WithNamespaces, withNamespaces } from "react-i18next";
import api from "../../util/api";
import TopTable from "./TopTable";
import i18next from "i18next";
+import { TimeRangeContext } from "../common/context/TimeRangeContext";
export interface TopBlockedData {
totalBlocked: number;
@@ -65,7 +66,11 @@ export const generateRows = (t: i18next.TranslationFunction) => (
});
};
-const TopBlocked = ({ t, ...props }: WithNamespaces) => (
+const TopBlocked = ({
+ apiCall,
+ t,
+ ...props
+}: WithNamespaces & { apiCall: () => Promise }) => (
(
headers={[t("Domain"), t("Hits"), t("Frequency")]}
emptyMessage={t("No Domains Found")}
isEmpty={data => data.topBlocked.length === 0}
- apiCall={api.getTopBlocked}
+ apiCall={apiCall}
apiHandler={transformData}
generateRows={generateRows(t)}
/>
);
-export default withNamespaces(["common", "dashboard"])(TopBlocked);
+const TopBlockedContainer = (props: WithNamespaces) => (
+
+ {context => (
+
+ context.range
+ ? api.getTopBlockedDb(context.range)
+ : api.getTopBlocked()
+ }
+ />
+ )}
+
+);
+
+export default withNamespaces(["common", "dashboard"])(TopBlockedContainer);
diff --git a/src/components/dashboard/TopClients.tsx b/src/components/dashboard/TopClients.tsx
index 8fa551e..bf789ac 100644
--- a/src/components/dashboard/TopClients.tsx
+++ b/src/components/dashboard/TopClients.tsx
@@ -13,6 +13,7 @@ import { WithNamespaces, withNamespaces } from "react-i18next";
import api from "../../util/api";
import TopTable from "./TopTable";
import i18next from "i18next";
+import { TimeRangeContext } from "../common/context/TimeRangeContext";
export interface TopClientsData {
totalQueries: number;
@@ -65,7 +66,11 @@ export const generateRows = (t: i18next.TranslationFunction) => (
});
};
-const TopClients = ({ t, ...props }: WithNamespaces) => (
+const TopClients = ({
+ apiCall,
+ t,
+ ...props
+}: WithNamespaces & { apiCall: () => Promise }) => (
(
headers={[t("Client"), t("Requests"), t("Frequency")]}
emptyMessage={t("No Clients Found")}
isEmpty={data => data.topClients.length === 0}
- apiCall={api.getTopClients}
+ apiCall={apiCall}
apiHandler={transformData}
generateRows={generateRows(t)}
/>
);
-export default withNamespaces(["common", "dashboard"])(TopClients);
+const TopClientsContainer = (props: WithNamespaces) => (
+
+ {context => (
+
+ context.range
+ ? api.getTopClientsDb(context.range)
+ : api.getTopClients()
+ }
+ />
+ )}
+
+);
+
+export default withNamespaces(["common", "dashboard"])(TopClientsContainer);
diff --git a/src/components/dashboard/TopDomains.tsx b/src/components/dashboard/TopDomains.tsx
index e2813a4..3bbca52 100644
--- a/src/components/dashboard/TopDomains.tsx
+++ b/src/components/dashboard/TopDomains.tsx
@@ -13,6 +13,7 @@ import { WithNamespaces, withNamespaces } from "react-i18next";
import api from "../../util/api";
import TopTable from "./TopTable";
import i18next from "i18next";
+import { TimeRangeContext } from "../common/context/TimeRangeContext";
export interface TopDomainsData {
totalQueries: number;
@@ -65,7 +66,11 @@ export const generateRows = (t: i18next.TranslationFunction) => (
});
};
-const TopDomains = ({ t, ...props }: WithNamespaces) => (
+const TopDomains = ({
+ apiCall,
+ t,
+ ...props
+}: WithNamespaces & { apiCall: () => Promise }) => (
(
headers={[t("Domain"), t("Hits"), t("Frequency")]}
emptyMessage={t("No Domains Found")}
isEmpty={data => data.topDomains.length === 0}
- apiCall={api.getTopDomains}
+ apiCall={apiCall}
apiHandler={transformData}
generateRows={generateRows(t)}
/>
);
-export default withNamespaces(["common", "dashboard"])(TopDomains);
+const TopDomainsContainer = (props: WithNamespaces) => (
+
+ {context => (
+
+ context.range
+ ? api.getTopDomainsDb(context.range)
+ : api.getTopDomains()
+ }
+ />
+ )}
+
+);
+
+export default withNamespaces(["common", "dashboard"])(TopDomainsContainer);
diff --git a/src/components/dashboard/UpstreamsChart.tsx b/src/components/dashboard/UpstreamsChart.tsx
index 20f447c..60e4c6a 100644
--- a/src/components/dashboard/UpstreamsChart.tsx
+++ b/src/components/dashboard/UpstreamsChart.tsx
@@ -12,11 +12,15 @@ import React from "react";
import { WithNamespaces, withNamespaces } from "react-i18next";
import api from "../../util/api";
import GenericDoughnutChart from "./GenericDoughnutChart";
+import { TimeRangeContext } from "../common/context/TimeRangeContext";
-const UpstreamsChart = ({ t }: WithNamespaces) => (
+const UpstreamsChart = ({
+ t,
+ apiCall
+}: WithNamespaces & { apiCall: () => Promise }) => (
data.upstreams.map(upstream => ({
name: upstream.name,
@@ -27,4 +31,17 @@ const UpstreamsChart = ({ t }: WithNamespaces) => (
/>
);
-export default withNamespaces("dashboard")(UpstreamsChart);
+export const UpstreamsChartContainer = (props: WithNamespaces) => (
+
+ {context => (
+
+ context.range ? api.getUpstreamsDb(context.range) : api.getUpstreams()
+ }
+ />
+ )}
+
+);
+
+export default withNamespaces("dashboard")(UpstreamsChartContainer);
diff --git a/src/components/dashboard/__tests__/ClientsGraph.test.tsx b/src/components/dashboard/__tests__/ClientsGraph.test.tsx
index ee07882..2d04c89 100644
--- a/src/components/dashboard/__tests__/ClientsGraph.test.tsx
+++ b/src/components/dashboard/__tests__/ClientsGraph.test.tsx
@@ -53,7 +53,7 @@ it("hides loading indicator correctly", async () => {
});
it("loads API data correctly", async () => {
- const data = transformData(fakeData);
+ const data = transformData(fakeData, null);
expect(data.labels[0]).toEqual(
new Date(1000 * fakeData.over_time[0].timestamp)
diff --git a/src/components/log/QueryLog.tsx b/src/components/log/QueryLog.tsx
index 57e8496..a2b9421 100644
--- a/src/components/log/QueryLog.tsx
+++ b/src/components/log/QueryLog.tsx
@@ -15,13 +15,11 @@ import ReactTable, {
RowInfo,
RowRenderProps
} from "react-table";
-import DateRangePicker from "react-bootstrap-daterangepicker";
-import { Button } from "reactstrap";
import i18n from "i18next";
import i18next from "i18next";
import { WithNamespaces, withNamespaces } from "react-i18next";
import debounce from "lodash.debounce";
-import moment, { Moment } from "moment";
+import moment from "moment";
import {
CancelablePromise,
ignoreCancel,
@@ -29,6 +27,9 @@ import {
padNumber
} from "../../util";
import api from "../../util/api";
+import { dateRanges } from "../../util/dateRanges";
+import { TranslatedTimeRangeSelector } from "../dashboard/TimeRangeSelector";
+import { TimeRange } from "../common/context/TimeRangeContext";
import "react-table/react-table.css";
import "bootstrap-daterangepicker/daterangepicker.css";
@@ -41,6 +42,22 @@ export interface QueryLogState {
filters: Array;
}
+/**
+ * Get the default time range for the query log
+ *
+ * @param t The translation function
+ */
+const getDefaultRange = (t: i18next.TranslationFunction): TimeRange => {
+ const translatedDateRanges = dateRanges(t);
+ const last24Hours = t("Last 24 Hours");
+
+ return {
+ from: translatedDateRanges[last24Hours][0],
+ until: translatedDateRanges[last24Hours][1],
+ name: last24Hours
+ };
+};
+
class QueryLog extends Component {
private updateHandler: null | CancelablePromise = null;
@@ -56,15 +73,14 @@ class QueryLog extends Component {
constructor(props: WithNamespaces) {
super(props);
- // This happens in the constructor to avoid using dateRanges before it's
- // created
+ const { t } = this.props;
+
+ // This happens in the constructor to more easily use the translated date
+ // ranges
this.state.filters = [
{
id: "time",
- value: {
- start: dateRanges.Today[0],
- end: dateRanges.Today[1]
- }
+ value: getDefaultRange(t)
}
];
}
@@ -109,16 +125,8 @@ class QueryLog extends Component {
for (const filter of tableFilters) {
switch (filter.id) {
case "time":
- filters.from = Math.floor(
- moment(filter.value.start)
- .utc()
- .valueOf() / 1000
- );
- filters.until = Math.floor(
- moment(filter.value.end)
- .utc()
- .valueOf() / 1000
- );
+ filters.from = moment(filter.value.from).unix();
+ filters.until = moment(filter.value.until).unix();
break;
case "queryType":
if (filter.value === "all") {
@@ -380,34 +388,6 @@ const selectionFilter = (
);
};
-/**
- * Preconfigured date ranges listed in the date range picker
- */
-const dateRanges: { [name: string]: [Moment, Moment] } = {
- Today: [moment().startOf("day"), moment()],
- Yesterday: [
- moment()
- .subtract(1, "days")
- .startOf("day"),
- moment()
- .subtract(1, "days")
- .endOf("day")
- ],
- "Last 7 Days": [moment().subtract(6, "days"), moment()],
- "Last 30 Days": [moment().subtract(29, "days"), moment()],
- "This Month": [moment().startOf("month"), moment()],
- "Last Month": [
- moment()
- .subtract(1, "month")
- .startOf("month"),
- moment()
- .subtract(1, "month")
- .endOf("month")
- ],
- "This Year": [moment().startOf("year"), moment()],
- "All Time": [moment(0), moment()]
-};
-
/**
* The columns of the Query Log. Some pieces are translated, so you must pass in
* the translation function before using the columns.
@@ -445,21 +425,17 @@ const columns = (t: i18next.TranslationFunction) => [
filter: Filter;
onChange: ReactTableFunction;
}) => (
-
- onChange({ start: picker.startDate, end: picker.endDate })
- }
- timePicker={true}
- showDropdowns={true}
- ranges={dateRanges}
- >
-
-
+ {
+ if (range) {
+ onChange(range);
+ } else {
+ onChange(getDefaultRange(t));
+ }
+ }}
+ showLabel={false}
+ />
)
},
{
@@ -566,4 +542,4 @@ const columns = (t: i18next.TranslationFunction) => [
}
];
-export default withNamespaces(["common", "query-log"])(QueryLog);
+export default withNamespaces(["common", "query-log", "time-ranges"])(QueryLog);
diff --git a/src/components/settings/PreferenceSettings.tsx b/src/components/settings/PreferenceSettings.tsx
index e60be69..22ec7c3 100644
--- a/src/components/settings/PreferenceSettings.tsx
+++ b/src/components/settings/PreferenceSettings.tsx
@@ -14,7 +14,7 @@ import { CancelablePromise, ignoreCancel, makeCancelable } from "../../util";
import api from "../../util/api";
import Alert, { AlertType } from "../common/Alert";
import { Button, Col, Form, FormGroup, Input, Label } from "reactstrap";
-import { PreferencesContext } from "../common/context";
+import { PreferencesContext } from "../common/context/PreferencesContext";
import languages from "../../languages.json";
export interface PreferenceSettingsProps {
diff --git a/src/util/api.tsx b/src/util/api.tsx
index 93e46e9..ff97457 100644
--- a/src/util/api.tsx
+++ b/src/util/api.tsx
@@ -8,8 +8,9 @@
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
-import http, { paramsToString } from "./http";
+import http, { paramsToString, timeRangeToParams } from "./http";
import config from "../config";
+import { TimeRange } from "../components/common/context/TimeRangeContext";
export default {
loggedIn: false,
@@ -24,21 +25,55 @@ export default {
getSummary(): Promise {
return http.get("stats/summary");
},
+ getSummaryDb(range: TimeRange): Promise {
+ return http.get("stats/database/summary?" + timeRangeToParams(range));
+ },
getHistoryGraph(): Promise> {
return http.get("stats/overTime/history");
},
+ getHistoryGraphDb(
+ range: TimeRange,
+ interval: number
+ ): Promise> {
+ return http.get(
+ "stats/database/overTime/history?interval=" +
+ interval +
+ "&" +
+ timeRangeToParams(range)
+ );
+ },
getClientsGraph(): Promise {
return http.get("stats/overTime/clients");
},
+ getClientsGraphDb(
+ range: TimeRange,
+ interval: number
+ ): Promise {
+ return http.get(
+ "stats/database/overTime/clients?interval=" +
+ interval +
+ "&" +
+ timeRangeToParams(range)
+ );
+ },
getQueryTypes(): Promise> {
return http.get("stats/query_types");
},
+ getQueryTypesDb(range: TimeRange): Promise> {
+ return http.get("stats/database/query_types?" + timeRangeToParams(range));
+ },
getUpstreams(): Promise {
return http.get("stats/upstreams");
},
+ getUpstreamsDb(range: TimeRange): Promise {
+ return http.get("stats/database/upstreams?" + timeRangeToParams(range));
+ },
getTopDomains(): Promise {
return http.get("stats/top_domains");
},
+ getTopDomainsDb(range: TimeRange): Promise {
+ return http.get("stats/database/top_domains?" + timeRangeToParams(range));
+ },
getTopBlocked(): Promise {
// The API uses a GET parameter to differentiate top domains from top
// blocked, but the fake API is not able to handle GET parameters right now.
@@ -48,9 +83,17 @@ export default {
return http.get(url);
},
+ getTopBlockedDb(range: TimeRange): Promise {
+ return http.get(
+ "stats/database/top_domains?blocked=true&" + timeRangeToParams(range)
+ );
+ },
getTopClients(): Promise {
return http.get("stats/top_clients");
},
+ getTopClientsDb(range: TimeRange): Promise {
+ return http.get("stats/database/top_clients?" + timeRangeToParams(range));
+ },
getHistory(params: any): Promise {
return http.get("stats/history?" + paramsToString(params));
},
diff --git a/src/util/dateRanges.tsx b/src/util/dateRanges.tsx
new file mode 100644
index 0000000..ac49699
--- /dev/null
+++ b/src/util/dateRanges.tsx
@@ -0,0 +1,43 @@
+import moment, { Moment } from "moment";
+import i18next from "i18next";
+
+const now = moment();
+const oneDayAgo = moment().subtract(1, "day");
+const startOfDay = moment().startOf("day");
+const startOfYesterday = moment()
+ .subtract(1, "days")
+ .startOf("day");
+const endOfYesterday = moment()
+ .subtract(1, "days")
+ .endOf("day");
+const lastWeek = moment().subtract(7, "days");
+const lastMonth = moment().subtract(30, "days");
+const startOfMonth = moment().startOf("month");
+const startOfLastMonth = moment()
+ .subtract(1, "month")
+ .startOf("month");
+const endOfLastMonth = moment()
+ .subtract(1, "month")
+ .endOf("month");
+const startOfYear = moment().startOf("year");
+const epoch = moment(0);
+
+/**
+ * Preconfigured date ranges for use in a date range picker. The keys are
+ * translated, so this object must be computed using the translation function.
+ *
+ * @param t The translation function
+ */
+export const dateRanges: (
+ t: i18next.TranslationFunction
+) => { [name: string]: [Moment, Moment] } = t => ({
+ [t("Last 24 Hours")]: [oneDayAgo, now],
+ [t("Today")]: [startOfDay, now],
+ [t("Yesterday")]: [startOfYesterday, endOfYesterday],
+ [t("Last 7 Days")]: [lastWeek, now],
+ [t("Last 30 Days")]: [lastMonth, now],
+ [t("This Month")]: [startOfMonth, now],
+ [t("Last Month")]: [startOfLastMonth, endOfLastMonth],
+ [t("This Year")]: [startOfYear, now],
+ [t("All Time")]: [epoch, now]
+});
diff --git a/src/util/http.tsx b/src/util/http.tsx
index 37333b8..6c3234f 100644
--- a/src/util/http.tsx
+++ b/src/util/http.tsx
@@ -10,6 +10,7 @@
import api from "./api";
import config from "../config";
+import { TimeRange } from "../components/common/context/TimeRangeContext";
/**
* A group of HTTP functions. Each function parses the response checks for
@@ -182,3 +183,15 @@ export const paramsToString = (params: any) =>
Object.keys(params)
.map(key => key + "=" + params[key])
.join("&");
+
+/**
+ * Convert a time range into GET parameters
+ *
+ * @param range The time range to convert
+ * @return The time range as GET parameters
+ */
+export const timeRangeToParams = (range: TimeRange) =>
+ paramsToString({
+ from: range.from.unix(),
+ until: range.until.unix()
+ });
diff --git a/src/util/i18n.tsx b/src/util/i18n.tsx
index f49cbb9..16e0ffa 100644
--- a/src/util/i18n.tsx
+++ b/src/util/i18n.tsx
@@ -34,7 +34,8 @@ export function setupI18n() {
"query-log",
"settings",
"api-errors",
- "preferences"
+ "preferences",
+ "time-ranges"
],
nsSeparator: false,
keySeparator: false,
diff --git a/src/util/index.tsx b/src/util/index.tsx
index 54b41ae..b16364d 100644
--- a/src/util/index.tsx
+++ b/src/util/index.tsx
@@ -8,6 +8,8 @@
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
+import { TimeRange } from "../components/common/context/TimeRangeContext";
+
/**
* Pad a two digit number
*
@@ -18,6 +20,16 @@ export const padNumber = (num: number) => {
return ("00" + num).substr(-2, 2);
};
+/**
+ * Dynamically calculate a time interval so there are always 144 data points
+ * (144 so that every point represents 10 minutes when the range is 24 hours)
+ *
+ * @param range The range to find the interval for
+ */
+export const getIntervalForRange = (range: TimeRange): number => {
+ return Math.ceil((range.until.unix() - range.from.unix()) / 144);
+};
+
export interface CancelablePromise {
promise: Promise;
cancel: () => void;
@@ -27,7 +39,7 @@ export interface CancelableOptions {
/**
* The function to call to repeat the promise
*/
- repeat: (() => void);
+ repeat: () => void;
/**
* The amount of time to wait until repeating