add mpd status messages

This commit is contained in:
XenGi 2023-12-10 21:33:54 +01:00
parent 3889391f1b
commit 99dc857d41
Signed by: xengi
SSH key fingerprint: SHA256:FGp51kRvGOcWnTHiOI39ImwVO4A3fpvR30nPX3LpV7g
7 changed files with 338 additions and 196 deletions

View file

@ -18,3 +18,14 @@
- [ ] save playlist - [ ] save playlist
- [ ] delete playlist - [ ] delete playlist
# mpd state
- [x] state ("play", "stop", "pause")
- [x] repeat
- [ ] shuffle
- [ ] xfade
- [x] volume
- [x] track length/progress
- [x] track progress (seek)
- [ ] track name

BIN
favicon.xcf Normal file

Binary file not shown.

View file

@ -5,11 +5,11 @@
"systems": "systems" "systems": "systems"
}, },
"locked": { "locked": {
"lastModified": 1694529238, "lastModified": 1701680307,
"narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=", "narHash": "sha256-kAuep2h5ajznlPMD9rnQyffWG8EM/C73lejGofXvdM8=",
"owner": "numtide", "owner": "numtide",
"repo": "flake-utils", "repo": "flake-utils",
"rev": "ff7b65b44d01cf9ba6a71320833626af21126384", "rev": "4022d587cbbfd70fe950c1e2083a02621806a725",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -28,11 +28,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1699950847, "lastModified": 1701687253,
"narHash": "sha256-xN/yVtqHb7kimHA/WvQFrEG5WS38t0K+A/W+j/WhQWM=", "narHash": "sha256-qJCMxIKWXonJODPF2oV7mCd0xu7VYVenTucrY0bizto=",
"owner": "tweag", "owner": "tweag",
"repo": "gomod2nix", "repo": "gomod2nix",
"rev": "05c993c9a5bd55a629cd45ed49951557b7e9c61a", "rev": "001bbfa22e2adeb87c34c6015e5694e88721cabe",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -43,11 +43,11 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1701237617, "lastModified": 1702206697,
"narHash": "sha256-Ryd8xpNDY9MJnBFDYhB37XSFIxCPVVVXAbInNPa95vs=", "narHash": "sha256-vE9oEx3Y8TO5MnWwFlmopjHd1JoEBno+EhsfUCq5iR8=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "85306ef2470ba705c97ce72741d56e42d0264015", "rev": "29d6c96900b9b576c2fb89491452f283aa979819",
"type": "github" "type": "github"
}, },
"original": { "original": {

190
mpd.go Normal file
View file

@ -0,0 +1,190 @@
package main
import (
"github.com/fhs/gompd/v2/mpd"
"github.com/labstack/echo/v4"
"log"
"net/http"
"strconv"
"time"
)
// MPD API calls
func previousTrack(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
err = conn.Previous()
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusOK, "")
}
func nextTrack(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
err = conn.Next()
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusOK, "")
}
func stopPlayback(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
err = conn.Stop()
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusOK, "")
}
func resumePlayback(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
err = conn.Pause(false)
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusOK, "")
}
func pausePlayback(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
err = conn.Pause(true)
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusOK, "")
}
func seek(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
seconds, err := strconv.Atoi(c.Param("seconds"))
if err != nil {
log.Fatalln(err)
}
if seconds < 0 {
return c.String(http.StatusBadRequest, "seconds must be positive integer")
}
err = conn.SeekCur(time.Duration(seconds)*time.Second, false)
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusOK, "")
}
func toggleRepeat(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
status, err := conn.Status()
if err != nil {
log.Fatalln(err)
}
if status["repeat"] == "1" {
err = conn.Repeat(false)
} else {
err = conn.Repeat(true)
}
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusOK, "")
}
func toggleRandom(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
status, err := conn.Status()
if err != nil {
log.Fatalln(err)
}
if status["toggleRandom"] == "1" {
err = conn.Random(false)
} else {
err = conn.Random(true)
}
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusOK, "")
}
func setVolume(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
level, err := strconv.Atoi(c.Param("level"))
if err != nil {
log.Fatalln(err)
}
if level > 100 || level < 0 {
return c.String(http.StatusBadRequest, "Volume must be between 0 and 100")
}
err = conn.SetVolume(level)
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusOK, "")
}

