🐛 Adguard logic and several small bugs
This commit is contained in:
@@ -1,3 +1,4 @@
|
|||||||
|
import Consola from 'consola';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { findAppProperty } from '~/tools/client/app-properties';
|
import { findAppProperty } from '~/tools/client/app-properties';
|
||||||
import { getConfig } from '~/tools/config/getConfig';
|
import { getConfig } from '~/tools/config/getConfig';
|
||||||
@@ -14,19 +15,25 @@ export const dnsHoleRouter = createTRPCRouter({
|
|||||||
z.object({
|
z.object({
|
||||||
action: z.enum(['enable', 'disable']),
|
action: z.enum(['enable', 'disable']),
|
||||||
configName: z.string(),
|
configName: z.string(),
|
||||||
|
appsToChange: z.optional(z.array(z.string())),
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
.mutation(async ({ input }) => {
|
.mutation(async ({ input }) => {
|
||||||
const config = getConfig(input.configName);
|
const config = getConfig(input.configName);
|
||||||
|
|
||||||
const applicableApps = config.apps.filter(
|
const applicableApps = config.apps.filter(
|
||||||
(x) => x.integration?.type && ['pihole', 'adGuardHome'].includes(x.integration?.type)
|
(app) =>
|
||||||
|
app.id &&
|
||||||
|
app.integration?.type &&
|
||||||
|
input.appsToChange?.includes(app.id) &&
|
||||||
|
['pihole', 'adGuardHome'].includes(app.integration?.type)
|
||||||
);
|
);
|
||||||
|
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
applicableApps.map(async (app) => {
|
applicableApps.map(async (app) => {
|
||||||
if (app.integration?.type === 'pihole') {
|
if (app.integration?.type === 'pihole') {
|
||||||
await processPiHole(app, input.action === 'enable');
|
await processPiHole(app, input.action === 'enable');
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,8 +79,6 @@ export const dnsHoleRouter = createTRPCRouter({
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
//const data: AdStatistics = ;
|
|
||||||
|
|
||||||
data.adsBlockedTodayPercentage = data.adsBlockedToday / data.dnsQueriesToday;
|
data.adsBlockedTodayPercentage = data.adsBlockedToday / data.dnsQueriesToday;
|
||||||
if (Number.isNaN(data.adsBlockedTodayPercentage)) {
|
if (Number.isNaN(data.adsBlockedTodayPercentage)) {
|
||||||
data.adsBlockedTodayPercentage = 0;
|
data.adsBlockedTodayPercentage = 0;
|
||||||
@@ -90,22 +95,38 @@ const processAdGuard = async (app: ConfigAppType, enable: boolean) => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (enable) {
|
if (enable) {
|
||||||
await adGuard.disable();
|
try {
|
||||||
|
await adGuard.enable();
|
||||||
|
} catch (error) {
|
||||||
|
Consola.error((error as Error).message);
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await adGuard.enable();
|
try {
|
||||||
|
await adGuard.disable();
|
||||||
|
} catch (error) {
|
||||||
|
Consola.error((error as Error).message);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const processPiHole = async (app: ConfigAppType, enable: boolean) => {
|
const processPiHole = async (app: ConfigAppType, enable: boolean) => {
|
||||||
const pihole = new PiHoleClient(app.url, findAppProperty(app, 'apiKey'));
|
const pihole = new PiHoleClient(app.url, findAppProperty(app, 'apiKey'));
|
||||||
|
|
||||||
if (enable) {
|
if (enable) {
|
||||||
await pihole.enable();
|
try {
|
||||||
|
await pihole.enable();
|
||||||
|
} catch (error) {
|
||||||
|
Consola.error((error as Error).message);
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await pihole.disable();
|
try {
|
||||||
|
await pihole.disable();
|
||||||
|
} catch (error) {
|
||||||
|
Consola.error((error as Error).message);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const collectPiHoleSummary = async (app: ConfigAppType) => {
|
const collectPiHoleSummary = async (app: ConfigAppType) => {
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
|
import axios from 'axios';
|
||||||
|
import Consola from 'consola';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
import { trimStringEnding } from '../../../shared/strings';
|
import { trimStringEnding } from '../../../shared/strings';
|
||||||
import {
|
import {
|
||||||
adGuardApiFilteringStatusSchema,
|
adGuardApiFilteringStatusSchema,
|
||||||
@@ -60,19 +63,41 @@ export class AdGuard {
|
|||||||
await this.changeProtectionStatus(false);
|
await this.changeProtectionStatus(false);
|
||||||
}
|
}
|
||||||
async enable() {
|
async enable() {
|
||||||
await this.changeProtectionStatus(false);
|
await this.changeProtectionStatus(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Make a post request to the AdGuard API to change the protection status based on the value of newStatus
|
||||||
|
* @param {boolean} newStatus - The new status of the protection
|
||||||
|
* @param {number} duration - Duration of a pause, in milliseconds. Enabled should be false.
|
||||||
|
* @returns {string} - The response from the AdGuard API
|
||||||
|
*/
|
||||||
private async changeProtectionStatus(newStatus: boolean, duration = 0) {
|
private async changeProtectionStatus(newStatus: boolean, duration = 0) {
|
||||||
await fetch(`${this.baseHostName}/control/protection`, {
|
try {
|
||||||
method: 'POST',
|
const { data }: { data: string } = await axios.post(
|
||||||
body: JSON.stringify({
|
`${this.baseHostName}/control/protection`,
|
||||||
enabled: newStatus,
|
{
|
||||||
duration,
|
enabled: newStatus,
|
||||||
}),
|
duration,
|
||||||
});
|
},
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Basic ${this.getAuthorizationHeaderValue()}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
} catch (error) {
|
||||||
|
if (axios.isAxiosError(error)) {
|
||||||
|
Consola.error(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* It return a base64 username:password string
|
||||||
|
* @returns {string} The base64 encoded username and password
|
||||||
|
*/
|
||||||
private getAuthorizationHeaderValue() {
|
private getAuthorizationHeaderValue() {
|
||||||
return Buffer.from(`${this.username}:${this.password}`).toString('base64');
|
return Buffer.from(`${this.username}:${this.password}`).toString('base64');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,6 +62,18 @@ export class PiHoleClient {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return json as PiHoleApiStatusChangeResponse;
|
for(let loops = 0; loops < 10; loops++){
|
||||||
|
const summary = await this.getSummary()
|
||||||
|
if (summary.status === action + 'd'){
|
||||||
|
return json as PiHoleApiStatusChangeResponse;
|
||||||
|
}
|
||||||
|
await new Promise ((resolve) => { setTimeout(resolve, 50)});
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.reject(
|
||||||
|
new Error(
|
||||||
|
`Although PiHole received the command, it failed to update it's status: ${json}`
|
||||||
|
)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,25 @@
|
|||||||
import { Badge, Box, Button, Card, Group, Image, SimpleGrid, Stack, Text } from '@mantine/core';
|
import {
|
||||||
|
Badge,
|
||||||
|
Box,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Group,
|
||||||
|
Image,
|
||||||
|
SimpleGrid,
|
||||||
|
Stack,
|
||||||
|
Text,
|
||||||
|
UnstyledButton,
|
||||||
|
} from '@mantine/core';
|
||||||
import { useElementSize } from '@mantine/hooks';
|
import { useElementSize } from '@mantine/hooks';
|
||||||
import { IconDeviceGamepad, IconPlayerPlay, IconPlayerStop } from '@tabler/icons-react';
|
import { IconDeviceGamepad, IconPlayerPlay, IconPlayerStop } from '@tabler/icons-react';
|
||||||
import { useTranslation } from 'next-i18next';
|
import { useTranslation } from 'next-i18next';
|
||||||
import { api } from '~/utils/api';
|
import { api } from '~/utils/api';
|
||||||
|
|
||||||
import { useConfigContext } from '../../config/provider';
|
import { useConfigContext } from '../../config/provider';
|
||||||
import { queryClient } from '../../tools/server/configurations/tanstack/queryClient.tool';
|
|
||||||
import { defineWidget } from '../helper';
|
import { defineWidget } from '../helper';
|
||||||
import { WidgetLoading } from '../loading';
|
import { WidgetLoading } from '../loading';
|
||||||
import { IWidget } from '../widgets';
|
import { IWidget } from '../widgets';
|
||||||
import { useDnsHoleSummeryQuery } from './DnsHoleSummary';
|
import { useDnsHoleSummeryQuery } from './DnsHoleSummary';
|
||||||
import { PiholeApiSummaryType } from './type';
|
|
||||||
|
|
||||||
const definition = defineWidget({
|
const definition = defineWidget({
|
||||||
id: 'dns-hole-controls',
|
id: 'dns-hole-controls',
|
||||||
@@ -31,29 +40,83 @@ interface DnsHoleControlsWidgetProps {
|
|||||||
widget: IDnsHoleControlsWidget;
|
widget: IDnsHoleControlsWidget;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param fetching - a expression that return a boolean if the data is been fetched
|
||||||
|
* @param currentStatus the current status of the dns integration, either enabled or disabled
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
const dnsLightStatus = (
|
||||||
|
fetching: boolean,
|
||||||
|
currentStatus: 'enabled' | 'disabled'
|
||||||
|
): 'blue' | 'green' | 'red' => {
|
||||||
|
if (fetching) {
|
||||||
|
return 'blue';
|
||||||
|
}
|
||||||
|
if (currentStatus === 'enabled') {
|
||||||
|
return 'green';
|
||||||
|
}
|
||||||
|
return 'red';
|
||||||
|
};
|
||||||
|
|
||||||
function DnsHoleControlsWidgetTile({ widget }: DnsHoleControlsWidgetProps) {
|
function DnsHoleControlsWidgetTile({ widget }: DnsHoleControlsWidgetProps) {
|
||||||
const { isInitialLoading, data } = useDnsHoleSummeryQuery();
|
const { isInitialLoading, data, isFetching: fetchingDnsSummary } = useDnsHoleSummeryQuery();
|
||||||
const { mutateAsync } = useDnsHoleControlMutation();
|
const { mutateAsync, isLoading: changingStatus } = useDnsHoleControlMutation();
|
||||||
const { width, ref } = useElementSize();
|
const { width, ref } = useElementSize();
|
||||||
const { t } = useTranslation('common');
|
const { t } = useTranslation('common');
|
||||||
|
|
||||||
const { name: configName, config } = useConfigContext();
|
const { name: configName, config } = useConfigContext();
|
||||||
|
|
||||||
|
const trpcUtils = api.useContext();
|
||||||
|
|
||||||
if (isInitialLoading || !data || !configName) {
|
if (isInitialLoading || !data || !configName) {
|
||||||
return <WidgetLoading />;
|
return <WidgetLoading />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type getDnsStatusAcc = {
|
||||||
|
enabled: string[];
|
||||||
|
disabled: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const getDnsStatus = () => {
|
||||||
|
const dnsList = data?.status.reduce(
|
||||||
|
(acc: getDnsStatusAcc, dns) => {
|
||||||
|
if (dns.status === 'enabled') {
|
||||||
|
acc.enabled.push(dns.appId);
|
||||||
|
} else if (dns.status === 'disabled') {
|
||||||
|
acc.disabled.push(dns.appId);
|
||||||
|
}
|
||||||
|
return acc;
|
||||||
|
},
|
||||||
|
{ enabled: [], disabled: [] }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (dnsList.enabled.length === 0 && dnsList.disabled.length === 0) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return dnsList;
|
||||||
|
};
|
||||||
|
|
||||||
|
const reFetchSummaryDns = () => {
|
||||||
|
trpcUtils.dnsHole.summary.invalidate();
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack justify="space-between" h={'100%'} spacing="0.25rem">
|
<Stack justify="space-between" h={'100%'} spacing="0.25rem">
|
||||||
<SimpleGrid ref={ref} cols={width > 275 ? 2 : 1} verticalSpacing="0.25rem" spacing="0.25rem">
|
<SimpleGrid ref={ref} cols={width > 275 ? 2 : 1} spacing="0.25rem">
|
||||||
<Button
|
<Button
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
await mutateAsync({
|
await mutateAsync({
|
||||||
action: 'enable',
|
action: 'enable',
|
||||||
configName,
|
configName,
|
||||||
|
appsToChange: getDnsStatus()?.disabled,
|
||||||
|
},{
|
||||||
|
onSettled: () => {
|
||||||
|
reFetchSummaryDns();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
await queryClient.invalidateQueries({ queryKey: ['dns-hole-summary'] });
|
|
||||||
}}
|
}}
|
||||||
|
disabled={getDnsStatus()?.disabled.length === 0 || fetchingDnsSummary || changingStatus}
|
||||||
leftIcon={<IconPlayerPlay size={20} />}
|
leftIcon={<IconPlayerPlay size={20} />}
|
||||||
variant="light"
|
variant="light"
|
||||||
color="green"
|
color="green"
|
||||||
@@ -66,9 +129,14 @@ function DnsHoleControlsWidgetTile({ widget }: DnsHoleControlsWidgetProps) {
|
|||||||
await mutateAsync({
|
await mutateAsync({
|
||||||
action: 'disable',
|
action: 'disable',
|
||||||
configName,
|
configName,
|
||||||
|
appsToChange: getDnsStatus()?.enabled,
|
||||||
|
},{
|
||||||
|
onSettled: () => {
|
||||||
|
reFetchSummaryDns();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
await queryClient.invalidateQueries({ queryKey: ['dns-hole-summary'] });
|
|
||||||
}}
|
}}
|
||||||
|
disabled={getDnsStatus()?.enabled.length === 0 || fetchingDnsSummary || changingStatus}
|
||||||
leftIcon={<IconPlayerStop size={20} />}
|
leftIcon={<IconPlayerStop size={20} />}
|
||||||
variant="light"
|
variant="light"
|
||||||
color="red"
|
color="red"
|
||||||
@@ -79,15 +147,15 @@ function DnsHoleControlsWidgetTile({ widget }: DnsHoleControlsWidgetProps) {
|
|||||||
</SimpleGrid>
|
</SimpleGrid>
|
||||||
|
|
||||||
<Stack spacing="0.25rem">
|
<Stack spacing="0.25rem">
|
||||||
{data.status.map((status, index) => {
|
{data.status.map((dnsHole, index) => {
|
||||||
const app = config?.apps.find((x) => x.id === status.appId);
|
const app = config?.apps.find((x) => x.id === dnsHole.appId);
|
||||||
|
|
||||||
if (!app) {
|
if (!app) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card withBorder={true} key={index} p="xs">
|
<Card withBorder={true} key={dnsHole.appId} p="xs">
|
||||||
<Group>
|
<Group>
|
||||||
<Box
|
<Box
|
||||||
sx={(theme) => ({
|
sx={(theme) => ({
|
||||||
@@ -102,7 +170,43 @@ function DnsHoleControlsWidgetTile({ widget }: DnsHoleControlsWidgetProps) {
|
|||||||
</Box>
|
</Box>
|
||||||
<Stack spacing="0rem">
|
<Stack spacing="0rem">
|
||||||
<Text>{app.name}</Text>
|
<Text>{app.name}</Text>
|
||||||
<StatusBadge status={status.status} />
|
<UnstyledButton
|
||||||
|
onClick={async () => {
|
||||||
|
await mutateAsync({
|
||||||
|
action: dnsHole.status === 'enabled' ? 'disable' : 'enable',
|
||||||
|
configName,
|
||||||
|
appsToChange: [app.id],
|
||||||
|
},{
|
||||||
|
onSettled: () => {
|
||||||
|
reFetchSummaryDns();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
disabled={fetchingDnsSummary || changingStatus}
|
||||||
|
>
|
||||||
|
<Badge
|
||||||
|
variant="dot"
|
||||||
|
color={dnsLightStatus(fetchingDnsSummary || changingStatus, dnsHole.status)}
|
||||||
|
styles={(theme) => ({
|
||||||
|
root: {
|
||||||
|
'&:hover': {
|
||||||
|
background:
|
||||||
|
theme.colorScheme === 'dark'
|
||||||
|
? theme.colors.dark[4]
|
||||||
|
: theme.colors.gray[2],
|
||||||
|
},
|
||||||
|
'&:active': {
|
||||||
|
background:
|
||||||
|
theme.colorScheme === 'dark'
|
||||||
|
? theme.colors.dark[5]
|
||||||
|
: theme.colors.gray[3],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
{t(dnsHole.status)}
|
||||||
|
</Badge>
|
||||||
|
</UnstyledButton>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Group>
|
</Group>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -112,24 +216,6 @@ function DnsHoleControlsWidgetTile({ widget }: DnsHoleControlsWidgetProps) {
|
|||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const StatusBadge = ({ status }: { status: PiholeApiSummaryType['status'] }) => {
|
|
||||||
const { t } = useTranslation('common');
|
|
||||||
if (status === 'enabled') {
|
|
||||||
return (
|
|
||||||
<Badge variant="dot" color="green">
|
|
||||||
{t('enabled')}
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Badge variant="dot" color="red">
|
|
||||||
{t('disabled')}
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const useDnsHoleControlMutation = () => api.dnsHole.control.useMutation();
|
const useDnsHoleControlMutation = () => api.dnsHole.control.useMutation();
|
||||||
|
|
||||||
export default definition;
|
export default definition;
|
||||||
|
|||||||
@@ -58,8 +58,13 @@ function DnsHoleSummaryWidgetTile({ widget }: DnsHoleSummaryWidgetProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Container h="100%" p={0} style={constructContainerStyle(widget.properties.layout)}>
|
<Container h="100%" p={0} style={constructContainerStyle(widget.properties.layout)}>
|
||||||
{stats.map((item) => (
|
{stats.map((item, index) => (
|
||||||
<StatCard item={item} usePiHoleColors={widget.properties.usePiHoleColors} data={data} />
|
<StatCard
|
||||||
|
key={item.label ?? index}
|
||||||
|
item={item}
|
||||||
|
usePiHoleColors={widget.properties.usePiHoleColors}
|
||||||
|
data={data}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
@@ -107,7 +112,7 @@ export const useDnsHoleSummeryQuery = () => {
|
|||||||
configName: configName!,
|
configName: configName!,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
refetchInterval: 3 * 60 * 1000,
|
staleTime: 1000 * 60 * 2,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user