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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
//! # maguro
//!
//! An async library for downloading and streaming media, with
//! out-of-the-box support for YouTube.
//!
//! ## Example
//!
//! ```
//! use maguro;
//! use tokio::fs::OpenOptions;
//!
//! // ...
//!
//! // Get our video information and location the first format
//! // available.
//! let video_info = maguro::get_video_info("VfWgE7D1pYY").await?;
//! let format = video_info.all_formats().first().cloned()?;
//!
//! // Open an asynchronous file handle.
//! let mut output = OpenOptions::new()
//!     .read(false)
//!     .write(true)
//!     .create(true)
//!     .open("maguro.mp4")
//!     .await?;
//!
//! // Download the video.
//! format.download(&mut output).await?;
//! ```

use ::serde::{Deserialize, Serialize};
use hyper::{
    body::{self, HttpBody},
    Client,
};
use hyper_tls::HttpsConnector;
use std::{
    error,
    fmt::{self, Display},
    str,
    time::Duration,
};
use tokio::{fs::File, io::AsyncWriteExt};

pub mod serde;

/// Endpoint to request against.
const ENDPOINT_URI: &'static str = "https://www.youtube.com/get_video_info";

/// Form an endpoint URI for the given video ID.
fn endpoint_from_id<T: Display>(id: T) -> String {
    format!("{}?video_id={}", ENDPOINT_URI, id)
}

#[derive(Serialize, Deserialize, Clone, Debug)]
/// Describes a single streaming format for a YouTube video.
pub struct Format {
    itag: u32,
    url: String,

    // Width and height are optional in the case formats
    // are audio only.
    width: Option<u32>,
    height: Option<u32>,

    #[serde(rename = "mimeType")]
    mime_type: String,

    #[serde(
        default,
        rename = "contentLength",
        deserialize_with = "serde::u32::from_str_option"
    )]
    // A stream may not have a defined size.
    content_length: Option<u32>,

    quality: String,
    fps: Option<u32>,

    #[serde(
        default,
        rename = "approxDurationMs",
        deserialize_with = "serde::duration::from_millis_option"
    )]
    // A stream may not have a defined length.
    approx_duration: Option<Duration>,
}

impl Format {
    /// Whether the given streaming format is a video.
    pub fn is_video(&self) -> bool {
        match self.width {
            Some(_) => true,
            None => false,
        }
    }

    pub fn itag(&self) -> u32 {
        self.itag
    }

    pub fn size(&self) -> Option<u32> {
        self.content_length.clone()
    }

    /// Read the entire YouTube video into a vector.
    pub async fn to_vec(&self) -> Result<Vec<u8>, Box<dyn error::Error + Send + Sync>> {
        self.to_vec_callback(|_| Ok(())).await
    }

    /// Downloads the entire YouTube video in chunks with the given closure.
    /// On receipt of a new chunk of bytes, it calls the closure.
    pub async fn to_vec_callback<T>(
        &self,
        on_chunk: T,
    ) -> Result<Vec<u8>, Box<dyn error::Error + Send + Sync>>
    where
        T: Fn(Vec<u8>) -> Result<(), Box<dyn error::Error + Send + Sync>>,
    {
        let https = HttpsConnector::new();
        let client = Client::builder().build::<_, hyper::Body>(https);

        let mut res = client.get(self.url.parse().unwrap()).await.unwrap();

        let mut v: Vec<u8> = Vec::new();
        while let Some(chunk) = res.body_mut().data().await {
            let as_bytes: Vec<u8> = chunk?.iter().cloned().collect();
            on_chunk(as_bytes.clone())?;
            v.extend(as_bytes.iter());
        }
        Ok(v)
    }

    /// Downloads the entire YouTube video into a `File`.
    pub async fn download(
        &self,
        dest: &mut File,
    ) -> Result<(), Box<dyn error::Error + Send + Sync>> {
        let https = HttpsConnector::new();
        let client = Client::builder().build::<_, hyper::Body>(https);

        let mut res = client.get(self.url.parse().unwrap()).await.unwrap();

        while let Some(chunk) = res.body_mut().data().await {
            dest.write(&chunk?).await?;
        }

        Ok(())
    }
}

impl Display for Format {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "itag: {:03}\tQuality: {}\tMime Type: {}",
            self.itag, self.quality, self.mime_type
        )
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
/// The set of sources available to download a YouTube
/// video with.
pub struct StreamingData {
    #[serde(
        rename = "expiresInSeconds",
        deserialize_with = "serde::duration::from_secs"
    )]
    expires_in_seconds: Duration,

    // In the case of streams, the `formats` field is empty.
    formats: Option<Vec<Format>>,

    #[serde(rename = "adaptiveFormats")]
    adaptive_formats: Vec<Format>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
/// Details about some YouTube video.
pub struct VideoDetails {
    #[serde(rename = "videoId")]
    video_id: String,

    title: String,

    #[serde(rename = "author")]
    author: String,

    #[serde(
        rename = "lengthSeconds",
        deserialize_with = "serde::duration::from_secs_option"
    )]
    approx_length: Option<Duration>,

    #[serde(rename = "viewCount", deserialize_with = "serde::u32::from_str")]
    views: u32,

    #[serde(rename = "isPrivate")]
    private: bool,

    #[serde(rename = "isLiveContent")]
    live: bool,
}

impl VideoDetails {
    pub fn id(&self) -> String {
        self.video_id.clone()
    }
}

#[derive(Deserialize, Clone, Debug)]
/// YouTube get_video_info response.
pub struct InfoResponse {
    #[serde(rename = "streamingData")]
    streaming_data: StreamingData,

    #[serde(rename = "videoDetails")]
    video_details: VideoDetails,
}

impl InfoResponse {
    pub fn formats(&self) -> Option<Vec<Format>> {
        self.streaming_data.formats.clone()
    }

    pub fn adaptive_formats(&self) -> Vec<Format> {
        self.streaming_data.adaptive_formats.clone()
    }

    pub fn details(&self) -> VideoDetails {
        self.video_details.clone()
    }

    /// Returns a vector of all formats available for the given
    /// video.
    pub fn all_formats(&self) -> Vec<Format> {
        if let Some(fmts) = self.formats() {
            return fmts
                .iter()
                .cloned()
                .chain(self.adaptive_formats().iter().cloned())
                .collect();
        }
        self.adaptive_formats().iter().cloned().collect()
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
/// Wrapper describing the outermost URL-encoded parameters of
/// a get_video_info response.
struct InfoWrapper {
    pub player_response: String,
}

/// Acquires the [InfoResponse] struct for a given video ID.
pub async fn get_video_info(id: &str) -> Result<InfoResponse, Box<dyn error::Error>> {
    let https = HttpsConnector::new();
    let client = Client::builder().build::<_, hyper::Body>(https);

    let mut res = client
        .get(endpoint_from_id(id).parse().unwrap())
        .await
        .unwrap();
    let body = body::to_bytes(res.body_mut()).await.unwrap();

    let stream_info: InfoResponse =
        serde_json::from_str(&serde_urlencoded::from_bytes::<InfoWrapper>(&body)?.player_response)?;
    Ok(stream_info)
}