yt-dlp 2.7.2

🎬️ A Rust library (with auto dependencies installation) for Youtube downloading
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! Redis cache backend for distributed/server deployments.
//!
//! This module provides a persistent cache backed by Redis, suitable for multi-process or
//! distributed environments. Redis handles TTL expiration natively via `SETEX`.
//! File content is NOT stored in Redis — only metadata. Files are stored on disk.

use std::path::{Path, PathBuf};

use redis::AsyncCommands;

use super::{
    DEFAULT_FILE_TTL, DEFAULT_PLAYLIST_TTL, DEFAULT_VIDEO_TTL, FileBackend, PlaylistBackend, VideoBackend,
    copy_to_cache, url_hash,
};
use crate::cache::playlist::CachedPlaylist;
use crate::cache::video::{CachedFile, CachedThumbnail, CachedVideo};
use crate::error::Result;
use crate::model::Video;
use crate::model::playlist::Playlist;
use crate::model::selector::FormatPreferences;

const PREFIX_VIDEO: &str = "yt-dlp:video:";
const PREFIX_VIDEO_ID: &str = "yt-dlp:video_id:";
const PREFIX_PLAYLIST: &str = "yt-dlp:playlist:";
const PREFIX_PLAYLIST_ID: &str = "yt-dlp:playlist_id:";
const PREFIX_FILE: &str = "yt-dlp:file:";
const PREFIX_THUMBNAIL: &str = "yt-dlp:thumbnail:";

async fn get_redis_connection(client: &redis::Client) -> Result<redis::aio::MultiplexedConnection> {
    client
        .get_multiplexed_async_connection()
        .await
        .map_err(|e| crate::error::Error::redis("get connection", e))
}

fn prefixed_url_key(prefix: &str, url: &str) -> String {
    format!("{}{}", prefix, url_hash(url))
}

fn prefixed_id_key(prefix: &str, id: &str) -> String {
    format!("{}{}", prefix, id)
}

/// Redis-backed video cache.
#[derive(Debug, Clone)]
pub struct RedisVideoCache {
    client: redis::Client,
    ttl: u64,
}

impl RedisVideoCache {
    /// Creates a new Redis video cache.
    pub async fn new(redis_url: impl Into<String>, ttl: Option<u64>) -> Result<Self> {
        let url = redis_url.into();

        tracing::debug!(redis_url = url, "🔧 Connecting to Redis for video cache");

        let client = redis::Client::open(url.as_str()).map_err(|e| crate::error::Error::redis("connect", e))?;

        // Test connection
        let mut conn = client
            .get_multiplexed_async_connection()
            .await
            .map_err(|e| crate::error::Error::redis("connect", e))?;
        redis::cmd("PING")
            .query_async::<String>(&mut conn)
            .await
            .map_err(|e| crate::error::Error::redis("ping", e))?;

        Ok(Self {
            client,
            ttl: ttl.unwrap_or(DEFAULT_VIDEO_TTL),
        })
    }

    async fn conn(&self) -> Result<redis::aio::MultiplexedConnection> {
        get_redis_connection(&self.client).await
    }
}

impl VideoBackend for RedisVideoCache {
    async fn get(&self, url: &str) -> Result<Option<Video>> {
        tracing::debug!(url = url, "🔍 Looking for video in Redis cache by URL");

        let mut conn = self.conn().await?;
        let key = prefixed_url_key(PREFIX_VIDEO, url);

        let data: Option<Vec<u8>> = conn
            .get(&key)
            .await
            .map_err(|e| crate::error::Error::redis("get video", e))?;

        if let Some(bytes) = data {
            let cached: CachedVideo = serde_json::from_slice(&bytes)?;
            return Ok(Some(cached.video()?));
        }

        Ok(None)
    }

    async fn put(&self, url: String, video: Video) -> Result<()> {
        tracing::debug!(url = url, video_id = video.id, "⚙️ Caching video to Redis backend");

        let mut conn = self.conn().await?;
        let cached = CachedVideo::new(url.clone(), &video)?;
        let bytes = serde_json::to_vec(&cached)?;

        let url_k = prefixed_url_key(PREFIX_VIDEO, &url);
        let id_k = prefixed_id_key(PREFIX_VIDEO_ID, &cached.id);

        // Store by URL and by ID atomically with TTL via pipeline
        redis::pipe()
            .atomic()
            .set_ex(&url_k, &bytes, self.ttl)
            .set_ex(&id_k, &bytes, self.ttl)
            .query_async::<()>(&mut conn)
            .await
            .map_err(|e| crate::error::Error::redis("pipeline set video", e))?;

        Ok(())
    }

