Bläddra i källkod

V2 API is working

Benoit 2 år sedan
förälder
incheckning
eafcc20597
1 ändrade filer med 120 tillägg och 51 borttagningar
  1. 120 51
      src/widgets/omada/proxy.js

+ 120 - 51
src/widgets/omada/proxy.js

@@ -1,11 +1,11 @@
 import cache from "memory-cache";
 
+import { addCookieToJar, setCookieHeader } from "../../utils/proxy/cookie-jar";
 
 import { httpProxy } from "utils/proxy/http";
 import getServiceWidget from "utils/config/service-helpers";
 import createLogger from "utils/logger";
 import widgets from "widgets/widgets";
-import { addCookieToJar, setCookieHeader } from "utils/proxy/cookie-jar";
 
 const proxyName = "omadaProxyHandler";
 const tokenCacheKey = `${proxyName}__token`;
@@ -15,7 +15,7 @@ const logger = createLogger(proxyName);
 async function login(loginUrl, username, password, legacy) {
 
   if (legacy) {
-    console.log("Legacy");
+
     const authResponse = await httpProxy(loginUrl,
       {
         method: "POST",
@@ -29,9 +29,9 @@ async function login(loginUrl, username, password, legacy) {
         },
       }
     );
-    let data;
+
     const status = authResponse[0];
-    data = JSON.parse(authResponse[2]);
+    const data = JSON.parse(authResponse[2]);
     const {token} = data.result;
     try {
       if (status === 200) {
@@ -41,25 +41,9 @@ async function login(loginUrl, username, password, legacy) {
       logger.error(`Error ${status} logging into Omada`, authResponse[2]);
     }
     return [status, token ?? data];
-  } else {
-    setCookieHeader(loginUrl, );
-    const authResponse = await httpProxy(loginUrl,
-      {
-        method: "POST",
-        body: JSON.stringify({
-            "name": username,
-            "password": password
-          }),
-        headers: {
-          "Content-Type": "application/json",
-        },
-        }
-      );
-    let data;
-    const status = authResponse[0];
-    console.log("Status: ", status);
   }
-  return [null, null];
+
+  return null
 }
 
 
@@ -81,6 +65,7 @@ export default async function omadaProxyHandler(req, res) {
         let data;
         let result;
         let token;
+        // eslint-disable-next-line prefer-const
         [status, token] = await login(loginUrl, widget.username, widget.password, widget.legacy);
         if (status !== 200) {
           logger.debug(`HTTTP ${status} logging into Omada api: ${token}`);
@@ -136,7 +121,7 @@ export default async function omadaProxyHandler(req, res) {
 
         const url = `${widget.url}/web/v1/controller?globalStat=&token=${token}`;
 
-        // eslint-disable-next-line prefer-const
+        // eslint-disable-next-line prefer-const,no-unused-vars
         [status, contentType, result] = await httpProxy(url, {
           method: "POST",
           params: { "token": token },
@@ -156,51 +141,135 @@ export default async function omadaProxyHandler(req, res) {
         }
 
         return res.send(data.result);
-      } else {
-        // Working on it but I can't test it
-
-        const controlleridurl = `${widget.url}/api/info`;
-        let cidstatus, cidcontentType, cidresult;
-
-        [cidstatus, cidcontentType, cidresult] = await httpProxy(controlleridurl, {
+      }
+      // code for modern API, not working yet
+      // Working on it but I can't test it
+        const {url} = widget;
+        const controllerInfoUrl = `${url}/api/info`;
+        const cInfoResponse = await httpProxy(controllerInfoUrl, {
           method: "GET",
           headers: {
             "Content-Type": "application/json",
           },
         });
+        const cidresult = cInfoResponse[2];
 
         const cid = JSON.parse(cidresult).result.omadacId;
+        const cversion = JSON.parse(cidresult).result.controllerVer;
+        let loginUrl;
+        if (cversion >= "5.0.0"){
+          loginUrl = `${url}/${cid}/api/v2/login`;
+        } else {
+          loginUrl = `${url}/api/v2/login`;
+        }
 
-        const loginUrl = `${widget.url}/${cid}/login`;
-        let status;
-
-        let token;
         const params = {
           method: "POST",
-          body: JSON.stringify({
-            "name": widget.username,
-            "password": widget.password
-          }),
+          body: JSON.stringify({ "username": widget.username, "password": widget.password }),
           headers: {"Content-Type": "application/json"} };
-        // setCookieHeader(loginUrl, params);
-        const authResponse = await httpProxy(loginUrl,
-          params,
+        setCookieHeader(url, params);
+        const authResponse = await httpProxy(loginUrl,params);
+        addCookieToJar(url, authResponse[3]);
+        setCookieHeader(url, params);
 
-        );
-        status = authResponse[0];
+        const status = authResponse[0];
         const data = JSON.parse(authResponse[2]);
-        console.log("Data: ", data);
-        // addCookieToJar(loginUrl, authResponse[3]);
-        // setCookieHeader(loginUrl, params);
-
-        console.log("Status: ", status);
-        console.log("Token: ", token);
-        if (status !== 200) {
-          logger.debug(`HTTTP ${status} logging into Omada api: ${token}`);
+        const {token} = data.result;
+        if (data.errorCode !== 0) {
+          logger.debug(`HTTTP ${data.errorCode} logging into Omada api: ${data.error}`);
           return res.status(status).send(token);
         }
+        let sitesUrl;
+        if (cversion >= "5.0.0") {
+          sitesUrl = `${url}/${cid}/api/v2/sites?token=${token}&currentPage=1&currentPageSize=1000`;
+        } else {
+          sitesUrl = `${url}/api/v2/sites?token=${token}&currentPage=1&currentPageSize=1000`;
+        }
+        let response;
+        response = await httpProxy(sitesUrl, {
+          method: "GET",
+          headers: {
+            "Csrf-Token": token,
+          },
+        });
+
+        const listresult = JSON.parse(response[2]);
+        if (listresult.errorCode !== 0) {
+          logger.debug(`HTTTP ${listresult.errorCode} getting list of sites with message ${listresult.msg}`);
+          return res.status(status).send(data);
+        }
+
+      const sites = JSON.parse(response[2]);
+
+      const sitetoswitch = sites.result.data.filter(site => site.name === widget.site);
+      const siteName = sitetoswitch[0].id;
+
+      let switchUrl;
+      if (cversion >= "5.0.0") {
+        switchUrl = `${url}/${cid}/api/v2/sites/${siteName}/cmd/switch?token=${token}`;
+      } else {
+        switchUrl = `${url}/api/v2/sites/${siteName}/cmd/switch?token=${token}`;
+      }
+      response = await httpProxy(switchUrl, {
+        method: "POST",
+        headers: {
+          "Csrf-Token": token,
+        },
+      });
+
+      const switchresult = JSON.parse(response[2]);
+      if (switchresult.errorCode !== 0) {
 
+        logger.debug(`HTTTP ${listresult.errorCode} switching to site ${widget.site} with message ${listresult.msg}`);
+        return res.status(status).send(data);
       }
+
+      // get the number of devices connected to the site
+
+      let clientUrl;
+      if (cversion >= "5.0.0") {
+        clientUrl=`${url}/${cid}/api/v2/sites/${siteName}/dashboard/overviewDiagram?token=${token}&currentPage=1&currentPageSize=1000`;
+      } else {
+        clientUrl=`${url}/api/v2/sites/${siteName}/dashboard/overviewDiagram?token=${token}&currentPage=1&currentPageSize=1000`;
+      }
+      response = await httpProxy(clientUrl, {
+        method: "GET",
+        headers: {
+          "Csrf-Token": token,
+        },
+      });
+      const clientresult = JSON.parse(response[2]);
+      if (clientresult.errorCode !== 0) {
+        logger.debug(`HTTTP ${listresult.errorCode} getting clients stats for site ${widget.site} with message ${listresult.msg}`);
+        return res.status(status).send(data);
+      }
+      const activeuser = clientresult.result.totalClientNum;
+      const connectedAp = clientresult.result.connectedApNum;
+
+      let alertUrl;
+      if (cversion >= "5.0.0") {
+        alertUrl=`${url}/${cid}/api/v2/sites/${siteName}/alerts/num?token=${token}&currentPage=1&currentPageSize=1000`;
+      } else {
+        alertUrl=`${url}/api/v2/sites/${siteName}/alerts/num?token=${token}&currentPage=1&currentPageSize=1000`;
+      }
+      response = await httpProxy(alertUrl, {
+        method: "GET",
+        headers: {
+          "Csrf-Token": token,
+        },
+      });
+
+      const alertresult = JSON.parse(response[2]);
+      const alerts = alertresult.result.alertNum;
+
+
+
+      const returnvalue = JSON.stringify({
+        "connectedAp": connectedAp,
+        "activeUser": activeuser,
+        "alerts": alerts
+      });
+      return res.send(returnvalue);
     }
   }