Files
homarr/packages/integrations/src/unifi-os/unifi-os-api.ts
T
2026-10-08 00:23:44 +02:00

119 lines
4.3 KiB
TypeScript

import { ResponseError } from "@homarr/common/server";
import type { RequestInit, Response } from "undici";
import type { z } from "zod/v4";
import { parseUnifiOsAsync } from "./unifi-os-parse";
import type { UnifiOsClientCounts, UnifiOsDevice, UnifiOsDeviceStatistics, UnifiOsSite } from "./unifi-os-types";
import {
countClients,
createUnifiOsPageSchema,
unifiOsClientSchema,
unifiOsDeviceSchema,
unifiOsDeviceStatisticsSchema,
unifiOsInfoSchema,
unifiOsSiteSchema,
} from "./unifi-os-types";
/**
* Déclaré sur les types d'undici, pas sur ceux du DOM : le dépôt n'utilise que
* `undici` côté serveur. Aligner les deux évite les `as unknown as` qui
* désactivaient le contrôle de type à la frontière du transport.
*/
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);
/**
* 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,
);
}
/**
* 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);
}
}