    async fn remove(&self, url: &str) -> Result<()> {
        tracing::debug!(url = url, "⚙️ Removing video from Redis cache");

        let mut conn = self.conn().await?;
        let key = prefixed_url_key(PREFIX_VIDEO, url);

        // Try to get the video ID for cleanup
        let data: Option<Vec<u8>> = conn
            .get(&key)
            .await
            .map_err(|e| crate::error::Error::redis("get video for remove", e))?;

        if let Some(bytes) = data
            && let Ok(cached) = serde_json::from_slice::<CachedVideo>(&bytes)
        {
            let id_k = prefixed_id_key(PREFIX_VIDEO_ID, &cached.id);
            conn.del::<_, ()>(&id_k)
                .await
                .map_err(|e| crate::error::Error::redis("del video by id", e))?;
        }

        conn.del::<_, ()>(&key)
            .await
            .map_err(|e| crate::error::Error::redis("del video by url", e))?;

        Ok(())
    }

    async fn clean(&self) -> Result<()> {
        // Redis handles TTL expiration natively — nothing to do
        Ok(())
    }

    async fn get_by_id(&self, id: &str) -> Result<CachedVideo> {
        tracing::debug!(video_id = id, "🔍 Looking up video by ID in Redis cache");

        let mut conn = self.conn().await?;
        let key = prefixed_id_key(PREFIX_VIDEO_ID, id);

        let data: Option<Vec<u8>> = conn
            .get(&key)
            .await
            .map_err(|e| crate::error::Error::redis("get video by id", e))?;

        if let Some(bytes) = data {
            let cached: CachedVideo = serde_json::from_slice(&bytes)?;
            return Ok(cached);
        }

        Err(crate::error::Error::cache_miss(format!("video:{}", id)))
    }
}

/// Redis-backed playlist cache.
#[derive(Debug, Clone)]
pub struct RedisPlaylistCache {
    client: redis::Client,
    ttl: u64,
}

impl RedisPlaylistCache {
    /// Creates a new Redis playlist cache.
    pub async fn new(redis_url: impl Into<String>, ttl: Option<u64>) -> Result<Self> {
        let url = redis_url.into();
        let client = redis::Client::open(url.as_str()).map_err(|e| crate::error::Error::redis("connect", e))?;

        Ok(Self {
            client,
            ttl: ttl.unwrap_or(DEFAULT_PLAYLIST_TTL),
        })
    }

    async fn conn(&self) -> Result<redis::aio::MultiplexedConnection> {
        get_redis_connection(&self.client).await
    }
}

impl PlaylistBackend for RedisPlaylistCache {
    async fn get(&self, url: &str) -> Result<Option<Playlist>> {
        tracing::debug!(url = url, "🔍 Looking for playlist in Redis cache by URL");

        let mut conn = self.conn().await?;
        let key = prefixed_url_key(PREFIX_PLAYLIST, url);

        let data: Option<Vec<u8>> = conn
            .get(&key)
            .await
            .map_err(|e| crate::error::Error::redis("get playlist", e))?;

        if let Some(bytes) = data {
            let cached: CachedPlaylist = serde_json::from_slice(&bytes)?;
            return Ok(Some(cached.playlist()?));
        }

        Ok(None)
    }

    async fn get_by_id(&self, id: &str) -> Result<Option<Playlist>> {
        tracing::debug!(playlist_id = id, "🔍 Looking up playlist by ID in Redis cache");

        let mut conn = self.conn().await?;
        let key = prefixed_id_key(PREFIX_PLAYLIST_ID, id);

        let data: Option<Vec<u8>> = conn
            .get(&key)
            .await
            .map_err(|e| crate::error::Error::redis("get playlist by id", e))?;

        if let Some(bytes) = data {
            let cached: CachedPlaylist = serde_json::from_slice(&bytes)?;
            return Ok(Some(cached.playlist()?));
        }

        Ok(None)
    }

