aria2-core 0.3.2

aria2-rust core download engine: multi-protocol segmented downloads, rate limiting, configuration, session persistence, and BitTorrent seeding
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
mod execution;
#[cfg(test)]
mod tests;
mod types;

pub use types::{select_mirrors_by_priority, try_mirrors_with_failover};

use std::sync::Arc;
use std::time::Duration;

use aria2_protocol::metalink::parser::UrlEntry;
use tracing::info;

use crate::download::{DownloadContext, file_entry::FileEntry};
use crate::error::{Aria2Error, FatalError, Result};
use crate::rate_limiter::RateLimiter;
use crate::request::request_group::{DownloadOptions, GroupId, RequestGroup};
use crate::util::rwlock_ext::RwLockRecover;

use types::FileDownloadInfo;

/// Information about a single file download created from a multi-file Metalink.
///
/// Returned by [`MetalinkDownloadCommand::create_multi_file`] so the caller
/// can track each per-file command independently.
pub struct MetalinkFileInfo {
    /// The download command for this file.
    pub command: MetalinkDownloadCommand,
    /// The original file index in the Metalink document (0-based).
    pub file_index: usize,
}

pub struct MetalinkDownloadCommand {
    pub(crate) group: Arc<std::sync::RwLock<RequestGroup>>,
    pub(crate) client: reqwest::Client,
    pub(crate) output_path: std::path::PathBuf,
    pub(crate) started: bool,
    pub(crate) completed: bool,
    pub(crate) completed_bytes: u64,
    /// Raw Metalink data for re-parsing during execute().
    /// Only used for single-file mode. Empty in multi-file mode
    /// (each per-file command stores only its own file's data).
    pub(crate) metalink_data: Vec<u8>,
    /// Parsed file info for per-file mode (set by create_multi_file).
    /// When present, execute() uses this instead of re-parsing metalink_data.
    pub(crate) file_info: Option<FileDownloadInfo>,
    /// Parsed files for a grouped Metalink payload. A single command owns
    /// the group so the request context can schedule all selected files.
    pub(crate) grouped_file_infos: Vec<(std::path::PathBuf, FileDownloadInfo)>,
    pub(crate) checkpoint: Option<crate::engine::progress_checkpoint::ProgressCheckpoint>,
    /// Process-wide rate limiter from `DownloadEngine::global_limiter`.
    /// When `Some`, passed down to `ThrottledWriter` for mirror downloads.
    pub(crate) global_limiter: Option<RateLimiter>,
    #[cfg(feature = "bittorrent")]
    pub(crate) public_tracker_catalog:
        Option<Arc<aria2_protocol::bittorrent::tracker::public_list::PublicTrackerList>>,
    #[cfg(feature = "bittorrent")]
    pub(crate) bt_registry: Option<Arc<std::sync::RwLock<crate::engine::bt_registry::BtRegistry>>>,
    #[cfg(feature = "bittorrent")]
    pub(crate) bt_listener: Option<Arc<crate::engine::bt_peer_listener::BtPeerListenerManager>>,
    #[cfg(feature = "bittorrent")]
    pub(crate) lpd_manager: Option<Arc<crate::engine::lpd_manager::LpdManager>>,
}

