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
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use reqwest::Client;
use serde::Serialize;
use tokio::sync::{RwLock, mpsc};

use crate::events::{DownloadEvent, EventFilter, RetryStrategy};
use crate::utils::retry::RetryPolicy;

/// HTTP method for webhook delivery
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Default)]
pub enum WebhookMethod {
    /// HTTP POST
    #[default]
    Post,
    /// HTTP PUT
    Put,
    /// HTTP PATCH
    Patch,
}

/// Webhook configuration
#[derive(Debug, Clone)]
pub struct WebhookConfig {
    /// Webhook URL
    url: String,
    /// HTTP method
    method: WebhookMethod,
    /// Custom headers
    headers: HashMap<String, String>,
    /// Event filter
    filter: EventFilter,
    /// Retry policy
    retry_policy: RetryPolicy,
    /// Request timeout
    timeout: Duration,
    /// Whether to include full event data or just summary
    include_full_data: bool,
}

impl WebhookConfig {
    /// Creates a new webhook configuration
    ///
    /// # Arguments
    ///
    /// * `url` - The webhook URL
    ///
    /// # Returns
    ///
    /// A new WebhookConfig with default settings
    pub fn new(url: impl Into<String>) -> Self {
        let url_string = url.into();

        tracing::debug!(
            url = %url_string,
            "⚙️ Creating new WebhookConfig"
        );

        Self {
            url: url_string,
            method: WebhookMethod::default(),
            headers: HashMap::new(),
            filter: EventFilter::all(),
            retry_policy: RetryPolicy::default(),
            timeout: Duration::from_secs(10),
            include_full_data: true,
        }
    }

    /// Creates a webhook from environment variables
    ///
    /// Reads the following environment variables:
    /// - `YTDLP_WEBHOOK_URL` - Webhook URL (required)
    /// - `YTDLP_WEBHOOK_METHOD` - HTTP method (optional, default: POST)
    /// - `YTDLP_WEBHOOK_TIMEOUT` - Timeout in seconds (optional, default: 10)
    ///
    /// # Returns
    ///
    /// Some(WebhookConfig) if YTDLP_WEBHOOK_URL is set, None otherwise
    pub fn from_env() -> Option<Self> {
        tracing::debug!("⚙️ Loading WebhookConfig from environment");

        let url = std::env::var("YTDLP_WEBHOOK_URL").ok()?;

        tracing::debug!(
            url = %url,
            "⚙️ Found YTDLP_WEBHOOK_URL in environment"
        );

        let mut config = Self::new(url);

        if let Ok(method) = std::env::var("YTDLP_WEBHOOK_METHOD") {
            config.method = match method.to_uppercase().as_str() {
                "POST" => WebhookMethod::Post,
                "PUT" => WebhookMethod::Put,
                "PATCH" => WebhookMethod::Patch,
                _ => WebhookMethod::Post,
            };
        }

        if let Ok(timeout_str) = std::env::var("YTDLP_WEBHOOK_TIMEOUT")
            && let Ok(timeout_secs) = timeout_str.parse::<u64>()
        {
            config.timeout = Duration::from_secs(timeout_secs);
        }

        tracing::debug!(
            url = %config.url,
            method = ?config.method,
            timeout_secs = config.timeout.as_secs(),
            "✅ WebhookConfig created from environment"
        );

        Some(config)
    }

    /// Sets the HTTP method
    ///
    /// # Arguments
    ///
    /// * `method` - The HTTP method to use
    ///
    /// # Returns
    ///
    /// Self for method chaining
    pub fn with_method(mut self, method: WebhookMethod) -> Self {
        self.method = method;
        self
    }

    /// Adds a custom header.
    ///
    /// # Arguments
    ///
    /// * `key` - Header name
    /// * `value` - Header value
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(key.into(), value.into());
        self
    }

    /// Sets multiple headers at once.
    ///
    /// # Arguments
    ///
    /// * `headers` - Map of header names to values
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    pub fn with_headers(mut self, headers: HashMap<String, String>) -> Self {
        self.headers.extend(headers);
        self
    }

    /// Sets the event filter.
    ///
    /// # Arguments
    ///
    /// * `filter` - The event filter to apply
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    pub fn with_filter(mut self, filter: EventFilter) -> Self {
        self.filter = filter;
        self
    }

    /// Sets the retry strategy.
    ///
    /// # Arguments
    ///
    /// * `strategy` - The retry strategy to use for failed deliveries
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    pub fn with_retry_strategy(mut self, strategy: RetryStrategy) -> Self {
        self.retry_policy = RetryPolicy::builder()
            .max_attempts(strategy.max_attempts as u32)
            .initial_delay(strategy.initial_delay)
            .max_delay(strategy.max_delay)
            .backoff_factor(strategy.backoff_multiplier)
            .build();
        self
    }

    /// Sets the request timeout.
    ///
    /// # Arguments
    ///
    /// * `timeout` - The request timeout duration
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Sets whether to include full event data.
    ///
    /// # Arguments
    ///
    /// * `include` - Whether to include full event data or just a summary
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    pub fn with_full_data(mut self, include: bool) -> Self {
        self.include_full_data = include;
        self
    }

    /// Returns the URL.
    ///
    /// # Returns
    ///
    /// The webhook URL as a string slice.
    pub fn url(&self) -> &str {
        &self.url
    }

    /// Returns the filter.
    ///
    /// # Returns
    ///
    /// A reference to the configured event filter.
    pub fn filter(&self) -> &EventFilter {
        &self.filter
    }
}

