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
use std::future::Future;
use crate::Downloader;
use crate::error::Error;
use crate::model::Video;
impl Downloader {
/// Helper to check if a video is in the cache by URL.
///
/// # Arguments
///
/// * `url` - The video URL to check
///
/// # Returns
///
/// `Some(Video)` if found in cache and not expired, `None` otherwise
pub(crate) async fn check_video_cache(&self, url: &str) -> Option<Video> {
#[cfg(cache)]
{
tracing::debug!(url = url, "🔍 Checking video cache");
let cache = self.cache.as_ref()?;
let video = cache.videos.get(url).await.ok().flatten()?;
// If format URLs have expired according to available_at, invalidate and force re-fetch
if !video.are_format_urls_fresh() {
tracing::debug!(
url = url,
video_id = %video.id,
"🔍 Cached video has expired format URLs, invalidating"
);
let _ = cache.videos.remove(url).await;
return None;
}
tracing::debug!(
url = url,
video_id = %video.id,
"🔍 Video cache hit with fresh format URLs"
);
Some(video)
}
#[cfg(not(cache))]
{
tracing::debug!(url = url, "🔍 Cache feature disabled");
let _ = url;
None
}
}
/// Helper to determine the correct extractor for a given URL.
///
/// # Arguments
///
/// * `url` - The video URL
///
/// # Returns
///
/// Reference to the appropriate video extractor (YouTube or Generic)
pub(crate) fn get_extractor(&self, url: &str) -> &dyn crate::extractor::VideoExtractor {
let is_youtube = crate::extractor::Youtube::supports_url(url);
tracing::debug!(url = url, is_youtube = is_youtube, "📡 Selecting video extractor");
if is_youtube {
&self.youtube_extractor
} else {
&self.generic_extractor
}
}
/// Emits a `DownloadEvent` through all registered sinks in order:
/// hooks (with 30 s timeout), webhooks (non-blocking channel send), then the broadcast bus.
///
/// # Arguments
///
/// * `event` - The event to emit.
pub(crate) async fn emit_event(&self, event: crate::events::DownloadEvent) {
#[cfg(feature = "hooks")]
if let Some(registry) = &self.hook_registry {
registry.execute(&event).await;
}
#[cfg(feature = "webhooks")]
if let Some(delivery) = &self.webhook_delivery {
delivery.process_event(&event).await;
}
self.event_bus.emit_if_subscribed(event);
}
/// Fetch the video information from the given URL.
///
/// # Arguments
///
/// * `url` - The URL of the video.
///
/// # Returns
///
/// A `Video` struct containing metadata about the video.
///
/// # Errors
///
/// Returns an error if the yt-dlp command fails or the output cannot be parsed.
///
/// # Examples
///
/// ```rust,no_run
/// # use yt_dlp::Downloader;
/// # use std::path::PathBuf;
/// # use yt_dlp::client::deps::Libraries;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let libraries = Libraries::new(PathBuf::from("libs/yt-dlp"), PathBuf::from("libs/ffmpeg"));
/// # let downloader = Downloader::builder(libraries, "output").build().await?;
/// let video = downloader.fetch_video_infos("https://www.youtube.com/watch?v=gXtp6C-3JKo").await?;
/// println!("Video title: {}", video.title);
/// # Ok(())
/// # }
/// ```
pub async fn fetch_video_infos(&self, url: impl AsRef<str>) -> crate::error::Result<Video> {
let url_str = url.as_ref();
tracing::info!(url = url_str, "📡 Fetching video information");
if let Some(video) = self.check_video_cache(url_str).await {
tracing::debug!(
url = url_str,
video_id = %video.id,
video_title = %video.title,
"🔍 Cache hit, returning cached video"
);
return Ok(video);
}
self.fetch_video_infos_internal(url_str, "fetching from extractor")
.await
}
/// Fetch the video information from the given URL, bypassing the cache.
///
/// # Arguments
///
/// * `url` - The URL of the video.
///
/// # Returns
///
/// A `Video` struct containing metadata about the video.
///
/// # Errors
///
/// Returns an error if the yt-dlp command fails or the output cannot be parsed.
pub async fn fetch_video_infos_fresh(&self, url: impl AsRef<str>) -> crate::error::Result<Video> {
let url_str = url.as_ref();
self.fetch_video_infos_internal(url_str, "fetching fresh video information (bypassing cache)")
.await
}
/// Internal helper to fetch video information, emit events, and update cache.
async fn fetch_video_infos_internal(&self, url: &str, log_message: &str) -> crate::error::Result<Video> {
tracing::debug!(url = url, message = log_message, "📡 Fetching video information");
let start = std::time::Instant::now();
let result = self.get_extractor(url).fetch_video(url).await;
let duration = start.elapsed();
let video = match result {
Ok(v) => {
tracing::debug!(
url = url,
video_id = %v.id,
video_title = %v.title,
format_count = v.formats.len(),
duration = ?duration,
"✅ Video information fetched"
);
self.emit_event(crate::events::DownloadEvent::VideoFetched {
url: url.to_string(),
video: Box::new(v.clone()),
duration,
})
.await;
v
}
Err(e) => {
tracing::debug!(
url = url,
error = %e,
duration = ?duration,
"📡 Video information fetch failed"
);
self.emit_event(crate::events::DownloadEvent::VideoFetchFailed {
url: url.to_string(),
error: e.to_string(),
duration,
})
.await;
return Err(e);
}
};
#[cfg(cache)]
if let Some(cache) = &self.cache {
tracing::debug!(video_id = %video.id, "🔍 Updating cache with video data");
let _ = cache.videos.put(url.to_string(), video.clone()).await;
}
Ok(video)
}
/// Helper to get video by ID from cache (if available)
///
/// # Arguments
///
/// * `id` - The video ID.
///
/// # Returns
///
/// `Some(Video)` if found in cache, `None` otherwise.
pub async fn get_video_by_id(&self, id: &str) -> Option<Video> {
#[cfg(cache)]
{
tracing::debug!(video_id = id, "🔍 Getting video from cache by ID");
let cache = self.cache.as_ref()?;
let cached_video = cache.videos.get_by_id(id).await.ok()?;
let video = cached_video.video().ok();
tracing::debug!(
video_id = id,
found = video.is_some(),
"🔍 Video cache lookup by ID completed"
);
video
}
#[cfg(not(cache))]
{
tracing::debug!(video_id = id, "🔍 Cache feature disabled");
let _ = id;
None
}
}
/// Helper to execute an action with automatic URL expiry retry.
///
/// This method will execute the given action. If it fails with `Error::UrlExpired`,
/// it will refresh the video metadata and retry the action once.
///
/// # Arguments
///
/// * `url` - The URL of the video.
/// * `action` - A closure that takes a `Video` and returns a Future.
pub async fn execute_with_retry<T, F, Fut>(&self, url: String, action: F) -> crate::error::Result<T>
where
F: Fn(Video) -> Fut + Send + Sync + Clone,
Fut: Future<Output = crate::error::Result<T>> + Send,
{
// First attempt with potentially cached metadata
let video = self.fetch_video_infos(url.clone()).await?;
match action(video.clone()).await {
Ok(result) => Ok(result),
Err(Error::UrlExpired) => {
tracing::warn!("URL expired, refreshing metadata and retrying...");
// Refresh metadata bypassing cache
let video = self.fetch_video_infos_fresh(&url).await?;
// Retry action with fresh metadata
action(video).await
}
Err(e) => Err(e),
}
}
}