impl MetalinkDownloadCommand {
    /// Create a `MetalinkDownloadCommand` for a single-file Metalink.
    ///
    /// For multi-file Metalinks, use [`create_multi_file`] instead, which
    /// returns one command per file. This method also works for multi-file
    /// Metalinks: it picks the first file and downloads it.
    ///
    /// # Arguments
    ///
    /// * `gid` - Group ID for the download
    /// * `metalink_bytes` - Raw Metalink XML data
    /// * `options` - Download options
    /// * `output_dir` - Override output directory (takes precedence over `options.dir`)
    pub fn new(
        gid: GroupId,
        metalink_bytes: &[u8],
        options: &DownloadOptions,
        output_dir: Option<&str>,
    ) -> Result<Self> {
        let doc = aria2_protocol::metalink::parser::MetalinkDocument::parse(metalink_bytes, None)
            .map_err(|e| {
            Aria2Error::Fatal(FatalError::Config(format!("Metalink parse failed: {}", e)))
        })?;

        if doc.files.is_empty() {
            return Err(Aria2Error::Fatal(FatalError::Config(
                "Metalink contains no files".into(),
            )));
        }

        // Use the first file (single-file mode). For multi-file Metalinks,
        // the caller should use create_multi_file() instead.
        let file = &doc.files[0];

        if file.urls.is_empty() {
            // A torrent metaurl is still a valid download path (C++
            // BtDependency); reject only when there is nothing at all.
            let has_torrent_metaurl = file
                .meta_urls
                .iter()
                .any(|m| m.mediatype == aria2_protocol::metalink::parser::MediaType::Torrent);
            if !has_torrent_metaurl {
                return Err(Aria2Error::Fatal(FatalError::Config(
                    "Metalink file has no download URL".into(),
                )));
            }
        }

        let dir = output_dir
            .map(|d| d.to_string())
            .or_else(|| options.dir.clone())
            .unwrap_or_else(|| ".".to_string());

        let filename = file.name.clone();
        let path = std::path::PathBuf::from(&dir).join(&filename);

        let urls: Vec<String> = file
            .get_sorted_urls()
            .iter()
            .map(|u| u.url.clone())
            .collect();
        let group = RequestGroup::new(gid, urls, options.clone());
        group.set_output_name(file.name.clone());

        let client = build_http_client(options)?;

        if doc.files.len() > 1 {
            info!(
                "MetalinkDownloadCommand created for first file of {}: {} -> {} ({} mirrors) \
                 [use create_multi_file() for all files]",
                doc.files.len(),
                file.name,
                path.display(),
                file.urls.len()
            );
        } else {
            info!(
                "MetalinkDownloadCommand created: {} -> {} ({} mirrors)",
                file.name,
                path.display(),
                file.urls.len()
            );
        }

        Ok(Self {
            group: Arc::new(std::sync::RwLock::new(group)),
            client,
            output_path: path,
            started: false,
            completed: false,
            completed_bytes: 0,
            metalink_data: metalink_bytes.to_vec(),
            file_info: None,
            grouped_file_infos: Vec::new(),
            checkpoint: None,
            global_limiter: None,
            #[cfg(feature = "bittorrent")]
            public_tracker_catalog: None,
            #[cfg(feature = "bittorrent")]
            bt_registry: None,
            #[cfg(feature = "bittorrent")]
            bt_listener: None,
            #[cfg(feature = "bittorrent")]
            lpd_manager: None,
        })
    }

    /// Create one `MetalinkDownloadCommand` per file in a multi-file Metalink.
    ///
    /// This is the Rust equivalent of C++ `Metalink2RequestGroup::createRequestGroup()`
    /// which creates one `RequestGroup` per `MetalinkEntry`. Each command
    /// downloads exactly one file from the Metalink using its own mirror list.
    /// Torrent metaurls are retained in `FileDownloadInfo` for the execution
    /// fallback when no direct mirror succeeds.
    ///
    /// # Arguments
    ///
    /// * `metalink_bytes` - Raw Metalink XML data
    /// * `options` - Download options (shared by all files)
    /// * `output_dir` - Override output directory
    /// * `gid_start` - Starting GID; each file gets `gid_start + i`
    ///
    /// # Returns
    ///
    /// A vector of `MetalinkFileInfo`, one per file with HTTP/FTP resources or
    /// a BitTorrent metaurl. Files with no supported resource are skipped.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let commands = MetalinkDownloadCommand::create_multi_file(
    ///     &metalink_xml, &options, None, 100
    /// )?;
    /// for info in commands {
    ///     println!("File {}: {}", info.file_index, info.command.output_path.display());
    /// }
    /// ```
    pub fn create_multi_file(
        metalink_bytes: &[u8],
        options: &DownloadOptions,
        output_dir: Option<&str>,
        gid_start: u64,
    ) -> Result<Vec<MetalinkFileInfo>> {
        Self::create_multi_file_with_base_uri(metalink_bytes, options, output_dir, None, gid_start)
    }

