add websockets to get downloads list

This commit is contained in:
2026-02-20 22:54:26 +03:00
parent e87d02b1cb
commit de495c0f78
8 changed files with 121 additions and 43 deletions

56
main.go
View File

@@ -15,6 +15,7 @@ import (
"time"
"go.senan.xyz/taglib"
"golang.org/x/net/websocket"
)
func sendJSON(w http.ResponseWriter, data any, status int) {
@@ -71,6 +72,42 @@ func main() {
mux := http.NewServeMux()
wsServer := websocket.Server{
Handler: func(c *websocket.Conn) {
for {
time.Sleep(1 * time.Second)
type item struct {
ID int `json:"id"`
Album monochrome.AlbumInfo `json:"album"`
Status DownloadStatus `json:"status"`
InstalledFiles int `json:"installedFiles"`
TotalFiles int `json:"totalFiles"`
}
items := []item{}
for id, download := range downloads {
items = append(items, item{
ID: id,
Album: download.Album,
Status: download.Status,
InstalledFiles: download.InstalledFiles,
TotalFiles: download.TotalFiles,
})
}
if err := json.NewEncoder(c).Encode(struct {
Downloads []item `json:"downloads"`
}{
Downloads: items,
}); err != nil {
continue
}
}
},
}
mux.HandleFunc("GET /ws/downloads", wsServer.ServeHTTP)
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if path == "/" {
@@ -107,25 +144,6 @@ func main() {
}
})
mux.HandleFunc("GET /downloads", func(w http.ResponseWriter, r *http.Request) {
type item struct {
ID int `json:"id"`
Album monochrome.AlbumInfo `json:"album"`
InstalledFiles int `json:"installedFiles"`
TotalFiles int `json:"totalFiles"`
}
items := []item{}
for id, download := range downloads {
items = append(items, item{
ID: id,
Album: download.Album,
InstalledFiles: download.InstalledFiles,
TotalFiles: download.TotalFiles,
})
}
sendJSON(w, items, 200)
})
mux.HandleFunc("GET /download-album/{id}", func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {