79 lines
2.0 KiB
TypeScript
79 lines
2.0 KiB
TypeScript
|
|
import type { UnifiAccount } from './classes.unifi-account.js';
|
||
|
|
import { UnifiHost } from './classes.host.js';
|
||
|
|
import type { IUnifiHost, ISiteManagerListResponse } from './interfaces/index.js';
|
||
|
|
import { logger } from './unifi.logger.js';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Manager for UniFi hosts via Site Manager API
|
||
|
|
*/
|
||
|
|
export class HostManager {
|
||
|
|
private unifiAccount: UnifiAccount;
|
||
|
|
|
||
|
|
constructor(unifiAccount: UnifiAccount) {
|
||
|
|
this.unifiAccount = unifiAccount;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* List all hosts
|
||
|
|
*/
|
||
|
|
public async listHosts(): Promise<UnifiHost[]> {
|
||
|
|
logger.log('debug', 'Fetching all hosts from Site Manager');
|
||
|
|
|
||
|
|
const response = await this.unifiAccount.request<ISiteManagerListResponse<IUnifiHost>>(
|
||
|
|
'GET',
|
||
|
|
'/ea/hosts'
|
||
|
|
);
|
||
|
|
|
||
|
|
const hosts: UnifiHost[] = [];
|
||
|
|
for (const hostData of response.data || []) {
|
||
|
|
hosts.push(UnifiHost.createFromApiObject(hostData, this.unifiAccount));
|
||
|
|
}
|
||
|
|
|
||
|
|
logger.log('info', `Found ${hosts.length} hosts`);
|
||
|
|
return hosts;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Get a host by ID
|
||
|
|
*/
|
||
|
|
public async getHostById(hostId: string): Promise<UnifiHost | null> {
|
||
|
|
logger.log('debug', `Fetching host: ${hostId}`);
|
||
|
|
|
||
|
|
try {
|
||
|
|
const response = await this.unifiAccount.request<IUnifiHost>(
|
||
|
|
'GET',
|
||
|
|
`/ea/hosts/${hostId}`
|
||
|
|
);
|
||
|
|
|
||
|
|
return UnifiHost.createFromApiObject(response, this.unifiAccount);
|
||
|
|
} catch (error) {
|
||
|
|
logger.log('warn', `Host not found: ${hostId}`);
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Find a host by name
|
||
|
|
*/
|
||
|
|
public async findHostByName(name: string): Promise<UnifiHost | null> {
|
||
|
|
const hosts = await this.listHosts();
|
||
|
|
return hosts.find((host) => host.name === name) || null;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Get hosts by site ID
|
||
|
|
*/
|
||
|
|
public async getHostsBySiteId(siteId: string): Promise<UnifiHost[]> {
|
||
|
|
const hosts = await this.listHosts();
|
||
|
|
return hosts.filter((host) => host.siteId === siteId);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Get online hosts only
|
||
|
|
*/
|
||
|
|
public async getOnlineHosts(): Promise<UnifiHost[]> {
|
||
|
|
const hosts = await this.listHosts();
|
||
|
|
return hosts.filter((host) => host.checkOnline());
|
||
|
|
}
|
||
|
|
}
|