    async fn put(&self, url: String, playlist: Playlist) -> Result<()> {
        tracing::debug!(
            url = url,
            playlist_id = playlist.id,
            "⚙️ Caching playlist to Redis backend"
        );

        let mut conn = self.conn().await?;
        let cached = CachedPlaylist::from((url.clone(), playlist));
        let bytes = serde_json::to_vec(&cached)?;

        let url_k = prefixed_url_key(PREFIX_PLAYLIST, &url);
        let id_k = prefixed_id_key(PREFIX_PLAYLIST_ID, &cached.id);

        // Store by URL and by ID atomically with TTL via pipeline
        redis::pipe()
            .atomic()
            .set_ex(&url_k, &bytes, self.ttl)
            .set_ex(&id_k, &bytes, self.ttl)
            .query_async::<()>(&mut conn)
            .await
            .map_err(|e| crate::error::Error::redis("pipeline set playlist", e))?;

        Ok(())
    }

    async fn invalidate(&self, url: &str) -> Result<()> {
        tracing::debug!(url = url, "⚙️ Invalidating playlist in Redis cache");

        let mut conn = self.conn().await?;
        let key = prefixed_url_key(PREFIX_PLAYLIST, url);

        // Get cached to remove ID key too
        let data: Option<Vec<u8>> = conn
            .get(&key)
            .await
            .map_err(|e| crate::error::Error::redis("get playlist for invalidate", e))?;

        if let Some(bytes) = data
            && let Ok(cached) = serde_json::from_slice::<CachedPlaylist>(&bytes)
        {
            let id_k = prefixed_id_key(PREFIX_PLAYLIST_ID, &cached.id);
            conn.del::<_, ()>(&id_k)
                .await
                .map_err(|e| crate::error::Error::redis("del playlist by id", e))?;
        }

        conn.del::<_, ()>(&key)
            .await
            .map_err(|e| crate::error::Error::redis("del playlist by url", e))?;

        Ok(())
    }

    async fn clean(&self) -> Result<()> {
        // Redis handles TTL expiration natively
        Ok(())
    }

    async fn clear_all(&self) -> Result<()> {
        tracing::debug!("⚙️ Clearing all playlists from Redis cache");

        let mut conn = self.conn().await?;

        // Cursor-based scan for all playlist URL keys
        let pattern = format!("{}*", PREFIX_PLAYLIST);
        let mut keys: Vec<String> = Vec::new();
        let mut cursor: u64 = 0;
        loop {
            let (next_cursor, batch): (u64, Vec<String>) = redis::cmd("SCAN")
                .arg(cursor)
                .arg("MATCH")
                .arg(&pattern)
                .arg("COUNT")
                .arg(100)
                .query_async(&mut conn)
                .await
                .map_err(|e| crate::error::Error::redis("scan playlist keys", e))?;
            keys.extend(batch);
            cursor = next_cursor;
            if cursor == 0 {
                break;
            }
        }

        let pattern_id = format!("{}*", PREFIX_PLAYLIST_ID);
        let mut keys_id: Vec<String> = Vec::new();
        cursor = 0;
        loop {
            let (next_cursor, batch): (u64, Vec<String>) = redis::cmd("SCAN")
                .arg(cursor)
                .arg("MATCH")
                .arg(&pattern_id)
                .arg("COUNT")
                .arg(100)
                .query_async(&mut conn)
                .await
                .map_err(|e| crate::error::Error::redis("scan playlist id keys", e))?;
            keys_id.extend(batch);
            cursor = next_cursor;
            if cursor == 0 {
                break;
            }
        }

        let all_keys: Vec<&str> = keys.iter().chain(keys_id.iter()).map(|s| s.as_str()).collect();
        if !all_keys.is_empty() {
            conn.del::<_, ()>(all_keys)
                .await
                .map_err(|e| crate::error::Error::redis("del all playlist keys", e))?;
        }

        Ok(())
    }
}

/// Redis-backed file cache.
///
/// File content is stored on disk; Redis stores only metadata and the path.
#[derive(Debug, Clone)]
pub struct RedisFileCache {
    client: redis::Client,
    cache_dir: PathBuf,
    ttl: u64,
}

impl RedisFileCache {
    /// Creates a new Redis file cache.
    pub async fn new(redis_url: impl Into<String>, cache_dir: PathBuf, ttl: Option<u64>) -> Result<Self> {
        let url = redis_url.into();
        let client = redis::Client::open(url.as_str()).map_err(|e| crate::error::Error::redis("connect", e))?;

        if !cache_dir.exists() {
            tokio::fs::create_dir_all(&cache_dir).await?;
        }

        Ok(Self {
            client,
            cache_dir,
            ttl: ttl.unwrap_or(DEFAULT_FILE_TTL),
        })
    }

    async fn conn(&self) -> Result<redis::aio::MultiplexedConnection> {
        get_redis_connection(&self.client).await
    }
}

