Remove node-unifi package dependency

- Add custom Unifi proxy built on existing cookie jar and httpProxy
- Change formatApiCall to emit empty string instead of undefined on missing key
This commit is contained in:
Jason Fischer
2022-10-07 17:12:29 -07:00
parent 952f0295cc
commit ac4dcd3222
8 changed files with 148 additions and 163 deletions

View File

@@ -1,17 +1,18 @@
import useSWR from "swr";
import { BiError, BiWifi, BiCheckCircle, BiXCircle } from "react-icons/bi";
import { MdSettingsEthernet } from "react-icons/md";
import { useTranslation } from "next-i18next";
import { SiUbiquiti } from "react-icons/si";
import useWidgetAPI from "utils/proxy/use-widget-api";
export default function Widget({ options }) {
const { t, i18n } = useTranslation();
const { t } = useTranslation();
const { data, error } = useSWR(
`/api/widgets/unifi?${new URLSearchParams({ lang: i18n.language, ...options }).toString()}`
);
// eslint-disable-next-line no-param-reassign
options.type = "unifi_console";
const { data: statsData, error: statsError } = useWidgetAPI(options, "stat/sites");
if (error || data?.error) {
if (statsError || statsData?.error) {
return (
<div className="flex flex-col justify-center first:ml-0 ml-4">
<div className="flex flex-row items-center justify-end">
@@ -27,7 +28,9 @@ export default function Widget({ options }) {
);
}
if (!data) {
const defaultSite = statsData?.data?.find(s => s.name === "default");
if (!defaultSite) {
return (
<div className="flex flex-col justify-center first:ml-0 ml-4">
<div className="flex flex-row items-center justify-end">
@@ -42,6 +45,23 @@ export default function Widget({ options }) {
);
}
const wan = defaultSite.health.find(h => h.subsystem === "wan");
const lan = defaultSite.health.find(h => h.subsystem === "lan");
const wlan = defaultSite.health.find(h => h.subsystem === "wlan");
const data = {
name: wan.gw_name,
uptime: wan["gw_system-stats"].uptime,
up: wan.status === 'ok',
wlan: {
users: wlan.num_user,
status: wlan.status
},
lan: {
users: lan.num_user,
status: lan.status
}
};
return (
<div className="flex-none flex flex-row items-center mr-3 py-1.5">
<div className="flex flex-col">

View File

@@ -1,53 +0,0 @@
import { Controller } from "node-unifi";
export default async function handler(req, res) {
const { host, port, username, password } = req.query;
if (!host) {
return res.status(400).json({ error: "Missing host" });
}
if (!username) {
return res.status(400).json({ error: "Missing username" });
}
if (!password) {
return res.status(400).json({ error: "Missing password" });
}
const controller = new Controller({
host: host,
port: port,
sslverify: false
});
try {
//login to the controller
await controller.login(username, password);
//retrieve sites
const sites = await controller.getSitesStats();
const default_site = sites.find(s => s.name == "default");
const wan = default_site.health.find(h => h.subsystem == "wan");
const lan = default_site.health.find(h => h.subsystem == "lan");
const wlan = default_site.health.find(h => h.subsystem == "wlan");
return res.status(200).json({
name: wan.gw_name,
uptime: wan['gw_system-stats']['uptime'],
up: wan.status == 'ok',
wlan: {
users: wlan.num_user,
status: wlan.status
},
lan: {
users: lan.num_user,
status: lan.status
}
});
} catch (e) {
return res.status(400).json({
error: `Error communicating with UniFi Console: ${e.message}`
})
}
}

View File

@@ -2,7 +2,7 @@ export function formatApiCall(url, args) {
const find = /\{.*?\}/g;
const replace = (match) => {
const key = match.replace(/\{|\}/g, "");
return args[key];
return args[key] || "";
};
return url.replace(/\/+$/, "").replace(find, replace);

103
src/widgets/unifi/proxy.js Normal file
View File

@@ -0,0 +1,103 @@
import { formatApiCall } from "utils/proxy/api-helpers";
import { httpProxy } from "utils/proxy/http";
import { addCookieToJar, setCookieHeader } from "utils/proxy/cookie-jar";
import { getSettings } from "utils/config/config";
import getServiceWidget from "utils/config/service-helpers";
import createLogger from "utils/logger";
import widgets from "widgets/widgets";
const logger = createLogger("unifiProxyHandler");
async function getWidget(req) {
const { group, service, type } = req.query;
let widget = null;
if (type === 'unifi_console') {
const settings = getSettings();
widget = settings.unifi_console;
if (!widget) {
logger.debug("There is no unifi_console section in settings.yaml");
return null;
}
widget.type = "unifi";
} else {
if (!group || !service) {
logger.debug("Invalid or missing service '%s' or group '%s'", service, group);
return null;
}
widget = await getServiceWidget(group, service);
if (!widget) {
logger.debug("Invalid or missing widget for service '%s' in group '%s'", service, group);
return null;
}
}
return widget;
}
async function login(widget) {
logger.debug("Unifi isn't logged in or is rejecting the reqeust, logging in.");
const loginBody = { username: widget.username, password: widget.password, remember: true };
let loginUrl = `${widget.url}/api`;
if (widget.version === "udm-pro") {
loginUrl += "/auth"
}
loginUrl += "/login";
const loginParams = { method: "POST", body: JSON.stringify(loginBody) };
const [status, contentType, data, responseHeaders] = await httpProxy(loginUrl, loginParams);
return [status, contentType, data, responseHeaders];
}
export default async function unifiProxyHandler(req, res) {
const widget = await getWidget(req);
if (!widget) {
return res.status(400).json({ error: "Invalid proxy service type" });
}
const api = widgets?.[widget.type]?.api;
if (!api) {
return res.status(403).json({ error: "Service does not support API calls" });
}
widget.prefx = "";
if (widget.version === "udm-pro") {
widget.prefix = "/proxy/network"
}
const { endpoint } = req.query;
const url = new URL(formatApiCall(api, { endpoint, ...widget }));
const params = { method: "GET", headers: {} };
setCookieHeader(url, params);
let [status, contentType, data, responseHeaders] = await httpProxy(url, params);
if (status === 401) {
[status, contentType, data, responseHeaders] = await login(widget);
if (status !== 200) {
logger.error("HTTP %d logging in to Unifi. Data: %s", status, data);
return res.status(status).end(data);
}
const json = JSON.parse(data.toString());
if (json?.meta?.rc !== "ok") {
logger.error("Error logging in to Unifi: Data: %s", data);
return res.status(401).end(data);
}
addCookieToJar(url, responseHeaders);
setCookieHeader(url, params);
}
[status, contentType, data] = await httpProxy(url, params);
if (status !== 200) {
logger.error("HTTP %d getting data from Unifi. Data: %s", status, data);
}
if (contentType) res.setHeader("Content-Type", contentType);
return res.status(status).send(data);
}

View File

@@ -0,0 +1,14 @@
import unifiProxyHandler from "./proxy";
const widget = {
api: "{url}{prefix}/api/{endpoint}",
proxyHandler: unifiProxyHandler,
mappings: {
"stat/sites": {
endpoint: "stat/sites",
},
}
};
export default widget;

View File

@@ -27,6 +27,7 @@ import strelaysrv from "./strelaysrv/widget";
import tautulli from "./tautulli/widget";
import traefik from "./traefik/widget";
import transmission from "./transmission/widget";
import unifi from "./unifi/widget";
const widgets = {
adguard,
@@ -59,6 +60,8 @@ const widgets = {
tautulli,
traefik,
transmission,
unifi,
unifi_console: unifi
};
export default widgets;