feat(integrations): add UniFi OS local API client
Implements HTTP client for UniFi OS console integration API with support for fetching site information, client counts, device statistics, and VPN server configs. Includes pagination handling with filter-based fallback when client count exceeds API limit. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
65d1266e63
commit
c17b863e3f
2 files changed
+238
No files matched your search
@@ -0,0 +1,119 @@
|
||||
import { ResponseError } from "@homarr/common/server";
|
||||
import type { z } from "zod/v4";
|
||||
|
||||
import type { UnifiOsClientCounts, UnifiOsDevice, UnifiOsDeviceStatistics, UnifiOsSite } from "./unifi-os-types";
|
||||
import {
|
||||
countClients,
|
||||
createUnifiOsPageSchema,
|
||||
parseUnifiOsAsync,
|
||||
unifiOsClientSchema,
|
||||
unifiOsDeviceSchema,
|
||||
unifiOsDeviceStatisticsSchema,
|
||||
unifiOsInfoSchema,
|
||||
unifiOsSiteSchema,
|
||||
unifiOsVpnServerSchema,
|
||||
} from "./unifi-os-types";
|
||||
|
||||
export type UnifiOsFetch = (url: string, init?: RequestInit & { timeout?: number }) => Promise<Response>;
|
||||
|
||||
const INTEGRATION_PATH = "/proxy/network/integration/v1";
|
||||
const REQUEST_TIMEOUT_MS = 10_000;
|
||||
|
||||
/** Plafond imposé par l'API : demander davantage renvoie quand même 200. */
|
||||
const MAX_PAGE_LIMIT = 200;
|
||||
|
||||
const PARSE_ERROR_MESSAGE = "Invalid UniFi OS response";
|
||||
|
||||
const clientPageSchema = createUnifiOsPageSchema(unifiOsClientSchema);
|
||||
const devicePageSchema = createUnifiOsPageSchema(unifiOsDeviceSchema);
|
||||
const sitePageSchema = createUnifiOsPageSchema(unifiOsSiteSchema);
|
||||
const vpnServerPageSchema = createUnifiOsPageSchema(unifiOsVpnServerSchema);
|
||||
|
||||
/**
|
||||
* Client de l'API d'intégration locale d'UniFi OS.
|
||||
*
|
||||
* Ne connaît ni Homarr ni la notion d'intégration : il ne sait que parler à une
|
||||
* console. Le `fetch` est injecté pour que les tests n'aient pas à mocker un module.
|
||||
*/
|
||||
export class UnifiOsApi {
|
||||
private readonly baseUrl: string;
|
||||
|
||||
constructor(
|
||||
origin: string,
|
||||
private readonly apiKey: string,
|
||||
private readonly fetchAsync: UnifiOsFetch,
|
||||
) {
|
||||
this.baseUrl = `${origin.replace(/\/+$/, "")}${INTEGRATION_PATH}`;
|
||||
}
|
||||
|
||||
public async getInfoAsync(): Promise<{ applicationVersion: string }> {
|
||||
return await this.requestAsync("/info", unifiOsInfoSchema);
|
||||
}
|
||||
|
||||
public async getFirstSiteAsync(): Promise<UnifiOsSite | null> {
|
||||
const page = await this.requestAsync("/sites", sitePageSchema);
|
||||
return page.data[0] ?? null;
|
||||
}
|
||||
|
||||
public async getDevicesAsync(siteId: string): Promise<UnifiOsDevice[]> {
|
||||
const page = await this.requestAsync(
|
||||
`/sites/${encodeURIComponent(siteId)}/devices?limit=${MAX_PAGE_LIMIT}`,
|
||||
devicePageSchema,
|
||||
);
|
||||
return page.data;
|
||||
}
|
||||
|
||||
public async getDeviceStatisticsAsync(siteId: string, deviceId: string): Promise<UnifiOsDeviceStatistics> {
|
||||
return await this.requestAsync(
|
||||
`/sites/${encodeURIComponent(siteId)}/devices/${encodeURIComponent(deviceId)}/statistics/latest`,
|
||||
unifiOsDeviceStatisticsSchema,
|
||||
);
|
||||
}
|
||||
|
||||
public async getVpnServersAsync(siteId: string): Promise<{ enabled: boolean }[]> {
|
||||
const page = await this.requestAsync(`/sites/${encodeURIComponent(siteId)}/vpn/servers`, vpnServerPageSchema);
|
||||
return page.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sous le plafond de 200 clients, une seule page suffit et le comptage se fait
|
||||
* en mémoire. Au-delà, rapatrier tous les enregistrements pour n'en tirer que
|
||||
* des compteurs coûterait plus cher que cinq requêtes bornées.
|
||||
*/
|
||||
public async getClientCountsAsync(siteId: string): Promise<UnifiOsClientCounts> {
|
||||
const path = `/sites/${encodeURIComponent(siteId)}/clients`;
|
||||
const firstPage = await this.requestAsync(`${path}?limit=${MAX_PAGE_LIMIT}`, clientPageSchema);
|
||||
|
||||
if (firstPage.totalCount <= MAX_PAGE_LIMIT) {
|
||||
return countClients(firstPage.data);
|
||||
}
|
||||
|
||||
const countByFilterAsync = async (filter: string) => {
|
||||
const page = await this.requestAsync(`${path}?limit=1&filter=${encodeURIComponent(filter)}`, clientPageSchema);
|
||||
return page.totalCount;
|
||||
};
|
||||
|
||||
const [wired, wireless, vpn, teleport, guests] = await Promise.all([
|
||||
countByFilterAsync("type.eq('WIRED')"),
|
||||
countByFilterAsync("type.eq('WIRELESS')"),
|
||||
countByFilterAsync("type.eq('VPN')"),
|
||||
countByFilterAsync("type.eq('TELEPORT')"),
|
||||
countByFilterAsync("access.type.eq('GUEST')"),
|
||||
]);
|
||||
|
||||
return { total: firstPage.totalCount, wired, wireless, vpn: vpn + teleport, guests };
|
||||
}
|
||||
|
||||
private async requestAsync<TOutput>(path: string, schema: z.ZodType<TOutput>): Promise<TOutput> {
|
||||
const response = await this.fetchAsync(`${this.baseUrl}${path}`, {
|
||||
headers: { "X-API-KEY": this.apiKey, Accept: "application/json" },
|
||||
timeout: REQUEST_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ResponseError(response);
|
||||
}
|
||||
|
||||
return await parseUnifiOsAsync(await response.json(), schema, PARSE_ERROR_MESSAGE);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user