aria2-core 0.3.4

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
//! Rich download result for RPC consumers.
//!
//! Mirrors C++ `DownloadResult` which carries the full download snapshot
//! for `aria2.tellStatus`, `aria2.tellStopped`, `aria2.getDownloadResult`
//! RPC methods. Contains GID, progress stats, file entries, BT info hash,
//! and relationship GIDs (followedBy / following / belongsTo).

use serde::{Deserialize, Serialize};

use super::GroupId;
use super::result_code::DownloadResultCode;
use super::status::DownloadStatus;

/// File entry within a download result.
///
/// Mirrors C++ `FileData` / `FileEntry` information exposed by RPC.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileEntry {
    /// File index (1-based, matching C++ convention).
    pub index: usize,
    /// File path relative to download directory.
    pub path: String,
    /// Total file length in bytes.
    pub length: u64,
    /// Completed bytes for this file.
    pub completed_length: u64,
    /// Whether this file is selected for download.
    pub selected: bool,
    /// URIs associated with this file.
    pub uris: Vec<UriEntry>,
}

/// URI entry within a file entry.
///
/// Mirrors C++ `URIResult` exposed by RPC.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UriEntry {
    /// The URI string.
    pub uri: String,
    /// Current status of this URI ("used", "waiting", "spent").
    pub status: String,
}

/// Rich download result for RPC consumers.
///
/// Mirrors C++ `DownloadResult` with all fields needed for
/// `aria2.tellStatus`, `aria2.tellStopped`, and `aria2.getDownloadResult`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownloadResult {
    // ── Identity ────────────────────────────────────────────────────────
    /// GID of the download this result refers to.
    pub gid: GroupId,
    /// Download status at the time of result creation.
    pub status: DownloadStatus,
    /// Structured result code.
    pub code: DownloadResultCode,
    /// Human-readable error / status message.
    pub message: String,
    /// The request-option snapshot owned by this terminal result.
    ///
    /// C++ aria2 retains the group's `Option` so `aria2.getOption` continues
    /// to work after the request group has moved into stopped storage. This
    /// is adapter-facing state, not part of the serialized result payload.
    #[serde(skip)]
    option_snapshot: Option<std::collections::HashMap<String, serde_json::Value>>,

    // ── Progress ────────────────────────────────────────────────────────
    /// Total length of the download in bytes.
    pub total_length: u64,
    /// Completed length in bytes.
    pub completed_length: u64,
    /// Total uploaded bytes (BT only, 0 for non-BT).
    pub upload_length: u64,
    /// Download speed in bytes/sec at the time of snapshot.
    pub download_speed: u64,
    /// Upload speed in bytes/sec at the time of snapshot (BT only).
    pub upload_speed: u64,
    /// Total number of pieces.
    pub num_pieces: u32,
    /// Piece length in bytes.
    pub piece_length: u32,
    /// Bitfield representing completed pieces (hex string for RPC).
    /// Empty string if not applicable.
    pub bitfield: String,

    // ── Relationships ──────────────────────────────────────────────────
    /// GIDs of downloads that were spawned by this one
    /// (e.g. Metalink → child downloads, torrent → magnet).
    pub followed_by: Vec<GroupId>,
    /// GID of the parent download that spawned this one.
    pub following: Option<GroupId>,
    /// GID of the download this one belongs to (e.g. BT parent).
    pub belongs_to: Option<GroupId>,

    // ── File info ──────────────────────────────────────────────────────
    /// Download directory.
    pub dir: String,
    /// File entries for multi-file downloads.
    pub files: Vec<FileEntry>,
    /// BT info hash (empty string for non-BT).
    pub info_hash: String,

    // ── Metadata ───────────────────────────────────────────────────────
    /// Download context attributes (e.g. CTX_ATTR_ED2K for aria2-next).
    pub attrs: std::collections::HashMap<String, String>,
    /// Whether this was an in-memory download (metadata exchange only).
    pub in_memory_download: bool,
    /// Session download length (bytes downloaded since session start).
    pub session_download_length: u64,
    /// Session time (seconds since session start).
    pub session_time: u64,
}

