first
This commit is contained in:
76
src/data_mgt.rs
Normal file
76
src/data_mgt.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
use anyhow::Result;
|
||||
use chrono::{Duration, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::DATA_STORAGE;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
pub struct Asset {
|
||||
id: String,
|
||||
share_duration: u32,
|
||||
created_at: i64,
|
||||
expires_at: i64,
|
||||
mime: String,
|
||||
content: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Asset {
|
||||
pub fn new(share_duration: u32, mime: String, content: Vec<u8>) -> Self {
|
||||
let id = uuid::Uuid::new_v4().to_string();
|
||||
let created_at = Utc::now().timestamp_millis();
|
||||
let expires_at = created_at + Duration::minutes(share_duration as i64).num_milliseconds();
|
||||
Asset {
|
||||
id,
|
||||
share_duration,
|
||||
created_at,
|
||||
expires_at,
|
||||
mime,
|
||||
content,
|
||||
}
|
||||
}
|
||||
pub fn is_expired(&self) -> bool {
|
||||
Utc::now().timestamp_millis() > self.expires_at
|
||||
}
|
||||
|
||||
pub fn id(&self) -> &str {
|
||||
&self.id
|
||||
}
|
||||
|
||||
pub fn mime(&self) -> &str {
|
||||
&self.mime
|
||||
}
|
||||
|
||||
pub fn content(&self) -> Vec<u8> {
|
||||
self.content.clone()
|
||||
}
|
||||
|
||||
pub fn to_bytes(&self) -> Result<Vec<u8>> {
|
||||
let bytes = serde_json::to_vec(self)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
pub fn save(&self) -> Result<String> {
|
||||
let id = self.id.clone();
|
||||
let path = format!("{}{}", DATA_STORAGE, self.id);
|
||||
std::fs::create_dir_all(DATA_STORAGE)?;
|
||||
std::fs::write(&path, self.to_bytes()?)?;
|
||||
Ok(id)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn clear_assets() -> Result<()> {
|
||||
let entries = std::fs::read_dir(DATA_STORAGE)?;
|
||||
for entry in entries {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if path.is_file() {
|
||||
let data = std::fs::read(&path)?;
|
||||
let asset = serde_json::from_slice::<Asset>(&data)?;
|
||||
if asset.is_expired() {
|
||||
println!("Removing expired asset: {}", asset.id());
|
||||
std::fs::remove_file(&path)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user