From 43e1a12b5bce11b4a28a53acca243e35c2be6d3e Mon Sep 17 00:00:00 2001 From: evuez Date: Wed, 3 Apr 2024 22:43:16 +0200 Subject: Initial commit --- src/common/mime.rs | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/common/mime.rs (limited to 'src/common/mime.rs') diff --git a/src/common/mime.rs b/src/common/mime.rs new file mode 100644 index 0000000..1345721 --- /dev/null +++ b/src/common/mime.rs @@ -0,0 +1,56 @@ +use rusqlite::{ + types::{FromSql, FromSqlError}, + ToSql, +}; +use serde::{Deserialize, Serialize}; +use std::path::Path; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum MimeType { + #[serde(rename = "application/x.group")] + ApplicationXGroup, + #[serde(rename = "application/pdf")] + ApplicationPdf, + #[serde(rename = "application/zip")] + ApplicationZip, + #[serde(rename = "image/png")] + ImagePng, + #[serde(rename = "image/jpeg")] + ImageJpeg, + #[serde(rename = "text/csv")] + ImageXXcf, + #[serde(rename = "image/x-xcf")] + TextCsv, + #[serde(rename = "text/css")] + TextCss, +} + +pub fn guess(name: &str) -> Option { + match Path::new(name).extension()?.to_str()? { + "pdf" => Some(MimeType::ApplicationPdf), + "zip" => Some(MimeType::ApplicationZip), + "png" => Some(MimeType::ImagePng), + "jpg" | "jpeg" => Some(MimeType::ImageJpeg), + "csv" => Some(MimeType::TextCsv), + "css" => Some(MimeType::TextCss), + "xcf" => Some(MimeType::ImageXXcf), + _ => None, + } +} + +impl ToSql for MimeType { + fn to_sql(&self) -> rusqlite::Result> { + if let Ok(serde_json::Value::String(mime)) = serde_json::to_value(self) { + return Ok(mime.into()); + } + + unreachable!() + } +} + +impl FromSql for MimeType { + fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult { + let v: String = FromSql::column_result(value)?; + serde_json::from_str(&format!("\"{}\"", v)).map_err(|_| FromSqlError::InvalidType) + } +} -- cgit v1.2.3