diff --git a/front/deviceDetailsEdit.php b/front/deviceDetailsEdit.php index 51383063..d2771de3 100755 --- a/front/deviceDetailsEdit.php +++ b/front/deviceDetailsEdit.php @@ -308,6 +308,7 @@ const apiToken = getSetting("API_TOKEN"); // dynamic token const host = window.location.hostname; + const protocol = window.location.protocol; const port = getSetting("GRAPHQL_PORT"); mac = $('#NEWDEV_devMac').val(); @@ -356,7 +357,7 @@ $.ajax({ - url: "http://" + host + ":" + port + "/device/" + encodeURIComponent(mac), + url: `${protocol}//${host}:${port}/device/${encodeURIComponent(mac)}`, type: "POST", headers: { "Authorization": "Bearer " + apiToken, diff --git a/front/deviceDetailsTools.php b/front/deviceDetailsTools.php index 2c043aa9..989b76f9 100755 --- a/front/deviceDetailsTools.php +++ b/front/deviceDetailsTools.php @@ -6,7 +6,7 @@ - +

@@ -25,7 +25,7 @@ - +

@@ -34,8 +34,8 @@
- @@ -48,7 +48,7 @@ - +

@@ -75,12 +75,12 @@
-
@@ -88,19 +88,19 @@

- +


-
@@ -159,11 +159,11 @@
- +

- +

