tydle 0.1.15

YouTube video extractor written in Rust that can be used anywhere in web or native environments, based on an extremely small subset of yt-dlp.
Documentation
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use anyhow::Result;
use std::pin::Pin;
#[cfg(feature = "cipher")]
use std::sync::Mutex as StdMutex;
#[cfg(target_arch = "wasm32")]
use std::sync::Mutex;
use std::{future::Future, sync::Arc};
#[cfg(not(target_arch = "wasm32"))]
use tokio::sync::Mutex;

#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::wasm_bindgen;

use crate::cache::{CacheAccess, MemoryCacheStore, PlayerCacheHandle};
#[cfg(feature = "cipher")]
use crate::cipher::decipher::{SignatureDecipher, SignatureDecipherHandle};
use crate::cookies::DomainCookies;
use crate::yt_interface::{YtClient, YtManifest, YtStreamResponse, YtVideoInfo};
use crate::{
    extractor::extract::{InfoExtractor, YtExtractor},
    yt_interface::VideoId,
};

#[cfg_attr(
    target_arch = "wasm32",
    derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
    tsify(into_wasm_abi, from_wasm_abi),
    serde(rename_all = "camelCase"),
    serde(default)
)]
#[derive(Default)]
pub struct TydleOptions {
    /// Map of cookies extracted from an authenticated YouTube account.
    pub auth_cookies: DomainCookies,
    /// Attempts to fetch over http instead of https.
    pub prefer_insecure: bool,
    /// Provide an address to set it as the `X-Forwarded-For` header when requesting YouTube.
    pub source_address: String,
    /// Provide a proxy domain address which tydle will request to instead of `www.youtube.com` in cases where you are CORS restricted.
    pub proxy_address: String,
    /// Provide a default client that tydle will use to request YouTube when it fetches without a specific client internally.
    pub default_client: YtClient,
    /// Tell tydle to only fetch with the default_client.
    pub force_default_client: bool,
}

pub struct Tydle<P, C>
where
    P: CacheAccess<(String, String)> + PlayerCacheHandle + Send + Sync + 'static,
    C: CacheAccess + Send + Sync + 'static,
{
    yt_extractor: Arc<Mutex<YtExtractor<P, C>>>,
    #[cfg(feature = "cipher")]
    signature_decipher: Arc<StdMutex<SignatureDecipher<P, C>>>,
}

impl Tydle<MemoryCacheStore<(String, String)>, MemoryCacheStore> {
    #[cfg(not(target_arch = "wasm32"))]
    pub fn new(options: TydleOptions) -> Result<Self> {
        let player_cache = Arc::new(MemoryCacheStore::new());
        let code_cache = Arc::new(MemoryCacheStore::new());

        let yt_extractor = YtExtractor::new(player_cache.clone(), code_cache.clone(), options)?;

        #[cfg(feature = "cipher")]
        let signature_decipher = SignatureDecipher::new(player_cache, code_cache);

        Ok(Self {
            yt_extractor: Arc::new(Mutex::new(yt_extractor)),
            #[cfg(feature = "cipher")]
            signature_decipher: Arc::new(StdMutex::new(signature_decipher)),
        })
    }
}

impl<P, C> Tydle<P, C>
where
    P: CacheAccess<(String, String)> + PlayerCacheHandle + Send + Sync + 'static,
    C: CacheAccess + Send + Sync + 'static,
{
    #[cfg(not(target_arch = "wasm32"))]
    pub fn new_with_cache(options: TydleOptions, player_cache: P, code_cache: C) -> Result<Self> {
        let player_cache = Arc::new(player_cache);
        let code_cache = Arc::new(code_cache);
        let yt_extractor = YtExtractor::new(player_cache.clone(), code_cache.clone(), options)?;

        #[cfg(feature = "cipher")]
        let signature_decipher = SignatureDecipher::new(player_cache, code_cache);

        Ok(Self {
            yt_extractor: Arc::new(Mutex::new(yt_extractor)),
            #[cfg(feature = "cipher")]
            signature_decipher: Arc::new(StdMutex::new(signature_decipher)),
        })
    }
}

