Skip to main content

kget/
queue.rs

1//! Persistent download history.
2//!
3//! Every download — successful or not — is appended to a JSON file in the
4//! OS config directory so the record survives app restarts.
5//!
6//! **File locations**
7//! - macOS:   `~/Library/Application Support/kget/history.json`
8//! - Linux:   `~/.config/kget/history.json`
9//! - Windows: `%APPDATA%\kget\history.json`
10//!
11//! # Example
12//!
13//! ```rust,no_run
14//! use kget::queue::{DownloadHistory, EntryStatus, HistoryEntry};
15//!
16//! let mut history = DownloadHistory::load();
17//!
18//! let mut entry = HistoryEntry::new(
19//!     "https://example.com/file.iso",
20//!     "/home/user/Downloads",
21//!     None,
22//! );
23//! history.record(entry, EntryStatus::Completed, None);
24//! history.save().unwrap();
25//!
26//! for e in history.recent(10) {
27//!     println!("{} {} {}", e.created_at_display(), e.status, e.filename);
28//! }
29//! ```
30
31use crate::utils::get_filename_from_url_or_default;
32use serde::{Deserialize, Serialize};
33use std::path::PathBuf;
34use std::time::{SystemTime, UNIX_EPOCH};
35
36// ============================================================================
37// Public types
38// ============================================================================
39
40/// Outcome of a completed download attempt.
41#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
42#[serde(rename_all = "lowercase")]
43pub enum EntryStatus {
44    Completed,
45    Failed,
46    Cancelled,
47}
48
49impl std::fmt::Display for EntryStatus {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        match self {
52            EntryStatus::Completed => write!(f, "completed"),
53            EntryStatus::Failed => write!(f, "failed"),
54            EntryStatus::Cancelled => write!(f, "cancelled"),
55        }
56    }
57}
58
59/// A single record in the download history.
60#[derive(Serialize, Deserialize, Clone, Debug)]
61pub struct HistoryEntry {
62    /// Short hex identifier derived from the URL and creation time.
63    pub id: String,
64    /// Source URL or magnet link.
65    pub url: String,
66    /// Filename extracted from the URL or Content-Disposition.
67    pub filename: String,
68    /// Directory where the file was (or would be) saved.
69    pub output_dir: String,
70    /// Final outcome.
71    pub status: EntryStatus,
72    /// File size in bytes, if known after the download.
73    pub bytes_total: Option<u64>,
74    /// SHA-256 of the completed file, if computed.
75    pub sha256: Option<String>,
76    /// Expected SHA-256 supplied by the user, if any.
77    pub expected_sha256: Option<String>,
78    /// Unix timestamp (seconds UTC) when the download was enqueued.
79    pub created_at: u64,
80    /// Unix timestamp (seconds UTC) when the download finished.
81    pub finished_at: Option<u64>,
82    /// Error message for failed downloads.
83    pub error: Option<String>,
84}
85
86impl HistoryEntry {
87    /// Create a new pending entry.  Call [`DownloadHistory::record`] to
88    /// finalise it with a status and optional error once the download is done.
89    pub fn new(url: &str, output_dir: &str, expected_sha256: Option<&str>) -> Self {
90        let now = unix_now();
91        let url_hash: u64 = url
92            .bytes()
93            .fold(0u64, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u64));
94        let id = format!("{:08x}{:08x}", now as u32, url_hash as u32);
95        let filename = get_filename_from_url_or_default(url, "download");
96        Self {
97            id,
98            url: url.to_string(),
99            filename,
100            output_dir: output_dir.to_string(),
101            status: EntryStatus::Completed,
102            bytes_total: None,
103            sha256: None,
104            expected_sha256: expected_sha256.map(str::to_string),
105            created_at: now,
106            finished_at: None,
107            error: None,
108        }
109    }
110
111    /// Human-readable UTC string for `created_at` (e.g. `2026-05-21 14:32 UTC`).
112    pub fn created_at_display(&self) -> String {
113        format_unix(self.created_at)
114    }
115
116    /// Human-readable UTC string for `finished_at`, if set.
117    pub fn finished_at_display(&self) -> Option<String> {
118        self.finished_at.map(format_unix)
119    }
120}
121
122/// Persistent download history backed by a JSON file in the OS config dir.
123pub struct DownloadHistory {
124    entries: Vec<HistoryEntry>,
125    path: PathBuf,
126}
127
128impl DownloadHistory {
129    /// Load history from disk.  Returns an empty history if the file does
130    /// not exist or cannot be parsed.
131    pub fn load() -> Self {
132        let path = history_path();
133        let entries = try_load(&path).unwrap_or_default();
134        Self { entries, path }
135    }
136
137    /// Write the current history to disk.
138    pub fn save(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
139        if let Some(parent) = self.path.parent() {
140            std::fs::create_dir_all(parent)?;
141        }
142        let json = serde_json::to_string_pretty(&self.entries)?;
143        std::fs::write(&self.path, json)?;
144        Ok(())
145    }
146
147    /// Finalise an entry with a status and optional error message, then
148    /// append (or replace, if the same URL already has an entry) it.
149    pub fn record(&mut self, mut entry: HistoryEntry, status: EntryStatus, error: Option<String>) {
150        entry.status = status;
151        entry.finished_at = Some(unix_now());
152        entry.error = error;
153
154        if let Some(pos) = self.entries.iter().position(|e| e.url == entry.url) {
155            self.entries[pos] = entry;
156        } else {
157            self.entries.push(entry);
158        }
159    }
160
161    /// All history entries in insertion order (oldest first).
162    pub fn entries(&self) -> &[HistoryEntry] {
163        &self.entries
164    }
165
166    /// Up to `n` most-recent entries, newest first.
167    pub fn recent(&self, n: usize) -> Vec<&HistoryEntry> {
168        let mut v: Vec<&HistoryEntry> = self.entries.iter().collect();
169        v.sort_by(|a, b| b.created_at.cmp(&a.created_at));
170        v.into_iter().take(n).collect()
171    }
172
173    /// Remove entries whose status is `Completed` or `Cancelled`.
174    ///
175    /// Returns the number of entries removed.
176    pub fn clear_completed(&mut self) -> usize {
177        let before = self.entries.len();
178        self.entries.retain(|e| e.status == EntryStatus::Failed);
179        before - self.entries.len()
180    }
181
182    /// Remove every history entry.
183    ///
184    /// Returns the number of entries removed.
185    pub fn clear_all(&mut self) -> usize {
186        let n = self.entries.len();
187        self.entries.clear();
188        n
189    }
190
191    /// Filesystem path of the history file (OS config dir).
192    pub fn path(&self) -> &PathBuf {
193        &self.path
194    }
195}
196
197// ============================================================================
198// Internal helpers
199// ============================================================================
200
201fn history_path() -> PathBuf {
202    dirs::config_dir()
203        .unwrap_or_else(|| PathBuf::from("."))
204        .join("kget")
205        .join("history.json")
206}
207
208fn try_load(path: &PathBuf) -> Option<Vec<HistoryEntry>> {
209    let content = std::fs::read_to_string(path).ok()?;
210    serde_json::from_str(&content).ok()
211}
212
213fn unix_now() -> u64 {
214    SystemTime::now()
215        .duration_since(UNIX_EPOCH)
216        .unwrap_or_default()
217        .as_secs()
218}
219
220/// Format a Unix timestamp as `YYYY-MM-DD HH:MM UTC` without external crates.
221///
222/// Uses the civil-date algorithm described by Howard Hinnant.
223pub fn format_unix(secs: u64) -> String {
224    let days_since_epoch = secs / 86400;
225    let time_of_day = secs % 86400;
226    let h = time_of_day / 3600;
227    let m = (time_of_day % 3600) / 60;
228
229    let (y, mo, d) = civil_date(days_since_epoch);
230    format!("{:04}-{:02}-{:02} {:02}:{:02} UTC", y, mo, d, h, m)
231}
232
233/// Convert days since Unix epoch (1970-01-01) to (year, month, day).
234fn civil_date(days: u64) -> (u64, u64, u64) {
235    // Shift epoch to 0000-03-01 to simplify leap-year arithmetic.
236    let z = days as i64 + 719468;
237    let era: i64 = if z >= 0 { z } else { z - 146096 } / 146097;
238    let doe = (z - era * 146097) as u64; // day of era [0, 146096]
239    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // year of era [0, 399]
240    let y = yoe as i64 + era * 400;
241    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // day of year [0, 365]
242    let mp = (5 * doy + 2) / 153; // month of year (March-based) [0, 11]
243    let d = doy - (153 * mp + 2) / 5 + 1; // day [1, 31]
244    let m = if mp < 10 { mp + 3 } else { mp - 9 }; // month [1, 12]
245    let y = if m <= 2 { y + 1 } else { y };
246    (y as u64, m, d)
247}