diff --git a/src/routes.rs b/src/routes.rs index 246226f..e7fe40e 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -1,13 +1,21 @@ use crate::config::{AppConfig, normalize_extension}; use content_inspector::ContentType; use rocket::data::{Data, ToByteUnit}; -use rocket::{State, http::Status, response::content::RawHtml}; +use rocket::http::{Accept, MediaType, Status}; +use rocket::response::content::{RawHtml, RawText}; +use rocket::{Responder, State}; use std::fs; use std::io::Write; use std::path::Path; use tempfile::NamedTempFile; use tokio::fs as async_fs; +#[derive(Responder)] +pub enum FileResponse { + Html(RawHtml), + Text(RawText), +} + #[get("/")] pub fn index() -> Option> { let raw: &str = include_str!("assets/editor.html"); @@ -15,22 +23,28 @@ pub fn index() -> Option> { } #[get("/?")] -pub async fn get_file(id: &str, raw: Option, config: &State) -> Result { +pub async fn get_file( + id: &str, + raw: Option, + accept: Option<&Accept>, + config: &State, +) -> Result { let file_path = Path::new(&config.upload_dir).join(id); if file_path.exists() { if let Ok(content) = async_fs::read_to_string(file_path).await { - let is_mozilla = std::env::var("HTTP_USER_AGENT") - .as_deref() - .unwrap_or("") - .contains("Mozilla"); + let wants_html = accept + .map(|accept| accept.preferred().media_type() == &MediaType::HTML) + .unwrap_or(false); - if raw.unwrap_or(false) || !is_mozilla { - return Ok(content); + if raw.unwrap_or(false) || !wants_html { + return Ok(FileResponse::Text(RawText(content))); } let html: &str = include_str!("assets/editor.html"); - return Ok(html.replace("$%{defaultText}%$", &content)); + return Ok(FileResponse::Html(RawHtml( + html.replace("$%{defaultText}%$", &content), + ))); } }