Can download ISO file by URL
This commit is contained in:
@ -4,7 +4,10 @@ use crate::controllers::HttpResult;
|
||||
use crate::utils::files_utils;
|
||||
use actix_multipart::form::tempfile::TempFile;
|
||||
use actix_multipart::form::MultipartForm;
|
||||
use actix_web::HttpResponse;
|
||||
use actix_web::{web, HttpResponse};
|
||||
use futures_util::StreamExt;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
|
||||
#[derive(Debug, MultipartForm)]
|
||||
pub struct UploadIsoForm {
|
||||
@ -58,3 +61,47 @@ pub async fn upload_file(MultipartForm(mut form): MultipartForm<UploadIsoForm>)
|
||||
|
||||
Ok(HttpResponse::Accepted().finish())
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct DownloadFromURLReq {
|
||||
url: String,
|
||||
filename: String,
|
||||
}
|
||||
|
||||
/// Upload ISO file from URL
|
||||
pub async fn upload_from_url(req: web::Json<DownloadFromURLReq>) -> HttpResult {
|
||||
if !files_utils::check_file_name(&req.filename) || !req.filename.ends_with(".iso") {
|
||||
return Ok(HttpResponse::BadRequest().json("Invalid file name!"));
|
||||
}
|
||||
|
||||
let dest_file = AppConfig::get().iso_storage_path().join(&req.filename);
|
||||
|
||||
if dest_file.exists() {
|
||||
return Ok(HttpResponse::Conflict().json("A similar file already exists!"));
|
||||
}
|
||||
|
||||
let response = reqwest::get(&req.url).await?;
|
||||
|
||||
if let Some(len) = response.content_length() {
|
||||
if len > constants::ISO_MAX_SIZE as u64 {
|
||||
return Ok(HttpResponse::BadRequest().json("File is too large!"));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ct) = response.headers().get("content-type") {
|
||||
if !constants::ALLOWED_ISO_MIME_TYPES.contains(&ct.to_str()?) {
|
||||
return Ok(HttpResponse::BadRequest().json("Invalid file mimetype!"));
|
||||
}
|
||||
}
|
||||
|
||||
let mut stream = response.bytes_stream();
|
||||
|
||||
let mut file = File::create(dest_file)?;
|
||||
|
||||
while let Some(item) = stream.next().await {
|
||||
let bytes = item?;
|
||||
file.write_all(&bytes)?;
|
||||
}
|
||||
|
||||
Ok(HttpResponse::Accepted().finish())
|
||||
}
|
||||
|
@ -65,4 +65,16 @@ impl From<tempfile::PersistError> for HttpErr {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<reqwest::Error> for HttpErr {
|
||||
fn from(value: reqwest::Error) -> Self {
|
||||
HttpErr { err: value.into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<reqwest::header::ToStrError> for HttpErr {
|
||||
fn from(value: reqwest::header::ToStrError) -> Self {
|
||||
HttpErr { err: value.into() }
|
||||
}
|
||||
}
|
||||
|
||||
pub type HttpResult = Result<HttpResponse, HttpErr>;
|
||||
|
Reference in New Issue
Block a user