pub trait Extract {
    /// Extract the raw JSON manifest from YouTube's API.
    ///
    /// This method is useful if you need to fetch both the metadata and the streams of a particular video.
    /// Call this method once to extract the video's raw JSON manifest,
    /// and then pass it to either `Tydle::get_video_info_from_manifest` or `Tydle::get_streams_from_manifest`.
    /// It's better to use `Tydle::get_video_info` or `Tydle::get_streams` directly if you only
    /// need to fetch either and not both since they call `Tydle::get_manifest` themselves internally.
    ///
    /// ```
    /// use tydle::{Tydle, TydleOptions, Extract, VideoId, YtManifest};
    /// use anyhow::Result;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///   let ty = Tydle::new(TydleOptions{ ..Default::default() })?;
    ///
    ///   let video_id = VideoId::new("dQw4w9WgXcQ")?;
    ///
    ///   // Since you have this manifest separately, you can pass it to a fetcher.
    ///   let manifest: YtManifest = ty.get_manifest(&video_id).await?;
    ///   let streams = ty.get_streams_from_manifest(&manifest).await?;
    ///   let video_info = ty.get_video_info_from_manifest(&manifest).await?;
    ///
    ///   println!("Manifest: {:?}", manifest);
    ///   println!("Streams: {:?}", streams);
    ///   println!("Video Metadata: {:?}", video_info);
    ///   Ok(())
    /// }
    /// ```
    fn get_manifest<'a>(&'a self, video_id: &'a VideoId) -> Self::ExtractManifestFut<'a>;
    /// Extract the metadata of a video from YouTube.
    ///
    /// If you already have a raw manifest fetched, use `Tydle::get_video_info_from_manifest` instead to avoid refetching.
    ///
    /// ```
    /// use tydle::{Tydle, TydleOptions, Extract, VideoId, YtVideoInfo};
    /// use anyhow::Result;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///   let ty = Tydle::new(TydleOptions{ ..Default::default() })?;
    ///
    ///   let video_id = VideoId::new("dQw4w9WgXcQ")?;
    ///   let video_info: YtVideoInfo = ty.get_video_info(&video_id).await?;
    ///
    ///   println!("Video Metadata: {:?}", video_info);
    ///   Ok(())
    /// }
    /// ```
    fn get_video_info<'a>(&'a self, video_id: &'a VideoId) -> Self::ExtractInfoFut<'a>;
    /// Fetch and parse general video information (metadata) from an already fetched manifest.
    ///
    /// If you do not require using the manifest directly, use `Tydle::get_video_info` instead to fetch directly.
    ///
    /// ```
    /// use tydle::{Tydle, TydleOptions, Extract, VideoId, YtVideoInfo};
    /// use anyhow::Result;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///   let ty = Tydle::new(TydleOptions{ ..Default::default() })?;
    ///
    ///   let video_id = VideoId::new("dQw4w9WgXcQ")?;
    ///
    ///   let manifest = ty.get_manifest(&video_id).await?;
    ///   let video_info: YtVideoInfo = ty.get_video_info_from_manifest(&manifest).await?;
    ///
    ///   println!("Video Metadata: {:?}", video_info);
    ///   Ok(())
    /// }
    /// ```
    ///
    fn get_video_info_from_manifest<'a>(
        &'a self,
        manifest: &'a YtManifest,
    ) -> Self::ExtractInfoFut<'a>;
    /// Fetch and parse the streams from an already fetched manifest.
    ///
    /// If you do not require using the manifest directly, use `Tydle::get_streams` instead to fetch directly.
    ///
    /// ```
    /// use tydle::{Tydle, TydleOptions, Extract, VideoId, YtStreamResponse};
    /// use anyhow::Result;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///   let ty = Tydle::new(TydleOptions{ ..Default::default() })?;
    ///
    ///   let video_id = VideoId::new("dQw4w9WgXcQ")?;
    ///
    ///   let manifest = ty.get_manifest(&video_id).await?;
    ///   let stream_response: YtStreamResponse = ty.get_streams_from_manifest(&manifest).await?;
    ///
    ///   for stream in stream_response.streams {
    ///     println!("Stream: {:?}", stream);
    ///   }
    ///
    ///   Ok(())
    /// }
    /// ```
    ///
    fn get_streams_from_manifest<'a>(
        &'a self,
        manifest: &'a YtManifest,
    ) -> Self::ExtractStreamFut<'a>;
    /// Extract playable streams from YouTube and get their source either as a `Signature` or an `URL`
    ///
    /// If you already have a raw manifest fetched, use `Tydle::get_streams_from_manifest` instead to avoid refetching.
    ///
    /// ```
    /// use tydle::{Tydle, TydleOptions, Extract, VideoId, YtStreamResponse};
    /// use anyhow::Result;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///   let ty = Tydle::new(TydleOptions{ ..Default::default() })?;
    ///
    ///   let video_id = VideoId::new("dQw4w9WgXcQ")?;
    ///   let stream_response: YtStreamResponse = ty.get_streams(&video_id).await?;
    ///
    ///   for stream in stream_response.streams {
    ///     println!("Stream: {:?}", stream);
    ///   }
    ///
    ///   Ok(())
    /// }
    /// ```
    fn get_streams<'a>(&'a self, video_id: &'a VideoId) -> Self::ExtractStreamFut<'a>;

    type ExtractStreamFut<'a>: Future<Output = Result<YtStreamResponse>> + 'a
    where
        Self: 'a;
    type ExtractInfoFut<'a>: Future<Output = Result<YtVideoInfo>> + 'a
    where
        Self: 'a;
    type ExtractManifestFut<'a>: Future<Output = Result<YtManifest>> + 'a
    where
        Self: 'a;
}

