UNPKG

@panoptic-it-solutions/unifi-api-client

Version:

A Node.js client library for the UniFi Controller API

346 lines (345 loc) 10.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UniFiClient = void 0; const http_client_1 = require("./http-client"); const auth_1 = require("./auth"); const events_1 = require("events"); const logger_1 = require("./utils/logger"); const endpoints_1 = require("./endpoints"); const networks_1 = require("./endpoints/networks"); const wireless_1 = require("./endpoints/wireless"); const stats_1 = require("./endpoints/stats"); const system_1 = require("./endpoints/system"); class UniFiClient extends events_1.EventEmitter { constructor(controllerUrl, options = {}) { super(); if (options.logger instanceof logger_1.Logger) { this.logger = options.logger; } else { this.logger = new logger_1.Logger(options.logger || {}); } this.logger.info(`Initializing UniFi API client for ${controllerUrl}`); this.httpClient = new http_client_1.HttpClient(controllerUrl, { strictSSL: options.strictSSL, timeout: options.timeout, logger: this.logger, }); this.auth = new auth_1.UniFiAuth(this.httpClient, options.site || 'default'); this.devices = new endpoints_1.DeviceEndpoints(this.httpClient, options.site || 'default'); this.clients = new endpoints_1.ClientEndpoints(this.httpClient, this.auth.getSite()); this.sites = new endpoints_1.SiteEndpoints(this.httpClient); this.networks = new networks_1.NetworkEndpoints(this.httpClient, this.auth.getSite()); this.wireless = new wireless_1.WirelessEndpoints(this.httpClient, this.auth.getSite()); this.statsEndpoints = new stats_1.StatsEndpoints(this.httpClient, this.auth.getSite()); this.systemEndpoints = new system_1.SystemEndpoints(this.httpClient, this.auth.getSite()); if (typeof options.username === 'string') this.username = options.username; if (typeof options.password === 'string') this.password = options.password; } setLogLevel(level) { this.logger.setLevel(level); } async login(username, password) { const user = username !== null && username !== void 0 ? username : this.username; const pass = password !== null && password !== void 0 ? password : this.password; if (!user || !pass) throw new Error('Username and password required'); const result = await this.auth.login(user, pass); this.emit('login', result); return result; } async logout() { const result = await this.auth.logout(); this.emit('logout', result); return result; } isLoggedIn() { return this.auth.isAuthenticated(); } setSite(site) { this.auth.setSite(site); this.devices = new endpoints_1.DeviceEndpoints(this.httpClient, site); this.clients = new endpoints_1.ClientEndpoints(this.httpClient, site); this.emit('siteChanged', site); } getSite() { return this.auth.getSite(); } async request(method, path, data, params) { if (!this.isLoggedIn() || this.auth.isSessionExpired()) { if (this.auth.canReuseCredentials()) { await this.auth.refreshSession(); this.emit('sessionRefreshed'); } else { throw new Error('Not authenticated'); } } switch (method) { case 'get': return this.httpClient.get(path, params); case 'post': return this.httpClient.post(path, data); case 'put': return this.httpClient.put(path, data); case 'delete': return this.httpClient.delete(path); default: throw new Error('Invalid HTTP method'); } } /** * List all active clients. */ async getActiveClients(options) { return this.clients.getActiveClients(options); } /** * List all clients (active and historical). */ async getAllClients(options) { return this.clients.getAllClients(options); } /** * Get client details by identifier (MAC, IP, or name). */ async getClientDetails(identifier) { return this.clients.getClientDetails(identifier); } /** * Block a client by MAC address. */ async blockClient(mac) { return this.clients.blockClient(mac); } /** * Unblock a client by MAC address. */ async unblockClient(mac) { return this.clients.unblockClient(mac); } /** * Reconnect (kick) a client by MAC address. */ async reconnectClient(mac) { return this.clients.reconnectClient(mac); } /** * Authorize a guest client for a given number of minutes. */ async authorizeGuest(mac, minutes) { return this.clients.authorizeGuest(mac, minutes); } /** * Unauthorize a guest client by MAC address. */ async unauthorizeGuest(mac) { return this.clients.unauthorizeGuest(mac); } /** * List all networks. */ async getNetworks() { return this.networks.getNetworks(); } /** * Create a new network. */ async createNetwork(network) { return this.networks.createNetwork(network); } /** * Update an existing network. */ async updateNetwork(networkId, network) { return this.networks.updateNetwork(networkId, network); } /** * Delete a network. */ async deleteNetwork(networkId) { return this.networks.deleteNetwork(networkId); } /** * List all firewall rules. */ async getFirewallRules() { return this.networks.getFirewallRules(); } /** * Create a new firewall rule. */ async createFirewallRule(rule) { return this.networks.createFirewallRule(rule); } /** * Update an existing firewall rule. */ async updateFirewallRule(ruleId, rule) { return this.networks.updateFirewallRule(ruleId, rule); } /** * Delete a firewall rule. */ async deleteFirewallRule(ruleId) { return this.networks.deleteFirewallRule(ruleId); } /** * List all wireless networks (WLANs). */ async getWlanConfigs() { return this.wireless.getWlanConfigs(); } /** * Create a new wireless network (WLAN). */ async createWlanConfig(wlanConfig) { return this.wireless.createWlanConfig(wlanConfig); } /** * Update an existing wireless network (WLAN). */ async updateWlanConfig(wlanId, wlanConfig) { return this.wireless.updateWlanConfig(wlanId, wlanConfig); } /** * Delete a wireless network (WLAN). */ async deleteWlanConfig(wlanId) { return this.wireless.deleteWlanConfig(wlanId); } /** * Get radio settings for a device. */ async getRadioSettings(deviceMac) { return this.wireless.getRadioSettings(deviceMac); } /** * Update radio settings for a device. */ async updateRadioSettings(deviceMac, radioSettings) { return this.wireless.updateRadioSettings(deviceMac, radioSettings); } /** * Get wireless networks utilization statistics. */ async getWlanUtilization() { return this.wireless.getWlanUtilization(); } // Statistics methods async getSiteStats(options) { return this.statsEndpoints.getSiteStats(options); } async getClientStats(options) { return this.statsEndpoints.getClientStats(options); } async getDeviceStats(options) { return this.statsEndpoints.getDeviceStats(options); } async getSessions(options) { return this.statsEndpoints.getSessions(options); } async getHourlySiteStats(options) { return this.statsEndpoints.getHourlySiteStats(options); } async getTrafficStats(options) { return this.statsEndpoints.getTrafficStats(options); } async getAllUsers(options) { return this.statsEndpoints.getAllUsers(options); } async get5MinuteSiteStats(options) { return this.statsEndpoints.get5MinuteSiteStats(options); } async getGatewayStats(options) { return this.statsEndpoints.getGatewayStats(options); } /** * Get controller system status */ async getSystemStatus() { return this.systemEndpoints.getStatus(); } /** * Get controller system settings */ async getSystemSettings() { return this.systemEndpoints.getSettings(); } /** * Update controller system settings */ async updateSystemSettings(settings) { return this.systemEndpoints.updateSettings(settings); } /** * Create a system backup */ async createSystemBackup(options) { return this.systemEndpoints.createBackup(options); } /** * Restore a system backup */ async restoreSystemBackup(backupId, options) { return this.systemEndpoints.restoreBackup(backupId, options); } /** * Get available firmware versions */ async getAvailableFirmware() { return this.systemEndpoints.getAvailableFirmware(); } /** * Update device firmware */ async updateDeviceFirmware(deviceId, firmwareVersion) { return this.systemEndpoints.updateDeviceFirmware(deviceId, firmwareVersion); } /** * Reboot the controller */ async rebootController() { return this.systemEndpoints.rebootController(); } /** * Get system logs */ async getSystemLogs(limit) { return this.systemEndpoints.getLogs(limit); } /** * Get current system alerts */ async getSystemAlerts() { return this.systemEndpoints.getAlerts(); } /** * Reboot the system (with confirmation) */ async rebootSystem(confirm) { return this.systemEndpoints.rebootSystem(confirm); } /** * Factory reset the system (destructive!) */ async factoryReset(confirm) { return this.systemEndpoints.factoryReset(confirm); } /** * Export a site backup as a Buffer (binary .unf file) * @returns {Promise<Buffer>} The backup file contents */ async exportSiteBackup() { const site = this.auth.getSite(); const url = `/api/s/${site}/cmd/backup`; const response = await this.httpClient.postRaw(url, {}, { responseType: 'arraybuffer', headers: { Accept: 'application/octet-stream' }, }); return Buffer.from(response.data); } } exports.UniFiClient = UniFiClient;