Web-based Winamp controller for CarPC � Go backend, mobile-first UI
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

436 lines
12KB

  1. //go:build windows
  2. // Package server wires together the HTTP API, WebSocket hub, Winamp controller,
  3. // WASAPI viz capture, killist, and resume.
  4. package server
  5. import (
  6. "context"
  7. "encoding/json"
  8. "fmt"
  9. "io/fs"
  10. "log"
  11. "net/http"
  12. "os"
  13. "os/exec"
  14. "strconv"
  15. "time"
  16. "git.svabi.ch/jan/roadamp/internal/killist"
  17. "git.svabi.ch/jan/roadamp/internal/resume"
  18. "git.svabi.ch/jan/roadamp/internal/volume"
  19. "git.svabi.ch/jan/roadamp/internal/viz"
  20. "git.svabi.ch/jan/roadamp/internal/winamp"
  21. "github.com/gorilla/websocket"
  22. "gopkg.in/yaml.v3"
  23. )
  24. // ── Config ────────────────────────────────────────────────────────────────────
  25. type Config struct {
  26. Port int `yaml:"port"`
  27. WinampPath string `yaml:"winamp_path"`
  28. KillListFile string `yaml:"killist_file"`
  29. ResumeFile string `yaml:"resume_file"`
  30. }
  31. func loadConfig(path string) (Config, error) {
  32. cfg := Config{
  33. Port: 8080,
  34. KillListFile: "killist.dat",
  35. ResumeFile: "resume.dat",
  36. }
  37. data, err := os.ReadFile(path)
  38. if os.IsNotExist(err) {
  39. return cfg, nil
  40. }
  41. if err != nil {
  42. return cfg, err
  43. }
  44. return cfg, yaml.Unmarshal(data, &cfg)
  45. }
  46. // ── Server ────────────────────────────────────────────────────────────────────
  47. type Server struct {
  48. cfg Config
  49. wa *winamp.Controller
  50. kl *killist.KillList
  51. hub *hub
  52. mux *http.ServeMux
  53. staticFS fs.FS
  54. }
  55. func New(configPath string, staticFS fs.FS) (*Server, error) {
  56. cfg, err := loadConfig(configPath)
  57. if err != nil {
  58. return nil, fmt.Errorf("config: %w", err)
  59. }
  60. kl, err := killist.Load(cfg.KillListFile)
  61. if err != nil {
  62. return nil, fmt.Errorf("killist: %w", err)
  63. }
  64. s := &Server{cfg: cfg, wa: winamp.New(), kl: kl, mux: http.NewServeMux(), staticFS: staticFS}
  65. s.hub = newHub(s.handleCommand)
  66. s.routes()
  67. return s, nil
  68. }
  69. func (s *Server) Run() error {
  70. go s.hub.run()
  71. go s.broadcastStatus()
  72. go s.broadcastViz()
  73. go s.restoreResume()
  74. go s.killChecker()
  75. addr := fmt.Sprintf(":%d", s.cfg.Port)
  76. log.Printf("roadamp listening on http://localhost%s", addr)
  77. return http.ListenAndServe(addr, s.mux)
  78. }
  79. // ── Routes ────────────────────────────────────────────────────────────────────
  80. func (s *Server) routes() {
  81. s.mux.Handle("/", http.FileServer(http.FS(s.staticFS)))
  82. // WebSocket (primary interface)
  83. s.mux.HandleFunc("/ws", s.handleWS)
  84. // REST API (kept for curl/debugging)
  85. s.mux.HandleFunc("/api/status", s.handleStatus)
  86. s.mux.HandleFunc("/api/play", s.handlePlay)
  87. s.mux.HandleFunc("/api/pause", s.handlePause)
  88. s.mux.HandleFunc("/api/stop", s.handleStop)
  89. s.mux.HandleFunc("/api/next", s.handleNext)
  90. s.mux.HandleFunc("/api/prev", s.handlePrev)
  91. s.mux.HandleFunc("/api/seek", s.handleSeek)
  92. s.mux.HandleFunc("/api/volume", s.handleVolume)
  93. s.mux.HandleFunc("/api/mute", s.handleMute)
  94. s.mux.HandleFunc("/api/killist", s.handleKillist)
  95. s.mux.HandleFunc("/api/winamp/start", s.handleWinampStart)
  96. }
  97. // ── WebSocket ─────────────────────────────────────────────────────────────────
  98. var wsUpgrader = websocket.Upgrader{
  99. ReadBufferSize: 1024,
  100. WriteBufferSize: 4096,
  101. CheckOrigin: func(r *http.Request) bool { return true },
  102. }
  103. func (s *Server) handleWS(w http.ResponseWriter, r *http.Request) {
  104. conn, err := wsUpgrader.Upgrade(w, r, nil)
  105. if err != nil {
  106. log.Printf("ws upgrade: %v", err)
  107. return
  108. }
  109. c := &wsClient{hub: s.hub, conn: conn, send: make(chan []byte, 32)}
  110. s.hub.register <- c
  111. // Send current status immediately upon connect.
  112. if msg, err := s.statusMsg(); err == nil {
  113. c.send <- msg
  114. }
  115. go c.writePump()
  116. go c.readPump()
  117. }
  118. // ── WebSocket broadcast workers ───────────────────────────────────────────────
  119. // broadcastStatus pushes a status message to all clients every 500 ms.
  120. func (s *Server) broadcastStatus() {
  121. for range time.Tick(500 * time.Millisecond) {
  122. msg, err := s.statusMsg()
  123. if err != nil {
  124. continue
  125. }
  126. select {
  127. case s.hub.broadcast <- msg:
  128. default:
  129. }
  130. }
  131. }
  132. // broadcastViz starts the WASAPI loopback capturer and forwards spectrum
  133. // frames to all WebSocket clients at ~30 fps.
  134. func (s *Server) broadcastViz() {
  135. cap := viz.NewCapturer()
  136. ctx, cancel := context.WithCancel(context.Background())
  137. defer cancel()
  138. go cap.Start(ctx)
  139. for bars := range cap.C {
  140. data, err := json.Marshal(struct {
  141. Type string `json:"type"`
  142. Bars []float32 `json:"bars"`
  143. }{"viz", bars})
  144. if err != nil {
  145. continue
  146. }
  147. select {
  148. case s.hub.broadcast <- data:
  149. default:
  150. }
  151. }
  152. }
  153. // ── Command dispatcher (WebSocket) ────────────────────────────────────────────
  154. type wsCommand struct {
  155. Cmd string `json:"cmd"`
  156. Delta int `json:"delta"`
  157. Level int `json:"level"`
  158. Muted bool `json:"muted"`
  159. Title string `json:"title"`
  160. }
  161. func (s *Server) handleCommand(raw []byte) {
  162. var cmd wsCommand
  163. if err := json.Unmarshal(raw, &cmd); err != nil {
  164. return
  165. }
  166. switch cmd.Cmd {
  167. case "play":
  168. s.wa.Play()
  169. case "pause":
  170. s.wa.Pause()
  171. case "stop":
  172. if s.wa.IsPaused() {
  173. _ = resume.Save(s.cfg.ResumeFile, resume.State{
  174. PlaylistLength: s.wa.GetPlaylistLength(),
  175. PlaylistPos: s.wa.GetPlaylistPosition(),
  176. OffsetSeconds: s.wa.GetPosition(),
  177. TrackTitle: s.wa.GetTitle(),
  178. })
  179. }
  180. s.wa.Stop()
  181. case "next":
  182. s.wa.NextTrack()
  183. case "prev":
  184. s.wa.PrevTrack()
  185. case "seek":
  186. pos := s.wa.GetPosition() + cmd.Delta
  187. if pos < 0 {
  188. pos = 0
  189. }
  190. s.wa.Seek(pos)
  191. case "volume":
  192. _ = volume.Set(cmd.Level)
  193. case "mute":
  194. _ = volume.SetMute(cmd.Muted)
  195. case "killist_add":
  196. if title := s.wa.GetTitle(); title != "" {
  197. _ = s.kl.Add(title)
  198. }
  199. case "killist_remove":
  200. _ = s.kl.Remove(cmd.Title)
  201. case "winamp_start":
  202. if !s.wa.IsRunning() {
  203. if s.cfg.WinampPath != "" {
  204. _ = exec.Command(s.cfg.WinampPath).Start()
  205. }
  206. }
  207. }
  208. // Push a fresh status after any command.
  209. if msg, err := s.statusMsg(); err == nil {
  210. select {
  211. case s.hub.broadcast <- msg:
  212. default:
  213. }
  214. }
  215. }
  216. // ── Shared status builder ─────────────────────────────────────────────────────
  217. type statusMsg struct {
  218. Type string `json:"type"`
  219. Running bool `json:"running"`
  220. State string `json:"state"`
  221. Title string `json:"title"`
  222. Position int `json:"position"`
  223. Length int `json:"length"`
  224. PlaylistPos int `json:"playlist_pos"`
  225. PlaylistLength int `json:"playlist_length"`
  226. Version string `json:"version"`
  227. Volume int `json:"volume"`
  228. Muted bool `json:"muted"`
  229. }
  230. func (s *Server) statusMsg() ([]byte, error) {
  231. msg := statusMsg{Type: "status", Running: s.wa.IsRunning()}
  232. if msg.Running {
  233. switch s.wa.PlayState() {
  234. case 1:
  235. msg.State = "playing"
  236. case 3:
  237. msg.State = "paused"
  238. default:
  239. msg.State = "stopped"
  240. }
  241. msg.Title = s.wa.GetTitle()
  242. // Winamp returns 0xFFFFFFFF when stopped/no track — clamp to 0.
  243. pos := s.wa.GetPosition()
  244. length := s.wa.GetLength()
  245. if pos > 86400 { pos = 0 } // > 24h → garbage value
  246. if length > 86400 { length = 0 }
  247. msg.Position = pos
  248. msg.Length = length
  249. msg.PlaylistPos = s.wa.GetPlaylistPosition()
  250. msg.PlaylistLength = s.wa.GetPlaylistLength()
  251. msg.Version = s.wa.GetVersion()
  252. }
  253. if vol, err := volume.Get(); err == nil {
  254. msg.Volume = vol
  255. }
  256. if muted, err := volume.GetMute(); err == nil {
  257. msg.Muted = muted
  258. }
  259. return json.Marshal(msg)
  260. }
  261. // ── Background workers ────────────────────────────────────────────────────────
  262. func (s *Server) killChecker() {
  263. for range time.Tick(2 * time.Second) {
  264. if !s.wa.IsPlaying() {
  265. continue
  266. }
  267. if title := s.wa.GetTitle(); s.kl.Contains(title) {
  268. log.Printf("killist: skipping %q", title)
  269. s.wa.NextTrack()
  270. }
  271. }
  272. }
  273. func (s *Server) restoreResume() {
  274. deadline := time.Now().Add(30 * time.Second)
  275. for time.Now().Before(deadline) {
  276. if s.wa.IsRunning() {
  277. break
  278. }
  279. time.Sleep(500 * time.Millisecond)
  280. }
  281. st, err := resume.Load(s.cfg.ResumeFile)
  282. if err != nil || st == nil {
  283. return
  284. }
  285. if s.wa.GetPlaylistLength() != st.PlaylistLength {
  286. _ = resume.Delete(s.cfg.ResumeFile)
  287. return
  288. }
  289. s.wa.Play()
  290. s.wa.Seek(st.OffsetSeconds)
  291. s.wa.Pause()
  292. _ = resume.Delete(s.cfg.ResumeFile)
  293. log.Printf("resume: restored %q at %ds", st.TrackTitle, st.OffsetSeconds)
  294. }
  295. // ── REST handlers (for curl/debug) ───────────────────────────────────────────
  296. func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
  297. msg, err := s.statusMsg()
  298. if err != nil {
  299. http.Error(w, err.Error(), 500)
  300. return
  301. }
  302. w.Header().Set("Content-Type", "application/json")
  303. w.Write(msg)
  304. }
  305. func (s *Server) handlePlay(w http.ResponseWriter, r *http.Request) { jsonOK(w, s.wa.Play()) }
  306. func (s *Server) handlePause(w http.ResponseWriter, r *http.Request) { jsonOK(w, s.wa.Pause()) }
  307. func (s *Server) handleNext(w http.ResponseWriter, r *http.Request) { jsonOK(w, s.wa.NextTrack()) }
  308. func (s *Server) handlePrev(w http.ResponseWriter, r *http.Request) { jsonOK(w, s.wa.PrevTrack()) }
  309. func (s *Server) handleStop(w http.ResponseWriter, r *http.Request) {
  310. if s.wa.IsPaused() {
  311. _ = resume.Save(s.cfg.ResumeFile, resume.State{
  312. PlaylistLength: s.wa.GetPlaylistLength(),
  313. PlaylistPos: s.wa.GetPlaylistPosition(),
  314. OffsetSeconds: s.wa.GetPosition(),
  315. TrackTitle: s.wa.GetTitle(),
  316. })
  317. }
  318. jsonOK(w, s.wa.Stop())
  319. }
  320. func (s *Server) handleSeek(w http.ResponseWriter, r *http.Request) {
  321. delta, err := strconv.Atoi(r.URL.Query().Get("delta"))
  322. if err != nil {
  323. http.Error(w, "invalid delta", http.StatusBadRequest)
  324. return
  325. }
  326. pos := s.wa.GetPosition() + delta
  327. if pos < 0 {
  328. pos = 0
  329. }
  330. jsonOK(w, s.wa.Seek(pos))
  331. }
  332. func (s *Server) handleVolume(w http.ResponseWriter, r *http.Request) {
  333. if r.Method == http.MethodGet {
  334. vol, _ := volume.Get()
  335. jsonOK(w, map[string]int{"volume": vol})
  336. return
  337. }
  338. lvl, err := strconv.Atoi(r.URL.Query().Get("level"))
  339. if err != nil {
  340. http.Error(w, "invalid level", http.StatusBadRequest)
  341. return
  342. }
  343. _ = volume.Set(lvl)
  344. jsonOK(w, map[string]int{"volume": lvl})
  345. }
  346. func (s *Server) handleMute(w http.ResponseWriter, r *http.Request) {
  347. if r.Method == http.MethodGet {
  348. muted, _ := volume.GetMute()
  349. jsonOK(w, map[string]bool{"muted": muted})
  350. return
  351. }
  352. val := r.URL.Query().Get("muted")
  353. muted := val == "true" || val == "1"
  354. _ = volume.SetMute(muted)
  355. jsonOK(w, map[string]bool{"muted": muted})
  356. }
  357. func (s *Server) handleKillist(w http.ResponseWriter, r *http.Request) {
  358. switch r.Method {
  359. case http.MethodGet:
  360. jsonOK(w, s.kl.List())
  361. case http.MethodPost:
  362. title := s.wa.GetTitle()
  363. if title == "" {
  364. http.Error(w, "no track playing", http.StatusConflict)
  365. return
  366. }
  367. _ = s.kl.Add(title)
  368. jsonOK(w, map[string]string{"added": title})
  369. case http.MethodDelete:
  370. _ = s.kl.Remove(r.URL.Query().Get("title"))
  371. jsonOK(w, map[string]bool{"ok": true})
  372. }
  373. }
  374. func (s *Server) handleWinampStart(w http.ResponseWriter, r *http.Request) {
  375. if s.wa.IsRunning() {
  376. jsonOK(w, map[string]string{"status": "already_running"})
  377. return
  378. }
  379. if s.cfg.WinampPath == "" {
  380. http.Error(w, "winamp_path not configured", http.StatusServiceUnavailable)
  381. return
  382. }
  383. if err := exec.Command(s.cfg.WinampPath).Start(); err != nil {
  384. http.Error(w, err.Error(), 500)
  385. return
  386. }
  387. jsonOK(w, map[string]string{"status": "started"})
  388. }
  389. func jsonOK(w http.ResponseWriter, v any) {
  390. w.Header().Set("Content-Type", "application/json")
  391. json.NewEncoder(w).Encode(v)
  392. }