@@ -210,66 +210,195 @@
diff --git a/front/php/server/devices.php b/front/php/server/devices.php index 0852a1be..88095a0e 100755 --- a/front/php/server/devices.php +++ b/front/php/server/devices.php @@ -31,7 +31,7 @@ $action = $_REQUEST['action']; switch ($action) { // check server/api_server/api_server_start.py for equivalents - case 'getServerDeviceData': getServerDeviceData(); break; // equivalent: get_device_data + case 'getServerDeviceData': getServerDeviceData(); break; // equivalent: get_device_data case 'deleteDevice': deleteDevice(); break; // equivalent: delete_device(mac) case 'deleteAllWithEmptyMACs': deleteAllWithEmptyMACs(); break; // equivalent: delete_all_with_empty_macs @@ -41,7 +41,7 @@ case 'deleteEvents30': deleteEvents30(); break; // equivalent: delete_events_30 case 'deleteActHistory': deleteActHistory(); break; // equivalent: delete_online_history case 'deleteDeviceEvents': deleteDeviceEvents(); break; // equivalent: delete_device_events(mac) - case 'resetDeviceProps': resetDeviceProps(); break; // equivalent: reset_device_props + case 'ExportCSV': ExportCSV(); break; // equivalent: export_devices case 'ImportCSV': ImportCSV(); break; // equivalent: import_csv @@ -50,9 +50,6 @@ case 'updateNetworkLeaf': updateNetworkLeaf(); break; // equivalent: update_device_column(mac, column_name, column_value) - case 'copyFromDevice': copyFromDevice(); break; // equivalent: copy_device(mac_from, mac_to) - case 'wakeonlan': wakeonlan(); break; // equivalent: wakeonlan - default: logServerConsole ('Action: '. $action); break; // equivalent: } } @@ -202,149 +199,6 @@ function getServerDeviceData() { } - -//------------------------------------------------------------------------------ -// Update Device Data -//------------------------------------------------------------------------------ -function setDeviceData() { - global $db; - - // Sanitize input - $mac = quotes($_POST['mac']); - $name = urldecode(quotes($_POST['name'])); - $owner = urldecode(quotes($_POST['owner'])); - $type = urldecode(quotes($_POST['type'])); - $vendor = urldecode(quotes($_POST['vendor'])); - $icon = urldecode(quotes($_POST['icon'])); - $favorite = quotes($_POST['favorite']); - $group = urldecode(quotes($_POST['group'])); - $location = urldecode(quotes($_POST['location'])); - $comments = urldecode(quotes($_POST['comments'])); - $parentMac = quotes($_POST['networknode']); - $parentPort = quotes($_POST['networknodeport']); - $ssid = urldecode(quotes($_POST['ssid'])); - $site = quotes($_POST['networksite']); - $staticIP = quotes($_POST['staticIP']); - $scancycle = quotes($_POST['scancycle']); - $alertevents = quotes($_POST['alertevents']); - $alertdown = quotes($_POST['alertdown']); - $relType = quotes($_POST['relType']); - $reqNics = quotes($_POST['reqNics']); - $skiprepeated = quotes($_POST['skiprepeated']); - $newdevice = quotes($_POST['newdevice']); - $archived = quotes($_POST['archived']); - $devFirstConnection = quotes($_POST['devFirstConnection']); - $devLastConnection = quotes($_POST['devLastConnection']); - $ip = quotes($_POST['ip']); - $devCustomProps = quotes($_POST['devCustomProps']); - $createNew = quotes($_POST['createNew']); - $devNewGuid = generateGUID(); - - // An update - if ($_POST['createNew'] == 0) { - // UPDATE SQL query - $sql = "UPDATE Devices SET - devName = '$name', - devOwner = '$owner', - devType = '$type', - devVendor = '$vendor', - devIcon = '$icon', - devFavorite = '$favorite', - devGroup = '$group', - devLocation = '$location', - devComments = '$comments', - devParentMAC = '$parentMac', - devParentPort = '$parentPort', - devSSID = '$ssid', - devSite = '$site', - devStaticIP = '$staticIP', - devScan = '$scancycle', - devAlertEvents = '$alertevents', - devAlertDown = '$alertdown', - devParentRelType = '$relType', - devReqNicsOnline = '$reqNics', - devSkipRepeated = '$skiprepeated', - devIsNew = '$newdevice', - devIsArchived = '$archived', - devCustomProps = '$devCustomProps' - WHERE devMac = '$mac'"; - } else { // An INSERT - $sql = "INSERT INTO Devices ( - devMac, - devName, - devOwner, - devType, - devVendor, - devIcon, - devFavorite, - devGroup, - devLocation, - devComments, - devParentMAC, - devParentPort, - devSSID, - devSite, - devStaticIP, - devScan, - devAlertEvents, - devAlertDown, - devParentRelType, - devReqNicsOnline, - devSkipRepeated, - devIsNew, - devIsArchived, - devLastConnection, - devFirstConnection, - devLastIP, - devGUID, - devCustomProps, - devSourcePlugin - ) VALUES ( - '$mac', - '$name', - '$owner', - '$type', - '$vendor', - '$icon', - '$favorite', - '$group', - '$location', - '$comments', - '$parentMac', - '$parentPort', - '$ssid', - '$site', - '$staticIP', - '$scancycle', - '$alertevents', - '$alertdown', - '$relType', - '$reqNics', - '$skiprepeated', - '$newdevice', - '$archived', - '$devLastConnection', - '$devFirstConnection', - '$ip', - '$devNewGuid', - '$devCustomProps', - 'DUMMY' - )"; - } - - // Execute the query - $result = $db->query($sql); - - // Check the result - if ($result == TRUE) { - echo lang('BackDevices_DBTools_UpdDev'); - } else { - echo lang('BackDevices_DBTools_UpdDevError')."\n\n$sql \n\n". $db->lastErrorMsg(); - } -} - - - //------------------------------------------------------------------------------ // Delete Device //------------------------------------------------------------------------------ @@ -421,25 +275,6 @@ function deleteDeviceEvents() { } } -//------------------------------------------------------------------------------ -// Delete Device Properties -//------------------------------------------------------------------------------ -function resetDeviceProps() { - global $db; - - // sql - $sql = 'UPDATE Devices set devCustomProps = "'.getSettingValue("NEWDEV_devCustomProps").'" WHERE devMac="' . $_REQUEST['mac'] .'"'; - - // execute sql - $result = $db->query($sql); - - // check result - if ($result == TRUE) { - echo lang('Gen_Okay'); - } else { - echo lang('Gen_Error')."\n\n$sql \n\n". $db->lastErrorMsg(); - } -} //------------------------------------------------------------------------------ // Delete all devices @@ -767,69 +602,6 @@ function updateNetworkLeaf() } -//------------------------------------------------------------------------------ -// Wake-on-LAN -// Inspired by @leiweibau: https://github.com/leiweibau/Pi.Alert/commit/30427c7fea180670c71a2b790699e5d9e9e88ffd -//------------------------------------------------------------------------------ -function wakeonlan() { - - $WOL_HOST_IP = $_REQUEST['ip']; - $WOL_HOST_MAC = $_REQUEST['mac']; - - if (!filter_var($WOL_HOST_IP, FILTER_VALIDATE_IP)) { - echo "Invalid IP! ". lang('BackDevDetail_Tools_WOL_error'); exit; - } - elseif (!filter_var($WOL_HOST_MAC, FILTER_VALIDATE_MAC)) { - echo "Invalid MAC! ". lang('BackDevDetail_Tools_WOL_error'); exit; - } - - exec('wakeonlan '.$WOL_HOST_MAC , $output); - - echo lang('BackDevDetail_Tools_WOL_okay'); -} - -//------------------------------------------------------------------------------ -// Copy from device -//------------------------------------------------------------------------------ -function copyFromDevice() { - - $MAC_FROM = $_REQUEST['macFrom']; - $MAC_TO = $_REQUEST['macTo']; - - global $db; - - // clean-up temporary table - $sql = "DROP TABLE IF EXISTS temp_devices "; - $result = $db->query($sql); - - // create temporary table with the source data - $sql = "CREATE TABLE temp_devices AS SELECT * FROM Devices WHERE devMac = '". $MAC_FROM . "';"; - $result = $db->query($sql); - - // update temporary table with the correct target MAC - $sql = "UPDATE temp_devices SET devMac = '". $MAC_TO . "';"; - $result = $db->query($sql); - - // delete previous entry - $sql = "DELETE FROM Devices WHERE devMac = '". $MAC_TO . "';"; - $result = $db->query($sql); - - // insert new entry with the correct target MAC from the temporary table - $sql = "INSERT INTO Devices SELECT * FROM temp_devices WHERE devMac = '".$MAC_TO."'"; - $result = $db->query($sql); - - // clean-up temporary table - $sql = "DROP TABLE temp_devices "; - $result = $db->query($sql); - - // check result - if ($result == TRUE) { - echo 'OK'; - } else { - echo lang('BackDevices_Device_UpdDevError'); - } - -} //------------------------------------------------------------------------------ // Status Where conditions diff --git a/front/php/server/internetinfo.php b/front/php/server/internetinfo.php deleted file mode 100755 index 4fb1df3e..00000000 --- a/front/php/server/internetinfo.php +++ /dev/null @@ -1,59 +0,0 @@ -"; - echo $output; - echo ""; - exit; -} - -// Replace "{" with "" -$output = str_replace("{", "", $output); - -// Replace "}" with "" -$output = str_replace("}", "", $output); - -// Replace "," with "" -$output = str_replace(",", "", $output); - -// Replace '"' with "" -$output = str_replace('"', "", $output); - -// Show the result -echo "
";
-echo $output;
-echo "
"; - -?> diff --git a/front/php/server/nmap_scan.php b/front/php/server/nmap_scan.php deleted file mode 100755 index e07dd7f1..00000000 --- a/front/php/server/nmap_scan.php +++ /dev/null @@ -1,44 +0,0 @@ -Scan ('.$PIA_SCAN_MODE.') Results of: '.$PIA_HOST_IP.'
' - .'
';
-
-    foreach($output as $line){
-        $message = $message .$line . "
"; - } - - $message = $message .'
'; - - displayMessage($message, $logAlert = FALSE, $logConsole = TRUE, $logFile = TRUE, $logEcho = TRUE); - - -} else -{ - echo '

Internal error.

'; -} diff --git a/front/php/server/nslookup.php b/front/php/server/nslookup.php deleted file mode 100755 index 15e3c842..00000000 --- a/front/php/server/nslookup.php +++ /dev/null @@ -1,50 +0,0 @@ -"; - echo $output; - echo ""; - exit; -} - -// Test with the "nslookup" command -$output = shell_exec("nslookup $ip"); - -// Show the result -echo "
";
-echo $output;
-echo "
"; - -?> diff --git a/front/php/server/speedtestcli.php b/front/php/server/speedtestcli.php deleted file mode 100755 index d067a898..00000000 --- a/front/php/server/speedtestcli.php +++ /dev/null @@ -1,56 +0,0 @@ -' . lang('Speedtest_Results') . ''; - -if ($returnCode !== 0 || empty($output)) { - $errorMessage = $returnCode === 127 - ? 'speedtest-cli command not found. Checked paths: ' . $safePath - : (empty($output) ? 'speedtest-cli returned no output.' : implode("\n", $output)); - - echo '
' . htmlspecialchars('Speedtest failed: ' . $errorMessage, ENT_QUOTES, 'UTF-8') . '
'; - return; -} - -echo '
';
-foreach ($output as $line) {
-    echo htmlspecialchars($line, ENT_QUOTES, 'UTF-8') . "\n";
-}
-echo '
'; -?> diff --git a/front/php/server/traceroute.php b/front/php/server/traceroute.php deleted file mode 100755 index 0b26178d..00000000 --- a/front/php/server/traceroute.php +++ /dev/null @@ -1,51 +0,0 @@ -"; - echo $output; - echo ""; - exit; -} - -// Test with the "Traceroute" command -$output = shell_exec("traceroute $ip"); - -// Show the result -echo "
";
-echo $output;
-echo "
"; - -?> diff --git a/front/systeminfoNetwork.php b/front/systeminfoNetwork.php index 7a5fc4f0..048a47f3 100755 --- a/front/systeminfoNetwork.php +++ b/front/systeminfoNetwork.php @@ -31,12 +31,6 @@ function getExternalIp() { // Network // ---------------------------------------------------------- - - -// ---------------------------------------------------- -// Network Stats (General) -// ---------------------------------------------------- - // External IP $externalIp = getExternalIp(); @@ -58,12 +52,9 @@ $network_referer = !empty($_SERVER['HTTP_REFERER']) // ---------------------------------------------------- -// Network Hardware Stats (FAST VERSION) +// Network Hardware Stats // ---------------------------------------------------- -// ---------------------------------------------------- -// Network Stats (General) -// ---------------------------------------------------- // External IP $externalIp = getExternalIp(); @@ -345,12 +336,13 @@ function formatDataSize(bytes) { function loadInterfaces() { - const apiToken = getSetting("API_TOKEN"); + const apiToken = getSetting("API_TOKEN"); const host = window.location.hostname; + const protocol = window.location.protocol; const port = getSetting("GRAPHQL_PORT"); $.ajax({ - url: "http://" + host + ":" + port + "/nettools/interfaces", + url: `${protocol}//${host}:${port}/nettools/interfaces`, type: "GET", headers: { "Authorization": "Bearer " + apiToken, diff --git a/server/api_server/nettools_endpoint.py b/server/api_server/nettools_endpoint.py index c2f2c80e..6a15ba41 100755 --- a/server/api_server/nettools_endpoint.py +++ b/server/api_server/nettools_endpoint.py @@ -1,5 +1,6 @@ import subprocess import re +import json import sys import ipaddress import shutil @@ -94,7 +95,7 @@ def traceroute(ip): check=True, # Raise CalledProcessError on non-zero exit ) # Return success response with traceroute output - return jsonify({"success": True, "output": result.stdout.strip()}) + return jsonify({"success": True, "output": result.stdout.strip().splitlines()}) # -------------------------- # Step 3: Handle command errors @@ -247,29 +248,24 @@ def internet_info(): Returns JSON with the info or error. """ try: - # Perform the request via curl result = subprocess.run( - ["curl", "-s", "https://ipinfo.io"], + ["curl", "-s", "https://ipinfo.io/json"], capture_output=True, text=True, check=True, ) - output = result.stdout.strip() - if not output: + if not result.stdout: raise ValueError("Empty response from ipinfo.io") - # Clean up the JSON-like string by removing { } , and " - cleaned_output = ( - output.replace("{", "") - .replace("}", "") - .replace(",", "") - .replace('"', "") - ) + data = json.loads(result.stdout) - return jsonify({"success": True, "output": cleaned_output}) + return jsonify({ + "success": True, + "output": data + }) - except (subprocess.CalledProcessError, ValueError) as e: + except (subprocess.CalledProcessError, ValueError, json.JSONDecodeError) as e: return jsonify( { "success": False, diff --git a/test/api_endpoints/test_nettools_endpoints.py b/test/api_endpoints/test_nettools_endpoints.py index a860636e..9bacd5bf 100644 --- a/test/api_endpoints/test_nettools_endpoints.py +++ b/test/api_endpoints/test_nettools_endpoints.py @@ -127,7 +127,8 @@ def test_traceroute_device(client, api_token, test_mac): data = resp.json assert data.get("success") is True assert "output" in data - assert isinstance(data["output"], str) + assert isinstance(data["output"], list) + assert all(isinstance(line, str) for line in data["output"]) @pytest.mark.parametrize("ip,expected_status", [ @@ -201,8 +202,8 @@ def test_internet_info_endpoint(client, api_token): if resp.status_code == 200: assert data.get("success") is True - assert isinstance(data.get("output"), str) - assert len(data["output"]) > 0 # ensure output is not empty + assert isinstance(data.get("output"), dict) + assert len(data["output"]) > 0 # ensure output is not empty else: # Handle errors, e.g., curl failure assert data.get("success") is False