Web-based Winamp controller for CarPC � Go backend, mobile-first UI
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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