impl FileBackend for RedisFileCache {
    async fn get_by_hash(&self, hash: &str) -> Result<Option<(CachedFile, PathBuf)>> {
        tracing::debug!(hash = hash, "🔍 Looking for file in Redis cache by hash");

        let mut conn = self.conn().await?;
        let key = prefixed_id_key(PREFIX_FILE, hash);

        let data: Option<Vec<u8>> = conn
            .get(&key)
            .await
            .map_err(|e| crate::error::Error::redis("get file by hash", e))?;

        if let Some(bytes) = data
            && let Ok(cached) = serde_json::from_slice::<CachedFile>(&bytes)
        {
            let path = self.cache_dir.join(&cached.relative_path);
            return Ok(Some((cached, path)));
        }

        Ok(None)
    }

    async fn get_by_video_and_format(&self, video_id: &str, format_id: &str) -> Result<Option<(CachedFile, PathBuf)>> {
        tracing::debug!(
            video_id = video_id,
            format_id = format_id,
            "🔍 Looking for file by video and format in Redis cache"
        );

        let mut conn = self.conn().await?;
        let key = format!("{}vf:{}:{}", PREFIX_FILE, video_id, format_id);

        let data: Option<Vec<u8>> = conn
            .get(&key)
            .await
            .map_err(|e| crate::error::Error::redis("get file by video+format", e))?;

        if let Some(bytes) = data
            && let Ok(cached) = serde_json::from_slice::<CachedFile>(&bytes)
        {
            let path = self.cache_dir.join(&cached.relative_path);
            return Ok(Some((cached, path)));
        }

        Ok(None)
    }

    async fn get_by_video_and_preferences(
        &self,
        video_id: &str,
        preferences: &FormatPreferences,
    ) -> Result<Option<(CachedFile, PathBuf)>> {
        tracing::debug!(video_id = video_id, "🔍 Looking for file by preferences in Redis cache");

        let mut conn = self.conn().await?;
        let pattern = format!("{}vf:{}:*", PREFIX_FILE, video_id);
        let mut keys: Vec<String> = Vec::new();
        let mut cursor: u64 = 0;
        loop {
            let (next_cursor, batch): (u64, Vec<String>) = redis::cmd("SCAN")
                .arg(cursor)
                .arg("MATCH")
                .arg(&pattern)
                .arg("COUNT")
                .arg(100)
                .query_async(&mut conn)
                .await
                .map_err(|e| crate::error::Error::redis("scan files by preferences", e))?;
            keys.extend(batch);
            cursor = next_cursor;
            if cursor == 0 {
                break;
            }
        }

        for key in keys {
            let data: Option<Vec<u8>> = conn
                .get(&key)
                .await
                .map_err(|e| crate::error::Error::redis("get file by preferences", e))?;
            if let Some(bytes) = data
                && let Ok(cached) = serde_json::from_slice::<CachedFile>(&bytes)
                && cached.matches_preferences(preferences)
            {
                let path = self.cache_dir.join(&cached.relative_path);
                return Ok(Some((cached, path)));
            }
        }

        Ok(None)
    }

    async fn put(&self, file: CachedFile, source_path: &Path) -> Result<PathBuf> {
        tracing::debug!(
            file_id = file.id,
            filename = file.filename,
            "⚙️ Caching file to Redis backend"
        );

        let dest_path = copy_to_cache(&self.cache_dir, &file.relative_path, source_path).await?;

        let mut conn = self.conn().await?;
        let bytes = serde_json::to_vec(&file)?;

        // Store by hash
        let hash_key = prefixed_id_key(PREFIX_FILE, &file.id);
        conn.set_ex::<_, _, ()>(&hash_key, &bytes, self.ttl)
            .await
            .map_err(|e| crate::error::Error::redis("set file by hash", e))?;

        // Store by video+format for direct lookup
        if let Some(ref vid) = file.video_id
            && let Some(ref fid) = file.format_id
        {
            let vf_key = format!("{}vf:{}:{}", PREFIX_FILE, vid, fid);
            conn.set_ex::<_, _, ()>(&vf_key, &bytes, self.ttl)
                .await
                .map_err(|e| crate::error::Error::redis("set file by video+format", e))?;
        }

        // Store subtitle files by video+language for lookup via get_subtitle_by_language
        if file.file_type.eq_ignore_ascii_case("subtitle")
            && let Some(ref vid) = file.video_id
            && let Some(ref lang) = file.language_code
        {
            let sub_key = format!("{}sub:{}:{}", PREFIX_FILE, vid, lang);
            conn.set_ex::<_, _, ()>(&sub_key, &bytes, self.ttl)
                .await
                .map_err(|e| crate::error::Error::redis("set file by video+language", e))?;
        }

        Ok(dest_path)
    }

