From 700a5ad1ac91b4fc7e3b27123323d67ad66b8608 Mon Sep 17 00:00:00 2001 From: Sijmen Date: Mon, 1 May 2023 16:13:08 +0200 Subject: [PATCH] Move MPD idle command to mpd.rs --- src/main.rs | 32 +++----------------------------- src/mpd.rs | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 29 deletions(-) diff --git a/src/main.rs b/src/main.rs index d1053fa..8166331 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,6 @@ use std::path::Path; -use anyhow::anyhow; use askama::Template; -use async_std::prelude::*; -use async_std::{ - io::{BufReader, WriteExt}, - net::TcpStream, -}; use serde::Deserialize; mod mpd; @@ -137,34 +131,14 @@ async fn get_art(req: tide::Request<()>) -> tide::Result { } async fn sse(_req: tide::Request<()>, sender: tide::sse::Sender) -> tide::Result<()> { - // Needs to be async and all async mpd libraries suck - let mut stream = TcpStream::connect(mpd::host()).await?; - let mut reader = BufReader::new(stream.clone()); - - // skip OK MPD line - // TODO check if it is indeed OK - let mut buffer = String::new(); - reader.read_line(&mut buffer).await?; - // Update everything on connect sender.send("playlist", "", None).await?; sender.send("player", "", None).await?; loop { - stream.write_all(b"idle playlist player database\n").await?; - - loop { - buffer.clear(); - reader.read_line(&mut buffer).await?; - if buffer == "OK\n" { - break; - } - - let (_, changed) = buffer - .trim_end() - .split_once(": ") - .ok_or(anyhow!("unexpected response from MPD"))?; - sender.send(changed, "", None).await?; + let systems = mpd::idle(&["playlist", "player", "database"]).await?; + for system in systems { + sender.send(&system, "", None).await?; } } } diff --git a/src/mpd.rs b/src/mpd.rs index 61ade3b..94887f4 100644 --- a/src/mpd.rs +++ b/src/mpd.rs @@ -1,5 +1,10 @@ use std::borrow::Cow; +use anyhow::anyhow; +use async_std::{ + io::{prelude::BufReadExt, BufReader, WriteExt}, + net::TcpStream, +}; use mpdrs::lsinfo::LsInfoResponse; pub(crate) fn host() -> String { @@ -85,3 +90,32 @@ pub(crate) enum Entry { path: String, }, } + +pub(crate) async fn idle(systems: &[&str]) -> anyhow::Result> { + let mut stream = TcpStream::connect(host()).await?; + let mut reader = BufReader::new(stream.clone()); + + // skip OK MPD line + // TODO check if it is indeed OK + let mut buffer = String::new(); + reader.read_line(&mut buffer).await?; + + let systems = systems.join(" "); + let command = format!("idle {systems}\n"); + stream.write_all(command.as_bytes()).await?; + + let mut updated = vec![]; + loop { + buffer.clear(); + reader.read_line(&mut buffer).await?; + if buffer == "OK\n" { + break Ok(updated); + } + + let (_, changed) = buffer + .trim_end() + .split_once(": ") + .ok_or(anyhow!("unexpected response from MPD"))?; + updated.push(changed.to_string()); + } +}