#[cfg(feature = "cipher")]
pub trait Cipher {
    /// Deciphers a stream's signature and returns it's URL.
    fn decipher_signature<'a>(
        &'a self,
        signature: String,
        player_url: String,
    ) -> Self::DecipherFut<'a>;
    type DecipherFut<'a>: Future<Output = Result<String>> + 'a
    where
        Self: 'a;
}

impl<P, C> Extract for Tydle<P, C>
where
    P: crate::cache::CacheAccess<(String, String)> + PlayerCacheHandle + Send + Sync + 'static,
    C: crate::cache::CacheAccess + Send + Sync + 'static,
{
    #[cfg(not(target_arch = "wasm32"))]
    type ExtractStreamFut<'a> = Pin<Box<dyn Future<Output = Result<YtStreamResponse>> + Send + 'a>>;
    #[cfg(not(target_arch = "wasm32"))]
    type ExtractInfoFut<'a> = Pin<Box<dyn Future<Output = Result<YtVideoInfo>> + Send + 'a>>;
    #[cfg(not(target_arch = "wasm32"))]
    type ExtractManifestFut<'a> = Pin<Box<dyn Future<Output = Result<YtManifest>> + Send + 'a>>;

    #[cfg(target_arch = "wasm32")]
    type ExtractStreamFut<'a> = Pin<Box<dyn Future<Output = Result<YtStreamResponse>> + 'a>>;
    #[cfg(target_arch = "wasm32")]
    type ExtractInfoFut<'a> = Pin<Box<dyn Future<Output = Result<YtVideoInfo>> + 'a>>;
    #[cfg(target_arch = "wasm32")]
    type ExtractManifestFut<'a> = Pin<Box<dyn Future<Output = Result<YtManifest>> + 'a>>;

    fn get_streams<'a>(&'a self, video_id: &'a VideoId) -> Self::ExtractStreamFut<'a> {
        Box::pin(async move {
            #[cfg(not(target_arch = "wasm32"))]
            let extractor = self.yt_extractor.lock().await;
            #[cfg(target_arch = "wasm32")]
            let extractor = self
                .yt_extractor
                .lock()
                .map_err(|e| anyhow::anyhow!(e.to_string()))?;
            extractor.extract_streams(video_id).await
        })
    }

    fn get_manifest<'a>(&'a self, video_id: &'a VideoId) -> Self::ExtractManifestFut<'a> {
        Box::pin(async move {
            #[cfg(not(target_arch = "wasm32"))]
            let extractor = self.yt_extractor.lock().await;
            #[cfg(target_arch = "wasm32")]
            let extractor = self
                .yt_extractor
                .lock()
                .map_err(|e| anyhow::anyhow!(e.to_string()))?;
            extractor.extract_manifest(video_id).await
        })
    }

    fn get_video_info<'a>(&'a self, video_id: &'a VideoId) -> Self::ExtractInfoFut<'a> {
        Box::pin(async move {
            #[cfg(not(target_arch = "wasm32"))]
            let extractor = self.yt_extractor.lock().await;
            #[cfg(target_arch = "wasm32")]
            let extractor = self
                .yt_extractor
                .lock()
                .map_err(|e| anyhow::anyhow!(e.to_string()))?;
            extractor.extract_video_info(video_id).await
        })
    }

    fn get_streams_from_manifest<'a>(
        &'a self,
        manifest: &'a YtManifest,
    ) -> Self::ExtractStreamFut<'a> {
        Box::pin(async move {
            #[cfg(not(target_arch = "wasm32"))]
            let extractor = self.yt_extractor.lock().await;
            #[cfg(target_arch = "wasm32")]
            let extractor = self
                .yt_extractor
                .lock()
                .map_err(|e| anyhow::anyhow!(e.to_string()))?;
            extractor.extract_streams_from_manifest(manifest).await
        })
    }

    fn get_video_info_from_manifest<'a>(
        &'a self,
        manifest: &'a YtManifest,
    ) -> Self::ExtractInfoFut<'a> {
        Box::pin(async move {
            #[cfg(not(target_arch = "wasm32"))]
            let extractor = self.yt_extractor.lock().await;
            #[cfg(target_arch = "wasm32")]
            let extractor = self
                .yt_extractor
                .lock()
                .map_err(|e| anyhow::anyhow!(e.to_string()))?;
            extractor.extract_video_info_from_manifest(manifest).await
        })
    }
}

