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(&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 pub fn entries(&self) -> &[HistoryEntry] {
163 &self.entries
164 }
165
166 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 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 pub fn clear_all(&mut self) -> usize {
186 let n = self.entries.len();
187 self.entries.clear();
188 n
189 }
190
191 pub fn path(&self) -> &PathBuf {
193 &self.path
194 }
195}
196
197fn 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
220pub 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
233fn civil_date(days: u64) -> (u64, u64, u64) {
235 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; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; let y = yoe as i64 + era * 400;
241 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 };
246 (y as u64, m, d)
247}