Can download files
This commit is contained in:
@ -1,8 +1,14 @@
|
||||
use crate::controllers::HttpResult;
|
||||
use crate::extractors::auth_extractor::AuthExtractor;
|
||||
use crate::extractors::file_extractor::FileExtractor;
|
||||
use crate::extractors::file_id_extractor::FileIdExtractor;
|
||||
use crate::models::files::File;
|
||||
use crate::services::files_service;
|
||||
use actix_web::HttpResponse;
|
||||
use crate::utils::time_utils;
|
||||
use actix_web::http::header;
|
||||
use actix_web::{HttpRequest, HttpResponse};
|
||||
use std::ops::Add;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Upload a new file
|
||||
pub async fn upload(auth: AuthExtractor, file: FileExtractor) -> HttpResult {
|
||||
@ -16,3 +22,39 @@ pub async fn upload(auth: AuthExtractor, file: FileExtractor) -> HttpResult {
|
||||
|
||||
Ok(HttpResponse::Ok().json(file))
|
||||
}
|
||||
|
||||
/// Download an uploaded file
|
||||
pub async fn download(req: HttpRequest, file_extractor: FileIdExtractor) -> HttpResult {
|
||||
serve_file(req, file_extractor.as_ref()).await
|
||||
}
|
||||
|
||||
/// Serve a file, returning 304 status code if the requested file already exists
|
||||
pub async fn serve_file(req: HttpRequest, file: &File) -> HttpResult {
|
||||
// Check if the browser already knows the etag
|
||||
if let Some(c) = req.headers().get(header::IF_NONE_MATCH) {
|
||||
if c.to_str().unwrap_or("") == file.sha512.as_str() {
|
||||
return Ok(HttpResponse::NotModified().finish());
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the browser already knows the file by date
|
||||
if let Some(c) = req.headers().get(header::IF_MODIFIED_SINCE) {
|
||||
let date_str = c.to_str().unwrap_or("");
|
||||
if let Ok(date) = httpdate::parse_http_date(date_str) {
|
||||
if date.add(Duration::from_secs(1))
|
||||
>= time_utils::unix_to_system_time(file.time_create as u64)
|
||||
{
|
||||
return Ok(HttpResponse::NotModified().finish());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type(file.mime_type.as_str())
|
||||
.insert_header(("etag", file.sha512.as_str()))
|
||||
.insert_header((
|
||||
"last-modified",
|
||||
time_utils::unix_to_http_date(file.time_create as u64),
|
||||
))
|
||||
.body(files_service::get_file_content(file).await?))
|
||||
}
|
||||
|
@ -15,7 +15,7 @@ pub struct CreateTokenBody {
|
||||
right_account: bool,
|
||||
right_movement: bool,
|
||||
right_inbox: bool,
|
||||
right_attachment: bool,
|
||||
right_file: bool,
|
||||
right_auth: bool,
|
||||
}
|
||||
|
||||
@ -59,7 +59,7 @@ pub async fn create(auth: AuthExtractor, req: web::Json<CreateTokenBody>) -> Htt
|
||||
right_account: req.right_account,
|
||||
right_movement: req.right_movement,
|
||||
right_inbox: req.right_inbox,
|
||||
right_file: req.right_attachment,
|
||||
right_file: req.right_file,
|
||||
right_auth: req.right_auth,
|
||||
})
|
||||
.await?;
|
||||
|
Reference in New Issue
Block a user