/// Webhook payload that will be sent
impl std::fmt::Display for WebhookMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Post => f.write_str("Post"),
            Self::Put => f.write_str("Put"),
            Self::Patch => f.write_str("Patch"),
        }
    }
}

impl std::fmt::Display for WebhookConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "WebhookConfig(url={}, method={}, timeout={}s)",
            self.url,
            self.method,
            self.timeout.as_secs()
        )
    }
}

#[derive(Debug, Clone, Serialize)]
struct WebhookPayload {
    /// Event type
    event_type: String,
    /// Download ID if applicable
    download_id: Option<u64>,
    /// Timestamp when the event occurred
    timestamp: String,
    /// Full event data (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    data: Option<serde_json::Value>,
}

/// Webhook delivery system
pub struct WebhookDelivery {
    /// HTTP client for sending webhooks
    client: Arc<Client>,
    /// Registered webhooks
    webhooks: Arc<RwLock<Vec<WebhookConfig>>>,
    /// Channel for queuing webhook deliveries
    tx: mpsc::Sender<(WebhookConfig, DownloadEvent)>,
}

impl WebhookDelivery {
    /// Creates a new webhook delivery system
    ///
    /// # Returns
    ///
    /// A new WebhookDelivery instance with a background worker
    pub fn new() -> Self {
        tracing::debug!("⚙️ Creating new WebhookDelivery system");

        let client = crate::utils::http::build_http_client(crate::utils::http::HttpClientConfig {
            timeout: Some(Duration::from_secs(30)),
            ..Default::default()
        })
        .unwrap_or_else(|_| Arc::new(Client::new()));

        let (tx, mut rx) = mpsc::channel::<(WebhookConfig, DownloadEvent)>(1024);

        let webhooks = Arc::new(RwLock::new(Vec::new()));

        let client_clone = client.clone();

        tracing::debug!("⚙️ Spawning webhook delivery worker task");

        // Spawn worker task to process webhook deliveries with concurrency limit
        const MAX_CONCURRENT_DELIVERIES: usize = 16;
        let delivery_semaphore = Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_DELIVERIES));

        tokio::spawn(async move {
            tracing::debug!("⚙️ Webhook delivery worker started");

            while let Some((config, event)) = rx.recv().await {
                let client = client_clone.clone();
                let permit = delivery_semaphore.clone().acquire_owned().await;
                let Ok(permit) = permit else {
                    tracing::warn!("Webhook semaphore closed, stopping delivery worker");
                    break;
                };
                tokio::spawn(async move {
                    let _permit = permit;
                    Self::deliver_webhook(client, config, event).await;
                });
            }

            tracing::debug!("⚙️ Webhook delivery worker stopped");
        });

        Self { client, webhooks, tx }
    }

    /// Registers a new webhook
    ///
    /// # Arguments
    ///
    /// * `config` - The webhook configuration
    pub async fn register(&self, config: WebhookConfig) {
        tracing::debug!(
            url = %config.url,
            method = ?config.method,
            "🔔 Registering new webhook"
        );

        let mut webhooks = self.webhooks.write().await;
        webhooks.push(config);

        tracing::debug!(total_webhooks = webhooks.len(), "✅ Webhook registered");
    }

    /// Processes an event and delivers it to matching webhooks
    ///
    /// # Arguments
    ///
    /// * `event` - The event to deliver
    pub async fn process_event(&self, event: &DownloadEvent) {
        tracing::debug!(
            event_type = event.event_type(),
            download_id = event.download_id(),
            "🔔 Processing event for webhook delivery"
        );

        let webhooks = self.webhooks.read().await;
        let mut matched_count = 0;

        for webhook in webhooks.iter() {
            if webhook.filter.matches(event) {
                matched_count += 1;
                if let Err(e) = self.tx.try_send((webhook.clone(), event.clone())) {
                    tracing::warn!(error = %e, "Webhook channel full, dropping event");
                }
            }
        }

        tracing::debug!(
            event_type = event.event_type(),
            total_webhooks = webhooks.len(),
            matched_webhooks = matched_count,
            "✅ Event processed for webhook delivery"
        );
    }

    /// Returns the number of registered webhooks
    ///
    /// # Returns
    ///
    /// The total number of registered webhooks
    pub async fn count(&self) -> usize {
        let webhooks = self.webhooks.read().await;
        webhooks.len()
    }

    /// Clears all registered webhooks
    pub async fn clear(&self) {
        tracing::debug!("⚙️ Clearing all webhooks");

        let mut webhooks = self.webhooks.write().await;
        let count = webhooks.len();
        webhooks.clear();

        tracing::debug!(webhooks_cleared = count, "✅ All webhooks cleared");
    }

    /// Delivers a webhook with retry logic
    ///
    /// # Arguments
    ///
    /// * `client` - HTTP client for sending requests
    /// * `config` - Webhook configuration
    /// * `event` - Event to deliver
    async fn deliver_webhook(client: Arc<Client>, config: WebhookConfig, event: DownloadEvent) {
        tracing::debug!(
            url = %config.url,
            event_type = event.event_type(),
            download_id = event.download_id(),
            "🔔 Starting webhook delivery"
        );

        let payload = WebhookPayload {
            event_type: event.event_type().to_string(),
            download_id: event.download_id(),
            timestamp: chrono::Utc::now().to_rfc3339(),
            data: if config.include_full_data {
                serde_json::to_value(&event).ok()
            } else {
                None
            },
        };

        let policy = config.retry_policy.clone();

        let result = policy
            .execute_with_condition(
                || {
                    let client = &client;
                    let config = &config;
                    let payload = &payload;
                    async move { Self::send_webhook(client, config, payload).await }
                },
                |e: &String| {
                    // Don't retry permanent 4xx client errors (except 429 Too Many Requests)
                    if e.starts_with("HTTP 4") && !e.starts_with("HTTP 429") {
                        return false;
                    }
                    true
                },
            )
            .await;

        match result {
            Ok(_) => {
                tracing::debug!(url = config.url, "✅ Webhook delivered successfully");
            }
            Err(e) => {
                tracing::error!(url = config.url, error = %e, "Webhook delivery failed after retries");
            }
        }
    }

    /// Sends a single webhook request
    ///
    /// # Arguments
    ///
    /// * `client` - HTTP client
    /// * `config` - Webhook configuration
    /// * `payload` - Webhook payload to send
    ///
    /// # Returns
    ///
    /// Ok(()) on success, Err with error message on failure
    async fn send_webhook(client: &Client, config: &WebhookConfig, payload: &WebhookPayload) -> Result<(), String> {
        tracing::debug!(
            url = %config.url,
            method = ?config.method,
            event_type = %payload.event_type,
            "🔔 Sending webhook request"
        );

        let mut request = match config.method {
            WebhookMethod::Post => client.post(&config.url),
            WebhookMethod::Put => client.put(&config.url),
            WebhookMethod::Patch => client.patch(&config.url),
        };

        // Add custom headers
        for (key, value) in &config.headers {
            request = request.header(key, value);
        }

        // Add JSON content type
        request = request.header("Content-Type", "application/json");

        // Add payload
        request = request.json(payload);

        // Set timeout
        request = request.timeout(config.timeout);

        // Send request
        let response = request.send().await.map_err(|e| format!("Request failed: {}", e))?;

        // Check status code
        if !response.status().is_success() {
            let status = response.status();

            tracing::warn!(
                url = %config.url,
                status_code = status.as_u16(),
                "🔔 Webhook request failed"
            );

            return Err(format!("HTTP {}", status));
        }

        tracing::debug!(
            url = %config.url,
            status_code = response.status().as_u16(),
            "✅ Webhook request succeeded"
        );

        Ok(())
    }
}

impl Default for WebhookDelivery {
    fn default() -> Self {
        Self::new()
    }
}

impl Clone for WebhookDelivery {
    fn clone(&self) -> Self {
        Self {
            client: self.client.clone(),
            webhooks: self.webhooks.clone(),
            tx: self.tx.clone(),
        }
    }
}

impl std::fmt::Debug for WebhookDelivery {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WebhookDelivery")
            .field("webhooks_count", &"<async>")
            .finish()
    }
}

impl std::fmt::Display for WebhookDelivery {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("WebhookDelivery")
    }
}