-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
602 lines (538 loc) · 24 KB
/
index.php
File metadata and controls
602 lines (538 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
<?php
/**
* HomeSplash
*
* This script generates a server dashboard with configurable settings and links.
*
* Copyright (C) 2024 Jules Potvin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
if (is_file("config.php")) { include "config.php"; }
if (!is_dir('icons')) { mkdir('icons', 0755, true); }
if (!is_file('config.php')) {
$defaultConfig = "<?php\n\$server_name = 'My Server';\n\$server_desc = 'Description';\n\$color_bg = '#222222';\n\$color_name = '#ffffff';\n\$color_text = '#cccccc';\n\$showdisk = '/';\n\$custom_css = '';\n";
file_put_contents('config.php', $defaultConfig);
include 'config.php';
}
$windows = defined("PHP_WINDOWS_VERSION_MAJOR");
$mac = PHP_OS == "Darwin";
/* ---------------- SYSTEM STATS ---------------- */
function hs_powershell_json($psScript) {
// Returns decoded JSON array/object, or null on failure.
// Use -ExecutionPolicy Bypass for typical IIS/Windows PHP setups.
$cmd = 'powershell -NoProfile -ExecutionPolicy Bypass -Command ' . escapeshellarg($psScript);
$out = @shell_exec($cmd);
if (!$out) { return null; }
$decoded = json_decode($out, true);
return is_array($decoded) ? $decoded : null;
}
if ($windows) {
// WMIC has been deprecated/removed on newer Windows builds, so we:
// 1) try WMIC (for older boxes)
// 2) fall back to PowerShell CIM (recommended)
$drives = [];
$show_disk_usage = 0;
$memory = 0; $mem_total = 0; $mem_used = 0;
$uptime = 'N/A';
$num_cpus = (int)($_SERVER['NUMBER_OF_PROCESSORS'] ?? getenv('NUMBER_OF_PROCESSORS') ?? 1);
$df = @shell_exec("wmic logicaldisk get size,freespace,caption");
if ($df) {
preg_match_all('/\b([A-Z]):[^\d]*(\d+)[^\d]*(\d+)/', $df, $m, PREG_SET_ORDER);
foreach ($m as $x) {
$total = (int)$x[3];
$free = (int)$x[2];
$used = max(0, $total - $free);
$pct = $total ? round($used / $total * 100) : 0;
$drives[] = ['drive'=>$x[1].':', 'total'=>$total, 'used'=>$used, 'percent'=>$pct];
}
// If $showdisk is '/', default to system drive (e.g., C:)
$target = $showdisk ?? '';
$target = trim((string)$target);
if ($target === '' || $target === '/') {
$target = (string)($_SERVER['SystemDrive'] ?? getenv('SystemDrive') ?? 'C:');
}
$target = strtoupper(rtrim($target, "\\/"));
foreach ($drives as $d) {
if (strtoupper(rtrim($d['drive'], "\\/")) === $target) { $show_disk_usage = (int)$d['percent']; break; }
}
} else {
// PowerShell fallback (recommended on modern Windows)
$ps = <<<'PS'
$ErrorActionPreference = "Stop"
$os = Get-CimInstance Win32_OperatingSystem
$dr = Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | Select-Object DeviceID,Size,FreeSpace
$cs = Get-CimInstance Win32_ComputerSystem
$upt = (Get-Date) - $os.LastBootUpTime
$uptStr = if ($upt.Days -gt 0) { "{0}d {1}h" -f $upt.Days, $upt.Hours } else { "{0}h {1}m" -f $upt.Hours, $upt.Minutes }
[pscustomobject]@{
uptime = $uptStr
totalMemKB = [int64]$os.TotalVisibleMemorySize
freeMemKB = [int64]$os.FreePhysicalMemory
cpuThreads = [int]$cs.NumberOfLogicalProcessors
drives = $dr
} | ConvertTo-Json -Depth 4
PS;
$j = hs_powershell_json($ps);
if ($j) {
$uptime = $j['uptime'] ?? 'N/A';
$num_cpus = (int)($j['cpuThreads'] ?? $num_cpus);
$totalKB = (int)($j['totalMemKB'] ?? 0);
$freeKB = (int)($j['freeMemKB'] ?? 0);
$usedKB = max(0, $totalKB - $freeKB);
$mem_total = $totalKB ? (int)round($totalKB / 1024) : 0; // MB
$mem_used = $totalKB ? (int)round($usedKB / 1024) : 0; // MB
$memory = $totalKB ? (int)round(($usedKB / $totalKB) * 100) : 0;
$rows = $j['drives'] ?? [];
// PowerShell returns either an array or a single object depending on count
if (isset($rows['DeviceID'])) { $rows = [$rows]; }
foreach ($rows as $r) {
$drive = (string)($r['DeviceID'] ?? '');
$total = (int)($r['Size'] ?? 0);
$free = (int)($r['FreeSpace'] ?? 0);
$used = max(0, $total - $free);
$pct = $total ? (int)round($used / $total * 100) : 0;
if ($drive !== '') {
$drives[] = ['drive'=>$drive, 'total'=>$total, 'used'=>$used, 'percent'=>$pct];
}
}
$target = $showdisk ?? '';
$target = trim((string)$target);
if ($target === '' || $target === '/') {
$target = (string)($_SERVER['SystemDrive'] ?? getenv('SystemDrive') ?? 'C:');
}
$target = strtoupper(rtrim($target, "\\/"));
foreach ($drives as $d) {
if (strtoupper(rtrim($d['drive'], "\\/")) === $target) { $show_disk_usage = (int)$d['percent']; break; }
}
}
}
} else {
$uptime_raw = $mac
? time() - (int)rtrim(shell_exec("/usr/sbin/sysctl -n kern.boottime | awk '{print $4}'"), ",\n")
: (int)explode('.', file_get_contents('/proc/uptime'))[0];
$days=floor($uptime_raw/86400);
$hours=floor($uptime_raw/3600)%24;
$mins=floor($uptime_raw/60)%60;
$uptime=$days>0?"{$days}d {$hours}h":"{$hours}h {$mins}m";
$drives=[];
foreach(explode("\n",trim(shell_exec("df -P -T"))) as $i=>$l){
if($i==0)continue;
$p=preg_split('/\s+/',$l);
if(count($p)>=7){
$drives[]=[
'drive'=>$p[6],
'total'=>(int)$p[2],
'used'=>(int)$p[3],
'percent'=>(int)rtrim($p[5],'%'),
];
}
}
$show_disk_usage=0;
foreach($drives as $d){ if($d['drive']===$showdisk){$show_disk_usage=$d['percent'];break;} }
preg_match('/Mem:\s+(\d+)\s+(\d+)/', shell_exec("free -m"), $mm);
$mem_total=$mm[1]??0; $mem_used=$mm[2]??0;
$memory=$mem_total?round($mem_used/$mem_total*100):0;
$num_cpus = (int)shell_exec("nproc");
}
/* ---------------- JSON ENDPOINTS ---------------- */
if(isset($_GET['json'])){
header("Content-Type: application/json");
echo json_encode([
'uptime'=>$uptime??'N/A',
'memory'=>$memory,
'memory_total'=>$mem_total,
'memory_used'=>$mem_used,
'show_disk_usage'=>$show_disk_usage,
'drives'=>$drives,
'num_cpus'=>$num_cpus,
]);
exit;
}
if(isset($_GET['configjson'])){
header("Content-Type: application/json");
echo json_encode([
"server_name" => $server_name ?? "",
"server_desc" => $server_desc ?? "",
"color_bg" => $color_bg ?? "",
"color_name" => $color_name ?? "",
"color_text" => $color_text ?? "",
"showdisk" => $showdisk ?? "",
"custom_css" => $custom_css ?? "",
]);
exit;
}
$ringBase=339.292;
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $server_name; ?></title>
<link rel="stylesheet" href="https://unpkg.com/tabulator-tables@5.4.4/dist/css/tabulator.min.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style type="text/css">
body { height: 100vh; padding: 0; margin: 0; display: flex; flex-direction: column; font-family: -apple-system, sans-serif; background: <?php echo $color_bg; ?>; }
.main { padding: 6.5rem 15% 1rem 15%; color: <?php echo $color_name; ?>; }
.main h1 { font-size: 4rem; font-weight: 300; margin: 0; }
.main p { font-size: 2rem; color: <?php echo $color_text; ?>; margin: 0; }
.content { flex: 1; overflow-y: auto; padding: 2rem 15%; }
.footer { display: flex; align-items: center; padding: 3rem 15%; color: <?php echo $color_text; ?>; }
.uptime-sec { margin-right: 2.5rem; white-space: nowrap; }
.ring-container { position: relative; display: flex; align-items: center; margin-right: 2rem; }
.ring { transform: rotate(-90deg); fill: none; stroke-width: 12; height: 2.5rem; width: 2.5rem; margin-left: 0.7rem; }
.ring-background { stroke: rgba(127,127,127,0.15); }
.ring-value { stroke: <?php echo $color_text; ?>; stroke-dasharray: <?php echo $ringBase; ?>; transition: stroke-dashoffset 0.4s; }
.ring-label { position: absolute; right: 4px; width: 32px; text-align: center; font-size: 0.8rem; font-weight: bold; color: <?php echo $color_text; ?>; pointer-events: none; }
.footer-end { margin-left: auto; white-space: nowrap; }
a { color: <?php echo $color_name; ?>; text-decoration: none; cursor: pointer; }
/* Details panel (wrap-safe so it doesn't disappear off-screen) */
.details {
z-index: 100; position: fixed; bottom: 0; left: 0; width: 100%;
background: <?php echo $color_text; ?>; color: <?php echo $color_bg; ?>;
padding: 2em 15%;
transform: translateY(100%);
transition: transform .3s cubic-bezier(.15,.75,.55,1);
display: flex; flex-wrap: wrap; gap: 2rem; justify-content: flex-start; align-items: flex-start;
box-sizing: border-box;
}
.details.open { transform: translateY(0); }
.details > div { flex: 1 1 320px; min-width: 0; }
#stat-details { text-align: right; overflow-wrap: anywhere; }
.overlay { z-index: 90; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: black; opacity: 0.4; }
.form-group { display: flex; margin-bottom: 12px; align-items: center; gap: 12px; }
.form-group label { flex: 0 0 120px; text-align: right; margin-right: 0; }
.form-group input[type="text"], .form-group textarea { flex: 1; padding: 6px; box-sizing: border-box; min-width: 0; }
.form-group textarea { min-height: 120px; resize: vertical; }
.upload-row{display:flex;gap:10px;align-items:center;justify-content:flex-end;margin-top:6px}
.upload-row input[type="file"]{max-width:100%}
#icon-preview{width:36px;height:36px;object-fit:contain;display:none;border-radius:6px;background:rgba(0,0,0,.08);padding:4px}
.ui-dialog .ui-dialog-content{overflow:visible}
<?php echo $custom_css; ?>
</style>
</head>
<body>
<main class="main">
<h1><?php echo $server_name; ?></h1>
<p><?php echo $server_desc; ?></p>
</main>
<div class="content">
<div id="links-grid"></div>
</div>
<footer class="footer">
<div class="uptime-sec">Uptime: <span id="uptime">...</span></div>
<div class="ring-container" id="k-disk">Disk: <svg class="ring" viewBox="0 0 120 120"><circle class="ring-background" cx="60" cy="60" r="54"/><circle class="ring-value" cx="60" cy="60" r="54"/></svg><div class="ring-label">0</div></div>
<div class="ring-container" id="k-memory">Mem: <svg class="ring" viewBox="0 0 120 120"><circle class="ring-background" cx="60" cy="60" r="54"/><circle class="ring-value" cx="60" cy="60" r="54"/></svg><div class="ring-label">0</div></div>
<div class="footer-end"><a id="btn-detail">Detail</a> | <a id="edit-links">Links</a> | <a id="edit-config">Config</a></div>
</footer>
<div class="details">
<div><h2 style="margin:0;"><?php echo $windows ? "Windows" : shell_exec("hostname"); ?></h2><p><?php echo $_SERVER["SERVER_ADDR"]; ?></p></div>
<div id="stat-details">Loading stats...</div>
</div>
<div id="links-editor" style="display:none;"><div id="links-table"></div><button id="add-link-btn" style="margin-top:15px; padding: 8px;">Add Link</button></div>
<div id="add-link-form" title="Add Link" style="display:none;">
<form>
<div class="form-group"><label>Enable:</label><input type="checkbox" id="link-enabled" checked style="width:auto;"></div>
<div class="form-group"><label>Name:</label><input type="text" id="link-name"></div>
<div class="form-group"><label>URL:</label><input type="text" id="link-url"></div>
<div class="form-group"><label>Icon:</label><input type="text" id="link-icon" placeholder="icons/myicon.png or https://..."></div>
<div class="upload-row">
<img id="icon-preview" alt="icon preview">
<input type="file" id="icon-file" accept=".png,.jpg,.jpeg,.gif">
<button type="button" id="upload-icon-btn">Upload Icon</button>
</div>
<div id="upload-status" style="margin-top:10px; text-align:right; font-size:0.9rem;"></div>
</form>
</div>
<div id="config-editor" title="Edit Config" style="display:none;">
<form id="config-form">
<div class="form-group"><label>Server Name:</label><input type="text" id="cfg-server-name"></div>
<div class="form-group"><label>Server Desc:</label><input type="text" id="cfg-server-desc"></div>
<div class="form-group"><label>BG Color:</label><input type="text" id="cfg-color-bg" placeholder="#222222"></div>
<div class="form-group"><label>Name Color:</label><input type="text" id="cfg-color-name" placeholder="#ffffff"></div>
<div class="form-group"><label>Text Color:</label><input type="text" id="cfg-color-text" placeholder="#cccccc"></div>
<div class="form-group"><label>Show Disk:</label><input type="text" id="cfg-showdisk" placeholder="C:"></div>
<div class="form-group"><label>Custom CSS:</label><textarea id="cfg-custom-css" placeholder="Optional additional CSS"></textarea></div>
<div id="config-status" style="margin-top:10px; text-align:right; font-size:0.9rem;"></div>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://unpkg.com/tabulator-tables@5.4.4/dist/js/tabulator.min.js"></script>
<script>
const ringBase = <?php echo $ringBase; ?>;
let tableInstance = null;
let saveTimer = null;
function refreshGrid() {
$.getJSON('links.json?v=' + new Date().getTime(), function(data) {
let html = '<div style="margin-left: 5%;"><table style="width: 90%; border-collapse: separate; border-spacing: 20px;"><tr>';
let count = 0;
if (data.Links) {
data.Links.forEach(link => {
if (link.enabled === true || link.enabled === "true" || link.enabled === undefined) {
html += `<td style="text-align: center; width: 20%;">
<a href="${link.link}" target="_blank" rel="noopener">
<img src="${link.icon}" alt="" width="75" height="75" style="display:block; margin: 0 auto 10px auto;">
${link.name}
</a>
</td>`;
count++;
if (count % 5 === 0) html += '</tr><tr>';
}
});
}
html += '</tr></table></div>';
$('#links-grid').html(html);
});
}
function updateStats() {
$.getJSON('?json=1', function(data) {
$('#uptime').text(data.uptime);
$('#k-disk .ring-value').css('stroke-dashoffset', ringBase * (1 - (data.show_disk_usage / 100)));
$('#k-disk .ring-label').text(data.show_disk_usage);
$('#k-memory .ring-value').css('stroke-dashoffset', ringBase * (1 - (data.memory / 100)));
$('#k-memory .ring-label').text(data.memory);
let driveInfo = '';
(data.drives || []).forEach(d => {
driveInfo += `<b>${d.drive}:</b> ${Math.round(d.used/1024)}GB / ${Math.round(d.total/1024)}GB (${d.percent}%)<br>`;
});
$('#stat-details').html(`${driveInfo}<b>Memory:</b> ${data.memory_used}MB / ${data.memory_total}MB<br><b>CPU Threads:</b> ${data.num_cpus}`);
setTimeout(updateStats, 5000);
});
}
function triggerSaveDebounced() {
clearTimeout(saveTimer);
saveTimer = setTimeout(triggerSave, 150);
}
function triggerSave() {
if (!tableInstance) return;
$.ajax({
url: 'save_links.php',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ Links: tableInstance.getData() }),
success: function() { refreshGrid(); },
error: function(xhr) {
alert("Error saving: " + xhr.status + (xhr.responseText ? ("\n" + xhr.responseText) : ""));
}
});
}
function buildLinksTable(linksData) {
if (tableInstance) {
try { tableInstance.destroy(); } catch(e) {}
tableInstance = null;
}
tableInstance = new Tabulator("#links-table", {
data: linksData || [],
layout: "fitColumns",
movableRows: true,
columns: [
{rowHandle:true, formatter:"handle", width:40},
{
title: "Enable", field: "enabled", formatter: "tickCross",
hozAlign: "center", width: 80,
cellClick: function(e, cell) {
cell.setValue(!cell.getValue());
triggerSaveDebounced();
}
},
{ title: "Name", field: "name", editor: "input", cellEdited: function(){ triggerSaveDebounced(); } },
{ title: "Link", field: "link", editor: "input", cellEdited: function(){ triggerSaveDebounced(); } },
{ title: "Icon", field: "icon", editor: "input", cellEdited: function(){ triggerSaveDebounced(); } },
{
formatter: "buttonCross", width: 40,
cellClick: function(e, cell) {
if(confirm("Delete?")) {
cell.getRow().delete();
triggerSaveDebounced();
}
}
}
],
});
// Reliable drag/drop save
tableInstance.on("rowMoved", function(){
triggerSaveDebounced();
});
setTimeout(function(){
if (tableInstance) tableInstance.redraw(true);
}, 0);
}
/* Icon upload (matches your existing upload_icon.php: icon_file + {success, filename}) */
function setUploadStatus(msg, isError=false){
$('#upload-status').text(msg).css('color', isError ? '#b00020' : '#0b6');
}
function updateIconPreview(src){
if (!src) { $('#icon-preview').hide(); return; }
$('#icon-preview').attr('src', src).show();
}
$('#icon-file').on('change', function(){
const f = this.files && this.files[0];
if (!f) return;
updateIconPreview(URL.createObjectURL(f));
setUploadStatus("");
});
$('#upload-icon-btn').on('click', function(){
const fileInput = document.getElementById('icon-file');
const file = fileInput.files && fileInput.files[0];
if (!file) { setUploadStatus("Choose an icon file first.", true); return; }
const fd = new FormData();
fd.append('icon_file', file);
setUploadStatus("Uploading...");
$.ajax({
url: 'upload_icon.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function(resp){
let r = resp;
try { if (typeof resp === 'string') r = JSON.parse(resp); } catch(e) {}
if (!r || !r.success) {
setUploadStatus((r && r.error) ? r.error : "Upload failed.", true);
return;
}
const path = "icons/" + r.filename;
$('#link-icon').val(path);
updateIconPreview(path);
setUploadStatus("Uploaded: " + path);
},
error: function(xhr){
setUploadStatus("Upload error: " + xhr.status + (xhr.responseText ? (" - " + xhr.responseText) : ""), true);
}
});
});
/* Config dialog */
function setConfigStatus(msg, isError=false){
$('#config-status').text(msg).css('color', isError ? '#b00020' : '#0b6');
}
function openConfigDialog(){
setConfigStatus("");
$.getJSON('?configjson=1&v=' + Date.now(), function(cfg){
$('#cfg-server-name').val(cfg.server_name || "");
$('#cfg-server-desc').val(cfg.server_desc || "");
$('#cfg-color-bg').val(cfg.color_bg || "");
$('#cfg-color-name').val(cfg.color_name || "");
$('#cfg-color-text').val(cfg.color_text || "");
$('#cfg-showdisk').val(cfg.showdisk || "");
$('#cfg-custom-css').val(cfg.custom_css || "");
const dlgWidth = Math.min(860, Math.floor($(window).width() * 0.92));
$('#config-editor').dialog({
modal: true,
width: dlgWidth,
maxWidth: 860,
height: 640,
resizable: true,
buttons: {
"Save": function(){
const payload = {
server_name: $('#cfg-server-name').val(),
server_desc: $('#cfg-server-desc').val(),
color_bg: $('#cfg-color-bg').val(),
color_name: $('#cfg-color-name').val(),
color_text: $('#cfg-color-text').val(),
showdisk: $('#cfg-showdisk').val(),
custom_css: $('#cfg-custom-css').val()
};
setConfigStatus("Saving...");
$.ajax({
url: 'save_config.php',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(payload),
success: function(resp){
let r = resp;
try { if (typeof resp === 'string') r = JSON.parse(resp); } catch(e) {}
if (!r || !r.ok) {
setConfigStatus((r && r.error) ? r.error : "Save failed.", true);
return;
}
setConfigStatus("Saved. Reloading...");
setTimeout(function(){ window.location.reload(); }, 400);
},
error: function(xhr){
setConfigStatus("Save error: " + xhr.status + (xhr.responseText ? (" - " + xhr.responseText) : ""), true);
}
});
},
"Cancel": function(){ $(this).dialog('close'); }
}
});
}).fail(function(xhr){
alert("Could not load config: " + xhr.status);
});
}
/* UI hooks */
updateStats();
refreshGrid();
$('#edit-links').click(function(e){
e.preventDefault();
$.getJSON('links.json?v=' + new Date().getTime(), function(data) {
$('#links-editor').dialog({
modal: true,
width: '80%',
height: 600,
open: function() {
buildLinksTable((data && data.Links) ? data.Links : []);
},
close: function() {
if (tableInstance) {
try { tableInstance.destroy(); } catch(e) {}
tableInstance = null;
}
}
});
});
});
$('#add-link-btn').click(function(){
const dlgWidth = Math.min(720, Math.floor($(window).width() * 0.90));
$('#upload-status').text('');
$('#icon-file').val('');
updateIconPreview($('#link-icon').val() || '');
$('#add-link-form').dialog({
modal: true,
width: dlgWidth,
maxWidth: 720,
resizable: false,
position: { my: "center", at: "center", of: window },
buttons: {
"Add": function() {
tableInstance.addRow({
name: $('#link-name').val(),
link: $('#link-url').val(),
icon: $('#link-icon').val(),
enabled: $('#link-enabled').is(':checked')
}, true);
triggerSaveDebounced();
$(this).dialog('close');
$('#add-link-form form')[0].reset();
$('#upload-status').text('');
$('#icon-file').val('');
updateIconPreview('');
},
"Cancel": function() { $(this).dialog('close'); }
}
});
});
$('#edit-config').click(function(e){
e.preventDefault();
openConfigDialog();
});
$('#btn-detail').click(function(){
$('.details').addClass('open');
$('<div class="overlay"></div>').appendTo('body').one('click', function(){
$('.details').removeClass('open');
$(this).remove();
});
});
</script>
</body>
</html>