    /// Create per-file commands while resolving relative Metalink URLs
    /// against the source document URI.
    pub fn create_multi_file_with_base_uri(
        metalink_bytes: &[u8],
        options: &DownloadOptions,
        output_dir: Option<&str>,
        base_uri: Option<&str>,
        gid_start: u64,
    ) -> Result<Vec<MetalinkFileInfo>> {
        let doc =
            aria2_protocol::metalink::parser::MetalinkDocument::parse(metalink_bytes, base_uri)
                .map_err(|e| {
                    Aria2Error::Fatal(FatalError::Config(format!("Metalink parse failed: {}", e)))
                })?;

        if doc.files.is_empty() {
            return Err(Aria2Error::Fatal(FatalError::Config(
                "Metalink contains no files".into(),
            )));
        }

        let dir = output_dir
            .map(|d| d.to_string())
            .or_else(|| options.dir.clone())
            .unwrap_or_else(|| ".".to_string());

        let client = build_http_client(options)?;

        let mut commands = Vec::with_capacity(doc.files.len());

        for (i, file) in doc.files.iter().enumerate() {
            let has_torrent_metaurl = file.meta_urls.iter().any(|metaurl| {
                metaurl.mediatype == aria2_protocol::metalink::parser::MediaType::Torrent
            });
            if file.urls.is_empty() && !has_torrent_metaurl {
                tracing::debug!(
                    index = i,
                    name = %file.name,
                    "Skipping Metalink file with no downloadable resources"
                );
                continue;
            }

            let gid = GroupId::new(gid_start + i as u64);
            let path = std::path::PathBuf::from(&dir).join(&file.name);

            let sorted_urls: Vec<UrlEntry> = file
                .get_sorted_urls()
                .iter()
                .map(|u| (*u).clone())
                .collect();
            let urls: Vec<String> = sorted_urls
                .iter()
                .filter(|u| u.is_non_p2p())
                .map(|u| u.url.clone())
                .collect();
            let group = RequestGroup::new(gid, urls, options.clone());
            group.set_output_name(file.name.clone());

            let file_info = FileDownloadInfo {
                expected_size: file.size,
                hash_entry: file.strongest_hash().cloned(),
                sorted_urls,
                pieces: file.pieces.clone(),
                torrent_metaurls: file
                    .meta_urls
                    .iter()
                    .filter(|m| m.mediatype == aria2_protocol::metalink::parser::MediaType::Torrent)
                    .cloned()
                    .collect(),
            };

            info!(
                gid = gid.value(),
                index = i,
                name = %file.name,
                path = %path.display(),
                mirrors = file.urls.len(),
                "Created MetalinkDownloadCommand for file"
            );

            commands.push(MetalinkFileInfo {
                command: Self {
                    group: Arc::new(std::sync::RwLock::new(group)),
                    client: client.clone(),
                    output_path: path,
                    started: false,
                    completed: false,
                    completed_bytes: 0,
                    metalink_data: Vec::new(),
                    file_info: Some(file_info),
                    grouped_file_infos: Vec::new(),
                    checkpoint: None,
                    global_limiter: None,
                    #[cfg(feature = "bittorrent")]
                    public_tracker_catalog: None,
                    #[cfg(feature = "bittorrent")]
                    bt_registry: None,
                    #[cfg(feature = "bittorrent")]
                    bt_listener: None,
                    #[cfg(feature = "bittorrent")]
                    lpd_manager: None,
                },
                file_index: i,
            });
        }

        Ok(commands)
    }

