Debian Codegraph @

examples/actix_multipart.rs

raw symbols SCIP
1 // Copyright (c) 2022 FL33TW00D (https://github.com/FL33TW00D)
2 // Copyright (c) 2021 Harry [Majored] [[email protected]]
3 // MIT License (https://github.com/Majored/rs-async-zip/blob/main/LICENSE
4
5 #[cfg(features = "deflate")]
6 mod inner {
7 use async_zip::write::ZipFileWriter;
8 use async_zip::{Compression, ZipEntryBuilder};
9
10 use std::path::Path;
11
12 use actix_multipart::Multipart;
13 use actix_web::{web, App, HttpServer, Responder, ResponseError, Result};
14 use derive_more::{Display, Error};
15 use futures::StreamExt;
16 use futures_lite::io::AsyncWriteExt;
17 use tokio::fs::File;
18 use uuid::Uuid;
19
20 const TMP_DIR: &str = "./tmp/";
21
22 #[derive(Debug, Display, Error)]
23 #[display("An error occurred during ZIP creation which was logged to stderr.")]
24 struct CreationError;
25
26 impl ResponseError for CreationError {}
27
28 async fn do_main() -> std::io::Result<()> {
29 let tmp_path = Path::new(TMP_DIR);
30
31 if !tmp_path.exists() {
32 tokio::fs::create_dir(tmp_path).await?;
33 }
34
35 let factory = || App::new().route("/", web::post().to(handler));
36 HttpServer::new(factory).bind(("127.0.0.1", 8080))?.run().await
37 }
38
39 async fn handler(multipart: Multipart) -> Result<impl Responder, CreationError> {
40 match create_archive(multipart).await {
41 Ok(name) => Ok(format!("Successfully created archive: {}", name)),
42 Err(err) => {
43 eprintln!("[ERROR] {:?}", err);
44 Err(CreationError)
45 }
46 }
47 }
48
49 async fn create_archive(mut body: Multipart) -> Result<String, anyhow::Error> {
50 let archive_name = format!("tmp/{}", Uuid::new_v4());
51 let mut archive = File::create(archive_name.clone()).await?;
52 let mut writer = ZipFileWriter::new(&mut archive);
53
54 while let Some(item) = body.next().await {
55 let mut field = item?;
56
57 let filename = match field.content_disposition().get_filename() {
58 Some(filename) => sanitize_filename::sanitize(filename),
59 None => Uuid::new_v4().to_string(),
60 };
61
62 let builder = ZipEntryBuilder::new(filename, Compression::Deflate);
63 let mut entry_writer = writer.write_entry_stream(builder).await.unwrap();
64
65 while let Some(chunk) = field.next().await {
66 entry_writer.write_all_buf(&mut chunk?).await?;
67 }
68
69 entry_writer.close().await.unwrap();
70 }
71
72 writer.close().await.unwrap();
73 archive.shutdown().await.unwrap();
74
75 Ok(archive_name)
76 }
77 }
78
79 #[actix_web::main]
80 async fn main() -> std::io::Result<()> {
81 #[cfg(features = "deflate")]
82 {
83 inner::do_main().await?;
84 }
85
86 Ok(())
87 }