add persistent state

This commit is contained in:
xenofem 2022-04-28 05:13:14 -04:00
parent 70384b04c3
commit 127d7e9c67
4 changed files with 139 additions and 12 deletions

View file

@ -1,10 +1,11 @@
mod download;
mod file;
mod state;
mod upload;
mod util;
mod zip;
use std::{
collections::HashMap,
path::PathBuf,
fs::File,
};
@ -14,6 +15,8 @@ use actix_web::{
get, middleware::Logger, web, App, HttpRequest, HttpServer, Responder, HttpResponse,
};
use actix_web_actors::ws;
use serde::{Deserialize, Serialize};
use state::PersistentState;
use time::OffsetDateTime;
use tokio::sync::RwLock;
@ -35,15 +38,17 @@ impl UploadedFile {
}
}
#[derive(Clone)]
#[derive(Clone, Deserialize, Serialize)]
pub struct DownloadableFile {
name: String,
size: u64,
#[serde(with = "state::timestamp")]
modtime: OffsetDateTime,
#[serde(skip)]
uploader: Option<Addr<upload::Uploader>>,
}
type AppData = web::Data<RwLock<HashMap<String, DownloadableFile>>>;
type AppData = web::Data<RwLock<PersistentState>>;
fn storage_dir() -> PathBuf {
PathBuf::from(std::env::var("STORAGE_DIR").unwrap_or_else(|_| String::from("storage")))
@ -52,11 +57,11 @@ fn storage_dir() -> PathBuf {
#[get("/download/{file_code}")]
async fn handle_download(req: HttpRequest, path: web::Path<String>, data: AppData) -> actix_web::Result<HttpResponse> {
let file_code = path.into_inner();
if !file_code.as_bytes().iter().all(|c| c.is_ascii_alphanumeric()) {
if !util::is_ascii_alphanumeric(&file_code) {
return Ok(HttpResponse::NotFound().finish());
}
let data = data.read().await;
let info = data.get(&file_code);
let info = data.lookup_file(&file_code);
if let Some(info) = info {
Ok(download::DownloadingFile {
file: File::open(storage_dir().join(file_code))?,
@ -76,7 +81,7 @@ async fn handle_upload(req: HttpRequest, stream: web::Payload, data: AppData) ->
async fn main() -> std::io::Result<()> {
env_logger::init();
let data: AppData = web::Data::new(RwLock::new(HashMap::new()));
let data: AppData = web::Data::new(RwLock::new(PersistentState::load().await?));
let static_dir =
PathBuf::from(std::env::var("STATIC_DIR").unwrap_or_else(|_| String::from("static")));