    /// Create a `MetalinkDownloadCommand` from a pre-parsed, pre-sorted
    /// `MetalinkFile` entry.
    ///
    /// This is used by `MetalinkToRequestGroup` which handles its own
    /// parsing, filtering, and priority reordering. Unlike `create_multi_file`,
    /// this method does not re-parse the XML.
    ///
    /// # Arguments
    ///
    /// * `file` - Pre-parsed Metalink file entry with sorted URLs
    /// * `options` - Download options
    /// * `output_dir` - Override output directory
    /// * `gid_start` - Starting GID for this command
    pub fn create_multi_file_for_single(
        file: &aria2_protocol::metalink::parser::MetalinkFile,
        options: &DownloadOptions,
        output_dir: Option<&str>,
        gid_start: u64,
    ) -> Result<Vec<MetalinkFileInfo>> {
        let dir = output_dir
            .map(|d| d.to_string())
            .or_else(|| options.dir.clone())
            .unwrap_or_else(|| ".".to_string());

        let client = build_http_client(options)?;

        let torrent_metaurls: Vec<_> = file
            .meta_urls
            .iter()
            .filter(|metaurl| {
                metaurl.mediatype == aria2_protocol::metalink::parser::MediaType::Torrent
            })
            .cloned()
            .collect();
        if file.urls.is_empty() && torrent_metaurls.is_empty() {
            return Ok(Vec::new());
        }

        let gid = GroupId::new(gid_start);
        let path = std::path::PathBuf::from(&dir).join(&file.name);

        let sorted_urls: Vec<UrlEntry> = file
            .get_sorted_urls()
            .iter()
            .map(|u| (*u).clone())
            .collect();

        // Collect only non-P2P URLs (HTTP, HTTPS, FTP) for the URI list.
        // BitTorrent URLs go through a separate dependency mechanism.
        // Mirrors C++ AccumulateNonP2PUri.
        let urls: Vec<String> = sorted_urls
            .iter()
            .filter(|u| u.is_non_p2p())
            .map(|u| u.url.clone())
            .collect();

        if urls.is_empty() && torrent_metaurls.is_empty() {
            tracing::debug!(
                name = %file.name,
                "Skipping Metalink file with no downloadable resources"
            );
            return Ok(Vec::new());
        }

        let group = RequestGroup::new(gid, urls, options.clone());
        group.set_output_name(file.name.clone());

        let file_info = FileDownloadInfo {
            expected_size: file.size,
            hash_entry: file.strongest_hash().cloned(),
            sorted_urls,
            pieces: file.pieces.clone(),
            torrent_metaurls,
        };

        info!(
            gid = gid.value(),
            name = %file.name,
            path = %path.display(),
            mirrors = file.urls.len(),
            "Created MetalinkDownloadCommand for single file"
        );

        Ok(vec![MetalinkFileInfo {
            command: Self {
                group: Arc::new(std::sync::RwLock::new(group)),
                client,
                output_path: path,
                started: false,
                completed: false,
                completed_bytes: 0,
                metalink_data: Vec::new(),
                file_info: Some(file_info),
                grouped_file_infos: Vec::new(),
                checkpoint: None,
                global_limiter: None,
                #[cfg(feature = "bittorrent")]
                public_tracker_catalog: None,
                #[cfg(feature = "bittorrent")]
                bt_registry: None,
                #[cfg(feature = "bittorrent")]
                bt_listener: None,
                #[cfg(feature = "bittorrent")]
                lpd_manager: None,
            },
            file_index: 0,
        }])
    }

