@oddbit/unifi
Version:
Unifi API client library
391 lines • 13 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const rp = require("request-promise");
const tough = require("tough-cookie");
const cookieParser = require("set-cookie-parser");
class UnifiController {
constructor(config) {
this._cookieJar = rp.jar();
this._isLoggedIn = false;
this._isSelfSigned = !!config.isSelfSigned;
this._siteName = config.siteName || "default";
this._host = config.host || "localhost";
this._port = config.port || 8443;
}
// ------------------------------------------------------------------------
//
// AUTH
//
/**
* Login to the UniFi controller
*
* @param username Admin username (provided user needs administrator rights)
* @param password Password
*/
login(username, password) {
return __awaiter(this, void 0, void 0, function* () {
if (this._isLoggedIn) {
yield this.logout();
}
const body = {
"username": username,
"password": password
};
yield this.post("/api/login", body);
this._isLoggedIn = true;
});
}
/**
* Logout from the UniFi controller.
*/
logout() {
return __awaiter(this, void 0, void 0, function* () {
if (!this._isLoggedIn) {
return;
}
yield this.post("/api/logout");
this._isLoggedIn = false;
});
}
// ------------------------------------------------------------------------
//
// CLIENTS / STA / DEVICES
//
/**
* Reconnect a client device
*
* @param mac MAC address of the client device to reconnect
*/
reconnectClient(mac) {
return __awaiter(this, void 0, void 0, function* () {
const body = {
cmd: "kick-sta",
mac: mac
};
yield this.post(`/api/s/${this._siteName}/cmd/stamgr`, body);
});
}
/**
* Block a client device
*
* @param mac MAC of client device to block
*/
blockClient(mac) {
return __awaiter(this, void 0, void 0, function* () {
const body = {
cmd: "block-sta",
mac: mac
};
const response = yield this.post(`/api/s/${this._siteName}/cmd/stamgr`, body);
return response[0];
});
}
/**
* Unblock a client device
*
* @param mac MAC of client device to block
*/
unblockClient(mac) {
return __awaiter(this, void 0, void 0, function* () {
const body = {
cmd: "unblock-sta",
mac: mac
};
const response = yield this.post(`/api/s/${this._siteName}/cmd/stamgr`, body);
return response[0];
});
}
/**
* Create an alias for a client.
*
* @param id Id of the client
* @param alias Alias name
*/
setClientAlias(id, alias) {
return __awaiter(this, void 0, void 0, function* () {
const body = {
name: alias
};
const response = yield this.post(`/api/s/${this._siteName}/upd/user/${id}`, body);
return response[0];
});
}
/**
* Remove a client alias.
*
* @param id Id of the client
*/
removeClientAlias(id) {
return __awaiter(this, void 0, void 0, function* () {
const body = {
name: null
};
const response = yield this.post(`/api/s/${this._siteName}/upd/user/${id}`, body);
return response[0];
});
}
/**
* Set a client note.
*
* @param id Id of the client
* @param note Note
*/
setClientNote(id, note) {
return __awaiter(this, void 0, void 0, function* () {
const body = {
note: note,
noted: true
};
const response = yield this.post(`/api/s/${this._siteName}/upd/user/${id}`, body);
return response[0];
});
}
/**
* Remove a client note.
*
* @param id Id of the client
* @param note Note
*/
removeClientNote(id) {
return __awaiter(this, void 0, void 0, function* () {
const body = {
note: null,
noted: false
};
const response = yield this.post(`/api/s/${this._siteName}/upd/user/${id}`, body);
return response[0];
});
}
/**
* List connected clients
*/
listClients() {
return __awaiter(this, void 0, void 0, function* () {
return this.post(`/api/s/${this._siteName}/stat/sta`);
});
}
/**
* Get a single client's info
*
* @param mac MAC address of the client
*/
getClient(mac) {
return __awaiter(this, void 0, void 0, function* () {
const result = yield this.post(`/api/s/${this._siteName}/stat/sta/${mac}`);
return result[0];
});
}
// ------------------------------------------------------------------------
//
// HOTSPOT / GUESTS / VOUCHERS
//
/**
* Authorize a client device to connect through the hotspot.
*
* @param mac MAC address of the client device
* @param ap The access point MAC to which the client device connected
* @param [opts] Auth/connection options (see `AuthClientOpts`)
* @returns Authorized client data
*/
authorizeGuest(mac, ap, opts) {
return __awaiter(this, void 0, void 0, function* () {
const defaultOpts = {
minutes: 60 * 24
};
// Overwrite values from left to right
const body = Object.assign(defaultOpts, opts, {
cmd: "authorize-guest",
mac: mac,
ap_mac: ap
});
const response = yield this.post(`/api/s/${this._siteName}/cmd/stamgr`, body);
return response[0];
});
}
/**
* Unauthorize a client device
*
* @param mac MAC address of the client device
*/
unauthorizeGuest(mac) {
return __awaiter(this, void 0, void 0, function* () {
const body = {
cmd: "unauthorize-guest",
mac: mac
};
yield this.post(`/api/s/${this._siteName}/cmd/stamgr`, body);
});
}
/**
* Create multi or single use voucher access tokens.
*
* @param quantity The number of vouchers to create
* @param minutes How many minutes of uptime that will be included
* @param [opts] Additional options
*/
createVouchers(quantity, minutes, opts) {
return __awaiter(this, void 0, void 0, function* () {
if (quantity < 1) {
throw Error("Quatity must be greater than zero");
}
if (minutes < 1) {
minutes = 1;
}
const defaultOpts = {
quota: 1
};
// Overwrite values from left to right
const body = Object.assign(defaultOpts, opts, {
cmd: "create-voucher",
expire: minutes,
n: quantity
});
const response = yield this.post(`/api/s/${this._siteName}/cmd/hotspot`, body);
return response[0] && response[0].create_time;
});
}
/**
* Get all vouchers. The result set can be limited by a timestamp. The provided timestamp must match the
* exact same timestamp on which the vouchers were created.
*
* @param timestamp The **exact** timestamp on which the desired vouchers were created on
*/
listVouchers(timestamp) {
return __awaiter(this, void 0, void 0, function* () {
const body = {};
if (timestamp != null) {
body.create_time = timestamp;
}
return this.post(`/api/s/${this._siteName}/stat/voucher`, body);
});
}
/**
* Delete a voucher.
*
* @param voucherId The `_id` of the created `Voucher`
*/
deleteVoucher(voucherId) {
return __awaiter(this, void 0, void 0, function* () {
const body = {
cmd: "delete-voucher",
_id: voucherId
};
yield this.post(`/api/s/${this._siteName}/cmd/hotspot`, body);
});
}
// ------------------------------------------------------------------------
//
// SYSTEM / INFORMATION
//
/**
* List known sessions during a certain period of time. Default is to show the last month's sessions.
*
* @param [timeframe] The window of time (in seconds) to limit results by (default is 30 days)
* @param [from] Alternative start time from where to list devices (default is "now")
*/
listSessions(timeframe, from) {
return __awaiter(this, void 0, void 0, function* () {
timeframe = timeframe || 60 * 60 * 24 * 30;
from = from || Math.round(Date.now() / 1000);
const body = {
start: timeframe,
end: from
};
return this.post(`/api/s/${this._siteName}/stat/authorization`, body);
});
}
/**
* List sites that are configured on the controller
*/
listSites() {
return __awaiter(this, void 0, void 0, function* () {
return this.get(`/api/self/sites`);
});
}
/**
* Get the name of the site that is targeted in API calls.
*/
getSite() {
return this._siteName;
}
/**
* Change the active site to target in API calls. This can be useful if site information was not known before
* retreiving site information in a call to `listSites()`.
*
* @param siteName Name of the site
*/
setSite(siteName) {
this._siteName = siteName || "default";
}
/**
* Get device info for one or all access points. Specifying an access point's MAC will limit
* the result to only that AP.
*
* @param [ap] Access point MAC
*/
listDevices(ap) {
return __awaiter(this, void 0, void 0, function* () {
return this.post(`/api/s/${this._siteName}/stat/device/${ap || ""}`);
});
}
/**
* Get controller system info
*/
getSystemInfo() {
return __awaiter(this, void 0, void 0, function* () {
const response = yield this.post(`/api/s/${this._siteName}/stat/sysinfo`);
return response[0];
});
}
// ------------------------------------------------------------------------
get(uri) {
return this.request("GET", uri);
}
post(uri, body) {
return this.request("POST", uri, body);
}
/**
* Make a request to the UniFi controller API.
* Successful requests always return an array, regardless of the context and amount of data.
* So requests that expect a single value response comes in an array with 1 element and requests
* that does not have a response are returned as an empty array.
*
* @param uri The API endpoint
* @param body JSON body
*/
request(method, uri, body) {
const opts = {
method: method,
uri: `https://${this._host}:${this._port}${uri}`,
resolveWithFullResponse: true,
jar: this._cookieJar,
json: true,
body: body
};
const nodeTslRejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
if (this._isSelfSigned) {
// Ignore self signed certificate warnings
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
}
return rp(opts)
.then((response) => {
cookieParser.parse(response).forEach(cookie => {
this._cookieJar.setCookie(new tough.Cookie(cookie), this._host);
});
return (response.body && response.body.data) || [];
}).finally(() => {
// Restore the environment variable value
process.env.NODE_TLS_REJECT_UNAUTHORIZED = nodeTslRejectUnauthorized;
});
}
}
exports.UnifiController = UnifiController;
//# sourceMappingURL=index.js.map