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
use crate::{
youtube::player_response::{CommonFormat, Quality},
Client,
};
use chrono::{DateTime, Utc};
use reqwest::Url;
use std::{collections::HashMap, sync::Arc, time::Duration};
#[derive(Debug)]
pub struct Stream {
pub(super) format: CommonFormat,
pub(super) client: Arc<Client>,
}
impl Stream {
pub async fn url(&self) -> crate::Result<Url> {
match &self.format.url {
Some(url) => Ok(url.clone()),
None => {
let signature_cipher = self
.format
.signature_cipher
.as_ref()
.expect("Stream did not have a URL or signatureCipher");
let root: HashMap<String, String> =
serde_urlencoded::from_str(signature_cipher.as_str())
.expect("signatureCipher was not urlencoded");
let signature = self.client.player().await.cipher().run(root["s"].clone());
let signature_arg = &root["sp"];
let mut url = Url::parse(&root["url"])
.expect("signatureCipher url attribute was not a valid URL");
let query = url
.query()
.map(|q| format!("{}&{}={}", q, signature_arg, signature));
if let Some(query) = query {
url.set_query(Some(&query));
} else {
panic!(
"URL('{}') did not have a query while trying to add '{}={}'",
url, signature_arg, signature
);
}
Ok(url)
}
}
}
pub async fn content_length(&self) -> crate::Result<u64> {
if let Some(content_length) = self.format.content_length {
Ok(content_length)
} else {
let res = self
.client
.client
.head(self.url().await?)
.send()
.await?
.error_for_status()?;
Ok(res
.content_length()
.ok_or(super::Error::UnknownContentLength)?)
}
}
pub async fn get(
&self,
) -> crate::Result<impl futures_core::Stream<Item = Result<bytes::Bytes, reqwest::Error>>> {
Ok(self
.client
.client
.get(self.url().await?)
.send()
.await?
.error_for_status()?
.bytes_stream())
}
pub fn quality(&self) -> &Quality {
&self.format.quality
}
pub fn mime_type(&self) -> &str {
&self.format.mime_type
}
pub fn last_modified(&self) -> DateTime<Utc> {
self.format.last_modified
}
pub fn bitrate(&self) -> u64 {
self.format.bitrate
}
pub fn duration(&self) -> Option<Duration> {
self.format.duration
}
}