2021-09-11 00:08:47 +00:00
|
|
|
use std::io::ErrorKind;
|
2021-08-18 21:22:50 +00:00
|
|
|
|
2021-04-04 12:30:31 +00:00
|
|
|
use crate::config::Config;
|
|
|
|
use crate::multipart::UploadConfig;
|
2022-10-07 13:51:38 +00:00
|
|
|
use crate::{mime_relations, multipart, template};
|
2021-12-08 17:54:55 +00:00
|
|
|
use actix_files::NamedFile;
|
2021-04-04 12:30:31 +00:00
|
|
|
use actix_multipart::Multipart;
|
2022-02-26 23:34:57 +00:00
|
|
|
use actix_web::http::header::LOCATION;
|
|
|
|
use actix_web::{error, web, Error, HttpRequest, HttpResponse};
|
2022-11-22 14:56:38 +00:00
|
|
|
use rand::{distributions::Slice, Rng};
|
2021-04-04 12:30:31 +00:00
|
|
|
use sqlx::postgres::PgPool;
|
2023-05-24 07:55:47 +00:00
|
|
|
use std::path::{Path, PathBuf};
|
2022-02-26 23:34:57 +00:00
|
|
|
use tokio::fs::{self, OpenOptions};
|
|
|
|
use tokio::sync::mpsc::Sender;
|
2021-04-04 12:30:31 +00:00
|
|
|
|
|
|
|
const ID_CHARS: &[char] = &[
|
2022-08-21 16:44:12 +00:00
|
|
|
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u',
|
|
|
|
'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9',
|
2021-04-04 12:30:31 +00:00
|
|
|
];
|
|
|
|
|
2021-12-08 17:54:55 +00:00
|
|
|
pub async fn index(config: web::Data<Config>) -> Result<NamedFile, Error> {
|
2022-01-29 11:50:44 +00:00
|
|
|
let file = NamedFile::open(config.static_dir.join("index.html")).map_err(|file_err| {
|
2021-12-08 17:54:55 +00:00
|
|
|
log::error!("index.html could not be read {:?}", file_err);
|
|
|
|
error::ErrorInternalServerError("this file should be here but could not be found")
|
2022-01-29 11:50:44 +00:00
|
|
|
})?;
|
|
|
|
Ok(file.disable_content_disposition())
|
2021-04-04 12:30:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn upload(
|
2022-02-26 23:34:57 +00:00
|
|
|
req: HttpRequest,
|
2021-04-04 12:30:31 +00:00
|
|
|
payload: Multipart,
|
|
|
|
db: web::Data<PgPool>,
|
|
|
|
expiry_watch_sender: web::Data<Sender<()>>,
|
|
|
|
config: web::Data<Config>,
|
|
|
|
) -> Result<HttpResponse, Error> {
|
2022-11-22 20:32:04 +00:00
|
|
|
let (file_id, file_path) = create_unique_file(&config).await.map_err(|file_err| {
|
2021-09-11 00:08:47 +00:00
|
|
|
log::error!("could not create file {:?}", file_err);
|
|
|
|
error::ErrorInternalServerError("could not create file")
|
|
|
|
})?;
|
2021-04-04 12:30:31 +00:00
|
|
|
|
2022-11-22 20:32:04 +00:00
|
|
|
let upload_config = multipart::parse_multipart(payload, &file_path, &config).await?;
|
|
|
|
let file_name = upload_config.original_name.clone().unwrap_or_else(|| {
|
2022-10-07 13:51:38 +00:00
|
|
|
format!(
|
2022-10-07 13:52:12 +00:00
|
|
|
"{file_id}.{}",
|
2022-11-22 20:32:04 +00:00
|
|
|
mime_relations::get_extension(&upload_config.content_type).unwrap_or("txt")
|
2022-10-07 13:51:38 +00:00
|
|
|
)
|
|
|
|
});
|
2022-11-22 20:32:04 +00:00
|
|
|
|
2023-05-24 07:55:47 +00:00
|
|
|
insert_file_metadata(&file_id, file_name, &file_path, &upload_config, db).await?;
|
2022-11-22 20:32:04 +00:00
|
|
|
|
|
|
|
log::info!(
|
|
|
|
"{} create new file {} (valid_till: {}, content_type: {}, delete_on_download: {})",
|
|
|
|
req.connection_info().realip_remote_addr().unwrap_or("-"),
|
|
|
|
file_id,
|
2022-11-23 23:04:09 +00:00
|
|
|
upload_config.valid_till,
|
2022-11-22 20:32:04 +00:00
|
|
|
upload_config.content_type,
|
2022-11-23 23:04:09 +00:00
|
|
|
upload_config.delete_on_download
|
2022-11-22 20:32:04 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
expiry_watch_sender.send(()).await.unwrap();
|
|
|
|
|
|
|
|
let redirect = get_redirect_url(&file_id, upload_config.original_name.as_deref());
|
2023-02-10 23:17:21 +00:00
|
|
|
let url = template::get_file_url(&req, &file_id, upload_config.original_name.as_deref());
|
2022-11-22 20:32:04 +00:00
|
|
|
Ok(HttpResponse::SeeOther()
|
|
|
|
.insert_header((LOCATION, redirect))
|
|
|
|
.body(format!("{url}\n")))
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn insert_file_metadata(
|
|
|
|
file_id: &String,
|
|
|
|
file_name: String,
|
2023-05-24 07:55:47 +00:00
|
|
|
file_path: &Path,
|
2022-11-22 20:32:04 +00:00
|
|
|
upload_config: &UploadConfig,
|
|
|
|
db: web::Data<sqlx::Pool<sqlx::Postgres>>,
|
|
|
|
) -> Result<(), Error> {
|
2021-04-04 12:30:31 +00:00
|
|
|
let db_insert = sqlx::query(
|
2022-08-18 21:20:56 +00:00
|
|
|
"INSERT INTO Files (file_id, file_name, content_type, valid_till, delete_on_download) \
|
2021-04-04 12:30:31 +00:00
|
|
|
VALUES ($1, $2, $3, $4, $5)",
|
|
|
|
)
|
2022-11-22 20:32:04 +00:00
|
|
|
.bind(file_id)
|
2022-08-18 21:20:56 +00:00
|
|
|
.bind(&file_name)
|
2022-11-22 20:32:04 +00:00
|
|
|
.bind(&upload_config.content_type.to_string())
|
|
|
|
.bind(upload_config.valid_till)
|
|
|
|
.bind(upload_config.delete_on_download)
|
2021-04-04 12:30:31 +00:00
|
|
|
.execute(db.as_ref())
|
|
|
|
.await;
|
2021-04-07 22:33:22 +00:00
|
|
|
if let Err(db_err) = db_insert {
|
|
|
|
log::error!("could not insert into datebase {:?}", db_err);
|
2023-05-24 07:55:47 +00:00
|
|
|
|
|
|
|
if let Err(file_err) = fs::remove_file(file_path).await {
|
2021-04-07 22:33:22 +00:00
|
|
|
log::error!("could not remove file {:?}", file_err);
|
2022-11-22 20:32:04 +00:00
|
|
|
}
|
2021-04-04 12:30:31 +00:00
|
|
|
return Err(error::ErrorInternalServerError(
|
|
|
|
"could not insert file into database",
|
|
|
|
));
|
|
|
|
}
|
2022-11-22 20:32:04 +00:00
|
|
|
Ok(())
|
2021-04-04 12:30:31 +00:00
|
|
|
}
|
|
|
|
|
2021-09-11 00:08:47 +00:00
|
|
|
async fn create_unique_file(
|
|
|
|
config: &web::Data<Config>,
|
|
|
|
) -> Result<(String, PathBuf), std::io::Error> {
|
|
|
|
loop {
|
|
|
|
let file_id = gen_file_id();
|
2023-01-23 10:23:48 +00:00
|
|
|
let file_path = config.files_dir.join(&file_id);
|
2021-09-11 00:08:47 +00:00
|
|
|
match OpenOptions::new()
|
|
|
|
.write(true)
|
|
|
|
.create_new(true)
|
2022-11-22 20:32:04 +00:00
|
|
|
.open(&file_path)
|
2021-09-11 00:08:47 +00:00
|
|
|
.await
|
|
|
|
{
|
2022-11-22 20:32:04 +00:00
|
|
|
Ok(_) => return Ok((file_id, file_path)),
|
2021-09-11 00:08:47 +00:00
|
|
|
Err(error) if error.kind() == ErrorKind::AlreadyExists => continue,
|
|
|
|
Err(error) => return Err(error),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-04 12:30:31 +00:00
|
|
|
fn gen_file_id() -> String {
|
2022-11-22 14:56:38 +00:00
|
|
|
let distribution = Slice::new(ID_CHARS).expect("ID_CHARS is not empty");
|
|
|
|
rand::thread_rng()
|
|
|
|
.sample_iter(distribution)
|
|
|
|
.take(5)
|
|
|
|
.collect()
|
2021-04-04 12:30:31 +00:00
|
|
|
}
|
|
|
|
|
2022-11-22 20:32:04 +00:00
|
|
|
fn get_redirect_url(id: &str, name: Option<&str>) -> String {
|
|
|
|
if let Some(name) = name {
|
|
|
|
let encoded_name = urlencoding::encode(name);
|
|
|
|
format!("/upload/{id}/{encoded_name}")
|
|
|
|
} else {
|
|
|
|
format!("/upload/{id}")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-10 23:16:51 +00:00
|
|
|
pub async fn uploaded(req: HttpRequest, config: web::Data<Config>) -> Result<HttpResponse, Error> {
|
2022-11-23 23:04:09 +00:00
|
|
|
let id = req.match_info().query("id");
|
|
|
|
let name = req
|
|
|
|
.match_info()
|
|
|
|
.get("name")
|
|
|
|
.map(urlencoding::decode)
|
|
|
|
.transpose()
|
|
|
|
.map_err(|_| error::ErrorBadRequest("name is invalid utf-8"))?;
|
2023-02-10 23:17:21 +00:00
|
|
|
let uploaded_html = template::build_uploaded_html(&req, id, name.as_deref(), &config);
|
2021-04-04 12:30:31 +00:00
|
|
|
Ok(HttpResponse::Ok()
|
|
|
|
.content_type("text/html")
|
2023-02-10 23:17:21 +00:00
|
|
|
.body(uploaded_html))
|
2021-04-04 12:30:31 +00:00
|
|
|
}
|