Repository navigation
Expand file tree
/
Copy pathliquidsoap.rs
More file actions
214 lines (191 loc) · 7.09 KB
/
Copy pathliquidsoap.rs
File metadata and controls
214 lines (191 loc) · 7.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
use crate::config::Lane;
use std::path::Path;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
pub fn queue_name(lane: &Lane) -> &'static str {
match lane {
Lane::Next => "next",
Lane::Duck => "duck",
Lane::Takeover => "takeover",
}
}
pub async fn push(addr: &str, lane: &Lane, clip: &Path, title: &str) -> anyhow::Result<String> {
let mut stream = TcpStream::connect(addr).await?;
// annotate: attaches metadata to the request so Icecast broadcasts the
// correct StreamTitle immediately, instead of falling back to the file's
// (often missing) ID3 tags and showing the previous track.
let request = format!("annotate:title={title:?}:{}", clip.display());
let command = format!("{}.push {request}\n", queue_name(lane));
stream.write_all(command.as_bytes()).await?;
stream.write_all(b"quit\n").await?;
stream.flush().await?;
let mut response = String::new();
stream.read_to_string(&mut response).await?;
Ok(response.trim().to_string())
}
/// What Liquidsoap is currently streaming (music bed or a pushed program),
/// via the telnet `request.on_air` + `request.metadata` commands.
#[derive(Debug, Clone)]
pub struct Track {
pub title: Option<String>,
pub artist: Option<String>,
pub filename: Option<String>,
}
impl Track {
/// Display name, composed like Icecast's StreamTitle: `artist - title`
/// when both are present, otherwise whichever exists, else the file name.
pub fn display(&self) -> Option<String> {
match (self.artist.as_deref(), self.title.as_deref()) {
(Some(a), Some(t)) => Some(format!("{a} - {t}")),
(Some(a), None) => Some(a.to_string()),
(None, Some(t)) => Some(t.to_string()),
(None, None) => self
.filename
.as_deref()
.map(|f| f.rsplit(['/', '\\']).next().unwrap_or(f).to_string()),
}
}
}
pub async fn current(addr: &str) -> anyhow::Result<Option<Track>> {
let mut stream = TcpStream::connect(addr).await?;
let on_air = telnet(&mut stream, "request.on_air").await?;
let rid = on_air.split_whitespace().last().unwrap_or_default().to_string();
if rid.parse::<u64>().is_err() {
let _ = stream.write_all(b"quit\n").await;
return Ok(None);
}
let meta = telnet(&mut stream, &format!("request.metadata {rid}")).await?;
let _ = stream.write_all(b"quit\n").await;
Ok(Some(parse_metadata(&meta)))
}
/// Send one telnet command and read the response up to Liquidsoap's `END` line.
async fn telnet(stream: &mut TcpStream, cmd: &str) -> anyhow::Result<String> {
stream.write_all(format!("{cmd}\n").as_bytes()).await?;
stream.flush().await?;
let mut buf = [0u8; 2048];
let mut acc = String::new();
loop {
let n = stream.read(&mut buf).await?;
if n == 0 {
break;
}
acc.push_str(&String::from_utf8_lossy(&buf[..n]));
if acc.lines().any(|line| line.trim() == "END") {
break;
}
}
Ok(acc
.lines()
.take_while(|line| line.trim() != "END")
.collect::<Vec<_>>()
.join("\n"))
}
fn parse_metadata(s: &str) -> Track {
let mut title = None;
let mut artist = None;
let mut filename = None;
for line in s.lines() {
if let Some((key, value)) = line.split_once('=') {
let value = value.trim().trim_matches('"').to_string();
if value.is_empty() {
continue;
}
match key.trim() {
"title" => title = Some(value),
"artist" => artist = Some(value),
"filename" if filename.is_none() => filename = Some(value),
_ => {}
}
}
}
Track {
title,
artist,
filename,
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
#[test]
fn queue_name_maps_each_lane() {
assert_eq!(queue_name(&Lane::Next), "next");
assert_eq!(queue_name(&Lane::Duck), "duck");
assert_eq!(queue_name(&Lane::Takeover), "takeover");
}
#[tokio::test]
async fn push_sends_lane_push_then_quit() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap().to_string();
let server = tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 256];
let mut received = String::new();
loop {
let n = sock.read(&mut buf).await.unwrap();
if n == 0 {
break;
}
received.push_str(&String::from_utf8_lossy(&buf[..n]));
if received.contains("quit") {
break;
}
}
received
});
push(&addr, &Lane::Duck, Path::new("/content/music/one.mp3"), "calm")
.await
.unwrap();
let received = server.await.unwrap();
assert!(received.contains("duck.push annotate:title=\"calm\":/content/music/one.mp3"));
assert!(received.contains("quit"));
}
#[test]
fn parse_metadata_extracts_title_artist_and_filename() {
let raw = "title=\"Gole Yakh\"\nartist=\"Kourosh Yaghmaei\"\nfilename=\"/app/content/x.mp3\"";
let t = parse_metadata(raw);
assert_eq!(t.title.as_deref(), Some("Gole Yakh"));
assert_eq!(t.artist.as_deref(), Some("Kourosh Yaghmaei"));
assert_eq!(t.filename.as_deref(), Some("/app/content/x.mp3"));
}
#[test]
fn display_composes_artist_and_title() {
let raw = "title=\"Gole Yakh\"\nartist=\"Kourosh Yaghmaei\"";
assert_eq!(
parse_metadata(raw).display().as_deref(),
Some("Kourosh Yaghmaei - Gole Yakh")
);
// title only
assert_eq!(
parse_metadata("title=\"Calm & Ambient\"").display().as_deref(),
Some("Calm & Ambient")
);
// neither → filename basename
assert_eq!(
parse_metadata("filename=\"/c/song.mp3\"").display().as_deref(),
Some("song.mp3")
);
}
#[tokio::test]
async fn current_reads_on_air_metadata() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap().to_string();
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 256];
// respond to request.on_air
sock.read(&mut buf).await.unwrap();
sock.write_all(b"7\nEND\n").await.unwrap();
// respond to request.metadata 7
sock.read(&mut buf).await.unwrap();
sock.write_all(b"title=\"calm\"\nfilename=\"/c/x.mp3\"\nEND\n")
.await
.unwrap();
});
let track = current(&addr).await.unwrap().unwrap();
assert_eq!(track.title.as_deref(), Some("calm"));
assert_eq!(track.filename.as_deref(), Some("/c/x.mp3"));
}
}