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
- [ ] 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"
},
"locked": {
"lastModified": 1694529238,
"narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=",
"lastModified": 1701680307,
"narHash": "sha256-kAuep2h5ajznlPMD9rnQyffWG8EM/C73lejGofXvdM8=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "ff7b65b44d01cf9ba6a71320833626af21126384",
"rev": "4022d587cbbfd70fe950c1e2083a02621806a725",
"type": "github"
},
"original": {
@ -28,11 +28,11 @@
]
},
"locked": {
"lastModified": 1699950847,
"narHash": "sha256-xN/yVtqHb7kimHA/WvQFrEG5WS38t0K+A/W+j/WhQWM=",
"lastModified": 1701687253,
"narHash": "sha256-qJCMxIKWXonJODPF2oV7mCd0xu7VYVenTucrY0bizto=",
"owner": "tweag",
"repo": "gomod2nix",
"rev": "05c993c9a5bd55a629cd45ed49951557b7e9c61a",
"rev": "001bbfa22e2adeb87c34c6015e5694e88721cabe",
"type": "github"
},
"original": {
@ -43,11 +43,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1701237617,
"narHash": "sha256-Ryd8xpNDY9MJnBFDYhB37XSFIxCPVVVXAbInNPa95vs=",
"lastModified": 1702206697,
"narHash": "sha256-vE9oEx3Y8TO5MnWwFlmopjHd1JoEBno+EhsfUCq5iR8=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "85306ef2470ba705c97ce72741d56e42d0264015",
"rev": "29d6c96900b9b576c2fb89491452f283aa979819",
"type": "github"
},
"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
import (
"encoding/json"
"fmt"
"github.com/fhs/gompd/v2/mpd"
"github.com/labstack/echo-contrib/echoprometheus"
@ -9,9 +10,9 @@ import (
"golang.org/x/net/websocket"
"log"
"net/http"
"strconv"
"os"
"os/exec"
"strings"
"time"
)
func main() {
@ -56,17 +57,25 @@ func main() {
g.GET("/random", toggleRandom)
g.GET("/volume/:level", setVolume)
g.GET("/download", downloadTrack)
e.GET("/ws", wsServe)
e.Logger.Fatal(e.StartTLS(":1323", "cert.pem", "key.pem"))
//e.Logger.Fatal(e.Start(":1323"))
//e.Logger.Fatal(e.StartTLS(":1323", "cert.pem", "key.pem"))
e.Logger.Fatal(e.Start(":1323"))
}
func wsServe(c echo.Context) error {
fmt.Println("wsServe")
websocket.Handler(func(ws *websocket.Conn) {
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 {
// Read
msg := ""
@ -75,205 +84,66 @@ func wsServe(c echo.Context) error {
c.Logger().Error(err)
break
} else {
if strings.HasPrefix(strings.ToUpper(msg), "MPD#") {
// Forward MPD communication
// TODO: forward request to mpd and response back to client
err := websocket.Message.Send(ws, "MPD command received, processing... processing...")
log.Println(msg)
if strings.ToLower(msg) == "#status" {
// TODO: Get current MPD status and return it
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 {
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
uri := strings.SplitN(msg, " ", 2)[1]
// 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 {
c.Logger().Error(err)
}
}
}
//fmt.Println(msg)
}
}).ServeHTTP(c.Response(), c.Request())
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 {
// 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 {
cmd := exec.Command(
"yt-dlp",
"--no-wait-for-video",
"--no-playlist",
"--windows-filenames",
"--newline",
"--extract-audio",
"--audio-format", "mp3",
"--audio-quality", "0",
"--format", "bestaudio/best",
c.Param("url"),
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatalln(err)
}
return c.String(http.StatusNoContent, "")
}
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, "")
return c.String(http.StatusAccepted, "")
}

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>