fork/gdu

git clone https://git.julia.blue/fork/gdu

Daniel Mildefeat: add web UI (#617)d672bf4

ignore
3.8 KiB157 linesraw
1package webui
2
3import (
4	"encoding/json"
5	"errors"
6	"fmt"
7	"net/http"
8
9	log "github.com/sirupsen/logrus"
10)
11
12// statusResponse describes the current scan state and display preferences.
13type statusResponse struct {
14	State            string       `json:"state"` // "scanning" | "done" | "error"
15	Error            string       `json:"error,omitempty"`
16	RootPath         string       `json:"rootPath"`
17	Progress         progressJSON `json:"progress"`
18	ShowApparentSize bool         `json:"showApparentSize"`
19	ShowRelativeSize bool         `json:"showRelativeSize"`
20	UseSIPrefix      bool         `json:"useSIPrefix"`
21}
22
23type progressJSON struct {
24	CurrentItem string `json:"currentItem"`
25	ItemCount   int64  `json:"itemCount"`
26	TotalUsage  int64  `json:"totalUsage"`
27}
28
29type deviceJSON struct {
30	Name       string `json:"name"`
31	MountPoint string `json:"mountPoint"`
32	Fstype     string `json:"fstype"`
33	Size       int64  `json:"size"`
34	Free       int64  `json:"free"`
35}
36
37func (ui *UI) buildStatus() statusResponse {
38	ui.mu.RLock()
39	defer ui.mu.RUnlock()
40
41	state := "done"
42	switch {
43	case ui.scanErr != nil:
44		state = "error"
45	case ui.scanning:
46		state = "scanning"
47	case ui.topDir == nil:
48		state = "scanning"
49	}
50
51	resp := statusResponse{
52		State:    state,
53		RootPath: ui.topDirPath,
54		Progress: progressJSON{
55			CurrentItem: ui.progress.CurrentItemName,
56			ItemCount:   ui.progress.ItemCount,
57			TotalUsage:  ui.progress.TotalUsage,
58		},
59		ShowApparentSize: ui.ShowApparentSize,
60		ShowRelativeSize: ui.ShowRelativeSize,
61		UseSIPrefix:      ui.UseSIPrefix,
62	}
63	if ui.scanErr != nil {
64		resp.Error = ui.scanErr.Error()
65	}
66	return resp
67}
68
69func (ui *UI) handleStatus(w http.ResponseWriter, _ *http.Request) {
70	writeJSON(w, http.StatusOK, ui.buildStatus())
71}
72
73func (ui *UI) handleNodes(w http.ResponseWriter, r *http.Request) {
74	path := r.URL.Query().Get("path")
75
76	node, err := ui.findNode(path)
77	if err != nil {
78		switch {
79		case errors.Is(err, errOutsideRoot):
80			writeError(w, http.StatusForbidden, err.Error())
81		case errors.Is(err, errNotFound):
82			writeError(w, http.StatusNotFound, err.Error())
83		default:
84			writeError(w, http.StatusInternalServerError, err.Error())
85		}
86		return
87	}
88
89	sortBy, order := parseSort(r.URL.Query().Get("sort"), r.URL.Query().Get("order"))
90	writeJSON(w, http.StatusOK, buildNodeResponse(node, sortBy, order))
91}
92
93func (ui *UI) handleDevices(w http.ResponseWriter, _ *http.Request) {
94	ui.mu.RLock()
95	devices := ui.devices
96	ui.mu.RUnlock()
97
98	out := make([]deviceJSON, 0, len(devices))
99	for _, d := range devices {
100		out = append(out, deviceJSON{
101			Name:       d.Name,
102			MountPoint: d.MountPoint,
103			Fstype:     d.Fstype,
104			Size:       d.Size,
105			Free:       d.Free,
106		})
107	}
108	writeJSON(w, http.StatusOK, out)
109}
110
111// handleEvents streams scan status updates using Server-Sent Events.
112func (ui *UI) handleEvents(w http.ResponseWriter, r *http.Request) {
113	flusher, ok := w.(http.Flusher)
114	if !ok {
115		writeError(w, http.StatusInternalServerError, "streaming unsupported")
116		return
117	}
118
119	w.Header().Set("Content-Type", "text/event-stream")
120	w.Header().Set("Cache-Control", "no-cache")
121	w.Header().Set("Connection", "keep-alive")
122
123	ch, last := ui.hub.subscribe()
124	defer ui.hub.unsubscribe(ch)
125
126	// send current state immediately on connect
127	if last == "" {
128		last = ui.statusJSON()
129	}
130	fmt.Fprintf(w, "data: %s\n\n", last)
131	flusher.Flush()
132
133	for {
134		select {
135		case <-r.Context().Done():
136			return
137		case msg, open := <-ch:
138			if !open {
139				return
140			}
141			fmt.Fprintf(w, "data: %s\n\n", msg)
142			flusher.Flush()
143		}
144	}
145}
146
147func writeJSON(w http.ResponseWriter, status int, payload any) {
148	w.Header().Set("Content-Type", "application/json")
149	w.WriteHeader(status)
150	if err := json.NewEncoder(w).Encode(payload); err != nil {
151		log.Printf("webui: encoding response: %s", err)
152	}
153}
154
155func writeError(w http.ResponseWriter, status int, message string) {
156	writeJSON(w, status, map[string]string{"error": message})
157}