shrupl/src/appstate.rs

60 lines
1.5 KiB
Rust
Raw Normal View History

2025-06-02 23:57:17 +00:00
use std::{
fs,
io::{self, Write},
path::{Path, PathBuf},
2025-06-02 23:57:17 +00:00
};
use log::{debug, trace};
use serde::{Deserialize, Serialize};
use super::{
cli::Cli,
sharry::{Alias, FileChecked, FileUploading, Share},
2025-06-02 23:57:17 +00:00
};
#[derive(Serialize, Deserialize, Debug)]
pub struct AppState {
alias: Alias,
share: Share,
checked: Vec<FileChecked>,
uploading: Vec<FileUploading>,
}
fn get_cachefile(args: &Cli) -> Option<PathBuf> {
let file_name: PathBuf = dirs_next::cache_dir()?
.join("shrupl")
.join(format!("{}.json", args.get_hash()));
trace!("cachefile: {}", file_name.display());
Some(file_name)
2025-06-02 23:57:17 +00:00
}
impl AppState {
fn load(file_name: impl AsRef<Path>) -> io::Result<Self> {
let content = fs::read_to_string(file_name)?;
serde_json::from_str(&content).map_err(io::Error::other)
2025-06-02 23:57:17 +00:00
}
fn save(&self, file_name: impl AsRef<Path>) -> io::Result<()> {
let json = serde_json::to_string_pretty(self).map_err(io::Error::other)?;
let mut file = fs::File::create(file_name)?;
file.write_all(json.as_bytes())?;
Ok(())
}
pub fn try_resume(args: &Cli) -> Option<Self> {
let file_name = get_cachefile(args)?;
2025-06-02 23:57:17 +00:00
// let content = fs::read_to_string(&file_name).ok()?;
// serde_json::from_str(&content)
// .inspect_err(|e| debug!("could not resume from {}: {e}", &file_name.display()))
// .ok()
2025-06-02 23:57:17 +00:00
Self::load(&file_name)
.inspect_err(|e| debug!("could not resume from {}: {e}", file_name.display()))
.ok()
}
}