    async fn remove(&self, id: &str) -> Result<()> {
        tracing::debug!(file_id = id, "⚙️ Removing file from Redis cache");

        let mut conn = self.conn().await?;
        let key = prefixed_id_key(PREFIX_FILE, id);

        // Get file metadata to remove physical file and secondary keys
        let data: Option<Vec<u8>> = conn
            .get(&key)
            .await
            .map_err(|e| crate::error::Error::redis("get file for remove", e))?;

        if let Some(bytes) = data
            && let Ok(cached) = serde_json::from_slice::<CachedFile>(&bytes)
        {
            let path = self.cache_dir.join(&cached.relative_path);
            let _ = tokio::fs::remove_file(path).await;

            // Remove video+format key
            if let Some(ref vid) = cached.video_id
                && let Some(ref fid) = cached.format_id
            {
                let vf_key = format!("{}vf:{}:{}", PREFIX_FILE, vid, fid);
                conn.del::<_, ()>(&vf_key)
                    .await
                    .map_err(|e| crate::error::Error::redis("del file by video+format", e))?;
            }
        }

        conn.del::<_, ()>(&key)
            .await
            .map_err(|e| crate::error::Error::redis("del file by hash", e))?;

        Ok(())
    }

    async fn clean(&self) -> Result<()> {
        // Redis handles TTL expiration natively
        Ok(())
    }

    async fn get_thumbnail_by_video_id(&self, video_id: &str) -> Result<Option<(CachedThumbnail, PathBuf)>> {
        tracing::debug!(video_id = video_id, "🔍 Looking for thumbnail in Redis cache");

        let mut conn = self.conn().await?;
        let key = prefixed_id_key(PREFIX_THUMBNAIL, video_id);

        let data: Option<Vec<u8>> = conn
            .get(&key)
            .await
            .map_err(|e| crate::error::Error::redis("get thumbnail by video", e))?;

        if let Some(bytes) = data
            && let Ok(cached) = serde_json::from_slice::<CachedThumbnail>(&bytes)
        {
            let path = self.cache_dir.join(&cached.relative_path);
            return Ok(Some((cached, path)));
        }

        Ok(None)
    }

    async fn put_thumbnail(&self, thumbnail: CachedThumbnail, source_path: &Path) -> Result<PathBuf> {
        tracing::debug!(
            thumbnail_id = thumbnail.id,
            video_id = thumbnail.video_id,
            "⚙️ Caching thumbnail to Redis backend"
        );

        let dest_path = copy_to_cache(&self.cache_dir, &thumbnail.relative_path, source_path).await?;

        let mut conn = self.conn().await?;
        let bytes = serde_json::to_vec(&thumbnail)?;

        // Store by video_id (one thumbnail per video)
        let key = prefixed_id_key(PREFIX_THUMBNAIL, &thumbnail.video_id);
        conn.set_ex::<_, _, ()>(&key, &bytes, self.ttl)
            .await
            .map_err(|e| crate::error::Error::redis("set thumbnail", e))?;

        // Also store by thumbnail hash
        let hash_key = prefixed_id_key(PREFIX_THUMBNAIL, &thumbnail.id);
        conn.set_ex::<_, _, ()>(&hash_key, &bytes, self.ttl)
            .await
            .map_err(|e| crate::error::Error::redis("set thumbnail by hash", e))?;

        Ok(dest_path)
    }

    async fn get_subtitle_by_language(&self, video_id: &str, language: &str) -> Result<Option<(CachedFile, PathBuf)>> {
        tracing::debug!(
            video_id = video_id,
            language = language,
            "🔍 Looking for subtitle in Redis cache"
        );

        let mut conn = self.conn().await?;
        let key = format!("{}sub:{}:{}", PREFIX_FILE, video_id, language);

        let data: Option<Vec<u8>> = conn
            .get(&key)
            .await
            .map_err(|e| crate::error::Error::redis("get subtitle by language", e))?;

        if let Some(bytes) = data
            && let Ok(cached) = serde_json::from_slice::<CachedFile>(&bytes)
        {
            let path = self.cache_dir.join(&cached.relative_path);
            return Ok(Some((cached, path)));
        }

        Ok(None)
    }
}