Skip to content

Commit 0727798

Browse files
committed
FE: refactor apiBase
Signed-off-by: jokob-sk <jokob.sk@gmail.com>
1 parent 49a075c commit 0727798

10 files changed

Lines changed: 76 additions & 92 deletions

docs/DEBUG_INVALID_JSON.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ Check the the HTTP response of the failing backend call by following these steps
99

1010
- Copy the URL causing the error and enter it in the address bar of your browser directly and hit enter. The copied URLs could look something like this (notice the query strings at the end):
1111
- `http://<server>:20211/api/table_devices.json?nocache=1704141103121`
12-
- `http://<server>:20211/php/server/devices.php?action=getDevicesTotals`
1312

1413

1514
- Post the error response in the existing issue thread on GitHub or create a new issue and include the redacted response of the failing query.

front/deviceDetails.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -418,8 +418,8 @@ function initializeTabs () {
418418
// Get data from the server
419419
const apiToken = getSetting("API_TOKEN");
420420

421-
const apiBase = getApiBase();
422-
const url = `${apiBase}/device/${getMac()}?period=${encodeURIComponent(period)}`;
421+
const apiBaseUrl = getApiBase();
422+
const url = `${apiBaseUrl}/device/${getMac()}?period=${encodeURIComponent(period)}`;
423423

424424
const response = await fetch(url, {
425425
method: "GET",

front/deviceDetailsEdit.php

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@ function getDeviceData() {
4646
const apiToken = getSetting("API_TOKEN");
4747
let period = $("#period").val()
4848

49-
const apiBase = getApiBase();
50-
const url = `${apiBase}/device/${mac}?period=${encodeURIComponent(period)}`;
49+
const apiBaseUrl = getApiBase();
50+
const url = `${apiBaseUrl}/device/${mac}?period=${encodeURIComponent(period)}`;
5151

5252
// get data from server
5353
$.ajax({
@@ -89,7 +89,7 @@ function getDeviceData() {
8989
]
9090
};
9191

92-
const graphQlUrl = `${apiBase}/graphql`;
92+
const graphQlUrl = `${apiBaseUrl}/graphql`;
9393

9494
$.ajax({
9595
url: graphQlUrl,
@@ -354,7 +354,7 @@ function setDeviceData(direction = '', refreshCallback = '') {
354354
showSpinner();
355355

356356
const apiToken = getSetting("API_TOKEN"); // dynamic token
357-
const apiBase = getApiBase();
357+
const apiBaseUrl = getApiBase();
358358

359359
mac = $('#NEWDEV_devMac').val();
360360

@@ -402,7 +402,7 @@ function setDeviceData(direction = '', refreshCallback = '') {
402402

403403

404404
$.ajax({
405-
url: `${apiBase}/device/${encodeURIComponent(mac)}`,
405+
url: `${apiBaseUrl}/device/${encodeURIComponent(mac)}`,
406406
type: "POST",
407407
headers: {
408408
"Authorization": "Bearer " + apiToken,

front/deviceDetailsEvents.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,8 @@ function loadEventsData() {
5050

5151
const apiToken = getSetting("API_TOKEN");
5252

53-
const apiBase = getApiBase();
54-
const url = `${apiBase}/dbquery/read`;
53+
const apiBaseUrl = getApiBase();
54+
const url = `${apiBaseUrl}/dbquery/read`;
5555

5656
$.ajax({
5757
url: url,

front/deviceDetailsPresence.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,8 @@
3838
function loadPresenceData() {
3939
const apiToken = getSetting("API_TOKEN");
4040

41-
const apiBase = getApiBase();
42-
const url = `${apiBase}/sessions/calendar`;
41+
const apiBaseUrl = getApiBase();
42+
const url = `${apiBaseUrl}/sessions/calendar`;
4343

4444
$('#calendar').fullCalendar('removeEventSources');
4545

front/deviceDetailsSessions.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,8 @@ function loadSessionsData() {
105105
// Build API base
106106
const apiToken = getSetting("API_TOKEN");
107107

108-
const apiBase = getApiBase();
109-
const url = `${apiBase}/sessions/${getMac()}?period=${encodeURIComponent(period)}`;
108+
const apiBaseUrl = getApiBase();
109+
const url = `${apiBaseUrl}/sessions/${getMac()}?period=${encodeURIComponent(period)}`;
110110

111111
// Call API with Authorization header
112112
$.ajax({

front/deviceDetailsTools.php

Lines changed: 12 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -211,22 +211,16 @@ class="btn btn-default pa-btn pa-btn-delete"
211211

212212
<script>
213213

214-
const protocol = window.location.protocol;
215-
const host = window.location.hostname;
216-
const port = getSetting("GRAPHQL_PORT");
217-
const apiToken = getSetting("API_TOKEN");
214+
const apiToken = getSetting("API_TOKEN");
215+
const apiBaseUrl = getApiBase();
218216

219217
// ----------------------------------------------------------------
220218
function manualnmapscan(targetip, mode) {
221219
$("#scanoutput").empty();
222220

223-
224-
const baseUrl = getApiBase();
225-
226-
227221
$.ajax({
228222
method: "POST",
229-
url: `${baseUrl}/nettools/nmap`,
223+
url: `${apiBaseUrl}/nettools/nmap`,
230224
contentType: "application/json",
231225
dataType: "json",
232226
data: JSON.stringify({
@@ -265,7 +259,7 @@ function speedtestcli() {
265259

266260
$.ajax({
267261
method: "GET",
268-
url: `${protocol}//${host}:${port}/nettools/speedtest`,
262+
url: `${apiBaseUrl}/nettools/speedtest`,
269263
headers: {
270264
"Authorization": "Bearer " + apiToken,
271265
"Content-Type": "application/json"
@@ -316,7 +310,7 @@ function traceroute() {
316310

317311
$.ajax({
318312
method: "POST",
319-
url: `${protocol}//${host}:${port}/nettools/traceroute`,
313+
url: `${apiBaseUrl}/nettools/traceroute`,
320314
headers: {
321315
"Authorization": "Bearer " + apiToken,
322316
"Content-Type": "application/json"
@@ -362,11 +356,9 @@ function nslookup() {
362356

363357
$("#nslookupoutput").empty();
364358

365-
366-
367359
$.ajax({
368360
method: "POST",
369-
url: `${protocol}//${host}:${port}/nettools/nslookup`,
361+
url: `${apiBaseUrl}/nettools/nslookup`,
370362
headers: {
371363
"Authorization": "Bearer " + apiToken,
372364
"Content-Type": "application/json"
@@ -450,7 +442,7 @@ function wakeonlan() {
450442

451443
$.ajax({
452444
method: "POST",
453-
url: `${protocol}//${host}:${port}/nettools/wakeonlan`,
445+
url: `${apiBaseUrl}/nettools/wakeonlan`,
454446
headers: {
455447
"Authorization": "Bearer " + apiToken,
456448
"Content-Type": "application/json"
@@ -492,7 +484,7 @@ function copyFromDevice() {
492484

493485
$.ajax({
494486
method: "POST",
495-
url: `${protocol}//${host}:${port}/device/copy`,
487+
url: `${apiBaseUrl}/device/copy`,
496488
headers: {
497489
"Authorization": "Bearer " + apiToken,
498490
"Content-Type": "application/json"
@@ -585,18 +577,14 @@ function deleteDeviceEvents () {
585577
return;
586578
}
587579

588-
const protocol = window.location.protocol; // "http:" or "https:"
589-
const host = window.location.hostname; // current hostname
590-
const port = getSetting("GRAPHQL_PORT"); // your dynamic port
591580
const apiToken = getSetting("API_TOKEN"); // optional token if needed
592581

593-
// Build base URL dynamically
594-
const baseUrl = getApiBase();
582+
595583

596584
// Delete device events
597585
$.ajax({
598586
method: "DELETE",
599-
url: `${baseUrl}/device/${encodeURIComponent(mac)}/events/delete`,
587+
url: `${apiBaseUrl}/device/${encodeURIComponent(mac)}/events/delete`,
600588
headers: {
601589
"Authorization": "Bearer " + apiToken
602590
},
@@ -641,11 +629,9 @@ function resetDeviceProps () {
641629
return;
642630
}
643631

644-
const baseUrl = getApiBase();
645-
646632
$.ajax({
647633
method: "POST",
648-
url: `${baseUrl}/device/${encodeURIComponent(mac)}/reset-props`,
634+
url: `${apiBaseUrl}/device/${encodeURIComponent(mac)}/reset-props`,
649635
dataType: "json",
650636
headers: {
651637
"Authorization": "Bearer " + apiToken
@@ -675,7 +661,7 @@ function internetinfo() {
675661

676662
$.ajax({
677663
method: "GET",
678-
url: `${protocol}//${host}:${port}/nettools/internetinfo`,
664+
url: `${apiBaseUrl}/nettools/internetinfo`,
679665
headers: {
680666
"Authorization": "Bearer " + apiToken,
681667
"Content-Type": "application/json"

front/php/server/devices.php

Lines changed: 0 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@
4444
case 'ExportCSV': ExportCSV(); break; // equivalent: export_devices
4545
case 'ImportCSV': ImportCSV(); break; // equivalent: import_csv
4646

47-
case 'getDevicesTotals': getDevicesTotals(); break; // equivalent: devices_totals
4847
case 'getDevicesListCalendar': getDevicesListCalendar(); break; // equivalent: devices_by_status
4948

5049
case 'updateNetworkLeaf': updateNetworkLeaf(); break; // equivalent: update_device_column(mac, column_name, column_value)
@@ -338,41 +337,6 @@ function ImportCSV() {
338337
}
339338

340339

341-
//------------------------------------------------------------------------------
342-
// Query total numbers of Devices by status
343-
//------------------------------------------------------------------------------
344-
function getDevicesTotals() {
345-
346-
$resultJSON = "";
347-
348-
if(getCache("getDevicesTotals") != "")
349-
{
350-
$resultJSON = getCache("getDevicesTotals");
351-
} else
352-
{
353-
global $db;
354-
355-
// combined query
356-
$result = $db->query(
357-
'SELECT
358-
(SELECT COUNT(*) FROM Devices '. getDeviceCondition ('my').') as devices,
359-
(SELECT COUNT(*) FROM Devices '. getDeviceCondition ('connected').') as connected,
360-
(SELECT COUNT(*) FROM Devices '. getDeviceCondition ('favorites').') as favorites,
361-
(SELECT COUNT(*) FROM Devices '. getDeviceCondition ('new').') as new,
362-
(SELECT COUNT(*) FROM Devices '. getDeviceCondition ('down').') as down,
363-
(SELECT COUNT(*) FROM Devices '. getDeviceCondition ('archived').') as archived
364-
');
365-
366-
$row = $result -> fetchArray (SQLITE3_NUM);
367-
$resultJSON = json_encode (array ($row[0], $row[1], $row[2], $row[3], $row[4], $row[5]));
368-
369-
// save to cache
370-
setCache("getDevicesTotals", $resultJSON );
371-
}
372-
373-
echo ($resultJSON);
374-
}
375-
376340
//------------------------------------------------------------------------------
377341
// Determine if Random MAC
378342
//------------------------------------------------------------------------------

front/plugins/_publisher_mqtt/mqtt.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -567,7 +567,7 @@ def publish_notifications(db, mqtt_client):
567567
try:
568568
payload = json.loads(payload_str) # Deserialize JSON string
569569
except Exception as e:
570-
mylog('minimal', [f"[{pluginName}] ⚠ ERROR decoding JSON for notification GUID {notification["GUID"]}: {e}"])
570+
mylog('minimal', [f"[{pluginName}] ⚠ ERROR decoding JSON for notification GUID {notification['GUID']}: {e}"])
571571
continue # skip this notification
572572
else:
573573
# fallback generic payload (like webhook does)

front/presence.php

Lines changed: 50 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -352,27 +352,62 @@ function initializeCalendar () {
352352

353353

354354
// -----------------------------------------------------------------------------
355+
/**
356+
* Fetch device totals from the API and update dashboard counters.
357+
*
358+
* This function:
359+
* - Stops the automatic refresh timer
360+
* - Calls the `/devices/totals` API endpoint using Bearer token authentication
361+
* - Updates the device summary boxes (all, connected, favorites, new, down, archived)
362+
* - Restarts the refresh timer after completion
363+
*
364+
* Expected API response format:
365+
* [
366+
* devices, // Total devices
367+
* connected, // Currently connected devices
368+
* favorites, // Favorite devices
369+
* new, // Newly discovered devices
370+
* down, // Devices marked as down
371+
* archived // Archived / hidden devices
372+
* ]
373+
*/
355374
function getDevicesTotals () {
356375
// stop timer
357376
stopTimerRefreshData();
358377

359-
// get totals and put in boxes
360-
$.get('php/server/devices.php?action=getDevicesTotals', function(data) {
361-
var totalsDevices = JSON.parse(data);
378+
const apiToken = getSetting("API_TOKEN");
379+
const apiBaseUrl = getApiBase();
380+
const totalsUrl = `${apiBaseUrl}/devices/totals`;
362381

363-
$('#devicesAll').html (totalsDevices[0].toLocaleString());
364-
$('#devicesConnected').html (totalsDevices[1].toLocaleString());
365-
$('#devicesFavorites').html (totalsDevices[2].toLocaleString());
366-
$('#devicesNew').html (totalsDevices[3].toLocaleString());
367-
$('#devicesDown').html (totalsDevices[4].toLocaleString());
368-
$('#devicesHidden').html (totalsDevices[5].toLocaleString());
382+
$.ajax({
383+
url: totalsUrl,
384+
method: "GET",
385+
headers: {
386+
"Authorization": `Bearer ${apiToken}`
387+
},
388+
success: function (totalsDevices) {
389+
390+
$('#devicesAll').html (totalsDevices[0].toLocaleString());
391+
$('#devicesConnected').html (totalsDevices[1].toLocaleString());
392+
$('#devicesFavorites').html (totalsDevices[2].toLocaleString());
393+
$('#devicesNew').html (totalsDevices[3].toLocaleString());
394+
$('#devicesDown').html (totalsDevices[4].toLocaleString());
395+
$('#devicesHidden').html (totalsDevices[5].toLocaleString());
369396

370-
// Timer for refresh data
371-
newTimerRefreshData (getDevicesTotals);
372-
} );
397+
// Timer for refresh data
398+
newTimerRefreshData(getDevicesTotals);
399+
},
400+
error: function (xhr) {
401+
console.error("Failed to load device totals:", xhr.responseText);
402+
403+
// Ensure refresh loop continues even on failure
404+
newTimerRefreshData(getDevicesTotals);
405+
}
406+
});
373407
}
374408

375409

410+
376411
// -----------------------------------------------------------------------------
377412
function getDevicesPresence (status) {
378413
// Save status selected
@@ -423,12 +458,12 @@ function getDevicesPresence (status) {
423458

424459
const apiToken = getSetting("API_TOKEN");
425460

426-
const apiBase = getApiBase();
461+
const apiBaseUrl = getApiBase();
427462

428463
// -----------------------------
429464
// Load Devices as Resources
430465
// -----------------------------
431-
const devicesUrl = `${apiBase}/devices/by-status?status=${deviceStatus}`;
466+
const devicesUrl = `${apiBaseUrl}/devices/by-status?status=${deviceStatus}`;
432467

433468
$.ajax({
434469
url: devicesUrl,
@@ -451,7 +486,7 @@ function getDevicesPresence (status) {
451486
// -----------------------------
452487
// Load Events
453488
// -----------------------------
454-
const eventsUrl = `${apiBase}/sessions/calendar?start=${startDate}&end=${endDate}`;
489+
const eventsUrl = `${apiBaseUrl}/sessions/calendar?start=${startDate}&end=${endDate}`;
455490

456491
$('#calendar').fullCalendar('removeEventSources');
457492
$('#calendar').fullCalendar('addEventSource', {

0 commit comments

Comments
 (0)