1use crate::utils::get_filename_from_url_or_default;
32use serde::{Deserialize, Serialize};
33use std::path::PathBuf;
34use std::time::{SystemTime, UNIX_EPOCH};
35
36#[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#[derive(Serialize, Deserialize, Clone, Debug)]
61pub struct HistoryEntry {
62 pub id: String,
64 pub url: String,
66 pub filename: String,
68 pub output_dir: String,
70 pub status: EntryStatus,
72 pub bytes_total: Option<u64>,
74 pub sha256: Option<String>,
76 pub expected_sha256: Option<String>,
78 pub created_at: u64,
80 pub finished_at: Option<u64>,
82 pub error: Option<String>,
84}
85
86impl HistoryEntry {
87 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 pub fn created_at_display(&self) -> String {
113 format_unix(self.created_at)
114 }
115
116 pub fn finished_at_display(&self) -> Option<String> {
118 self.finished_at.map(format_unix)
119 }
120}
121
122pub struct DownloadHistory {
124 entries: Vec<HistoryEntry>,
125 path: PathBuf,
126}
127
128impl DownloadHistory {
129 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 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 pub fn record(
150 &mut self,
151 mut entry: HistoryEntry,
152 status: EntryStatus,
153 error: Option<String>,
154 ) {
155 entry.status = status;
156 entry.finished_at = Some(unix_now());
157 entry.error = error;
158
159 if let Some(pos) = self.entries.iter().position(|e| e.url == entry.url) {
160 self.entries[pos] = entry;
161 } else {
162 self.entries.push(entry);
163 }
164 }
165
166 pub fn entries(&self) -> &[HistoryEntry] {
168 &self.entries
169 }
170
171 pub fn recent(&self, n: usize) -> Vec<&HistoryEntry> {
173 let mut v: Vec<&HistoryEntry> = self.entries.iter().collect();
174 v.sort_by(|a, b| b.created_at.cmp(&a.created_at));
175 v.into_iter().take(n).collect()
176 }
177
178 pub fn clear_completed(&mut self) -> usize {
182 let before = self.entries.len();
183 self.entries
184 .retain(|e| e.status == EntryStatus::Failed);
185 before - self.entries.len()
186 }
187
188 pub fn clear_all(&mut self) -> usize {
192 let n = self.entries.len();
193 self.entries.clear();
194 n
195 }
196
197 pub fn path(&self) -> &PathBuf {
199 &self.path
200 }
201}
202
203fn history_path() -> PathBuf {
208 dirs::config_dir()
209 .unwrap_or_else(|| PathBuf::from("."))
210 .join("kget")
211 .join("history.json")
212}
213
214fn try_load(path: &PathBuf) -> Option<Vec<HistoryEntry>> {
215 let content = std::fs::read_to_string(path).ok()?;
216 serde_json::from_str(&content).ok()
217}
218
219fn unix_now() -> u64 {
220 SystemTime::now()
221 .duration_since(UNIX_EPOCH)
222 .unwrap_or_default()
223 .as_secs()
224}
225
226pub fn format_unix(secs: u64) -> String {
230 let days_since_epoch = secs / 86400;
231 let time_of_day = secs % 86400;
232 let h = time_of_day / 3600;
233 let m = (time_of_day % 3600) / 60;
234
235 let (y, mo, d) = civil_date(days_since_epoch);
236 format!("{:04}-{:02}-{:02} {:02}:{:02} UTC", y, mo, d, h, m)
237}
238
239fn civil_date(days: u64) -> (u64, u64, u64) {
241 let z = days as i64 + 719468;
243 let era: i64 = if z >= 0 { z } else { z - 146096 } / 146097;
244 let doe = (z - era * 146097) as u64; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; let y = yoe as i64 + era * 400;
247 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; let y = if m <= 2 { y + 1 } else { y };
252 (y as u64, m, d)
253}