-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwebui_components.go
More file actions
824 lines (744 loc) · 29.9 KB
/
Copy pathwebui_components.go
File metadata and controls
824 lines (744 loc) · 29.9 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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
/*
File: webui_components.go
Version: 1.27.0
Updated: 31-May-2026 21:20 CEST
Description:
HTML String builders, template injection, and UI logic for the sdproxy web UI.
Changes:
1.27.0 - [UI] Injected dynamic formatting and parsing structures to support the
new `UNTRIGGER` budget bounds inside the UI's table generator cleanly.
1.26.0 - [REFACTOR] Centralized redundant True State color computation logic
into `getDynamicHeaderClass` natively, streamlining device and group
HTML generations organically.
*/
package main
import (
"fmt"
"sort"
"strings"
"time"
)
// ---------------------------------------------------------------------------
// Stat card builders
// ---------------------------------------------------------------------------
// buildStatCardSub renders a stat tile with an extra sub-line below the value.
func buildStatCardSub(id, val, subID, sub, label, subLabel string) string {
return `<div class="stat-card">` +
`<div class="stat-lbl">` + esc(label) + `</div>` +
`<div class="stat-val" id="` + id + `">` + esc(val) + `</div>` +
`<div class="stat-lbl stat-lbl-since">` + esc(subLabel) + `</div>` +
`<div class="stat-sub" id="` + subID + `">` + sub + `</div>` +
`</div>`
}
func buildHourlyGraph() string {
if !cfg.WebUI.StatsGraphsEnabled {
return ""
}
return `<div class="hchart-section">` +
`<div class="section-label">⏱ Activity — Retention Window</div>` +
`<div class="hchart-outer">` +
`<div class="hchart-layout">` +
`<div class="hchart-y" id="hchart-y">` +
`<span>0</span><span>0</span><span>0</span>` +
`</div>` +
`<div id="hourly-chart" class="hchart">` +
`<span class="top10-none">Collecting data…</span>` +
`</div>` +
`</div>` +
`<div class="hchart-legend">` +
`<span class="hchart-dot hchart-fwd"></span>Forwarded` +
` <span class="hchart-dot hchart-blk"></span>Blocked` +
`</div></div></div>`
}
func buildTopNTable(title, tbodyID string, rows []TopEntry, topN int, scrollStyle string) string {
var b strings.Builder
b.WriteString(`<div class="top10-panel">`)
b.WriteString(`<div class="top10-title">` + esc(title) + `</div>`)
b.WriteString(`<div class="top10-tbl-wrap"` + scrollStyle + `>`)
b.WriteString(`<table class="top10-tbl"><tbody id="` + tbodyID + `">`)
if len(rows) == 0 {
b.WriteString(`<tr><td colspan="3"><span class="top10-none">No data yet</span></td></tr>`)
} else {
for i, row := range rows {
rawName := row.Name
filterStr := rawName
if tbodyID == "top-domains" || tbodyID == "top-blocked" || tbodyID == "top-nxdomain" {
filterStr = "-> " + rawName + "."
} else if tbodyID == "top-tlds" {
if !strings.HasPrefix(filterStr, ".") {
filterStr = "." + filterStr
}
filterStr = filterStr + "."
} else if tbodyID == "top-groups" {
filterStr = "(" + rawName + ")"
} else if tbodyID == "top-upstreams" {
filterStr = "ROUTE: " + rawName + " ("
} else if tbodyID == "top-upstream-hosts" {
filterStr = "UPSTREAM: " + rawName
}
fTerm := strings.ReplaceAll(filterStr, "&", "&")
fTerm = strings.ReplaceAll(fTerm, "<", "<")
fTerm = strings.ReplaceAll(fTerm, "\"", """)
n := esc(rawName)
var hintHtml string
if row.Hint != "" {
if tbodyID == "top-talkers" {
n = esc(row.Hint) + " (" + n + ")"
} else if tbodyID == "top-blocked" || tbodyID == "top-tlds" || tbodyID == "top-block-reasons" || tbodyID == "top-filtered-ips" {
hintHtml = `<span class="reason-badge">` + esc(row.Hint) + `</span>`
}
}
linkedName := `<a href="#" class="qlog-link" data-filter="` + fTerm + `" title="View in Query Log">` + n + `</a>`
var addRuleBtn string
if tbodyID == "top-domains" || tbodyID == "top-blocked" || tbodyID == "top-nxdomain" {
addRuleBtn = `<button class="top10-add-rule" data-domain="` + esc(rawName) + `" title="Add to Custom Rules">+</button>`
}
b.WriteString(`<tr>` +
`<td class="top10-rank">` + fmt.Sprintf("%d", i+1) + `</td>` +
`<td class="top10-name">` + linkedName + hintHtml + `</td>` +
`<td class="top10-cnt">` + fmt.Sprintf("%d", row.Count) + addRuleBtn + `</td>` +
`</tr>`)
}
}
b.WriteString(`</tbody></table></div>`)
b.WriteString(`</div>`)
return b.String()
}
// ---------------------------------------------------------------------------
// Group status helpers
// ---------------------------------------------------------------------------
type statusResult struct {
text string
cls string
}
// computeStatus calculates the high-level dynamic runtime state of a group natively.
func computeStatus(name, sk string, grp GroupConfig) statusResult {
// Evaluate dynamic schedule boundaries natively BEFORE state resolution
if len(grp.Schedule) > 0 && !inAnyScheduleWindow(grp.Schedule) {
return statusResult{"Blocked: outside schedule", "st-block"}
}
// An absolute block configuration for the "total" umbrella restricts the entire group unconditionally
if strings.ToUpper(grp.Budget["total"]) == "BLOCK" {
return statusResult{"Blocked: total (config)", "st-block"}
}
if sk == "" {
sk = name
}
parentalStateMu.RLock()
gs, ok := groupStates[sk]
parentalStateMu.RUnlock()
if !ok {
// If no runtime state exists, it means no client has queried yet,
// or it's a device-tracked group summary. Budget constraints are inherently intact.
if strings.ToLower(grp.BudgetTracking) == "device" {
return statusResult{"Allowed", "st-ok"}
}
return statusResult{"No data yet", "st-muted"}
}
gs.mu.Lock()
defer gs.mu.Unlock()
// Dynamic budget exhaustion constraints
if rem, limited := gs.remaining["total"]; limited && rem <= 0 {
return statusResult{"Blocked: total budget exhausted", "st-block"}
}
var cats []string
for c := range gs.remaining {
if c != "total" {
cats = append(cats, c)
}
}
sort.Strings(cats)
// We exclusively report dynamic runtime exhaustion states for categories natively.
// Static configuration blocks (`BLOCK`) are omitted to prevent misleading/redundant UI badges.
for _, cat := range cats {
if rem, ok := gs.remaining[cat]; ok && rem <= 0 {
return statusResult{"Blocked: " + esc(cat) + " budget exhausted", "st-block"}
}
}
return statusResult{"Allowed", "st-ok"}
}
func renderBadge(sr statusResult, extraClass ...string) string {
if sr.text == "" {
return ""
}
cls := "sbadge"
if len(extraClass) > 0 && extraClass[0] != "" {
cls += " " + extraClass[0]
}
return `<span class="` + cls + ` ` + sr.cls + `">` + sr.text + `</span>`
}
// getDynamicHeaderClass cleanly resolves the visual UI color code for a tracking header natively.
func getDynamicHeaderClass(curMode string, grp GroupConfig, gs *groupState) string {
isRed := false
isOrange := false
if gs != nil {
gs.mu.Lock()
if curMode != "ALLOW" && curMode != "LOG" {
if len(grp.Schedule) > 0 && !inAnyScheduleWindow(grp.Schedule) && curMode != "FREE" {
isRed = true // Global Schedule is blocked
} else if gs.hardBlocked["total"] {
isRed = true // The entire group is configured to block by default
} else if rem, limited := gs.remaining["total"]; limited && rem <= 0 && curMode != "FREE" {
isRed = true // Total umbrella time is exhausted
} else if curMode != "FREE" {
for key, rem := range gs.remaining {
if key != "total" && rem <= 0 {
isOrange = true // A specific category is exhausted
break
}
}
}
}
gs.mu.Unlock()
}
if curMode == "BLOCK" {
return " dev-hdr-block" // Mode Override (Red)
} else if curMode == "ALLOW" {
return " dev-hdr-allow" // Mode Override (Green)
} else if curMode == "FREE" {
return " dev-hdr-free" // Mode Override (Yellow)
} else if curMode == "LOG" {
return " dev-hdr-log" // Mode Override (Blue)
} else if isRed {
return " dev-hdr-block" // True State Restricted (Red)
} else if isOrange {
return " dev-hdr-warn" // True State Category Exhausted (Yellow)
}
return ""
}
func buildGroupDetail(name string, grp GroupConfig, rulesCount int, curMode string) string {
var b strings.Builder
b.WriteString(`<div class="detail">`)
isDeviceTracking := strings.ToLower(grp.BudgetTracking) == "device"
sk := ""
if !isDeviceTracking {
sk = name
}
status := computeStatus(name, sk, grp)
upstream := grp.Upstream
if upstream == "" {
upstream = `<span class="muted">inherited</span>`
} else {
upstream = esc(upstream)
}
tracking := grp.BudgetTracking
if tracking == "" {
tracking = "group"
}
// Calculate true dynamically mapped physical device states
activeTrackers := 0
parentalStateMu.RLock()
for k := range groupStates {
if stateToGroup[k] == name {
activeTrackers++
}
}
parentalStateMu.RUnlock()
b.WriteString(`<div class="meta">`)
b.WriteString(`<span>Upstream: <b>` + upstream + `</b></span>`)
b.WriteString(`<span>Tracking: <b>` + esc(tracking) + `</b></span>`)
b.WriteString(fmt.Sprintf(`<span>Static Rules: <b>%d</b></span>`, rulesCount))
b.WriteString(fmt.Sprintf(`<span>Active Trackers: <b>%d</b></span>`, activeTrackers))
// Exposed the actively evaluated schedule time natively to verify time offsets transparently
evalTime := time.Now().Local().Add(time.Duration(cfg.Parental.TimeOffsetHours) * time.Hour)
b.WriteString(`<span>Schedule Time: <b>` + evalTime.Format("02-Jan-2006 15:04") + `</b></span>`)
b.WriteString(renderBadge(status, "group-badge"))
b.WriteString(`</div>`)
// Override Banner Context Injection
if curMode != "DEFAULT" {
var cls, desc string
switch curMode {
case "ALLOW":
cls = "st-allow"
desc = "All time limits, schedules, and explicit blocks are currently <b>bypassed</b>."
case "FREE":
cls = "st-free"
desc = "Time limits and schedules are <b>suspended</b>. Explicit category blocks still apply natively."
case "BLOCK":
cls = "st-block"
desc = "Internet access is <b>completely cut</b> for this group."
case "LOG":
cls = "st-log"
desc = "Log-only mode. All restrictions are bypassed, but categorical queries are heavily logged."
}
if cls != "" {
b.WriteString(`<div class="override-banner ` + cls + `">`)
b.WriteString(`⚠ <strong>OVERRIDE (` + curMode + `):</strong> ` + desc)
b.WriteString(`</div>`)
}
}
if len(grp.Schedule) > 0 {
b.WriteString(`<div class="sched-pills">`)
for _, s := range grp.Schedule {
b.WriteString(`<span class="pill">` + esc(s) + `</span>`)
}
b.WriteString(`</div>`)
}
if isDeviceTracking {
parentalStateMu.RLock()
var deviceKeys []string
for k := range groupStates {
if stateToGroup[k] == name {
deviceKeys = append(deviceKeys, k)
}
}
parentalStateMu.RUnlock()
sort.Strings(deviceKeys)
if len(deviceKeys) == 0 {
b.WriteString(`<div class="muted-line" style="margin-top: 10px;">No device activity yet. Budgets will populate dynamically when clients execute queries.</div>`)
} else {
for _, dk := range deviceKeys {
parentalStateMu.RLock()
gs, ok := groupStates[dk]
parentalStateMu.RUnlock()
if !ok {
continue
}
live := make(map[string]int64)
gs.mu.Lock()
for k, v := range gs.remaining { live[k] = v }
lastIP := gs.lastClientIP
lastName := gs.lastClientName
gs.mu.Unlock()
hdrClass := getDynamicHeaderClass(curMode, grp, gs)
deviceID := dk
if parts := strings.SplitN(dk, "/", 2); len(parts) == 2 {
deviceID = parts[1]
}
label := deviceID
if lastName != "" && lastName != deviceID {
if lastIP != "" && lastIP != deviceID {
label = fmt.Sprintf("%s (%s, %s)", lastName, deviceID, lastIP)
} else {
label = fmt.Sprintf("%s (%s)", lastName, deviceID)
}
} else if lastIP != "" && lastIP != deviceID {
label = fmt.Sprintf("%s (%s)", deviceID, lastIP)
}
// Collapsible details card for Device Tracking
b.WriteString(`<details class="dev-section" data-device="` + esc(dk) + `">`)
b.WriteString(`<summary class="dev-hdr` + hdrClass + `">`)
b.WriteString(`<div style="display:flex; align-items:center;">`)
b.WriteString(`<span class="dev-name">` + esc(label) + `</span>`)
b.WriteString(`</div>`)
b.WriteString(`</summary>`)
b.WriteString(`<div class="dev-table-wrap">`)
b.WriteString(renderBudgetTable(collectBudgetRows(grp, live), curMode))
b.WriteString(`</div>`)
b.WriteString(`</details>`)
}
}
} else {
// Group Tracking Mode
parentalStateMu.RLock()
gs, ok := groupStates[name]
parentalStateMu.RUnlock()
live := make(map[string]int64)
if ok {
gs.mu.Lock()
for k, v := range gs.remaining { live[k] = v }
gs.mu.Unlock()
}
hdrClass := getDynamicHeaderClass(curMode, grp, gs)
// Static styled card for Group Tracking
b.WriteString(`<div class="dev-section" style="margin-top: 10px;">`)
b.WriteString(`<div class="dev-hdr` + hdrClass + `">`)
b.WriteString(`<div style="display:flex; align-items:center;">`)
b.WriteString(`<span class="dev-name">Group Budget</span>`)
b.WriteString(`</div>`)
b.WriteString(`</div>`)
b.WriteString(`<div class="dev-table-wrap">`)
b.WriteString(renderBudgetTable(collectBudgetRows(grp, live), curMode))
b.WriteString(`</div>`)
b.WriteString(`</div>`)
}
b.WriteString(`</div>`)
return b.String()
}
func buildMobileCard(name, cur string, grp GroupConfig, clients int, detail, durSel string) string {
modeClass := map[string]string{
"DEFAULT": "st-ok", "LOG": "st-log", "ALLOW": "st-allow", "FREE": "st-free", "BLOCK": "st-block",
}
modeLabel := map[string]string{
"DEFAULT": "Default (normal)",
"LOG": "Override: LOG \u2014 log-only bypass",
"ALLOW": "Override: ALLOW \u2014 bypass all restrictions",
"FREE": "Override: FREE \u2014 suspend time/sched limits",
"BLOCK": "Override: BLOCK \u2014 internet cut",
}
bc := modeClass[cur]
if bc == "" {
bc = "st-ok"
}
bl := modeLabel[cur]
if bl == "" {
bl = "Default (normal)"
}
var b strings.Builder
b.WriteString(`<div class="card" data-group="` + esc(name) + `">`)
b.WriteString(`<div class="card-header">`)
b.WriteString(`<span class="card-name">` + esc(name) + `</span>`)
b.WriteString(`<span id="timer_m_` + esc(name) + `" class="timer-badge hidden" data-group="` + esc(name) + `" title="Cancel timer"></span>`)
b.WriteString(`<span class="sbadge group-badge ` + bc + `">` + bl + `</span>`)
b.WriteString(`</div>`)
b.WriteString(`<div style="padding: 8px 14px; border-bottom: 1px solid var(--border-light); display: flex; flex-direction: column; gap: 4px;">`)
b.WriteString(`<div style="display: flex; justify-content: space-between; align-items: center; font-size: 0.85em;"><span>Override Duration:</span>` + durSel + `</div>`)
b.WriteString(`<div style="font-size: 0.75em; color: var(--text-hint); text-align: right;">(Set duration first, then select mode)</div>`)
b.WriteString(`</div>`)
b.WriteString(`<div class="radio-grid">`)
for _, mode := range []string{"DEFAULT", "LOG", "ALLOW", "FREE", "BLOCK"} {
chk := ""
if cur == mode {
chk = " checked"
}
b.WriteString(`<label class="radio-btn mode-` + strings.ToLower(mode) + `">` +
`<input type="radio" name="m_` + esc(name) + `" value="` + mode + `"` + chk + `> ` +
mode + `</label>`)
}
b.WriteString(`</div>`)
b.WriteString(`<details data-group="` + esc(name) + `"><summary class="detail-toggle">Details</summary>`)
b.WriteString(detail)
b.WriteString(`</details>`)
b.WriteString(`</div>`)
return b.String()
}
type budgetRow struct {
key string
configured string
remaining string
exhausted bool
isAllow bool
isBlock bool
isFree bool
isLog bool
isUntrigger bool
}
func collectBudgetRows(grp GroupConfig, liveRemaining map[string]int64) []budgetRow {
if len(grp.Budget) == 0 {
return nil
}
keys := make([]string, 0, len(grp.Budget))
for k := range grp.Budget {
keys = append(keys, k)
}
sort.Strings(keys)
rows := make([]budgetRow, 0, len(keys))
for _, k := range keys {
raw := grp.Budget[k]
row := budgetRow{key: k, configured: raw}
switch strings.ToUpper(raw) {
case "ALLOW":
row.isAllow = true
row.remaining = "—"
case "BLOCK":
row.isBlock = true
row.remaining = "—"
case "FREE":
row.isFree = true
row.remaining = "—"
case "LOG":
row.isLog = true
row.remaining = "—"
default:
if strings.HasPrefix(strings.ToUpper(raw), "UNTRIGGER") {
row.isUntrigger = true
durStr := ""
if len(raw) > 9 {
durStr = strings.TrimSpace(raw[9:])
}
if durStr == "" {
durStr = "5m"
}
row.remaining = "trigger (" + durStr + ")"
} else if liveRemaining != nil {
if rem, ok := liveRemaining[k]; ok {
if rem <= 0 {
row.exhausted = true
row.remaining = "exhausted"
} else {
row.remaining = fmtSeconds(rem)
}
} else {
row.remaining = "—"
}
} else {
row.remaining = "—"
}
}
rows = append(rows, row)
}
return rows
}
func renderBudgetTable(rows []budgetRow, curMode string) string {
if len(rows) == 0 {
return `<div class="muted-line">no budget entries</div>`
}
var b strings.Builder
b.WriteString(`<table class="btable"><thead><tr>` +
`<th>Category</th><th>Limit</th><th>Remaining</th>` +
`</tr></thead><tbody>`)
for _, r := range rows {
remCls, cfgCls := "", ""
remStr := r.remaining
// Apply dynamic state text if the current mode intercepts the physical budget constraints
if !r.isAllow && !r.isBlock && !r.isFree && !r.isLog && !r.isUntrigger { // Standard time limit
if curMode == "ALLOW" || curMode == "FREE" || curMode == "LOG" {
remStr = `<span class="muted">suspended (` + curMode + `)</span>`
r.exhausted = false // Remove red highlight
} else if curMode == "BLOCK" {
remStr = `<span class="muted">blocked (` + curMode + `)</span>`
r.exhausted = false
}
} else if r.isBlock && (curMode == "ALLOW" || curMode == "LOG") { // Bypass explicit block
remStr = `<span class="muted">bypassed (` + curMode + `)</span>`
} else if r.isAllow && curMode == "BLOCK" { // Hard-block an explicit allow
remStr = `<span class="muted">blocked (` + curMode + `)</span>`
}
switch {
case r.exhausted: remCls = ` class="rem-exhausted"`
case r.isAllow: remCls = ` class="rem-allow"`
case r.isBlock: remCls = ` class="rem-block"`
case r.isFree: remCls = ` class="rem-free"`
case r.isLog: remCls = ` class="rem-log"`
case r.isUntrigger: remCls = ` class="rem-untrigger"`
}
switch {
case r.isAllow: cfgCls = ` class="cfg-allow"`
case r.isBlock: cfgCls = ` class="cfg-block"`
case r.isFree: cfgCls = ` class="cfg-free"`
case r.isLog: cfgCls = ` class="cfg-log"`
case r.isUntrigger: cfgCls = ` class="cfg-untrigger"`
}
b.WriteString(`<tr>`)
b.WriteString(`<td class="bkey">` + esc(r.key) + `</td>`)
b.WriteString(`<td` + cfgCls + `>` + esc(r.configured) + `</td>`)
b.WriteString(`<td` + remCls + `>` + remStr + `</td>`)
b.WriteString(`</tr>`)
}
b.WriteString(`</tbody></table>`)
return b.String()
}
func esc(s string) string {
s = strings.ReplaceAll(s, "&", "&")
s = strings.ReplaceAll(s, "<", "<")
s = strings.ReplaceAll(s, ">", ">")
s = strings.ReplaceAll(s, `"`, """)
return s
}
// buildGroupsHTML organically generates the Desktop and Mobile group layouts
// utilizing active server states. Returns pre-rendered HTML snippets to satisfy
// the synchronous HandleRoot rendering and dynamic HandleApiGroups endpoints.
func buildGroupsHTML() (string, string) {
names := make([]string, 0, len(cfg.Groups))
for n := range cfg.Groups {
names = append(names, n)
}
sort.Strings(names)
// Dynamically map exact client counts loaded from both inline routes AND external routes_files
clientCount := make(map[string]int, len(cfg.Groups))
parentalStateMu.RLock()
for k, v := range ParentalGroupClients {
clientCount[k] = v
}
parentalStateMu.RUnlock()
var tableRows strings.Builder
var mobileCards strings.Builder
if len(names) == 0 {
tableRows.WriteString(`<tr><td colspan="7" class="empty">No groups configured in config.yaml.</td></tr>`)
mobileCards.WriteString(`<div class="empty">No groups configured in config.yaml.</div>`)
}
for _, name := range names {
grp := cfg.Groups[name]
groupOverrideMu.RLock()
ovState := groupOverride[name]
groupOverrideMu.RUnlock()
cur := ovState.Mode
if cur == "" {
tot := strings.ToUpper(grp.Budget["total"])
if tot == "FREE" || tot == "LOG" || tot == "ALLOW" || tot == "BLOCK" {
cur = tot
} else {
cur = "DEFAULT"
}
}
detail := buildGroupDetail(name, grp, clientCount[name], cur)
durSel := `<select name="duration_` + esc(name) + `" class="dur-sel" data-group="` + esc(name) + `">` +
`<option value="0">Forever</option>` +
`<option value="15">15 min</option>` +
`<option value="30">30 min</option>` +
`<option value="60">1 hour</option>` +
`<option value="120">2 hours</option>` +
`<option value="1440">24 hours</option>` +
`</select>`
var radios strings.Builder
for _, mode := range []string{"DEFAULT", "LOG", "ALLOW", "FREE", "BLOCK"} {
chk := ""
if cur == mode {
chk = " checked"
}
radios.WriteString(
`<td><label class="mode-` + strings.ToLower(mode) + `">` +
`<input type="radio" name="` + esc(name) +
`" value="` + mode + `"` + chk + `> ` + mode +
`</label></td>`)
}
tableRows.WriteString(
`<tr class="group-row" data-group="` + esc(name) + `">` +
`<td class="name-cell">` +
`<details data-group="` + esc(name) + `">` +
`<summary class="group-name">` + esc(name) +
` <span id="timer_` + esc(name) + `" class="timer-badge hidden" data-group="` + esc(name) + `" title="Cancel timer"></span>` +
`</summary>` +
detail + `</details>` +
`</td>` + radios.String() + `<td>` + durSel + `</td></tr>`)
mobileCards.WriteString(buildMobileCard(name, cur, grp, clientCount[name], detail, durSel))
}
return tableRows.String(), mobileCards.String()
}
func mainPage(title, body string) string {
return `<!doctype html><html lang="en"><head>` +
`<meta charset="utf-8">` +
`<meta name="viewport" content="width=device-width,initial-scale=1">` +
`<title>` + esc(title) + `</title>` +
`<script>` +
`(function(){var t=localStorage.getItem('sdp_theme')||'auto';` +
`if(t!=='auto')document.documentElement.setAttribute('data-theme',t);})();` +
`</script>` +
`<style>` + css + `</style>` +
`</head><body>` +
`<div class="wrap">` + body + `</div>` +
`<div class="toast" id="sdp-toast"></div>` +
// ---------------------------------------------------------------------------
// Query Log Modal
// ---------------------------------------------------------------------------
`<div id="qlog-modal" class="modal">` +
`<div class="modal-content" id="qlog-modal-content">` +
`<!-- 8-way custom resize handles -->` +
`<div class="resizer n"></div><div class="resizer e"></div><div class="resizer s"></div><div class="resizer w"></div>` +
`<div class="resizer nw"></div><div class="resizer ne"></div><div class="resizer sw"></div><div class="resizer se"></div>` +
`<div class="modal-header" id="qlog-modal-header" title="Drag to move, double-click to maximize">` +
`<div class="modal-header-top">` +
`<h3>Live Query Log</h3>` +
`<button id="qlog-close">×</button>` +
`</div>` +
`<div class="modal-header-bot">` +
`<div style="display:flex; align-items:center; gap:8px; flex:1; min-width:200px; max-width:450px;">` +
`<div class="filter-box" style="flex:1; min-width:0; max-width:none;">` +
`<input type="text" id="qlog-filter" placeholder="Filter (grep)...">` +
`<button id="qlog-clear" class="hidden" title="Clear filter">×</button>` +
`</div>` +
`<label class="filter-invert" title="Show entries NOT matching the filter"><input type="checkbox" id="qlog-invert"> Invert</label>` +
`</div>` +
`<div class="log-meta">` +
`<span>Last</span>` +
`<button id="qlog-limit-minus" class="limit-btn" title="Decrease limit">−</button>` +
`<input type="number" id="qlog-limit" value="500" min="10" max="5000" step="50" class="limit-input" title="Number of lines to keep">` +
`<button id="qlog-limit-plus" class="limit-btn" title="Increase limit">+</button>` +
`<span>messages</span>` +
`<span id="qlog-time-range" class="time-range-txt"></span>` +
`</div>` +
`<button id="qlog-tail" class="hidden">Live ↓</button>` +
`<div class="zoom-controls">` +
`<button id="qlog-zoom-out" title="Decrease font size (Zoom Out)">−</button>` +
`<button id="qlog-zoom-reset" title="Default font size (Reset)">=</button>` +
`<button id="qlog-zoom-in" title="Increase font size (Zoom In)">+</button>` +
`</div>` +
`</div>` +
`</div>` +
`<div class="modal-body" id="qlog-lines"></div>` +
`</div>` +
`</div>` +
// ---------------------------------------------------------------------------
// Custom Rules Editor Modal
// ---------------------------------------------------------------------------
`<div id="rules-modal" class="modal">` +
`<div class="modal-content" style="max-width: 650px; left: 50%; top: 5vh; transform: translateX(-50%); height: 85vh;">` +
`<div class="modal-header">` +
`<div class="modal-header-top">` +
`<h3>Custom Rules</h3>` +
`<button id="rules-close" style="background:none;border:none;font-size:1.6em;cursor:pointer;color:var(--text-muted);">×</button>` +
`</div>` +
`<p style="font-size:0.85em; color:var(--text-dim); margin-top:6px;">Allowlist or blocklist specific domains (including subdomains) per-group or globally.</p>` +
`</div>` +
`<div class="modal-body" style="background:var(--bg-body); color:var(--text-main); font-family:inherit; font-size: 0.9em; padding: 0; display: flex; flex-direction: column; overflow: hidden;">` +
`<div class="table-wrap" style="border-radius:0; box-shadow:none; border:none; flex: 1; overflow-y: auto;">` +
`<table class="rules-table" style="border-radius:0; border:none; width: 100%;">` +
`<thead class="sticky-th"><tr>` +
`<th style="text-align:left;">Domain</th>` +
`<th>Group</th>` +
`<th>Action</th>` +
`<th>Active</th>` +
`<th></th>` +
`</tr></thead>` +
`<tbody id="rules-tbody"></tbody>` +
`</table>` +
`</div>` +
`<div style="padding:16px;">` +
`<button id="btn-add-rule" class="pill" style="cursor:pointer; padding:6px 12px;">+ Add Rule</button>` +
`</div>` +
`</div>` +
`<div style="padding:14px 16px; border-top:1px solid var(--border-light); background:var(--bg-alt); display:flex; justify-content:flex-end; gap:10px;">` +
`<button id="rules-cancel" class="btn-cancel" style="padding:8px 16px;">Cancel</button>` +
`<button id="rules-save" class="btn-clear" style="padding:8px 16px; background:var(--accent); color:#fff;">Save Changes</button>` +
`</div>` +
`</div>` +
`</div>` +
// ---------------------------------------------------------------------------
// Cache Inspector Modal
// ---------------------------------------------------------------------------
`<div id="cache-modal" class="modal">` +
`<div class="modal-content" id="cache-modal-content">` +
`<div class="modal-header" id="cache-modal-header">` +
`<div class="modal-header-top">` +
`<h3>Cache Inspector</h3>` +
`<div style="display:flex; gap: 12px; align-items: center;">` +
`<button id="btn-cache-refresh" class="pill" style="cursor:pointer; padding:4px 10px;">Refresh</button>` +
`<button id="cache-close" style="background:none;border:none;font-size:1.6em;cursor:pointer;color:var(--text-muted); line-height: 1;">×</button>` +
`</div>` +
`</div>` +
`<div class="modal-header-bot">` +
`<div style="display:flex; align-items:center; gap:8px; flex:1; min-width:200px; max-width:450px;">` +
`<div class="filter-box" style="flex:1; min-width:0; max-width:none;">` +
`<input type="text" id="cache-filter" placeholder="Filter cache (grep)...">` +
`<button id="cache-clear" class="hidden" title="Clear filter">×</button>` +
`</div>` +
`<label class="filter-invert" title="Show entries NOT matching the filter"><input type="checkbox" id="cache-invert"> Invert</label>` +
`</div>` +
`</div>` +
`</div>` +
`<div class="modal-body" style="background:var(--bg-body); color:var(--text-main); font-family:inherit; font-size: 0.9em; padding: 0; display: flex; flex-direction: column; overflow: hidden;">` +
`<div class="table-wrap" style="border-radius:0; box-shadow:none; border:none; flex: 1; overflow-y: auto;">` +
`<table class="rules-table" style="border-radius:0; border:none; width: 100%; table-layout: fixed;">` +
`<thead class="sticky-th"><tr>` +
`<th class="sortable-th" data-sort="qname" style="text-align:left; width: 28%;">Domain (QNAME)<span class="sort-icon"></span></th>` +
`<th class="sortable-th" data-sort="qtype" style="text-align:center; width: 5%;">Type<span class="sort-icon"></span></th>` +
`<th class="sortable-th" data-sort="route" style="text-align:center; width: 12%;">Upstream<span class="sort-icon"></span></th>` +
`<th class="sortable-th" data-sort="response" style="text-align:left; width: 32%;">Response<span class="sort-icon"></span></th>` +
`<th class="sortable-th" data-sort="hits" style="text-align:center; width: 5%;">Hits<span class="sort-icon"></span></th>` +
`<th class="sortable-th" data-sort="cachedat" style="text-align:center; width: 10%;">Cached At<span class="sort-icon"></span></th>` +
`<th class="sortable-th" data-sort="ttl" style="text-align:center; width: 5%;">TTL<span class="sort-icon"></span></th>` +
`<th style="text-align:center; width: 3%;"></th>` +
`</tr></thead>` +
`<tbody id="cache-tbody"></tbody>` +
`</table>` +
`</div>` +
`</div>` +
`</div>` +
`</div>` +
// ---------------------------------------------------------------------------
// Reset Confirm Modal
// ---------------------------------------------------------------------------
`<div id="reset-modal" class="modal">` +
`<div class="confirm-modal-content">` +
`<h3>Reset Statistics</h3>` +
`<p>Are you sure you want to reset all statistics, historic data, query logs, and top lists?</p>` +
`<p style="color: var(--block-text); font-weight: 600; margin-top: 8px;">This action cannot be undone.</p>` +
`<div class="confirm-btns">` +
`<button id="reset-cancel" class="btn-cancel">CANCEL</button>` +
`<button id="reset-confirm" class="btn-clear">CLEAR</button>` +
`</div>` +
`</div>` +
`</div>` +
`<script>` + uiScript + `</script>` +
`</body></html>`
}