#[cfg(feature = "cipher")]
impl<P, C> Cipher for Tydle<P, C>
where
    P: crate::cache::CacheAccess<(String, String)> + PlayerCacheHandle + Send + Sync + 'static,
    C: crate::cache::CacheAccess + Send + Sync + 'static,
{
    type DecipherFut<'a> = Pin<Box<dyn Future<Output = Result<String>> + 'a>>;

    fn decipher_signature<'a>(
        &'a self,
        signature: String,
        player_url: String,
    ) -> Self::DecipherFut<'a> {
        Box::pin(async move {
            let signature_decipher = self
                .signature_decipher
                .lock()
                .map_err(|e| anyhow::anyhow!(e.to_string()))?;
            signature_decipher.decipher(signature, player_url).await
        })
    }
}

#[cfg(target_arch = "wasm32")]
mod wasm_api {
    use super::*;
    use wasm_bindgen::JsValue;

    #[wasm_bindgen]
    pub struct TydleClient {
        inner: Tydle<MemoryCacheStore<(String, String)>, MemoryCacheStore>,
    }

    #[wasm_bindgen]
    impl TydleClient {
        #[wasm_bindgen(constructor)]
        pub fn new(options: Option<TydleOptions>) -> Result<TydleClient, JsValue> {
            let player_cache = Arc::new(MemoryCacheStore::new());
            let code_cache = Arc::new(MemoryCacheStore::new());

            let yt_extractor = YtExtractor::new(
                player_cache.clone(),
                code_cache.clone(),
                options.unwrap_or_default(),
            )
            .map_err(|e| JsValue::from_str(&e.to_string()))?;

            let signature_decipher = SignatureDecipher::new(player_cache, code_cache);

            Ok(TydleClient {
                inner: Tydle {
                    yt_extractor: Arc::new(Mutex::new(yt_extractor)),
                    signature_decipher: Arc::new(Mutex::new(signature_decipher)),
                },
            })
        }

        #[wasm_bindgen(js_name = "fetchStreams")]
        pub async fn fetch_streams(
            &self,
            #[wasm_bindgen(js_name = "videoId")] video_id: String,
        ) -> Result<YtStreamResponse, JsValue> {
            let id = VideoId::new(&video_id).map_err(|e| JsValue::from_str(&e.to_string()))?;

            Ok(self
                .inner
                .get_streams(&id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?)
        }

        #[wasm_bindgen(js_name = "fetchVideoInfo")]
        pub async fn fetch_video_info(
            &self,
            #[wasm_bindgen(js_name = "videoId")] video_id: String,
        ) -> Result<YtVideoInfo, JsValue> {
            let id = VideoId::new(&video_id).map_err(|e| JsValue::from_str(&e.to_string()))?;

            Ok(self
                .inner
                .get_video_info(&id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?)
        }

        #[wasm_bindgen(js_name = "fetchVideoInfoFromManifest")]
        pub async fn fetch_video_info_from_manifest(
            &self,
            manifest: YtManifest,
        ) -> Result<YtVideoInfo, JsValue> {
            Ok(self
                .inner
                .get_video_info_from_manifest(&manifest)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?)
        }

        #[wasm_bindgen(js_name = "fetchStreamsFromManifest")]
        pub async fn fetch_streams_from_manifest(
            &self,
            manifest: YtManifest,
        ) -> Result<YtStreamResponse, JsValue> {
            Ok(self
                .inner
                .get_streams_from_manifest(&manifest)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?)
        }

        #[wasm_bindgen(js_name = "fetchManifest")]
        pub async fn fetch_manifest(
            &self,
            #[wasm_bindgen(js_name = "videoId")] video_id: String,
        ) -> Result<YtManifest, JsValue> {
            let id = VideoId::new(&video_id).map_err(|e| JsValue::from_str(&e.to_string()))?;

            Ok(self
                .inner
                .get_manifest(&id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?)
        }

        #[wasm_bindgen(js_name = "decipherSignature")]
        pub async fn decipher_signature_js(
            &self,
            signature: String,
            #[wasm_bindgen(js_name = "playerUrl")] player_url: String,
        ) -> Result<String, JsValue> {
            let res = self
                .inner
                .decipher_signature(signature, player_url)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            Ok(res)
        }
    }
}