impl DownloadResult {
    /// Create a new download result with identity fields and defaults.
    pub fn new(gid: GroupId, status: DownloadStatus, code: DownloadResultCode) -> Self {
        let message = match code {
            DownloadResultCode::Finished => "OK".to_string(),
            DownloadResultCode::Removed => "Download removed by user".to_string(),
            DownloadResultCode::InProgress => "Download interrupted by shutdown".to_string(),
            _ => format!("{}", code),
        };

        Self {
            gid,
            status,
            code,
            message,
            option_snapshot: None,
            total_length: 0,
            completed_length: 0,
            upload_length: 0,
            download_speed: 0,
            upload_speed: 0,
            num_pieces: 0,
            piece_length: 0,
            bitfield: String::new(),
            followed_by: Vec::new(),
            following: None,
            belongs_to: None,
            dir: String::new(),
            files: Vec::new(),
            info_hash: String::new(),
            attrs: std::collections::HashMap::new(),
            in_memory_download: false,
            session_download_length: 0,
            session_time: 0,
        }
    }

    pub(crate) fn set_option_snapshot(
        &mut self,
        options: Option<std::collections::HashMap<String, serde_json::Value>>,
    ) {
        self.option_snapshot = options;
    }

    /// Return the option state captured when the request became terminal.
    pub fn option_snapshot(&self) -> Option<&std::collections::HashMap<String, serde_json::Value>> {
        self.option_snapshot.as_ref()
    }

    /// Create a successful result (convenience for tests).
    pub fn finished() -> Self {
        Self {
            gid: GroupId(0),
            status: DownloadStatus::Complete,
            code: DownloadResultCode::Finished,
            message: String::from("OK"),
            option_snapshot: None,
            total_length: 0,
            completed_length: 0,
            upload_length: 0,
            download_speed: 0,
            upload_speed: 0,
            num_pieces: 0,
            piece_length: 0,
            bitfield: String::new(),
            followed_by: Vec::new(),
            following: None,
            belongs_to: None,
            dir: String::new(),
            files: Vec::new(),
            info_hash: String::new(),
            attrs: std::collections::HashMap::new(),
            in_memory_download: false,
            session_download_length: 0,
            session_time: 0,
        }
    }

    /// Create a result for a user-removed download.
    pub fn removed() -> Self {
        Self {
            gid: GroupId(0),
            status: DownloadStatus::Removed,
            code: DownloadResultCode::Removed,
            message: String::from("Download removed by user"),
            ..Self::finished()
        }
    }

    /// Create a result for an interrupted (shutdown) download.
    pub fn in_progress() -> Self {
        Self {
            gid: GroupId(0),
            status: DownloadStatus::Active,
            code: DownloadResultCode::InProgress,
            message: String::from("Download interrupted by shutdown"),
            ..Self::finished()
        }
    }

    /// Create a result for a paused download.
    pub fn paused() -> Self {
        Self {
            gid: GroupId(0),
            status: DownloadStatus::Paused,
            // C++ has no paused error code. A paused task is not normally
            // stored as a stopped result; keep this constructor wire-safe for
            // callers that need a snapshot before requeueing.
            code: DownloadResultCode::UnknownError,
            message: String::from("Download paused"),
            ..Self::finished()
        }
    }

    /// Create an error result with a specific code and message.
    pub fn error(code: DownloadResultCode, message: impl Into<String>) -> Self {
        Self {
            gid: GroupId(0),
            status: DownloadStatus::Error(String::new()),
            code,
            message: message.into(),
            ..Self::finished()
        }
    }

    /// Get the GID as a hex string (for RPC compatibility).
    pub fn gid_hex(&self) -> String {
        self.gid.to_hex_string()
    }