    /// Create one command for a Metalink metaurl group.
    ///
    /// The request context contains one `FileEntry` per selected Metalink
    /// file. This preserves aria2's multi-file group semantics while keeping
    /// execution in the Rust command model instead of duplicating a command
    /// per file.
    pub(crate) fn create_multi_file_group(
        files: &[aria2_protocol::metalink::parser::MetalinkFile],
        options: &DownloadOptions,
        output_dir: Option<&str>,
        gid: u64,
    ) -> Result<Self> {
        if files.is_empty() {
            return Err(Aria2Error::Fatal(FatalError::Config(
                "Metalink group contains no files".to_string(),
            )));
        }

        let dir = output_dir
            .map(str::to_owned)
            .or_else(|| options.dir.clone())
            .unwrap_or_else(|| ".".to_string());
        let client = build_http_client(options)?;
        let mut entries = Vec::with_capacity(files.len());
        let mut grouped_file_infos = Vec::with_capacity(files.len());
        let mut offset = 0u64;

        for file in files {
            let sorted_urls: Vec<UrlEntry> = file.get_sorted_urls().into_iter().cloned().collect();
            let urls: Vec<String> = sorted_urls
                .iter()
                .filter(|url| url.is_non_p2p())
                .map(|url| url.url.clone())
                .collect();
            let torrent_metaurls = file
                .meta_urls
                .iter()
                .filter(|metaurl| {
                    metaurl.mediatype == aria2_protocol::metalink::parser::MediaType::Torrent
                })
                .cloned()
                .collect::<Vec<_>>();
            if urls.is_empty() && torrent_metaurls.is_empty() {
                continue;
            }

            let path = std::path::PathBuf::from(&dir).join(&file.name);
            let mut entry = FileEntry::new(
                path.to_string_lossy().into_owned(),
                file.size.unwrap_or(0),
                offset,
                urls.clone(),
            );
            if let Some(original_name) = torrent_metaurls
                .first()
                .and_then(|metaurl| metaurl.name.clone())
            {
                entry.set_original_name(original_name);
            }
            entry.set_suffix_path(file.name.clone());
            entry.set_max_connection_per_server(
                options
                    .max_connection_per_server
                    .unwrap_or(crate::constants::DEFAULT_MAX_CONNECTION_PER_SERVER as u16)
                    .clamp(1, 16) as usize,
            );
            entry.set_unique_protocol(options.metalink_enable_unique_protocol);
            offset = offset.saturating_add(file.size.unwrap_or(0));
            entries.push(entry);
            grouped_file_infos.push((
                path,
                FileDownloadInfo {
                    expected_size: file.size,
                    hash_entry: file.strongest_hash().cloned(),
                    sorted_urls,
                    pieces: file.pieces.clone(),
                    torrent_metaurls,
                },
            ));
        }

        if grouped_file_infos.is_empty() {
            return Err(Aria2Error::Fatal(FatalError::Config(
                "Metalink group contains no downloadable files".to_string(),
            )));
        }

        let group = RequestGroup::new(GroupId::new(gid), Vec::new(), options.clone());
        let mut context = DownloadContext::new_default();
        context.set_file_entries(entries);
        group.set_download_context(Arc::new(context));
        group.set_output_name(files[0].name.clone());
        let output_path = grouped_file_infos[0].0.clone();

        Ok(Self {
            group: Arc::new(std::sync::RwLock::new(group)),
            client,
            output_path,
            started: false,
            completed: false,
            completed_bytes: 0,
            metalink_data: Vec::new(),
            file_info: None,
            grouped_file_infos,
            checkpoint: None,
            global_limiter: None,
            #[cfg(feature = "bittorrent")]
            public_tracker_catalog: None,
            #[cfg(feature = "bittorrent")]
            bt_registry: None,
            #[cfg(feature = "bittorrent")]
            bt_listener: None,
            #[cfg(feature = "bittorrent")]
            lpd_manager: None,
        })
    }

