Repository navigation
Expand file tree
/
Copy pathwebui_api.go
More file actions
157 lines (139 loc) · 4.32 KB
/
Copy pathwebui_api.go
File metadata and controls
157 lines (139 loc) · 4.32 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
/*
File: webui_api.go
Description:
JSON API endpoints for the sdproxy web UI.
Extracted from webui.go.
*/
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
)
// handleApiSet handles AJAX group-mode updates from the radio-click JS.
func handleApiSet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if !isAuthed(r) {
json.NewEncoder(w).Encode(map[string]interface{}{"ok": false, "error": "unauthorized"})
return
}
if r.Method != http.MethodPost {
json.NewEncoder(w).Encode(map[string]interface{}{"ok": false, "error": "method not allowed"})
return
}
r.ParseForm()
group := r.FormValue("group")
mode := strings.ToUpper(r.FormValue("mode"))
durStr := r.FormValue("duration")
dur, _ := strconv.Atoi(durStr)
if group == "" {
json.NewEncoder(w).Encode(map[string]interface{}{"ok": false, "error": "missing group"})
return
}
valid := map[string]bool{"DEFAULT": true, "LOG": true, "ALLOW": true, "FREE": true, "BLOCK": true, "CANCEL_TIMER": true}
if !valid[mode] {
json.NewEncoder(w).Encode(map[string]interface{}{"ok": false, "error": "invalid mode"})
return
}
resultingMode := SetGroupOverride(group, mode, dur)
json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "group": group, "mode": resultingMode, "duration": dur})
}
// handleApiStats returns a JSON StatsSnapshot. Auth required.
func handleApiStats(w http.ResponseWriter, r *http.Request) {
if !isAuthed(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(GetStats())
}
// handleApiReset completely zeroes out all analytical stats and histories. Auth required.
func handleApiReset(w http.ResponseWriter, r *http.Request) {
if !isAuthed(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
ResetStats()
WebUILogStreamer.Clear()
SaveLogs() // Flushes blank slate cleanly over disk remnants
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{"ok": true})
}
// handleApiLogs sends the live log stream over Server-Sent Events. Auth required.
// Reads ?limit=N from the query string to determine how many history lines to send.
func handleApiLogs(w http.ResponseWriter, r *http.Request) {
if !isAuthed(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
limitStr := r.URL.Query().Get("limit")
limit := 500 // Increased default to 500 to ensure clicked UI elements have historical context
if limitStr != "" {
if parsed, err := strconv.Atoi(limitStr); err == nil {
limit = parsed
}
}
if limit < 10 {
limit = 10
}
if limit > logRingSize {
limit = logRingSize
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
return
}
ch := make(chan string, limit)
WebUILogStreamer.mu.Lock()
count := len(WebUILogStreamer.ring)
if count > limit {
count = limit
}
history := make([]string, 0, count)
if len(WebUILogStreamer.ring) < logRingSize {
history = append(history, WebUILogStreamer.ring[len(WebUILogStreamer.ring)-count:]...)
} else {
startIdx := (WebUILogStreamer.ringIdx + logRingSize - count) % logRingSize
if startIdx < WebUILogStreamer.ringIdx {
history = append(history, WebUILogStreamer.ring[startIdx:WebUILogStreamer.ringIdx]...)
} else {
history = append(history, WebUILogStreamer.ring[startIdx:]...)
history = append(history, WebUILogStreamer.ring[:WebUILogStreamer.ringIdx]...)
}
}
WebUILogStreamer.clients[ch] = struct{}{}
WebUILogStreamer.mu.Unlock()
for _, line := range history {
for _, part := range strings.Split(line, "\n") {
fmt.Fprintf(w, "data: %s\n", part)
}
fmt.Fprintf(w, "\n")
}
flusher.Flush()
ctx := r.Context()
for {
select {
case <-ctx.Done():
WebUILogStreamer.mu.Lock()
delete(WebUILogStreamer.clients, ch)
WebUILogStreamer.mu.Unlock()
return
case line := <-ch:
for _, part := range strings.Split(line, "\n") {
fmt.Fprintf(w, "data: %s\n", part)
}
fmt.Fprintf(w, "\n")
flusher.Flush()
}
}
}