diff --git a/Rocket.toml b/Rocket.toml index be66c1e..1dc04c2 100644 --- a/Rocket.toml +++ b/Rocket.toml @@ -1,2 +1,3 @@ [default] limits = { file = "200MB" } +temp_dir = "user_files" diff --git a/src/api/mod.rs b/src/api/mod.rs index ad656ab..498da64 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -25,6 +25,15 @@ macro_rules! code0 { ); } +macro_rules! code1 { + ($msg:expr) => ( + Ok(json!({ + "code": 1, + "msg": $msg, + })) + ); +} + macro_rules! e2s { ($e:expr) => (json!({ "code": -1, diff --git a/src/api/upload.rs b/src/api/upload.rs index 0b3bc0a..1b7ea8a 100644 --- a/src/api/upload.rs +++ b/src/api/upload.rs @@ -1,46 +1,37 @@ use crate::api::{CurrentUser, JsonAPI}; -use chrono::offset::Local; use rocket::fs::TempFile; use rocket::serde::json::json; -use std::fs; -use std::path::Path; use std::process::Command; #[post("/upload", data = "")] -pub async fn ipfs_upload(user: CurrentUser, mut file: TempFile<'_>) -> JsonAPI { - let file_dir = Path::new("user_files").join(&user.namehash); - fs::create_dir_all(&file_dir)?; +pub async fn ipfs_upload(_user: CurrentUser, file: TempFile<'_>) -> JsonAPI { // dbg!(&file); - let filename = format!( - "{}-{}.{}", - Local::now().timestamp(), - &file.content_type().map_or("unknow", |ct| ct.top().as_str()), - &file.content_type().map_or("file", |ct| ct.sub().as_str()) - ); - debug!("dir: {}", &file_dir.to_str().unwrap()); - file.persist_to(file_dir.join(&filename)).await?; - // dbg!(&file_dir); - // dbg!(file_dir.with_file_name(&filename)); - let output = Command::new("ipfs") - .args([ - "add", - "-q", - "-r", - "-cid-version=1", - file_dir.to_str().unwrap(), - ]) - .output()?; - // dbg!(&output); - let hash = std::str::from_utf8(&output.stdout) - .unwrap() - .split_terminator("\n") - .last() - .unwrap_or_else(|| { - dbg!(&output.stdout); - panic!("get ipfs output error"); - }); - code0!(json!({ - "hash": hash, - "filename": filename, - })) + + // dbg!(&file.path()); + if let Some(filepath) = file.path() { + let output = Command::new("ipfs") + .args([ + "add", + "-q", + "-r", + "-cid-version=1", + filepath.to_str().unwrap(), + ]) + .output()?; + // dbg!(&output); + let hash = std::str::from_utf8(&output.stdout) + .unwrap() + .split_terminator("\n") + .last() + .unwrap_or_else(|| { + dbg!(&output); + dbg!(&file.path()); + panic!("get ipfs output error"); + }); + code0!(json!({ + "hash": hash, + })) + } else { + code1!("文件丢失") + } }