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
use crate::source::SourceStream;
use async_trait::async_trait;
use bytes::Bytes;
use futures::Stream;
use parking_lot::Mutex;
use reqwest::Client;
use std::sync::Arc;
use std::{
io,
pin::Pin,
str::FromStr,
task::{self, Poll},
};
use tracing::{info, warn};
const STONG_TITLE_ERROR: &str = "Error Please Try Again";
const CHUNKS_BEFORE_START: u8 = 20;
pub struct HttpStream {
stream: Box<dyn Stream<Item = Result<Bytes, reqwest::Error>> + Unpin + Send + Sync>,
client: Client,
content_length: Option<u64>,
url: reqwest::Url,
}
impl Stream for HttpStream {
type Item = Result<Bytes, reqwest::Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.stream).poll_next(cx)
}
}
#[async_trait]
impl SourceStream for HttpStream {
type Url = reqwest::Url;
type Error = reqwest::Error;
async fn create(
url: Self::Url,
is_radio: bool,
radio_title: Arc<Mutex<String>>,
) -> io::Result<Self> {
let client = Client::new();
info!("Requesting content length");
let response = client
.get(url.as_str())
.send()
.await
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
let mut content_length = None;
if let Some(length) = response.headers().get(reqwest::header::CONTENT_LENGTH) {
let length = u64::from_str(
length
.to_str()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?,
)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
info!("Got content length {length}");
content_length = Some(length);
} else {
warn!("Content length header missing");
}
let stream = response.bytes_stream();
let mut count_down = CHUNKS_BEFORE_START;
let url_inside = url.clone();
if is_radio {
let mut should_restart = true;
let client_inside = Client::new();
tokio::spawn(async move {
loop {
let mut response = match client_inside
.get(url_inside.as_str())
.header("icy-metadata", "1")
.send()
.await
{
Ok(t) => t,
Err(_) => {
*radio_title.lock() = STONG_TITLE_ERROR.to_string();
continue;
}
};
if let Some(header_value) = response.headers().get("content-type") {
if header_value.to_str().unwrap_or_default() != "audio/mpeg" {
*radio_title.lock() = STONG_TITLE_ERROR.to_string();
continue;
}
} else {
*radio_title.lock() = STONG_TITLE_ERROR.to_string();
continue;
}
let meta_interval: usize =
if let Some(header_value) = response.headers().get("icy-metaint") {
header_value
.to_str()
.unwrap_or_default()
.parse()
.unwrap_or_default()
} else {
0
};
let mut counter = meta_interval;
let mut awaiting_metadata_size = false;
let mut metadata_size: u8 = 0;
let mut awaiting_metadata = false;
let mut metadata: Vec<u8> = Vec::new();
let mut title_string = String::new();
while let Some(chunk) = response.chunk().await.expect("Couldn't get next chunk")
{
for byte in &chunk {
if meta_interval != 0 {
if awaiting_metadata_size {
awaiting_metadata_size = false;
metadata_size = *byte * 16;
if metadata_size == 0 {
counter = meta_interval;
} else {
awaiting_metadata = true;
}
} else if awaiting_metadata {
metadata.push(*byte);
metadata_size = metadata_size.saturating_sub(1);
if metadata_size == 0 {
awaiting_metadata = false;
let metadata_string =
std::str::from_utf8(&metadata).unwrap_or("");
if !metadata_string.is_empty() {
const STREAM_TITLE_KEYWORD: &str = "StreamTitle='";
if let Some(index) =
metadata_string.find(STREAM_TITLE_KEYWORD)
{
let left_index = index + 13;
let stream_title_substring =
&metadata_string[left_index..];
if let Some(right_index) =
stream_title_substring.find('\'')
{
let trimmed_song_title =
&stream_title_substring[..right_index];
title_string += " ";
title_string += trimmed_song_title;
*radio_title.lock() =
format!("Current playing: {title_string}");
}
}
}
metadata.clear();
counter = meta_interval;
}
} else {
// file.write_all(&[*byte]).expect("Couldn't write to file");
counter = counter.saturating_sub(1);
if counter == 0 {
awaiting_metadata_size = true;
}
}
} else {
// file.write_all(&[*byte]).expect("Couldn't write to file");
}
}
if should_restart {
if count_down == 0 {
should_restart = false;
title_string = String::new();
} else {
count_down -= 1;
}
}
}
}
});
}
Ok(Self {
stream: Box::new(stream),
client,
content_length,
url,
})
}
async fn content_length(&self) -> Option<u64> {
self.content_length
}
async fn seek_range(&mut self, start: u64, end: Option<u64>) -> io::Result<()> {
info!("Seeking: {start}-{end:?}");
let response = self
.client
.get(self.url.as_str())
.header(
"Range",
format!(
"bytes={start}-{}",
end.map(|e| e.to_string()).unwrap_or_default()
),
)
.send()
.await
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
if !response.status().is_success() {
return response
.error_for_status()
.map(|_| ())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()));
}
self.stream = Box::new(response.bytes_stream());
info!("Done seeking");
Ok(())
}
}