formatting

This commit is contained in:
Tickbase
2025-05-17 22:49:09 +02:00
parent ecd05f1980
commit 76bfea819b
46 changed files with 2905 additions and 2743 deletions

View File

@@ -1,13 +1,11 @@
// src/cache.rs
use serde::{Serialize, Deserialize};
use crate::dlc_manager::DlcInfoWithState;
use log::{info, warn};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::path::{PathBuf};
use std::fs;
use std::io;
use std::time::{SystemTime};
use log::{info, warn};
use crate::dlc_manager::DlcInfoWithState;
use std::path::PathBuf;
use std::time::SystemTime;
// Cache entry with timestamp for expiration
#[derive(Serialize, Deserialize)]
@@ -20,14 +18,14 @@ struct CacheEntry<T> {
fn get_cache_dir() -> io::Result<PathBuf> {
let xdg_dirs = xdg::BaseDirectories::with_prefix("creamlinux")
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
let cache_dir = xdg_dirs.get_cache_home();
// Make sure the cache directory exists
if !cache_dir.exists() {
fs::create_dir_all(&cache_dir)?;
}
Ok(cache_dir)
}
@@ -38,26 +36,26 @@ where
{
let cache_dir = get_cache_dir()?;
let cache_file = cache_dir.join(format!("{}.cache", key));
// Get current timestamp
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
// Create a JSON object with timestamp and data directly
let json_data = json!({
"timestamp": now,
"data": data // No clone needed here
});
// Serialize and write to file
let serialized = serde_json::to_string(&json_data)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
let serialized =
serde_json::to_string(&json_data).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
fs::write(cache_file, serialized)?;
info!("Saved cache for key: {}", key);
Ok(())
}
@@ -73,14 +71,14 @@ where
return None;
}
};
let cache_file = cache_dir.join(format!("{}.cache", key));
// Check if cache file exists
if !cache_file.exists() {
return None;
}
// Read and deserialize
let cached_data = match fs::read_to_string(&cache_file) {
Ok(data) => data,
@@ -89,54 +87,58 @@ where
return None;
}
};
// Parse the JSON
let json_value: serde_json::Value = match serde_json::from_str(&cached_data) {
Ok(v) => v,
Err(e) => {
warn!("Failed to parse cache file {}: {}", cache_file.display(), e);
return None;
}
};
// Extract timestamp
let timestamp = match json_value.get("timestamp").and_then(|v| v.as_u64()) {
Some(ts) => ts,
None => {
warn!("Invalid timestamp in cache file {}", cache_file.display());
return None;
}
};
// Check expiration
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let age_hours = (now - timestamp) / 3600;
if age_hours > ttl_hours {
info!("Cache for key {} is expired ({} hours old)", key, age_hours);
return None;
}
// Extract data
let data: T = match serde_json::from_value(json_value["data"].clone()) {
Ok(d) => d,
Err(e) => {
warn!("Failed to parse data in cache file {}: {}", cache_file.display(), e);
return None;
}
};
info!("Using cache for key {} ({} hours old)", key, age_hours);
Some(data)
Ok(v) => v,
Err(e) => {
warn!("Failed to parse cache file {}: {}", cache_file.display(), e);
return None;
}
};
// Extract timestamp
let timestamp = match json_value.get("timestamp").and_then(|v| v.as_u64()) {
Some(ts) => ts,
None => {
warn!("Invalid timestamp in cache file {}", cache_file.display());
return None;
}
};
// Check expiration
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let age_hours = (now - timestamp) / 3600;
if age_hours > ttl_hours {
info!("Cache for key {} is expired ({} hours old)", key, age_hours);
return None;
}
// Extract data
let data: T = match serde_json::from_value(json_value["data"].clone()) {
Ok(d) => d,
Err(e) => {
warn!(
"Failed to parse data in cache file {}: {}",
cache_file.display(),
e
);
return None;
}
};
info!("Using cache for key {} ({} hours old)", key, age_hours);
Some(data)
}
// Cache game scanning results
pub fn cache_games(games: &[crate::installer::Game]) -> io::Result<()> {
save_to_cache("games", games, 24) // Cache games for 24 hours
save_to_cache("games", games, 24) // Cache games for 24 hours
}
// Load cached game scanning results
@@ -146,7 +148,7 @@ pub fn load_cached_games() -> Option<Vec<crate::installer::Game>> {
// Cache DLC list for a game
pub fn cache_dlcs(game_id: &str, dlcs: &[DlcInfoWithState]) -> io::Result<()> {
save_to_cache(&format!("dlc_{}", game_id), dlcs, 168) // Cache DLCs for 7 days (168 hours)
save_to_cache(&format!("dlc_{}", game_id), dlcs, 168) // Cache DLCs for 7 days (168 hours)
}
// Load cached DLC list
@@ -157,11 +159,11 @@ pub fn load_cached_dlcs(game_id: &str) -> Option<Vec<DlcInfoWithState>> {
// Clear all caches
pub fn clear_all_caches() -> io::Result<()> {
let cache_dir = get_cache_dir()?;
for entry in fs::read_dir(cache_dir)? {
let entry = entry?;
let path = entry.path();
if path.is_file() && path.extension().map_or(false, |ext| ext == "cache") {
if let Err(e) = fs::remove_file(&path) {
warn!("Failed to remove cache file {}: {}", path.display(), e);
@@ -170,7 +172,7 @@ pub fn clear_all_caches() -> io::Result<()> {
}
}
}
info!("All caches cleared");
Ok(())
}
}