use crate::utils::get_filename_from_url_or_default;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum EntryStatus {
Completed,
Failed,
Cancelled,
}
impl std::fmt::Display for EntryStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EntryStatus::Completed => write!(f, "completed"),
EntryStatus::Failed => write!(f, "failed"),
EntryStatus::Cancelled => write!(f, "cancelled"),
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct HistoryEntry {
pub id: String,
pub url: String,
pub filename: String,
pub output_dir: String,
pub status: EntryStatus,
pub bytes_total: Option<u64>,
pub sha256: Option<String>,
pub expected_sha256: Option<String>,
pub created_at: u64,
pub finished_at: Option<u64>,
pub error: Option<String>,
}
impl HistoryEntry {
pub fn new(url: &str, output_dir: &str, expected_sha256: Option<&str>) -> Self {
let now = unix_now();
let url_hash: u64 = url
.bytes()
.fold(0u64, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u64));
let id = format!("{:08x}{:08x}", now as u32, url_hash as u32);
let filename = get_filename_from_url_or_default(url, "download");
Self {
id,
url: url.to_string(),
filename,
output_dir: output_dir.to_string(),
status: EntryStatus::Completed,
bytes_total: None,
sha256: None,
expected_sha256: expected_sha256.map(str::to_string),
created_at: now,
finished_at: None,
error: None,
}
}
pub fn created_at_display(&self) -> String {
format_unix(self.created_at)
}
pub fn finished_at_display(&self) -> Option<String> {
self.finished_at.map(format_unix)
}
}
pub struct DownloadHistory {
entries: Vec<HistoryEntry>,
path: PathBuf,
}
impl DownloadHistory {
pub fn load() -> Self {
let path = history_path();
let entries = try_load(&path).unwrap_or_default();
Self { entries, path }
}
pub fn save(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
if let Some(parent) = self.path.parent() {
std::fs::create_dir_all(parent)?;
}
let json = serde_json::to_string_pretty(&self.entries)?;
std::fs::write(&self.path, json)?;
Ok(())
}
pub fn record(&mut self, mut entry: HistoryEntry, status: EntryStatus, error: Option<String>) {
entry.status = status;
entry.finished_at = Some(unix_now());
entry.error = error;
if let Some(pos) = self.entries.iter().position(|e| e.url == entry.url) {
self.entries[pos] = entry;
} else {
self.entries.push(entry);
}
}
pub fn entries(&self) -> &[HistoryEntry] {
&self.entries
}
pub fn recent(&self, n: usize) -> Vec<&HistoryEntry> {
let mut v: Vec<&HistoryEntry> = self.entries.iter().collect();
v.sort_by(|a, b| b.created_at.cmp(&a.created_at));
v.into_iter().take(n).collect()
}
pub fn clear_completed(&mut self) -> usize {
let before = self.entries.len();
self.entries.retain(|e| e.status == EntryStatus::Failed);
before - self.entries.len()
}
pub fn clear_all(&mut self) -> usize {
let n = self.entries.len();
self.entries.clear();
n
}
pub fn path(&self) -> &PathBuf {
&self.path
}
}
fn history_path() -> PathBuf {
dirs::config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("kget")
.join("history.json")
}
fn try_load(path: &PathBuf) -> Option<Vec<HistoryEntry>> {
let content = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&content).ok()
}
fn unix_now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
pub fn format_unix(secs: u64) -> String {
let days_since_epoch = secs / 86400;
let time_of_day = secs % 86400;
let h = time_of_day / 3600;
let m = (time_of_day % 3600) / 60;
let (y, mo, d) = civil_date(days_since_epoch);
format!("{:04}-{:02}-{:02} {:02}:{:02} UTC", y, mo, d, h, m)
}
fn civil_date(days: u64) -> (u64, u64, u64) {
let z = days as i64 + 719468;
let era: i64 = if z >= 0 { z } else { z - 146096 } / 146097;
let doe = (z - era * 146097) as u64; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; let y = yoe as i64 + era * 400;
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 };
(y as u64, m, d)
}