first
This commit is contained in:
50
src/api.rs
Normal file
50
src/api.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use actix_web::{HttpRequest, HttpResponse, get, post, web};
|
||||
use base64::{Engine, engine::general_purpose};
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{DATA_STORAGE, logs::log_to_file};
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct UploadRequest {
|
||||
duration: u32,
|
||||
content_type: String,
|
||||
content: String, // text or base64 string
|
||||
}
|
||||
|
||||
#[post("/api/upload")]
|
||||
async fn api_upload(req: web::Json<UploadRequest>) -> Result<HttpResponse, actix_web::Error> {
|
||||
// Convert to bytes
|
||||
let content_bytes = if req.content_type == "text/plain" {
|
||||
req.content.as_bytes().to_vec() // UTF-8 bytes
|
||||
} else {
|
||||
// Decode base64 → bytes
|
||||
general_purpose::STANDARD.decode(&req.content).unwrap()
|
||||
};
|
||||
let asset = crate::data_mgt::Asset::new(req.duration, req.content_type.clone(), content_bytes);
|
||||
|
||||
let id = asset
|
||||
.save()
|
||||
.map_err(|e| actix_web::error::ErrorInternalServerError(format!("Failed to save asset: {}", e)))?;
|
||||
|
||||
let response_body = json!({ "link": format!("/bhs/{}", id) });
|
||||
Ok(HttpResponse::Ok().json(response_body))
|
||||
}
|
||||
|
||||
#[get("/api/content/{id}")]
|
||||
async fn api_get_asset(req: HttpRequest, path: web::Path<String>) -> Result<HttpResponse, actix_web::Error> {
|
||||
let now = std::time::Instant::now();
|
||||
|
||||
let id = path.into_inner();
|
||||
let asset_path = format!("{}{}", DATA_STORAGE, id);
|
||||
let data = std::fs::read(&asset_path).map_err(|_| actix_web::error::ErrorNotFound("Asset not found"))?;
|
||||
let asset = serde_json::from_slice::<crate::data_mgt::Asset>(&data)
|
||||
.map_err(|_| actix_web::error::ErrorInternalServerError("Failed to parse asset data"))?;
|
||||
|
||||
if asset.is_expired() {
|
||||
return Err(actix_web::error::ErrorNotFound("Asset has expired"));
|
||||
}
|
||||
|
||||
log_to_file(&req, now);
|
||||
Ok(HttpResponse::Ok().content_type(asset.mime()).body(asset.content()))
|
||||
}
|
||||
Reference in New Issue
Block a user