generated from mantinedev/next-pages-template
-
-
Notifications
You must be signed in to change notification settings - Fork 274
/
piHole.ts
83 lines (67 loc) · 2.37 KB
/
piHole.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { trimStringEnding } from '~/tools/shared/strings';
import { PiHoleApiStatusChangeResponse, PiHoleApiSummaryResponse } from './piHole.type';
export class PiHoleClient {
private readonly baseHostName: string;
constructor(
hostname: string,
private readonly apiToken: string
) {
this.baseHostName = trimStringEnding(hostname, ['/admin/index.php', '/admin', '/']);
}
async getSummary() {
const response = await fetch(
new URL(`${this.baseHostName}/admin/api.php?summaryRaw&auth=${this.apiToken}`)
);
if (response.status !== 200) {
throw new Error(`Status code does not indicate success: ${response.status}`);
}
const json = await response.json();
if (Array.isArray(json)) {
throw new Error(
`Response does not indicate success. Authentication is most likely invalid: ${json}`
);
}
return json as PiHoleApiSummaryResponse;
}
async enable() {
const response = await this.sendStatusChangeRequest('enable');
return response.status === 'enabled';
}
async disable(duration: number) {
const response = await this.sendStatusChangeRequest('disable', duration);
return response.status === 'disabled';
}
private async sendStatusChangeRequest(
action: 'enable' | 'disable',
duration = 0
): Promise<PiHoleApiStatusChangeResponse> {
const response = await fetch(
duration !== 0
? `${this.baseHostName}/admin/api.php?${action}=${duration}&auth=${this.apiToken}`
: `${this.baseHostName}/admin/api.php?${action}&auth=${this.apiToken}`
);
if (response.status !== 200) {
return Promise.reject(new Error(`Status code does not indicate success: ${response.status}`));
}
const json = await response.json();
if (Array.isArray(json)) {
return Promise.reject(
new Error(
`Response does not indicate success. Authentication is most likely invalid: ${json}`
)
);
}
for (let loops = 0; loops < 10; loops++) {
const summary = await this.getSummary();
if (summary.status === action + 'd') {
return { status: summary.status } 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}`)
);
}
}