    /// Fill in progress stats from the given `RequestGroup`.
    ///
    /// Reads `total_length`, `completed_length`, `upload_length`,
    /// `download_speed`, `upload_speed`, `dir`, and `info_hash`
    /// from the group's `AtomicProgress` and options.
    pub fn fill_from_group(&mut self, group: &super::RequestGroup) {
        self.total_length = group.total_length();
        self.completed_length = group.completed_length();
        self.upload_length = group.upload_length();
        self.download_speed = group.download_speed();
        self.upload_speed = group.upload_speed();
        self.session_time = group.elapsed_time().map_or(0, |elapsed| elapsed.as_secs());
        self.dir = group.options().dir.clone().unwrap_or_default();
        self.info_hash = group.info_hash_hex().unwrap_or_default();
        self.in_memory_download = group.is_in_memory_download();

        let files = if let Some(context) = group.get_download_context() {
            context
                .get_file_entries()
                .iter()
                .enumerate()
                .map(|(index, file)| {
                    let completed_length = self
                        .completed_length
                        .saturating_sub(file.offset())
                        .min(file.length());
                    let uris = file
                        .uris()
                        .into_iter()
                        .map(|uri| {
                            let status = if file.remaining_uris().iter().any(|value| value == &uri)
                            {
                                "waiting"
                            } else if file.spent_uris().iter().any(|value| value == &uri) {
                                "used"
                            } else {
                                "spent"
                            };
                            UriEntry {
                                uri,
                                status: status.to_string(),
                            }
                        })
                        .collect();

                    FileEntry {
                        index: index + 1,
                        path: file.path().to_string(),
                        length: file.length(),
                        completed_length,
                        selected: file.is_requested(),
                        uris,
                    }
                })
                .collect()
        } else {
            let uris = group
                .get_all_uris()
                .into_iter()
                .map(|uri| UriEntry {
                    uri,
                    status: "waiting".to_string(),
                })
                .collect();
            vec![FileEntry {
                index: 1,
                path: group
                    .output_name()
                    .or_else(|| group.options().out.clone())
                    .unwrap_or_default(),
                length: self.total_length,
                completed_length: self.completed_length,
                selected: true,
                uris,
            }]
        };
        self.files = if files.is_empty() {
            let uris = group
                .get_all_uris()
                .into_iter()
                .map(|uri| UriEntry {
                    uri,
                    status: "waiting".to_string(),
                })
                .collect();
            vec![FileEntry {
                index: 1,
                path: group
                    .output_name()
                    .or_else(|| group.options().out.clone())
                    .unwrap_or_default(),
                length: self.total_length,
                completed_length: self.completed_length,
                selected: true,
                uris,
            }]
        } else {
            files
        };

        self.num_pieces = group.get_bt_num_pieces();
        self.piece_length = group.get_bt_piece_length();
        if let Some(bitfield) = group.get_bt_bitfield() {
            self.bitfield = bitfield.iter().map(|byte| format!("{byte:02x}")).collect();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_result_code_roundtrip() {
        for code in [
            DownloadResultCode::Finished,
            DownloadResultCode::TimeOut,
            DownloadResultCode::Removed,
            DownloadResultCode::InProgress,
            DownloadResultCode::ChecksumError,
        ] {
            assert_eq!(DownloadResultCode::from_code(code.as_code()), Some(code));
        }
    }

    #[test]
    fn test_is_success() {
        assert!(DownloadResultCode::Finished.is_success());
        assert!(!DownloadResultCode::TimeOut.is_success());
    }

    #[test]
    fn test_is_resumable() {
        assert!(DownloadResultCode::InProgress.is_resumable());
        assert!(!DownloadResultCode::TimeOut.is_resumable());
    }

    #[test]
    fn test_is_user_stopped() {
        assert!(DownloadResultCode::Removed.is_user_stopped());
        assert!(!DownloadResultCode::InProgress.is_user_stopped());
    }

    #[test]
    fn test_download_result_finished() {
        let r = DownloadResult::finished();
        assert_eq!(r.code, DownloadResultCode::Finished);
        assert_eq!(r.total_length, 0);
        assert!(r.followed_by.is_empty());
    }

    #[test]
    fn test_download_result_removed() {
        let r = DownloadResult::removed();
        assert_eq!(r.code, DownloadResultCode::Removed);
    }

    #[test]
    fn test_download_result_in_progress() {
        let r = DownloadResult::in_progress();
        assert_eq!(r.code, DownloadResultCode::InProgress);
    }

    #[test]
    fn test_download_result_paused_has_no_rust_only_error_code() {
        let r = DownloadResult::paused();
        assert_eq!(r.status, DownloadStatus::Paused);
        assert_eq!(r.code, DownloadResultCode::UnknownError);
        assert_ne!(r.code.as_code(), 33);
    }

    #[test]
    fn test_download_result_has_all_rpc_fields() {
        let r = DownloadResult::finished();
        // Verify all fields that RPC consumers expect are present.
        assert_eq!(r.gid_hex(), "0000000000000000");
        assert_eq!(r.total_length, 0);
        assert_eq!(r.completed_length, 0);
        assert_eq!(r.upload_length, 0);
        assert_eq!(r.download_speed, 0);
        assert_eq!(r.upload_speed, 0);
        assert_eq!(r.num_pieces, 0);
        assert_eq!(r.piece_length, 0);
        assert!(r.bitfield.is_empty());
        assert!(r.followed_by.is_empty());
        assert!(r.following.is_none());
        assert!(r.belongs_to.is_none());
        assert!(r.dir.is_empty());
        assert!(r.files.is_empty());
        assert!(r.info_hash.is_empty());
        assert!(r.attrs.is_empty());
        assert!(!r.in_memory_download);
        assert_eq!(r.session_download_length, 0);
        assert_eq!(r.session_time, 0);
    }
}