upload.rs 1.67 KB
use actix_web::{Error, HttpResponse, web};
use anyhow::Result;
use futures::stream::StreamExt;
use async_std::{fs::OpenOptions, io::WriteExt};
use uuid::Uuid;

use crate::{AppData, models::image::{Upload, self}};

pub async fn upload( app_data :web::Data<AppData>
                   , mut body :web::Payload
                   , request  :web::HttpRequest ) -> Result<HttpResponse, Error>
{
    let pool = app_data.database_pool.clone();
    let worker = app_data.tx_upload_worker.clone();

    let random_uuid = Uuid::new_v4();
    let upload_uuid = Some(random_uuid.as_bytes().to_vec());
    let size = request.headers().get("content-length")
             . and_then(|h| Some(h.to_str().unwrap().parse::<i32>()))
             . unwrap().unwrap();
    let mime_type = String::from( request.headers().get("content-type")
                                . and_then(|h| Some(h.to_str().unwrap()))
                                . unwrap() );

    let upload_filename = format!("/tmp/upload_{}", random_uuid);
    let mut output = OpenOptions::new();
    let mut output = output
                   . create(true)
                   . write(true)
                   . open(&upload_filename).await?;

    while let Some(item) = body.next().await {
        output.write_all(&item?).await?;
    }

    let upload = Upload {
        upload_uuid,
        size,
        mime_type
    };

    Ok( match web::block(move || image::upload(pool, upload)).await {
        Ok(image) => {
            // TODO handle this as error response...
            worker.send(image.clone()).await.unwrap();
            HttpResponse::Ok().json(image)
        },
        Err(_) => HttpResponse::InternalServerError().finish()
    } )
}