Web-based Winamp controller for CarPC � Go backend, mobile-first UI
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

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