244
server.go
View file

@ -1,6 +1,7 @@
package main package main
import ( import (
"encoding/json"
"fmt" "fmt"
"github.com/fhs/gompd/v2/mpd" "github.com/fhs/gompd/v2/mpd"
"github.com/labstack/echo-contrib/echoprometheus" "github.com/labstack/echo-contrib/echoprometheus"
@ -9,9 +10,9 @@ import (
"golang.org/x/net/websocket" "golang.org/x/net/websocket"
"log" "log"
"net/http" "net/http"
"strconv" "os"
"os/exec"
"strings" "strings"
"time"
) )
func main() { func main() {
@ -56,17 +57,25 @@ func main() {
g.GET("/random", toggleRandom) g.GET("/random", toggleRandom)
g.GET("/volume/:level", setVolume) g.GET("/volume/:level", setVolume)
g.GET("/download", downloadTrack)
e.GET("/ws", wsServe) e.GET("/ws", wsServe)
e.Logger.Fatal(e.StartTLS(":1323", "cert.pem", "key.pem")) //e.Logger.Fatal(e.StartTLS(":1323", "cert.pem", "key.pem"))
//e.Logger.Fatal(e.Start(":1323")) e.Logger.Fatal(e.Start(":1323"))
} }
func wsServe(c echo.Context) error { func wsServe(c echo.Context) error {
fmt.Println("wsServe")
websocket.Handler(func(ws *websocket.Conn) { websocket.Handler(func(ws *websocket.Conn) {
defer ws.Close() defer ws.Close()
fmt.Println("handler")
// Connect to MPD server
mpdConn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer mpdConn.Close()
for { for {
// Read // Read
msg := "" msg := ""
@ -75,205 +84,66 @@ func wsServe(c echo.Context) error {
c.Logger().Error(err) c.Logger().Error(err)
break break
} else { } else {
if strings.HasPrefix(strings.ToUpper(msg), "MPD#") { log.Println(msg)
// Forward MPD communication if strings.ToLower(msg) == "#status" {
// TODO: forward request to mpd and response back to client // TODO: Get current MPD status and return it
err := websocket.Message.Send(ws, "MPD command received, processing... processing...") status, err := mpdConn.Status()
if err != nil {
log.Fatalln(err)
}
jsonData, err := json.Marshal(status)
if err != nil {
log.Fatalln(err)
}
err = websocket.Message.Send(ws, fmt.Sprintf("{\"mpd_status\":%s}", string(jsonData)))
if err != nil { if err != nil {
c.Logger().Error(err) c.Logger().Error(err)
} }
} else if strings.HasPrefix(strings.ToUpper(msg), "YT#") { } else if strings.HasPrefix(strings.ToLower(msg), "#download ") {
// Download video link as audio file // Download video link as audio file
uri := strings.SplitN(msg, " ", 2)[1]
// TODO: implement yt-dlp integration // TODO: implement yt-dlp integration
err := websocket.Message.Send(ws, "YT-DLP command received, processing... processing...") err := websocket.Message.Send(ws, fmt.Sprintf("Downloading %s", uri))
if err != nil { if err != nil {
c.Logger().Error(err) c.Logger().Error(err)
} }
} }
} }
//fmt.Println(msg)
} }
}).ServeHTTP(c.Response(), c.Request()) }).ServeHTTP(c.Response(), c.Request())
return nil return nil
} }
// API calls func downloadTrack(c echo.Context) error {
// yt-dlp \
// --no-wait-for-video \
// --no-playlist \
// --windows-filenames \
// --newline \
// --extract-audio \
// --audio-format mp3 \
// --audio-quality 0 \
// -f bestaudio/best \
// ${video_url}
func previousTrack(c echo.Context) error { cmd := exec.Command(
// Connect to MPD server "yt-dlp",
conn, err := mpd.Dial("tcp", "localhost:6600") "--no-wait-for-video",
if err != nil { "--no-playlist",
log.Fatalln(err) "--windows-filenames",
} "--newline",
defer conn.Close() "--extract-audio",
"--audio-format", "mp3",
err = conn.Previous() "--audio-quality", "0",
if err != nil { "--format", "bestaudio/best",
c.Param("url"),
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
return c.String(http.StatusNoContent, "") return c.String(http.StatusAccepted, "")
}
func nextTrack(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
err = conn.Next()
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusNoContent, "")
}
func stopPlayback(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
err = conn.Stop()
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusNoContent, "")
}
func resumePlayback(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
err = conn.Pause(false)
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusNoContent, "")
}
func pausePlayback(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
err = conn.Pause(true)
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusNoContent, "")
}
func seek(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
seconds, err := strconv.Atoi(c.Param("seconds"))
if err != nil {
log.Fatalln(err)
}
if seconds < 0 {
return c.String(http.StatusBadRequest, "seconds must be positive integer")
}
err = conn.SeekCur(time.Duration(seconds)*time.Second, false)
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusNoContent, "")
}
func toggleRepeat(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
status, err := conn.Status()
if err != nil {
log.Fatalln(err)
}
if status["repeat"] == "1" {
err = conn.Repeat(false)
} else {
err = conn.Repeat(true)
}
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusNoContent, "")
}
func toggleRandom(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
status, err := conn.Status()
if err != nil {
log.Fatalln(err)
}
if status["toggleRandom"] == "1" {
err = conn.Random(false)
} else {
err = conn.Random(true)
}
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusNoContent, "")
}
func setVolume(c echo.Context) error {
// Connect to MPD server
conn, err := mpd.Dial("tcp", "localhost:6600")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
level, err := strconv.Atoi(c.Param("level"))
if err != nil {
log.Fatalln(err)
}
if level > 100 || level < 0 {
return c.String(http.StatusBadRequest, "Volume must be between 0 and 100")
}
err = conn.SetVolume(level)
if err != nil {
log.Fatalln(err)
}
return c.String(http.StatusNoContent, "")
} }

