File size: 8,545 Bytes
b772fd3 3245107 249b27c b772fd3 d94c6df 6858ec5 249b27c 3fc700a 249b27c 6858ec5 1eb186a b772fd3 1eb186a b772fd3 1eb186a b772fd3 1eb186a 6858ec5 b772fd3 6858ec5 b772fd3 249b27c 6858ec5 249b27c b772fd3 3fc700a 249b27c 6858ec5 249b27c f4d1c72 3245107 249b27c 3245107 249b27c 3245107 b772fd3 249b27c b772fd3 f4d1c72 3245107 f4d1c72 3245107 f4d1c72 3245107 f4d1c72 3fc700a 3245107 6858ec5 249b27c 3245107 3fc700a 249b27c f4d1c72 3fc700a 1eb186a 3245107 d94c6df b772fd3 249b27c b772fd3 1eb186a 6858ec5 1eb186a b772fd3 6858ec5 1eb186a b772fd3 6858ec5 b772fd3 1eb186a 6858ec5 1eb186a b772fd3 6858ec5 d94c6df b772fd3 6858ec5 249b27c 1eb186a 6858ec5 1eb186a 6858ec5 1eb186a 6858ec5 1eb186a 6858ec5 1eb186a 3fc700a 1eb186a 6858ec5 1eb186a 6858ec5 1eb186a 6858ec5 1eb186a 6858ec5 1eb186a 6858ec5 1eb186a 6858ec5 1eb186a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 |
use std::collections::HashMap;
use std::io::BufReader;
use actix_multipart_extract::{ File, Multipart, MultipartForm };
use actix_web::{ HttpResponse, post, web };
use chrono::{ Utc, FixedOffset };
use minio::s3::args::{ BucketExistsArgs, MakeBucketArgs, PutObjectArgs };
use sea_orm::DbConn;
use crate::api::JsonResponse;
use crate::AppState;
use crate::entity::doc_info::Model;
use crate::errors::AppError;
use crate::service::doc_info::{ Mutation, Query };
use serde::Deserialize;
use regex::Regex;
fn now() -> chrono::DateTime<FixedOffset> {
Utc::now().with_timezone(&FixedOffset::east_opt(3600 * 8).unwrap())
}
#[derive(Debug, Deserialize)]
pub struct ListParams {
pub uid: i64,
pub filter: FilterParams,
pub sortby: String,
pub page: Option<u32>,
pub per_page: Option<u32>,
}
#[derive(Debug, Deserialize)]
pub struct FilterParams {
pub keywords: Option<String>,
pub folder_id: Option<i64>,
pub tag_id: Option<i64>,
pub kb_id: Option<i64>,
}
#[post("/v1.0/docs")]
async fn list(
params: web::Json<ListParams>,
data: web::Data<AppState>
) -> Result<HttpResponse, AppError> {
let docs = Query::find_doc_infos_by_params(&data.conn, params.into_inner()).await?;
let mut result = HashMap::new();
result.insert("docs", docs);
let json_response = JsonResponse {
code: 200,
err: "".to_owned(),
data: result,
};
Ok(
HttpResponse::Ok()
.content_type("application/json")
.body(serde_json::to_string(&json_response)?)
)
}
#[derive(Deserialize, MultipartForm, Debug)]
pub struct UploadForm {
#[multipart(max_size = 512MB)]
file_field: File,
uid: i64,
did: i64,
}
fn file_type(filename: &String) -> String {
let fnm = filename.to_lowercase();
if
let Some(_) = Regex::new(r"\.(mpg|mpeg|avi|rm|rmvb|mov|wmv|asf|dat|asx|wvx|mpe|mpa)$")
.unwrap()
.captures(&fnm)
{
return "Video".to_owned();
}
if
let Some(_) = Regex::new(
r"\.(jpg|jpeg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp|avif|apng)$"
)
.unwrap()
.captures(&fnm)
{
return "Picture".to_owned();
}
if
let Some(_) = Regex::new(r"\.(WAV|FLAC|APE|ALAC|WavPack|WV|MP3|AAC|Ogg|Vorbis|Opus)$")
.unwrap()
.captures(&fnm)
{
return "Music".to_owned();
}
if
let Some(_) = Regex::new(r"\.(pdf|doc|ppt|yml|xml|htm|json|csv|txt|ini|xsl|wps|rtf|hlp)$")
.unwrap()
.captures(&fnm)
{
return "Document".to_owned();
}
"Other".to_owned()
}
#[post("/v1.0/upload")]
async fn upload(
payload: Multipart<UploadForm>,
data: web::Data<AppState>
) -> Result<HttpResponse, AppError> {
let uid = payload.uid;
let file_name = payload.file_field.name.as_str();
async fn add_number_to_filename(
file_name: &str,
conn: &DbConn,
uid: i64,
parent_id: i64
) -> String {
let mut i = 0;
let mut new_file_name = file_name.to_string();
let arr: Vec<&str> = file_name.split(".").collect();
let suffix = String::from(arr[arr.len() - 1]);
let preffix = arr[..arr.len() - 1].join(".");
let mut docs = Query::find_doc_infos_by_name(
conn,
uid,
&new_file_name,
Some(parent_id)
).await.unwrap();
while docs.len() > 0 {
i += 1;
new_file_name = format!("{}_{}.{}", preffix, i, suffix);
docs = Query::find_doc_infos_by_name(
conn,
uid,
&new_file_name,
Some(parent_id)
).await.unwrap();
}
new_file_name
}
let fnm = add_number_to_filename(file_name, &data.conn, uid, payload.did).await;
let bucket_name = format!("{}-upload", payload.uid);
let s3_client: &minio::s3::client::Client = &data.s3_client;
let buckets_exists = s3_client
.bucket_exists(&BucketExistsArgs::new(&bucket_name).unwrap()).await
.unwrap();
if !buckets_exists {
print!("Create bucket: {}", bucket_name.clone());
s3_client.make_bucket(&MakeBucketArgs::new(&bucket_name).unwrap()).await.unwrap();
} else {
print!("Existing bucket: {}", bucket_name.clone());
}
let location = format!("/{}/{}", payload.did, fnm)
.as_bytes()
.to_vec()
.iter()
.map(|b| format!("{:02x}", b).to_string())
.collect::<Vec<String>>()
.join("");
print!("===>{}", location.clone());
s3_client.put_object(
&mut PutObjectArgs::new(
&bucket_name,
&location,
&mut BufReader::new(payload.file_field.bytes.as_slice()),
Some(payload.file_field.bytes.len()),
None
)?
).await?;
let doc = Mutation::create_doc_info(&data.conn, Model {
did: Default::default(),
uid: uid,
doc_name: fnm.clone(),
size: payload.file_field.bytes.len() as i64,
location,
r#type: file_type(&fnm),
thumbnail_base64: Default::default(),
created_at: now(),
updated_at: now(),
is_deleted: Default::default(),
}).await?;
let _ = Mutation::place_doc(&data.conn, payload.did, doc.did.unwrap()).await?;
Ok(HttpResponse::Ok().body("File uploaded successfully"))
}
#[derive(Deserialize, Debug)]
pub struct RmDocsParam {
uid: i64,
dids: Vec<i64>,
}
#[post("/v1.0/delete_docs")]
async fn delete(
params: web::Json<RmDocsParam>,
data: web::Data<AppState>
) -> Result<HttpResponse, AppError> {
let _ = Mutation::delete_doc_info(&data.conn, ¶ms.dids).await?;
let json_response = JsonResponse {
code: 200,
err: "".to_owned(),
data: (),
};
Ok(
HttpResponse::Ok()
.content_type("application/json")
.body(serde_json::to_string(&json_response)?)
)
}
#[derive(Debug, Deserialize)]
pub struct MvParams {
pub uid: i64,
pub dids: Vec<i64>,
pub dest_did: i64,
}
#[post("/v1.0/mv_docs")]
async fn mv(
params: web::Json<MvParams>,
data: web::Data<AppState>
) -> Result<HttpResponse, AppError> {
Mutation::mv_doc_info(&data.conn, params.dest_did, ¶ms.dids).await?;
let json_response = JsonResponse {
code: 200,
err: "".to_owned(),
data: (),
};
Ok(
HttpResponse::Ok()
.content_type("application/json")
.body(serde_json::to_string(&json_response)?)
)
}
#[derive(Debug, Deserialize)]
pub struct NewFoldParams {
pub uid: i64,
pub parent_id: i64,
pub name: String,
}
#[post("/v1.0/new_folder")]
async fn new_folder(
params: web::Json<NewFoldParams>,
data: web::Data<AppState>
) -> Result<HttpResponse, AppError> {
let doc = Mutation::create_doc_info(&data.conn, Model {
did: Default::default(),
uid: params.uid,
doc_name: params.name.to_string(),
size: 0,
r#type: "folder".to_string(),
location: "".to_owned(),
thumbnail_base64: Default::default(),
created_at: now(),
updated_at: now(),
is_deleted: Default::default(),
}).await?;
let _ = Mutation::place_doc(&data.conn, params.parent_id, doc.did.unwrap()).await?;
Ok(HttpResponse::Ok().body("Folder created successfully"))
}
#[derive(Debug, Deserialize)]
pub struct RenameParams {
pub uid: i64,
pub did: i64,
pub name: String,
}
#[post("/v1.0/rename")]
async fn rename(
params: web::Json<RenameParams>,
data: web::Data<AppState>
) -> Result<HttpResponse, AppError> {
let docs = Query::find_doc_infos_by_name(&data.conn, params.uid, ¶ms.name, None).await?;
if docs.len() > 0 {
let json_response = JsonResponse {
code: 500,
err: "Name duplicated!".to_owned(),
data: (),
};
return Ok(
HttpResponse::Ok()
.content_type("application/json")
.body(serde_json::to_string(&json_response)?)
);
}
let doc = Mutation::rename(&data.conn, params.did, ¶ms.name).await?;
let json_response = JsonResponse {
code: 200,
err: "".to_owned(),
data: doc,
};
Ok(
HttpResponse::Ok()
.content_type("application/json")
.body(serde_json::to_string(&json_response)?)
)
}
|