aboutsummaryrefslogtreecommitdiff
path: root/src/common/mime.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/common/mime.rs')
-rw-r--r--src/common/mime.rs56
1 files changed, 56 insertions, 0 deletions
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<MimeType> {
+ 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<rusqlite::types::ToSqlOutput<'_>> {
+ 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<Self> {
+ let v: String = FromSql::column_result(value)?;
+ serde_json::from_str(&format!("\"{}\"", v)).map_err(|_| FromSqlError::InvalidType)
+ }
+}