🐛 Adguard logic and several small bugs

This commit is contained in:
Angel
2023-09-01 15:59:01 -04:00
committed by GitHub
parent ba7e31b972
commit 1bb1a8f628
5 changed files with 198 additions and 49 deletions

View File

@@ -1,4 +1,7 @@
import axios from 'axios';
import Consola from 'consola';
import { z } from 'zod';
import { trimStringEnding } from '../../../shared/strings';
import {
adGuardApiFilteringStatusSchema,
@@ -60,19 +63,41 @@ export class AdGuard {
await this.changeProtectionStatus(false);
}
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) {
await fetch(`${this.baseHostName}/control/protection`, {
method: 'POST',
body: JSON.stringify({
enabled: newStatus,
duration,
}),
});
try {
const { data }: { data: string } = await axios.post(
`${this.baseHostName}/control/protection`,
{
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() {
return Buffer.from(`${this.username}:${this.password}`).toString('base64');
}

View File

@@ -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}`
)
)
}
}