    /// Create a manager-owned Metalink command for one parsed file entry.
    #[cfg(feature = "metalink")]
    pub(crate) fn new_with_group_source(
        group: Arc<std::sync::RwLock<RequestGroup>>,
        metalink_bytes: &[u8],
        file_index: usize,
        options: &DownloadOptions,
        base_uri: Option<&str>,
    ) -> Result<Self> {
        let doc =
            aria2_protocol::metalink::parser::MetalinkDocument::parse(metalink_bytes, base_uri)
                .map_err(|e| {
                    Aria2Error::Fatal(FatalError::Config(format!("Metalink parse failed: {e}")))
                })?;
        let mut file = doc.files.get(file_index).cloned().ok_or_else(|| {
            Aria2Error::Fatal(FatalError::Config(
                "Metalink file index out of range".to_string(),
            ))
        })?;
        // The manager stores raw Metalink bytes so the task can be rebuilt
        // after a restart. Reapply the same resource normalization used when
        // the group was created; otherwise location/protocol preferences are
        // silently lost at execution time.
        crate::engine::metalink_to_request_group::MetalinkToRequestGroup::new()
            .normalize_file_for_runtime(&mut file, options);
        let dir = options.dir.as_deref().unwrap_or(".");
        let output_name = group
            .recover()
            .output_name()
            .unwrap_or_else(|| file.name.clone());
        let path = std::path::PathBuf::from(dir).join(output_name);
        let sorted_urls: Vec<UrlEntry> = file.get_sorted_urls().into_iter().cloned().collect();
        let file_info = FileDownloadInfo {
            expected_size: file.size,
            hash_entry: file.strongest_hash().cloned(),
            pieces: file.pieces.clone(),
            torrent_metaurls: file
                .meta_urls
                .iter()
                .filter(|m| m.mediatype == aria2_protocol::metalink::parser::MediaType::Torrent)
                .cloned()
                .collect(),
            sorted_urls,
        };
        Ok(Self {
            group,
            client: build_http_client(options)?,
            output_path: path,
            started: false,
            completed: false,
            completed_bytes: 0,
            metalink_data: Vec::new(),
            file_info: Some(file_info),
            grouped_file_infos: Vec::new(),
            checkpoint: None,
            global_limiter: None,
            #[cfg(feature = "bittorrent")]
            public_tracker_catalog: None,
            #[cfg(feature = "bittorrent")]
            bt_registry: None,
            #[cfg(feature = "bittorrent")]
            bt_listener: None,
            #[cfg(feature = "bittorrent")]
            lpd_manager: None,
        })
    }

    /// Get the output path for this download.
    pub fn output_path(&self) -> &std::path::Path {
        &self.output_path
    }

    /// Set the process-wide rate limiter (from `DownloadEngine::global_limiter`).
    ///
    /// When set, mirror downloads acquire tokens from this limiter in addition
    /// to the per-download limiter.
    pub fn set_global_limiter(&mut self, limiter: RateLimiter) {
        self.global_limiter = Some(limiter);
    }

    #[cfg(feature = "bittorrent")]
    pub fn set_public_tracker_catalog(
        &mut self,
        catalog: Arc<aria2_protocol::bittorrent::tracker::public_list::PublicTrackerList>,
    ) {
        self.public_tracker_catalog = Some(catalog);
    }

    #[cfg(feature = "bittorrent")]
    pub fn set_bt_registry(
        &mut self,
        registry: Arc<std::sync::RwLock<crate::engine::bt_registry::BtRegistry>>,
    ) {
        self.bt_registry = Some(registry);
    }

    #[cfg(feature = "bittorrent")]
    pub fn set_bt_listener(
        &mut self,
        listener: Arc<crate::engine::bt_peer_listener::BtPeerListenerManager>,
    ) {
        self.bt_listener = Some(listener);
    }

    #[cfg(feature = "bittorrent")]
    pub fn set_lpd_manager(&mut self, manager: Arc<crate::engine::lpd_manager::LpdManager>) {
        self.lpd_manager = Some(manager);
    }

    pub fn group(&self) -> std::sync::RwLockReadGuard<'_, RequestGroup> {
        self.group.recover()
    }

    /// Consume this command and return the inner `RequestGroup` Arc.
    ///
    /// Used by post-download handlers that need to extract the group
    /// for insertion into the reserved queue without cloning.
    pub fn into_group(self) -> Arc<std::sync::RwLock<RequestGroup>> {
        self.group
    }
}

/// Build the shared HTTP client for Metalink downloads.
pub(crate) fn build_http_client(options: &DownloadOptions) -> Result<reqwest::Client> {
    crate::http::client_pool::ensure_rustls_provider();
    let client_tls = crate::http::client_identity::ClientTlsConfig::from_download_options(options);
    let builder = reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(30))
        .gzip(options.http_accept_gzip)
        .user_agent(crate::constants::USER_AGENT)
        .redirect(reqwest::redirect::Policy::limited(5));
    crate::http::client_identity::apply(builder, &client_tls)?
        .build()
        .map_err(|e| {
            Aria2Error::Fatal(FatalError::Config(format!(
                "HTTP client build failed: {}",
                e
            )))
        })
}