BIN
static/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

71
static/test.html Normal file
View file

@ -0,0 +1,71 @@
<!doctype html>
<html>
<head>
<title>API test</title>
<link rel="icon" href="/favicon.ico" sizes="16x16 32x32 48x48 64x64" type="image/png" />
</head>
<body>
<textarea id="log"></textarea>
<script>
// Create WebSocket connection.
const socket = new WebSocket("ws://localhost:1323/ws");
// Connection opened
socket.addEventListener("open", (event) => {
socket.send("Hello Server!");
});
// Listen for messages
socket.addEventListener("message", (event) => {
console.log("server: ", event.data);
if (typeof event.data === "object" && "mpd_status" in event.data) {
// {"consume":"0","mixrampdb":"0","partition":"default","playlist":"1","playlistlength":"0","random":"0","repeat":"0","single":"0","state":"stop","volume":"100"}
// random
if ("random" in event.data) {
const randomToggle = document.getElementById("randomToggle");
randomToggle.checked = event.data.random === "0";
}
// repeat
if ("repeat" in event.data) {
const repeatToggle = document.getElementById("repeatToggle");
repeatToggle.checked = event.data.repeat === "0";
}
// state
if ("state" in event.data) {
const playPauseButton = document.getElementById("playPauseButton");
switch (event.data.state) {
case "play":
playPauseButton.value = "||"
break;
case "stop":
case "pause":
playPauseButton.value = ">"
break;
}
}
// volume
if ("volume" in event.data) {
const volumeInput = document.getElementById("volumeInput");
volumeInput.value = event.data.volume
}
// current song
if ("elapsed" in event.data && "duration" in event.data) {
const seekTrackInput = document.getElementById("trackSeekInput");
seekTrackInput.max = event.data.duration;
seekTrackInput.value = event.data.elapsed;
const currentSongTimeText = document.getElementById("currentSongTimeText");
currentSongTimeText.text = event.data.elapsed + " | " + event.data.duration;
}
}
});
// window.setInterval(() => {
// socket.send("#status")
// }, 1000);
</script>
</body>
</html>