Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
chore: split out file types (#53)
Sean Aye36d2bf7aa7bf
diff --git a/.taplo.toml b/.taplo.tomlnew file mode 100644index 0000000000..42a0e24df3--- /dev/null+++ b/.taplo.toml@@ -0,0 +1,3 @@+[formatting]+reorder_arrays = true+reorder_keys = truediff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 0d72f8d4fb..ed9298815d 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -4219,6 +4219,7 @@ dependencies = ["cool_asserts","filter_ast","macro_user_id",+ "model_file_type","non_empty","schemars","serde",@@ -5104,13 +5105,13 @@ dependencies = ["base64 0.22.1","chrono","model-error-response",+ "model_file_type","model_user","models_bulk_upload","models_comms","models_email","models_pagination","models_permissions",- "once_cell","schemars","serde","serde_json",@@ -5143,6 +5144,15 @@ dependencies = ["utoipa",]+[[package]]+name = "model_file_type"+version = "0.1.0"+dependencies = [+ "serde",+ "thiserror 2.0.17",+ "utoipa",+]+[[package]]name = "model_notifications"version = "0.1.0"@@ -7206,6 +7216,7 @@ dependencies = ["aws_lambda_events","lambda_runtime","macro_entrypoint",+ "model_file_type","openssl","sqs_client","tokio",diff --git a/rust/cloud-storage/convert_service/src/api/convert.rs b/rust/cloud-storage/convert_service/src/api/convert.rsindex 100a731e8e..ee5aa1c34f 100644--- a/rust/cloud-storage/convert_service/src/api/convert.rs+++ b/rust/cloud-storage/convert_service/src/api/convert.rs@@ -1,4 +1,4 @@-use std::{fs::File, io::Write, thread, time::Duration};+use std::{fs::File, io::Write, str::FromStr, thread, time::Duration};use anyhow::Context;use axum::{@@ -55,7 +55,7 @@ pub async fn handler(.split('.').next_back().context("expected key to contain a file type")- .and_then(|s| s.try_into())+ .and_then(|s| FileType::from_str(s).map_err(anyhow::Error::from)).map_err(|e| {tracing::error!(error=?e, job_id=%job_id, "unable to get file type");(@@ -72,7 +72,7 @@ pub async fn handler(.split('.').next_back().context("expected key to contain a file type")- .and_then(|s| s.try_into())+ .and_then(|s| FileType::from_str(s).map_err(anyhow::Error::from)).map_err(|e| {tracing::error!(error=?e, job_id=%job_id, "unable to get file type");(diff --git a/rust/cloud-storage/convert_service/src/process/convert.rs b/rust/cloud-storage/convert_service/src/process/convert.rsindex 6618b73189..6d6fcd8e1b 100644--- a/rust/cloud-storage/convert_service/src/process/convert.rs+++ b/rust/cloud-storage/convert_service/src/process/convert.rs@@ -3,7 +3,7 @@ use nix::{unistd::{ForkResult, fork},};use rs_libreoffice_bindings::Office;-use std::{borrow::Cow, fs::File, io::Write, thread, time::Duration};+use std::{borrow::Cow, fs::File, io::Write, str::FromStr, thread, time::Duration};use anyhow::Context;use model::{convert::ConvertQueueMessage, document::FileType};@@ -136,16 +136,14 @@ pub async fn convert(.split('.').next_back().context("expected key to contain a file type")- .and_then(|s| s.try_into())- .context("unable to get from_file_type")?;+ .and_then(|s| Ok(FileType::from_str(s)?))?;let to_file_type: FileType = req.to_key.split('.').next_back().context("expected key to contain a file type")- .and_then(|s| s.try_into())- .context("unable to get to_file_type")?;+ .and_then(|s| Ok(FileType::from_str(s)?))?;let filter = get_lok_filter_from_file_types(&from_file_type, &to_file_type).context("unable to get lok filter")?;diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rsindex 3e9894d95b..1ea1ee759e 100644--- a/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs@@ -4,7 +4,7 @@ use anyhow::{Context, Result};use metering_service_client::{CreateUsageRecordRequest, OperationType, ServiceName};use model::document::FileType;use regex::Regex;-use std::sync::Arc;+use std::{str::FromStr, sync::Arc};use tracing::instrument;use uuid::Uuid;@@ -85,10 +85,10 @@ async fn build_completion_request(let file_type = FileType::from_str(&document.file_type);match file_type {- None => {+ Err(_) => {tracing::warn!(document_id=%attachment_id, "document type is missing");}- Some(FileType::Pdf) | Some(FileType::Docx) => {+ Ok(f @ FileType::Pdf) | Ok(f @ FileType::Docx) => {let document_text =get_pdf_docx_document_text(ctx.db.clone(), attachment_id).await?;if let Some(context) =@@ -96,10 +96,7 @@ async fn build_completion_request({prompt_attachments.push(PromptAttachment {id: attachment_id.to_string(),- file_type: file_type- .ok_or(anyhow::anyhow!("unkown file type"))?- .as_str()- .to_string(),+ file_type: f.as_str().to_string(),name: document.name,content: context,});@@ -111,7 +108,7 @@ async fn build_completion_request();}}- Some(file_type) => {+ Ok(file_type) => {let content = get_document_plaintext_content(&ctx, attachment_id).await?.text_content()?;diff --git a/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs b/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rsindex 6732b7ac63..618e07ef19 100644--- a/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs+++ b/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs@@ -3,7 +3,10 @@ use crate::core::constants::CHANNEL_TRANSCRIPT_MAX_MESSAGES;use ai::types::{Attachment, PromptAttachment};use ai_tools::read::EmailMessage;use anyhow::Context;-use model::chat::{AttachmentType, ChatAttachmentWithName};+use model::{+ chat::{AttachmentType, ChatAttachmentWithName},+ document::FileTypeExt,+};use std::sync::Arc;pub const EMAIL_THREAD_MESSAGE_LIMIT: i64 = 20;diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/get.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/get.rsindex ba5681f8b5..fc55abe39f 100644--- a/rust/cloud-storage/document_storage_service/src/api/annotations/get.rs+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/get.rs@@ -1,3 +1,5 @@+use std::str::FromStr;+use crate::{api::context::ApiContext,model::response::annotations::{AnchorResponse, ThreadResponse},@@ -78,7 +80,7 @@ pub async fn get_document_anchors_handler(match document_context.file_type.as_deref()- .and_then(|f| f.try_into().ok())+ .and_then(|f| FileType::from_str(f).ok()){Some(FileType::Pdf | FileType::Docx) => match get_pdf_anchors(&db, &document_id).await {Ok(pdf_anchors) => {diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rsindex 64cfd5522b..521cee220f 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs@@ -4,7 +4,7 @@ use crate::{};use axum::{http::StatusCode, response::Response};use macro_db_client::history::upsert_user_history;-use model::sync_service::SyncServiceVersionID;+use model::{document::FileTypeExt, sync_service::SyncServiceVersionID};use model::{document::{BomPart, CONVERTED_DOCUMENT_FILE_NAME, DocumentMetadata, FileType,diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/mod.rs b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/mod.rsindex 88c3a00dfe..8afc3624a1 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/mod.rs@@ -1,6 +1,8 @@mod copy_document_cleanup;mod copy_document_v2;+use std::str::FromStr;+use crate::{api::context::ApiContext,model::request::documents::copy::{CopyDocumentQueryParams, CopyDocumentRequest},@@ -13,7 +15,9 @@ use axum::{};use macro_middleware::cloud_storage::ensure_access::document::DocumentAccessExtractor;use model::{- document::{DocumentBasic, DocumentMetadata, FileType, response::GetDocumentResponse},+ document::{+ DocumentBasic, DocumentMetadata, FileType, FileTypeExt, response::GetDocumentResponse,+ },response::{ErrorResponse, GenericErrorResponse, GenericResponse},user::UserContext,};@@ -70,7 +74,8 @@ pub(in crate::api) async fn copy_document_handler(// Overrides the document name cleaned document name (removing file extension)// if it was accidentally included- req.document_name = FileType::clean_document_name(req.document_name);+ req.document_name =+ FileType::clean_document_name(&req.document_name).unwrap_or(req.document_name);let mut document_metadata: DocumentMetadata = if let Some(version_id) = params.version_id {match macro_db_client::document::get_document_version(@@ -126,7 +131,7 @@ pub(in crate::api) async fn copy_document_handler(let file_type: Option<FileType> = document_context.file_type.as_deref()- .and_then(|f| f.try_into().ok());+ .and_then(|f| FileType::from_str(f).ok());// If the docx doesn't have a document bom associated with it, we cannot copy itif file_type == Some(FileType::Docx) && document_metadata.document_bom.is_none() {diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rs b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rsindex 8913ed6d40..d82ec37ad7 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rs@@ -1,3 +1,5 @@+use std::str::FromStr;+use axum::{Extension, extract::State, http::StatusCode, response::IntoResponse};use macro_middleware::cloud_storage::ensure_access::project::ProjectBodyAccessLevelExtractor;use models_permissions::share_permission::access_level::EditAccessLevel;@@ -16,7 +18,7 @@ use crate::{},};use model::{- document::FileType,+ document::{FileType, FileTypeExt},response::{GenericErrorResponse, GenericResponse, TypedSuccessResponse},user::UserContext,};@@ -46,18 +48,20 @@ pub(in crate::api) async fn create_document_handler() -> impl IntoResponse {let req = project.into_inner();- let user_provided_file_type: Option<FileType> =- req.file_type.as_deref().and_then(|f| f.try_into().ok());+ let user_provided_file_type: Option<FileType> = req+ .file_type+ .as_deref()+ .and_then(|f| FileType::from_str(f).ok());let (document_name, file_type) = match user_provided_file_type {Some(file_type) => {// Strips any accidentally added extension from document name- let document_name = FileType::clean_document_name(req.document_name);- (document_name, Some(file_type))+ let document_name = FileType::clean_document_name(&req.document_name);+ (document_name.unwrap_or(req.document_name), Some(file_type))}None => match FileType::split_suffix_match(req.document_name.as_str()) {Some((file_name, extension)) => {- let file_type: Option<FileType> = extension.try_into().ok();+ let file_type: Option<FileType> = FileType::from_str(extension).ok();(file_name.to_string(), file_type)}None => (req.document_name, None),diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/edit_document/edit_document_v2.rs b/rust/cloud-storage/document_storage_service/src/api/documents/edit_document/edit_document_v2.rsindex de31db816f..32071aa7de 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/edit_document/edit_document_v2.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/edit_document/edit_document_v2.rs@@ -6,7 +6,7 @@ use axum::{};use macro_share_permissions::user_item_access::update_user_item_access;use model::{- document::{DocumentBasic, FileType},+ document::{DocumentBasic, FileType, FileTypeExt},response::{ErrorResponse, GenericSuccessResponse, SuccessResponse},user::UserContext,};@@ -25,7 +25,9 @@ pub async fn edit_document(let share_permission: Option<UpdateSharePermissionRequestV2> = req.share_permission.clone();// Overrides the document name cleaned document name (removing file extension)// if it was accidentally included- let document_name = req.document_name.map(FileType::clean_document_name);+ let document_name = req+ .document_name+ .map(|s| FileType::clean_document_name(&s).unwrap_or(s));if req.project_id.is_some() && users_access_level != AccessLevel::Owner {return Err((diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/export_document.rs b/rust/cloud-storage/document_storage_service/src/api/documents/export_document.rsindex a30ca1a96b..a5eeb6c23b 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/export_document.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/export_document.rs@@ -1,4 +1,7 @@-use std::io::{Cursor, Write};+use std::{+ io::{Cursor, Write},+ str::FromStr,+};use crate::{api::context::ApiContext, service::s3::TEMP_FILE_PREFIX};use axum::{@@ -66,7 +69,7 @@ pub async fn handler() -> Result<Response, Response> {tracing::info!("export document");if let Some(file_type) = document_context.file_type.as_deref() {- let file_type: FileType = file_type.try_into().map_err(|e| {+ let file_type = FileType::from_str(file_type).map_err(|e| {tracing::error!(error=?e, "unable to convert file type");(StatusCode::INTERNAL_SERVER_ERROR,diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/get_document_key.rs b/rust/cloud-storage/document_storage_service/src/api/documents/get_document_key.rsindex d6e3305e7a..960a304b22 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/get_document_key.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/get_document_key.rs@@ -1,3 +1,5 @@+use std::str::FromStr;+use crate::model::response::documents::get::{GetDocumentKeyResponse, GetDocumentKeyResponseData};use axum::extract::State;use axum::{Extension, extract::Path, http::StatusCode, response::IntoResponse};@@ -43,7 +45,7 @@ pub async fn get_document_key_handler(}): Path<Params>,) -> impl IntoResponse {let file_type: FileType = if let Some(file_type) = &document_context.file_type {- match file_type.as_str().try_into() {+ match FileType::from_str(file_type.as_str()) {Ok(file_type) => file_type,Err(e) => {tracing::error!(error=?e, "invalid file type");diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/get_full_pdf_modification_data.rs b/rust/cloud-storage/document_storage_service/src/api/documents/get_full_pdf_modification_data.rsindex 51dcc8476f..4131451811 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/get_full_pdf_modification_data.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/get_full_pdf_modification_data.rs@@ -1,4 +1,4 @@-use std::collections::HashMap;+use std::{collections::HashMap, str::FromStr};use crate::api::context::ApiContext;@@ -48,7 +48,7 @@ pub async fn handler() -> impl IntoResponse {// Get the file type, needed to short circuit if the file type is docxlet file_type: FileType = if let Some(file_type) = document_context.file_type.as_ref() {- if let Ok(file_type) = file_type.as_str().try_into() {+ if let Ok(file_type) = FileType::from_str(file_type.as_str()) {file_type} else {tracing::error!("unable to parse file type");diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/location.rs b/rust/cloud-storage/document_storage_service/src/api/documents/location.rsindex 250df7630e..561b539e02 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/location.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/location.rs@@ -3,7 +3,10 @@ use anyhow::anyhow;use macro_middleware::cloud_storage::ensure_access::document::DocumentAccessExtractor;use models_permissions::share_permission::access_level::ViewAccessLevel;use rayon::prelude::*;-use std::time::{SystemTime, UNIX_EPOCH};+use std::{+ str::FromStr,+ time::{SystemTime, UNIX_EPOCH},+};use crate::{model::request::documents::location::LocationQueryParams,@@ -20,9 +23,9 @@ use cloudfront_sign::{SignedOptions, get_signed_url};use futures::{FutureExt, pin_mut, select};use model::{document::{- CONVERTED_DOCUMENT_FILE_NAME, DocumentBasic, FileType,- build_cloud_storage_bucket_document_key, response::LocationResponseData,- response::LocationResponseV3,+ CONVERTED_DOCUMENT_FILE_NAME, DocumentBasic, FileType, FileTypeExt,+ build_cloud_storage_bucket_document_key,+ response::{LocationResponseData, LocationResponseV3},},response::{GenericErrorResponse, GenericResponse, PresignedUrl},user::UserContext,@@ -201,7 +204,7 @@ pub async fn get_location_handler(let file_type: Option<FileType> = document_context.file_type.as_deref()- .and_then(|f| f.try_into().ok());+ .and_then(|f| FileType::from_str(f).ok());let response_data = get_presigned_url_by_type(&state,diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/pre_save.rs b/rust/cloud-storage/document_storage_service/src/api/documents/pre_save.rsindex 40f32516dc..e0285ae3e9 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/pre_save.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/pre_save.rs@@ -1,3 +1,5 @@+use std::str::FromStr;+use crate::{api::context::ApiContext,model::{@@ -62,7 +64,7 @@ pub async fn presave_document_handler(let file_type: FileType = match document_context.file_type.as_deref()- .and_then(|f| f.try_into().ok())+ .and_then(|f| FileType::from_str(f).ok()){Some(file_type) => file_type,None => {diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save_document_handler.rs b/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save_document_handler.rsindex 12fa7712b3..d8ecc4c3bd 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save_document_handler.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save_document_handler.rs@@ -1,3 +1,5 @@+use std::str::FromStr;+use crate::{api::{context::ApiContext, documents::utils},model::{@@ -18,7 +20,7 @@ use macro_middleware::cloud_storage::ensure_access::{document::DocumentAccessExtractor, project::ProjectBodyAccessLevelExtractor,};use model::{- document::{DocumentBasic, FileType, build_cloud_storage_bucket_document_key},+ document::{DocumentBasic, FileType, FileTypeExt, build_cloud_storage_bucket_document_key},response::{ErrorResponse, GenericErrorResponse, GenericResponse},user::UserContext,};@@ -73,7 +75,7 @@ pub async fn save_document_handler(let file_type: FileType = match document_context.file_type.as_deref()- .and_then(|f| f.try_into().ok())+ .and_then(|f| FileType::from_str(f).ok()){Some(file_type) => file_type,None => {diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs b/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rsindex a2abceb35b..61c430890b 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs@@ -1,3 +1,5 @@+use std::str::FromStr;+use crate::{api::{context::ApiContext, documents::utils},model::response::documents::{@@ -14,7 +16,7 @@ use axum::{};use macro_middleware::cloud_storage::ensure_access::document::DocumentAccessExtractor;use model::{- document::{DocumentBasic, FileType, build_cloud_storage_bucket_document_key},+ document::{DocumentBasic, FileType, FileTypeExt, build_cloud_storage_bucket_document_key},response::{GenericErrorResponse, GenericResponse},user::UserContext,};@@ -56,7 +58,7 @@ pub async fn handler(let file_type: FileType = match document_context.file_type.as_deref()- .and_then(|f| f.try_into().ok())+ .and_then(|f| FileType::from_str(f).ok()){Some(f) => f,None => {diff --git a/rust/cloud-storage/document_storage_service/src/api/projects/upload_folder.rs b/rust/cloud-storage/document_storage_service/src/api/projects/upload_folder.rsindex a48d25c488..ae7817db8e 100644--- a/rust/cloud-storage/document_storage_service/src/api/projects/upload_folder.rs+++ b/rust/cloud-storage/document_storage_service/src/api/projects/upload_folder.rs@@ -1,4 +1,4 @@-use std::sync::Arc;+use std::{str::FromStr, sync::Arc};use crate::{api::context::{ApiContext, InternalFlag},@@ -271,7 +271,8 @@ async fn build_documents(let file_type: Option<FileType> = document.file_type.as_deref()- .and_then(|file_type| file_type.try_into().ok());+ .map(FileType::from_str)+ .transpose()?;let sha = document.sha.clone().context("document needs a sha")?;if file_type != Some(FileType::Docx) {let key = build_cloud_storage_bucket_document_key(diff --git a/rust/cloud-storage/document_storage_service/src/model/response/documents/mod.rs b/rust/cloud-storage/document_storage_service/src/model/response/documents/mod.rsindex d910b45f31..c2a00eab09 100644--- a/rust/cloud-storage/document_storage_service/src/model/response/documents/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/model/response/documents/mod.rs@@ -1,3 +1,5 @@+use std::str::FromStr;+use chrono::serde::ts_seconds_option;use model::document::{BomPart, DocumentMetadata, FileType};use tracing::instrument;@@ -94,7 +96,7 @@ impl DocumentResponseMetadata {if let Some(FileType::Docx) = document_metadata.file_type.as_deref()- .and_then(|file_type| file_type.try_into().ok())+ .and_then(|file_type| FileType::from_str(file_type).ok())&& let Some(document_bom) = &document_metadata.document_bom{let document_bom: Vec<BomPart> = match serde_json::from_value(document_bom.clone()) {diff --git a/rust/cloud-storage/item_filters/Cargo.toml b/rust/cloud-storage/item_filters/Cargo.tomlindex 0ec407daed..909a0d0fc1 100644--- a/rust/cloud-storage/item_filters/Cargo.toml+++ b/rust/cloud-storage/item_filters/Cargo.toml@@ -8,6 +8,7 @@ version = "0.1.0"chrono = { workspace = true }filter_ast = { path = "../filter_ast" }macro_user_id = { path = "../macro_user_id" }+model_file_type = { path = "../model_file_type" }non_empty = { path = "../non_empty" }schemars = { workspace = true }serde = { workspace = true }diff --git a/rust/cloud-storage/macro_db_client/src/dcs/get_document_name_and_type.rs b/rust/cloud-storage/macro_db_client/src/dcs/get_document_name_and_type.rsindex e69f48411d..7b420999c4 100644--- a/rust/cloud-storage/macro_db_client/src/dcs/get_document_name_and_type.rs+++ b/rust/cloud-storage/macro_db_client/src/dcs/get_document_name_and_type.rs@@ -1,5 +1,6 @@use model::document::FileType;use sqlx::{Pool, Postgres};+use std::str::FromStr;#[tracing::instrument(skip(db))]pub async fn get_document_name_and_type(@@ -22,10 +23,10 @@ pub async fn get_document_name_and_type(let name: String = row.name;let file_type_str: String = row.file_type;match FileType::from_str(&file_type_str) {- Some(file_type) => Ok((name, file_type)),- None => Err(sqlx::Error::ColumnDecode {+ Ok(file_type) => Ok((name, file_type)),+ Err(e) => Err(sqlx::Error::ColumnDecode {index: "file_type".to_string(),- source: format!("invalid file type {}", file_type_str).into(),+ source: e.into(),}),}})diff --git a/rust/cloud-storage/macro_db_client/src/document/get_documents_search.rs b/rust/cloud-storage/macro_db_client/src/document/get_documents_search.rsindex f694c5a6f7..b0e0ef80b1 100644--- a/rust/cloud-storage/macro_db_client/src/document/get_documents_search.rs+++ b/rust/cloud-storage/macro_db_client/src/document/get_documents_search.rs@@ -1,6 +1,8 @@+use std::str::FromStr;+use sqlx::{Pool, Postgres};-use model::document::BackfillSearchDocumentInformation;+use model::document::{BackfillSearchDocumentInformation, FileType};/// Used to get all documents in a paginated format/// This will get the latest version of the document for non-pdf documents@@ -64,11 +66,18 @@ pub async fn get_documents_for_search(offset,file_types)- .map(|row| BackfillSearchDocumentInformation {- document_id: row.document_id,- document_version_id: row.document_version_id,- owner: row.owner,- file_type: row.file_type.as_str().try_into().unwrap(),+ .try_map(|row| {+ Ok(BackfillSearchDocumentInformation {+ document_id: row.document_id,+ document_version_id: row.document_version_id,+ owner: row.owner,+ file_type: FileType::from_str(row.file_type.as_str()).map_err(|e| {+ sqlx::Error::ColumnDecode {+ index: "file_type".to_string(),+ source: e.into(),+ }+ })?,+ })}).fetch_all(db).await?@@ -123,11 +132,18 @@ pub async fn get_documents_for_search(limit,offset)- .map(|row| BackfillSearchDocumentInformation {- document_id: row.document_id,- document_version_id: row.document_version_id,- owner: row.owner,- file_type: row.file_type.as_str().try_into().unwrap(),+ .try_map(|row| {+ Ok(BackfillSearchDocumentInformation {+ document_id: row.document_id,+ document_version_id: row.document_version_id,+ owner: row.owner,+ file_type: FileType::from_str(row.file_type.as_str()).map_err(|e| {+ sqlx::Error::ColumnDecode {+ index: "file_type".to_string(),+ source: e.into(),+ }+ })?,+ })}).fetch_all(db).await?diff --git a/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs b/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rsindex cca1775098..432c0dbb84 100644--- a/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs+++ b/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs@@ -6,7 +6,7 @@ use crate::{};use async_recursion::async_recursion;use model::{- document::{DocumentMetadata, FileType},+ document::{DocumentMetadata, FileType, FileTypeExt},folder::{FileSystemNode, FileSystemNodeWithIds, UploadFolderWithIdsResponse},project::Project,};@@ -111,7 +111,8 @@ async fn traverse_with_ids(crate::document::v2::create::CreateDocumentArgs {id: None,sha: item.sha.as_str(),- document_name: &FileType::clean_document_name(item.name.clone()),+ document_name: &FileType::clean_document_name(&item.name)+ .unwrap_or_else(|| item.name.clone()),user_id,file_type: item.file_type,project_id: Some(project_id),diff --git a/rust/cloud-storage/model/Cargo.toml b/rust/cloud-storage/model/Cargo.tomlindex 0474224e3a..88063246a0 100644--- a/rust/cloud-storage/model/Cargo.toml+++ b/rust/cloud-storage/model/Cargo.toml@@ -16,13 +16,13 @@ axum = { workspace = true }base64 = { workspace = true }chrono = { workspace = true }model-error-response = { path = "../model-error-response" }+model_file_type = { path = "../model_file_type", features = ["utoipa"] }model_user = { path = "../model_user" }models_bulk_upload = { path = "../models_bulk_upload" }models_comms = { path = "../models_comms" }models_email = { path = "../models_email" }models_pagination = { path = "../models_pagination" }models_permissions = { path = "../models_permissions" }-once_cell = { workspace = true }schemars = { workspace = true }serde = { workspace = true }serde_json = { workspace = true, features = ["raw_value"] }diff --git a/rust/cloud-storage/model/src/document/basic.rs b/rust/cloud-storage/model/src/document/basic.rsindex df3fd3a18a..a205e7bcdc 100644--- a/rust/cloud-storage/model/src/document/basic.rs+++ b/rust/cloud-storage/model/src/document/basic.rs@@ -1,3 +1,7 @@+use std::str::FromStr;++use crate::document::FileTypeExt;+use super::file_type::FileType;use chrono::serde::ts_seconds_option;use utoipa::ToSchema;@@ -130,12 +134,16 @@ pub struct DocumentInfo {impl DocumentBasic {pub fn is_text_content(&self) -> bool {self.file_type- .clone()- .and_then(|f| FileType::from_str(f.as_str()))+ .as_deref()+ .map(FileType::from_str)+ .and_then(Result::ok).map(|ft| ft.is_text_content()).unwrap_or(false)}pub fn try_file_type(&self) -> Option<FileType> {- self.file_type.as_deref().and_then(FileType::from_str)+ self.file_type+ .as_deref()+ .map(FileType::from_str)+ .and_then(Result::ok)}}diff --git a/rust/cloud-storage/model/src/document/file_type/mod.rs b/rust/cloud-storage/model/src/document/file_type/mod.rsindex 0729bcdff4..97aceb8e9b 100644--- a/rust/cloud-storage/model/src/document/file_type/mod.rs+++ b/rust/cloud-storage/model/src/document/file_type/mod.rs@@ -1,12 +1,12 @@mod suffix_trie;--use once_cell::sync::Lazy;--use utoipa::ToSchema;-+pub use model_file_type::{ContentType, FileType};+use std::sync::LazyLock;use suffix_trie::ReversedSuffixTrie;-static SUFFIX_TRIE: Lazy<ReversedSuffixTrie> = Lazy::new(|| {+#[cfg(test)]+mod tests;++static SUFFIX_TRIE: LazyLock<ReversedSuffixTrie> = LazyLock::new(|| {let mut trie = ReversedSuffixTrie::new();for ft in FileType::all() {@@ -23,689 +23,51 @@ static SUFFIX_TRIE: Lazy<ReversedSuffixTrie> = Lazy::new(|| {const PLAINTEXT_TYPES: &[&str] = &["application/x-macro-canvas"];-macro_rules! generate_file_types {- ($(($variant:ident, $str_name:expr, $mime_type:expr, $app_path:expr)),* $(,)?) => {- /// Generates a FileType enum and associated ContentType enum with their implementations.- ///- /// This macro takes a list of tuples in the format:- /// (Variant, "extension", "mime_type", CONTENT_TYPE_VARIANT)- ///- /// For each tuple it generates:- /// - A variant in the FileType enum- /// - A variant in the ContentType enum- /// - Implementations for:- /// - FileType::to_str() - Converts FileType to extension string- /// - FileType::from_str() - Converts extension string to FileType- /// - From<FileType> for ContentType - Maps FileType to ContentType- /// - ContentType::mime_type() - Gets MIME type for ContentType- ///- #[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Copy, Clone, ToSchema)]- #[serde(rename_all = "lowercase")]- pub enum FileType {- $(- $variant,- )*- }-- impl FileType {- pub fn as_str(&self) -> &str {- match self {- $(- FileType::$variant => $str_name,- )*- }- }-- pub fn mime_type(&self) -> &'static str {- match self {- $(- FileType::$variant => $mime_type,- )*- }- }-- #[expect(clippy::should_implement_trait, reason = "FIXME implement FromStr instead")]- pub fn from_str(file_type: &str) -> Option<Self> {- let cleaned = file_type- .trim_start_matches('.') // remove leading dot- .to_ascii_lowercase(); // normalize to lowercase-- match cleaned.as_str() {- $(- $str_name => Some(FileType::$variant),- )*- _ => {- tracing::warn!("invalid file type {file_type} attempted to be made from_string");- None- }- }- }-- pub fn macro_app_path(&self) -> String {- match self {- $(- FileType::$variant => $app_path.to_string(),- )*- }- }-- pub fn all() -> &'static [FileType] {- &[- $(- FileType::$variant,- )*- ]- }- }-- impl std::fmt::Display for FileType {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- $(- FileType::$variant => write!(f, "{}", $str_name),- )*- }- }- }--- #[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone)]- pub enum ContentType {- $(- $variant,- )*- Default,- }-- impl From<FileType> for ContentType {- fn from(file_type: FileType) -> Self {- match file_type {- $(- FileType::$variant => ContentType::$variant,- )*- }- }- }-- impl From<Option<FileType>> for ContentType {- fn from(file_type: Option<FileType>) -> Self {- match file_type {- Some(file_type) => file_type.into(),- None => ContentType::Default,- }- }- }-- impl ContentType {- #[expect(clippy::should_implement_trait, reason = "FIXME implement FromStr instead")]- pub fn from_str(mime_type: &str) -> Option<Self> {- let cleaned = mime_type.to_ascii_lowercase();-- // there can be multiple variants for the same mime type- // but it does not matter for the purposes of this function- #[expect(unreachable_patterns)]- match cleaned.as_str() {- $(- $mime_type => Some(ContentType::$variant),- )*- _ => {- tracing::warn!("invalid mime type {mime_type} attempted to be made from string");- None- }- }- }+/// extension methods for the [FileType] enum+pub trait FileTypeExt {+ /// attempts to return the document name only if it can be parsed out of .e.g file.txt -> file+ fn clean_document_name(document_name: &str) -> Option<String> {+ FileType::split_suffix_match(document_name).map(|(s, _)| s.to_string())+ }- pub fn mime_type(&self) -> &'static str {- match self {- $(- ContentType::$variant => $mime_type,- )*- ContentType::Default => "application/octet-stream",- }- }- }- };-}+ /// returns true if the file type is an image+ fn is_image(&self) -> bool;-generate_file_types!(- (- Docx,- "docx",- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",- "write"- ),- (Pdf, "pdf", "application/pdf", "pdf"),- (Md, "md", "text/markdown", "md"),- (Canvas, "canvas", "application/x-macro-canvas", "canvas"),- // Code block: generated from VS Code extensions {- (Coffee, "coffee", "text/plain", "code"),- (Cson, "cson", "text/plain", "code"),- (Iced, "iced", "text/plain", "code"),- (C, "c", "text/plain", "code"),- (I, "i", "text/plain", "code"),- (Cpp, "cpp", "text/plain", "code"),- (Cppm, "cppm", "text/plain", "code"),- (Cc, "cc", "text/plain", "code"),- (Ccm, "ccm", "text/plain", "code"),- (Cxx, "cxx", "text/plain", "code"),- (Cxxm, "cxxm", "text/plain", "code"),- (CPlusPlus, "c++", "text/plain", "code"),- (CPlusPlusm, "c++m", "text/plain", "code"),- (Hpp, "hpp", "text/plain", "code"),- (Hh, "hh", "text/plain", "code"),- (Hxx, "hxx", "text/plain", "code"),- (HPlusPlus, "h++", "text/plain", "code"),- (H, "h", "text/plain", "code"),- (Ii, "ii", "text/plain", "code"),- (Ino, "ino", "text/plain", "code"),- (Inl, "inl", "text/plain", "code"),- (Ipp, "ipp", "text/plain", "code"),- (Ixx, "ixx", "text/plain", "code"),- (Tpp, "tpp", "text/plain", "code"),- (Txx, "txx", "text/plain", "code"),- (HppIn, "hpp.in", "text/plain", "code"),- (HIn, "h.in", "text/plain", "code"),- (Cu, "cu", "text/plain", "code"),- (Cuh, "cuh", "text/plain", "code"),- (Cs, "cs", "text/plain", "code"),- (Csx, "csx", "text/plain", "code"),- (Cake, "cake", "text/plain", "code"),- (Css, "css", "text/plain", "code"),- (Dart, "dart", "text/plain", "code"),- (Diff, "diff", "text/plain", "code"),- (Patch, "patch", "text/plain", "code"),- (Rej, "rej", "text/plain", "code"),- (Dockerfile, "dockerfile", "text/plain", "code"),- (Containerfile, "containerfile", "text/plain", "code"),- (Go, "go", "text/plain", "code"),- (Handlebars, "handlebars", "text/plain", "code"),- (Hbs, "hbs", "text/plain", "code"),- (Hjs, "hjs", "text/plain", "code"),- (Hlsl, "hlsl", "text/plain", "code"),- (Hlsli, "hlsli", "text/plain", "code"),- (Fx, "fx", "text/plain", "code"),- (Fxh, "fxh", "text/plain", "code"),- (Vsh, "vsh", "text/plain", "code"),- (Psh, "psh", "text/plain", "code"),- (Cginc, "cginc", "text/plain", "code"),- (Compute, "compute", "text/plain", "code"),- (Html, "html", "text/plain", "code"),- (Htm, "htm", "text/plain", "code"),- (Shtml, "shtml", "text/plain", "code"),- (Xhtml, "xhtml", "text/plain", "code"),- (Xht, "xht", "text/plain", "code"),- (Mdoc, "mdoc", "text/plain", "code"),- (Jsp, "jsp", "text/plain", "code"),- (Asp, "asp", "text/plain", "code"),- (Aspx, "aspx", "text/plain", "code"),- (Jshtm, "jshtm", "text/plain", "code"),- (Volt, "volt", "text/plain", "code"),- (Ejs, "ejs", "text/plain", "code"),- (Rhtml, "rhtml", "text/plain", "code"),- (Ini, "ini", "text/plain", "code"),- (Conf, "conf", "text/plain", "code"),- (Properties, "properties", "text/plain", "code"),- (Cfg, "cfg", "text/plain", "code"),- (Directory, "directory", "text/plain", "code"),- (Gitattributes, "gitattributes", "text/plain", "code"),- (Gitconfig, "gitconfig", "text/plain", "code"),- (Gitmodules, "gitmodules", "text/plain", "code"),- (Editorconfig, "editorconfig", "text/plain", "code"),- (Repo, "repo", "text/plain", "code"),- (Java, "java", "text/plain", "code"),- (Jav, "jav", "text/plain", "code"),- (Jsx, "jsx", "text/plain", "code"),- (Js, "js", "text/plain", "code"),- (Es6, "es6", "text/plain", "code"),- (Mjs, "mjs", "text/plain", "code"),- (Cjs, "cjs", "text/plain", "code"),- (Pac, "pac", "text/plain", "code"),- (Json, "json", "text/plain", "code"),- (Bowerrc, "bowerrc", "text/plain", "code"),- (Jscsrc, "jscsrc", "text/plain", "code"),- (Webmanifest, "webmanifest", "text/plain", "code"),- (JsMap, "js.map", "text/plain", "code"),- (CssMap, "css.map", "text/plain", "code"),- (TsMap, "ts.map", "text/plain", "code"),- (Har, "har", "text/plain", "code"),- (Jslintrc, "jslintrc", "text/plain", "code"),- (Jsonld, "jsonld", "text/plain", "code"),- (Geojson, "geojson", "text/plain", "code"),- (Ipynb, "ipynb", "text/plain", "code"),- (Vuerc, "vuerc", "text/plain", "code"),- (Jsonc, "jsonc", "text/plain", "code"),- (Eslintrc, "eslintrc", "text/plain", "code"),- (EslintrcJson, "eslintrc.json", "text/plain", "code"),- (Jsfmtrc, "jsfmtrc", "text/plain", "code"),- (Jshintrc, "jshintrc", "text/plain", "code"),- (Swcrc, "swcrc", "text/plain", "code"),- (Hintrc, "hintrc", "text/plain", "code"),- (Babelrc, "babelrc", "text/plain", "code"),- (Jsonl, "jsonl", "text/plain", "code"),- (Ndjson, "ndjson", "text/plain", "code"),- (CodeSnippets, "code-snippets", "text/plain", "code"),- (Jl, "jl", "text/plain", "code"),- (Jmd, "jmd", "text/plain", "code"),- (Sty, "sty", "text/plain", "code"),- (Cls, "cls", "text/plain", "code"),- (Bbx, "bbx", "text/plain", "code"),- (Cbx, "cbx", "text/plain", "code"),- (Tex, "tex", "text/plain", "code"),- (Ltx, "ltx", "text/plain", "code"),- (Ctx, "ctx", "text/plain", "code"),- (Bib, "bib", "text/plain", "code"),- (Less, "less", "text/plain", "code"),- (Log, "log", "text/plain", "code"),- (Lua, "lua", "text/plain", "code"),- (Mak, "mak", "text/plain", "code"),- (Mk, "mk", "text/plain", "code"),- (Mkd, "mkd", "text/plain", "code"),- (Mdwn, "mdwn", "text/plain", "code"),- (Mdown, "mdown", "text/plain", "code"),- (Markdown, "markdown", "text/plain", "code"),- (Markdn, "markdn", "text/plain", "code"),- (Mdtxt, "mdtxt", "text/plain", "code"),- (Mdtext, "mdtext", "text/plain", "code"),- (Workbook, "workbook", "text/plain", "code"),- (M, "m", "text/plain", "code"),- (Mm, "mm", "text/plain", "code"),- (Pl, "pl", "text/plain", "code"),- (Pm, "pm", "text/plain", "code"),- (Pod, "pod", "text/plain", "code"),- (T, "t", "text/plain", "code"),- (Psgi, "psgi", "text/plain", "code"),- (Raku, "raku", "text/plain", "code"),- (Rakumod, "rakumod", "text/plain", "code"),- (Rakutest, "rakutest", "text/plain", "code"),- (Rakudoc, "rakudoc", "text/plain", "code"),- (Nqp, "nqp", "text/plain", "code"),- (P6, "p6", "text/plain", "code"),- (Pl6, "pl6", "text/plain", "code"),- (Pm6, "pm6", "text/plain", "code"),- (Php, "php", "text/plain", "code"),- (Php4, "php4", "text/plain", "code"),- (Php5, "php5", "text/plain", "code"),- (Phtml, "phtml", "text/plain", "code"),- (Ctp, "ctp", "text/plain", "code"),- (Ps1, "ps1", "text/plain", "code"),- (Psm1, "psm1", "text/plain", "code"),- (Psd1, "psd1", "text/plain", "code"),- (Pssc, "pssc", "text/plain", "code"),- (Psrc, "psrc", "text/plain", "code"),- (Py, "py", "text/plain", "code"),- (Rpy, "rpy", "text/plain", "code"),- (Pyw, "pyw", "text/plain", "code"),- (Cpy, "cpy", "text/plain", "code"),- (Gyp, "gyp", "text/plain", "code"),- (Gypi, "gypi", "text/plain", "code"),- (Pyi, "pyi", "text/plain", "code"),- (Ipy, "ipy", "text/plain", "code"),- (Pyt, "pyt", "text/plain", "code"),- (R, "r", "text/plain", "code"),- (Rhistory, "rhistory", "text/plain", "code"),- (Rprofile, "rprofile", "text/plain", "code"),- (Rt, "rt", "text/plain", "code"),- (Cshtml, "cshtml", "text/plain", "code"),- (Razor, "razor", "text/plain", "code"),- (Rb, "rb", "text/plain", "code"),- (Rbx, "rbx", "text/plain", "code"),- (Rjs, "rjs", "text/plain", "code"),- (Gemspec, "gemspec", "text/plain", "code"),- (Rake, "rake", "text/plain", "code"),- (Ru, "ru", "text/plain", "code"),- (Erb, "erb", "text/plain", "code"),- (Podspec, "podspec", "text/plain", "code"),- (Rbi, "rbi", "text/plain", "code"),- (Rs, "rs", "text/plain", "code"),- (Scss, "scss", "text/plain", "code"),- (Shader, "shader", "text/plain", "code"),- (Sh, "sh", "text/plain", "code"),- (Bash, "bash", "text/plain", "code"),- (Bashrc, "bashrc", "text/plain", "code"),- (BashAliases, "bash_aliases", "text/plain", "code"),- (BashProfile, "bash_profile", "text/plain", "code"),- (BashLogin, "bash_login", "text/plain", "code"),- (Ebuild, "ebuild", "text/plain", "code"),- (Eclass, "eclass", "text/plain", "code"),- (Profile, "profile", "text/plain", "code"),- (BashLogout, "bash_logout", "text/plain", "code"),- (Xprofile, "xprofile", "text/plain", "code"),- (Xsession, "xsession", "text/plain", "code"),- (Xsessionrc, "xsessionrc", "text/plain", "code"),- (Zsh, "zsh", "text/plain", "code"),- (Zshrc, "zshrc", "text/plain", "code"),- (Zprofile, "zprofile", "text/plain", "code"),- (Zlogin, "zlogin", "text/plain", "code"),- (Zlogout, "zlogout", "text/plain", "code"),- (Zshenv, "zshenv", "text/plain", "code"),- (ZshTheme, "zsh-theme", "text/plain", "code"),- (Fish, "fish", "text/plain", "code"),- (Ksh, "ksh", "text/plain", "code"),- (Csh, "csh", "text/plain", "code"),- (Cshrc, "cshrc", "text/plain", "code"),- (Tcshrc, "tcshrc", "text/plain", "code"),- (Yashrc, "yashrc", "text/plain", "code"),- (YashProfile, "yash_profile", "text/plain", "code"),- (Sql, "sql", "text/plain", "code"),- (Dsql, "dsql", "text/plain", "code"),- (Swift, "swift", "text/plain", "code"),- (Ts, "ts", "text/plain", "code"),- (Cts, "cts", "text/plain", "code"),- (Mts, "mts", "text/plain", "code"),- (Tsx, "tsx", "text/plain", "code"),- (Tsbuildinfo, "tsbuildinfo", "text/plain", "code"),- (Xml, "xml", "text/plain", "code"),- (Xsd, "xsd", "text/plain", "code"),- (Ascx, "ascx", "text/plain", "code"),- (Atom, "atom", "text/plain", "code"),- (Axml, "axml", "text/plain", "code"),- (Axaml, "axaml", "text/plain", "code"),- (Bpmn, "bpmn", "text/plain", "code"),- (Cpt, "cpt", "text/plain", "code"),- (Csl, "csl", "text/plain", "code"),- (Csproj, "csproj", "text/plain", "code"),- (CsprojUser, "csproj.user", "text/plain", "code"),- (Dita, "dita", "text/plain", "code"),- (Ditamap, "ditamap", "text/plain", "code"),- (Dtd, "dtd", "text/plain", "code"),- (Ent, "ent", "text/plain", "code"),- (Mod, "mod", "text/plain", "code"),- (Dtml, "dtml", "text/plain", "code"),- (Fsproj, "fsproj", "text/plain", "code"),- (Fxml, "fxml", "text/plain", "code"),- (Iml, "iml", "text/plain", "code"),- (Isml, "isml", "text/plain", "code"),- (Jmx, "jmx", "text/plain", "code"),- (Launch, "launch", "text/plain", "code"),- (Menu, "menu", "text/plain", "code"),- (Mxml, "mxml", "text/plain", "code"),- (Nuspec, "nuspec", "text/plain", "code"),- (Opml, "opml", "text/plain", "code"),- (Owl, "owl", "text/plain", "code"),- (Proj, "proj", "text/plain", "code"),- (Props, "props", "text/plain", "code"),- (Pt, "pt", "text/plain", "code"),- (Publishsettings, "publishsettings", "text/plain", "code"),- (Pubxml, "pubxml", "text/plain", "code"),- (PubxmlUser, "pubxml.user", "text/plain", "code"),- (Rbxlx, "rbxlx", "text/plain", "code"),- (Rbxmx, "rbxmx", "text/plain", "code"),- (Rdf, "rdf", "text/plain", "code"),- (Rng, "rng", "text/plain", "code"),- (Rss, "rss", "text/plain", "code"),- (Shproj, "shproj", "text/plain", "code"),- (Storyboard, "storyboard", "text/plain", "code"),- (Targets, "targets", "text/plain", "code"),- (Tld, "tld", "text/plain", "code"),- (Tmx, "tmx", "text/plain", "code"),- (Vbproj, "vbproj", "text/plain", "code"),- (VbprojUser, "vbproj.user", "text/plain", "code"),- (Vcxproj, "vcxproj", "text/plain", "code"),- (VcxprojFilters, "vcxproj.filters", "text/plain", "code"),- (Wsdl, "wsdl", "text/plain", "code"),- (Wxi, "wxi", "text/plain", "code"),- (Wxl, "wxl", "text/plain", "code"),- (Wxs, "wxs", "text/plain", "code"),- (Xaml, "xaml", "text/plain", "code"),- (Xbl, "xbl", "text/plain", "code"),- (Xib, "xib", "text/plain", "code"),- (Xlf, "xlf", "text/plain", "code"),- (Xliff, "xliff", "text/plain", "code"),- (Xpdl, "xpdl", "text/plain", "code"),- (Xul, "xul", "text/plain", "code"),- (Xoml, "xoml", "text/plain", "code"),- (Xsl, "xsl", "text/plain", "code"),- (Xslt, "xslt", "text/plain", "code"),- (Yaml, "yaml", "text/plain", "code"),- (Yml, "yml", "text/plain", "code"),- (Eyaml, "eyaml", "text/plain", "code"),- (Eyml, "eyml", "text/plain", "code"),- (Cff, "cff", "text/plain", "code"),- (YamlTmlanguage, "yaml-tmlanguage", "text/plain", "code"),- (- YamlTmpreferences,- "yaml-tmpreferences",- "text/plain",- "code"- ),- (YamlTmtheme, "yaml-tmtheme", "text/plain", "code"),- (Winget, "winget", "text/plain", "code"),- (Txt, "txt", "text/plain", "code"),- (Csv, "csv", "text/plain", "code"),- (Tsv, "tsv", "text/plain", "code"),- // } Code block- // images- (Jpeg, "jpeg", "image/jpeg", "image"),- (Jpg, "jpg", "image/jpeg", "image"),- (Png, "png", "image/png", "image"),- (Gif, "gif", "image/gif", "image"),- (Svg, "svg", "image/svg+xml", "image"),- (Webp, "webp", "image/webp", "image"),- (Avif, "avif", "image/avif", "image"),- (Bmp, "bmp", "image/bmp", "image"),- (Ico, "ico", "image/x-icon", "image"),- (Tiff, "tiff", "image/tiff", "image"),- (Tif, "tif", "image/tiff", "image"),- (Heic, "heic", "image/heic", "image"),- (Heif, "heif", "image/heif", "image"),- // NOT SUPPORTED BLOCKS+ /// returns true if the document cannot be modified in macro+ fn is_static(&self) -> bool;- // Archives and compressed files- (Tar, "tar", "application/x-tar", "archive"),- (TarGz, "tar.gz", "application/gzip", "archive"),- (Tgz, "tgz", "application/gzip", "archive"),- (Gz, "gz", "application/gzip", "archive"),- (Bz2, "bz2", "application/x-bzip2", "archive"),- (TarBz2, "tar.bz2", "application/x-bzip2", "archive"),- (Tbz2, "tbz2", "application/x-bzip2", "archive"),- (Z, "z", "application/x-compress", "archive"),- (TarZ, "tar.z", "application/x-compress", "archive"),- (Lz, "lz", "application/x-lzip", "archive"),- (TarLz, "tar.lz", "application/x-lzip", "archive"),- (Xz, "xz", "application/x-xz", "archive"),- (TarXz, "tar.xz", "application/x-xz", "archive"),- (Txz, "txz", "application/x-xz", "archive"),- (Lzma, "lzma", "application/x-lzma", "archive"),- (TarLzma, "tar.lzma", "application/x-lzma", "archive"),- (Rar, "rar", "application/vnd.rar", "archive"),- (SevenZ, "7z", "application/x-7z-compressed", "archive"),- (Zst, "zst", "application/zstd", "archive"),- (TarZst, "tar.zst", "application/zstd", "archive"),- (Tzst, "tzst", "application/zstd", "archive"),- (Zip, "zip", "application/zip", "archive"),- // Executable files- (Exe, "exe", "application/x-msdownload", "executable"),- (Msi, "msi", "application/x-msi", "executable"),- (Dll, "dll", "application/x-msdownload", "executable"),- (Bat, "bat", "application/x-bat", "executable"),- (Cmd, "cmd", "application/x-cmd", "executable"),- (Com, "com", "application/x-msdownload", "executable"),- (- AppImage,- "appimage",- "application/x-executable",- "executable"- ),- (App, "app", "application/x-executable", "executable"),- (Bin, "bin", "application/octet-stream", "executable"),- (- Deb,- "deb",- "application/vnd.debian.binary-package",- "executable"- ),- (Rpm, "rpm", "application/x-rpm", "executable"),- (- Apk,- "apk",- "application/vnd.android.package-archive",- "executable"- ),- (Dmg, "dmg", "application/x-apple-diskimage", "executable"),- (- Pkg,- "pkg",- "application/vnd.apple.installer+xml",- "executable"- ),- (Crx, "crx", "application/x-chrome-extension", "executable"),- (Xpi, "xpi", "application/x-xpinstall", "executable"),- // Audio files- (Mp3, "mp3", "audio/mpeg", "audio"),- (Wav, "wav", "audio/wav", "audio"),- (Ogg, "ogg", "audio/ogg", "audio"),- (Flac, "flac", "audio/flac", "audio"),- (Aac, "aac", "audio/aac", "audio"),- (M4a, "m4a", "audio/mp4", "audio"),- (Wma, "wma", "audio/x-ms-wma", "audio"),- (Mid, "mid", "audio/midi", "audio"),- (Midi, "midi", "audio/midi", "audio"),- // Video files- (Mp4, "mp4", "video/mp4", "video"),- (Mkv, "mkv", "video/x-matroska", "video"),- (Webm, "webm", "video/webm", "video"),- (Avi, "avi", "video/x-msvideo", "video"),- (Mov, "mov", "video/quicktime", "video"),- (Wmv, "wmv", "video/x-ms-wmv", "video"),- (Mpg, "mpg", "video/mpeg", "video"),- (Mpeg, "mpeg", "video/mpeg", "video"),- (M4v, "m4v", "video/mp4", "video"),- (Flv, "flv", "video/x-flv", "video"),- (F4v, "f4v", "video/mp4", "video"),- (ThreeGp, "3gp", "video/3gpp", "video"),- // Font files- (Ttf, "ttf", "font/ttf", "font"),- (Otf, "otf", "font/otf", "font"),- (Woff, "woff", "font/woff", "font"),- (Woff2, "woff2", "font/woff2", "font"),- (Eot, "eot", "application/vnd.ms-fontobject", "font"),- // Document formats- (Rtf, "rtf", "application/rtf", "document"),- (- Odt,- "odt",- "application/vnd.oasis.opendocument.text",- "document"- ),- (- Ods,- "ods",- "application/vnd.oasis.opendocument.spreadsheet",- "document"- ),- (- Odp,- "odp",- "application/vnd.oasis.opendocument.presentation",- "document"- ),- (- Odg,- "odg",- "application/vnd.oasis.opendocument.graphics",- "document"- ),- (- Odf,- "odf",- "application/vnd.oasis.opendocument.formula",- "document"- ),- (Epub, "epub", "application/epub+zip", "document"),- (Mobi, "mobi", "application/x-mobipocket-ebook", "document"),- (Azw, "azw", "application/vnd.amazon.ebook", "document"),- (Azw3, "azw3", "application/vnd.amazon.ebook", "document"),- (Djvu, "djvu", "image/vnd.djvu", "document"),- (Xls, "xls", "application/vnd.ms-excel", "document"),- (Ppt, "ppt", "application/vnd.ms-powerpoint", "document"),- (Pptx, "pptx", "application/xml", "document"),- (Xlsx, "xlsx", "application/xml", "document"),- // Database files- (Db, "db", "application/octet-stream", "database"),- (Sqlite, "sqlite", "application/vnd.sqlite3", "database"),- (Sqlite3, "sqlite3", "application/vnd.sqlite3", "database"),- (Mdb, "mdb", "application/vnd.ms-access", "database"),- (Accdb, "accdb", "application/vnd.ms-access", "database"),- (Dbf, "dbf", "application/x-dbf", "database"),- // Data and config files- (Plist, "plist", "application/xml", "data"),- (Toml, "toml", "application/toml", "data"),- (Env, "env", "text/plain", "data"),- (Dot, "dot", "text/vnd.graphviz", "data"),- (Gv, "gv", "text/vnd.graphviz", "data"),- (Torrent, "torrent", "application/x-bittorrent", "data"),- (Ics, "ics", "text/calendar", "data"),- (Vcf, "vcf", "text/vcard", "data"),- // Vector graphics- (Ai, "ai", "application/postscript", "vector"),- (Eps, "eps", "application/postscript", "vector"),- (Ps, "ps", "application/postscript", "vector"),- (Dxf, "dxf", "image/vnd.dxf", "vector"),- (Dwg, "dwg", "image/vnd.dwg", "vector"),- // 3D files- (Stl, "stl", "model/stl", "3d"),- (Obj, "obj", "model/obj", "3d"),- (Fbx, "fbx", "application/octet-stream", "3d"),- (Blend, "blend", "application/x-blender", "3d"),- (Dae, "dae", "model/vnd.collada+xml", "3d"),- (ThreeDs, "3ds", "application/x-3ds", "3d"),- (Gltf, "gltf", "model/gltf+json", "3d"),- (Glb, "glb", "model/gltf-binary", "3d"),- // Virtual machine and container files- (Vhd, "vhd", "application/x-virtualbox-vhd", "vm"),- (Vhdx, "vhdx", "application/x-virtualbox-vhdx", "vm"),- (Vmdk, "vmdk", "application/x-vmdk", "vm"),- (Ova, "ova", "application/x-virtualbox-ova", "vm"),- (Ovf, "ovf", "application/x-virtualbox-ovf", "vm"),- (Iso, "iso", "application/x-iso9660-image", "vm"),- (Img, "img", "application/octet-stream", "vm"),- // Miscellaneous- (Swf, "swf", "application/x-shockwave-flash", "media"),-);+ /// the opposite of [FileTypeExt::is_static]+ fn is_editable(&self) -> bool {+ !self.is_static()+ }-// Uses the from_str function from the macro to convert a string to a FileType-impl TryInto<FileType> for &str {- type Error = anyhow::Error;- fn try_into(self) -> Result<FileType, Self::Error> {- FileType::from_str(self).ok_or_else(|| {- anyhow::anyhow!("invalid file type {self} attempted to be made from_string")- })+ /// returns true if the input filename has a supported suffix+ fn is_suffix_match(filename: &str) -> bool {+ SUFFIX_TRIE.string_has_suffix(filename)}-}-impl FileType {- pub fn clean_document_name(document_name: String) -> String {- match FileType::split_suffix_match(document_name.as_str()) {- Some((document_name, _)) => document_name.to_string(),- None => document_name,- }+ // Returns the file prefix and the extension (no period)+ fn split_suffix_match(filename: &str) -> Option<(&str, &str)> {+ SUFFIX_TRIE.split_suffix(filename)}- pub fn is_image(&self) -> bool {+ /// return true if the file type contains readable text content+ fn is_text_content(&self) -> bool;+}++impl FileTypeExt for FileType {+ fn is_image(&self) -> bool {matches!(self,FileType::Png | FileType::Jpg | FileType::Gif | FileType::Svg | FileType::Jpeg)}- pub fn is_static(&self) -> bool {+ fn is_static(&self) -> bool {matches!(self, FileType::Pdf) || self.is_image()}- pub fn is_editable(&self) -> bool {- !self.is_static()- }-- pub fn is_suffix_match(filename: &str) -> bool {- SUFFIX_TRIE.string_has_suffix(filename)- }-- // Returns the file prefix and the extension (no period)- pub fn split_suffix_match(filename: &str) -> Option<(&str, &str)> {- SUFFIX_TRIE.split_suffix(filename)- }-- pub fn is_text_content(&self) -> bool {+ fn is_text_content(&self) -> bool {if self == &FileType::Pdf || self == &FileType::Docx {return true;}@@ -718,12 +80,20 @@ impl FileType {}}-impl ContentType {- pub fn is_image(&self) -> bool {+/// extension trait for [ContentType]+pub trait ContentTypeExt {+ /// return true if the content type is an image+ fn is_image(&self) -> bool;+ /// return true if the content type contains readable text+ fn is_text_content(&self) -> bool;+}++impl ContentTypeExt for ContentType {+ fn is_image(&self) -> bool {self.mime_type().starts_with("image/")}- pub fn is_text_content(&self) -> bool {+ fn is_text_content(&self) -> bool {match self {ContentType::Pdf | ContentType::Docx => true,_ => {@@ -733,143 +103,3 @@ impl ContentType {}}}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_clean_document_name() {- assert_eq!(- FileType::clean_document_name("report.docx".to_string()),- "report"- );- assert_eq!(- FileType::clean_document_name("proposal.pdf".to_string()),- "proposal"- );- assert_eq!(- FileType::clean_document_name("testing.md".to_string()),- "testing"- );- assert_eq!(- FileType::clean_document_name("testing.py".to_string()),- "testing"- );- assert_eq!(- FileType::clean_document_name("testing.html".to_string()),- "testing"- );- assert_eq!(- FileType::clean_document_name("testing.txt".to_string()),- "testing"- );- assert_eq!(- FileType::clean_document_name("notes.backup.pdf".to_string()),- "notes.backup"- );-- assert_eq!(- FileType::clean_document_name("testing.random".to_string()),- "testing.random"- );- assert_eq!(FileType::clean_document_name("note.".to_string()), "note.");- assert_eq!(FileType::clean_document_name("".to_string()), "");- assert_eq!(- FileType::clean_document_name("testing".to_string()),- "testing"- );- assert_eq!(- FileType::clean_document_name("testing.zip".to_string()),- "testing"- );- assert_eq!(- FileType::clean_document_name("testing.tar.gz".to_string()),- "testing"- );- assert_eq!(- FileType::clean_document_name("testing.js.map".to_string()),- "testing"- );- }-- #[test]- fn test_is_suffix_match() {- assert!(FileType::is_suffix_match("testing.docx"));- assert!(FileType::is_suffix_match("testing.pdf"));- assert!(FileType::is_suffix_match("testing.md"));- assert!(FileType::is_suffix_match("testing.canvas"));- assert!(FileType::is_suffix_match("testing.coffee"));- assert!(FileType::is_suffix_match("testing.cson"));- assert!(FileType::is_suffix_match("testing.iced"));- assert!(FileType::is_suffix_match("testing.c"));- assert!(FileType::is_suffix_match("testing.i"));- assert!(FileType::is_suffix_match("testing.cpp"));- assert!(FileType::is_suffix_match("testing.c++m"));- assert!(FileType::is_suffix_match("testing.cppm"));- assert!(FileType::is_suffix_match("testing.cc"));- assert!(FileType::is_suffix_match("testing.ccm"));- assert!(FileType::is_suffix_match("testing.cxx"));- assert!(FileType::is_suffix_match("testing.cxxm"));- assert!(FileType::is_suffix_match("testing.zip"));- assert!(FileType::is_suffix_match("testing.js.map"));- assert!(FileType::is_suffix_match("testing.docx.zip"));- assert!(FileType::is_suffix_match("testing.tar.gz"));- assert!(FileType::is_suffix_match(".pdf"));- }-- #[test]- fn test_is_suffix_match_false() {- assert!(!FileType::is_suffix_match("testing.cp"));- assert!(!FileType::is_suffix_match("testing.cpm"));- assert!(!FileType::is_suffix_match("testing."));- assert!(!FileType::is_suffix_match(".testing"));- }-- #[test]- fn test_split_suffix_match() {- assert_eq!(FileType::split_suffix_match("testing"), None);- assert_eq!(FileType::split_suffix_match("testing."), None);- assert_eq!(FileType::split_suffix_match(".testing"), None);- assert_eq!(- FileType::split_suffix_match("testing.docx"),- Some(("testing", "docx"))- );- assert_eq!(- FileType::split_suffix_match("testing.pdf"),- Some(("testing", "pdf"))- );- assert_eq!(- FileType::split_suffix_match("testing.md"),- Some(("testing", "md"))- );- assert_eq!(- FileType::split_suffix_match("testing.canvas"),- Some(("testing", "canvas"))- );- assert_eq!(- FileType::split_suffix_match("testing.coffee"),- Some(("testing", "coffee"))- );- assert_eq!(- FileType::split_suffix_match("testing.cson"),- Some(("testing", "cson"))- );- assert_eq!(- FileType::split_suffix_match("testing.iced"),- Some(("testing", "iced"))- );- assert_eq!(- FileType::split_suffix_match("testing.c"),- Some(("testing", "c"))- );- assert_eq!(- FileType::split_suffix_match("testing.i"),- Some(("testing", "i"))- );- assert_eq!(- FileType::split_suffix_match("testing.1.5.0.tar.gz"),- Some(("testing.1.5.0", "tar.gz"))- );- }-}diff --git a/rust/cloud-storage/model/src/document/file_type/tests.rs b/rust/cloud-storage/model/src/document/file_type/tests.rsnew file mode 100644index 0000000000..e5f532262c--- /dev/null+++ b/rust/cloud-storage/model/src/document/file_type/tests.rs@@ -0,0 +1,133 @@+use super::*;++#[test]+fn test_clean_document_name() {+ assert_eq!(+ FileType::clean_document_name("report.docx").as_deref(),+ Some("report")+ );+ assert_eq!(+ FileType::clean_document_name("proposal.pdf").as_deref(),+ Some("proposal")+ );+ assert_eq!(+ FileType::clean_document_name("testing.md").as_deref(),+ Some("testing")+ );+ assert_eq!(+ FileType::clean_document_name("testing.py").as_deref(),+ Some("testing")+ );+ assert_eq!(+ FileType::clean_document_name("testing.html").as_deref(),+ Some("testing")+ );+ assert_eq!(+ FileType::clean_document_name("testing.txt").as_deref(),+ Some("testing")+ );+ assert_eq!(+ FileType::clean_document_name("notes.backup.pdf").as_deref(),+ Some("notes.backup")+ );++ assert_eq!(+ FileType::clean_document_name("testing.random").as_deref(),+ None+ );+ assert_eq!(FileType::clean_document_name("note."), None);+ assert_eq!(FileType::clean_document_name(""), None);+ assert_eq!(FileType::clean_document_name("testing"), None);+ assert_eq!(+ FileType::clean_document_name("testing.zip").as_deref(),+ Some("testing")+ );+ assert_eq!(+ FileType::clean_document_name("testing.tar.gz").as_deref(),+ Some("testing")+ );+ assert_eq!(+ FileType::clean_document_name("testing.js.map").as_deref(),+ Some("testing")+ );+}++#[test]+fn test_is_suffix_match() {+ assert!(FileType::is_suffix_match("testing.docx"));+ assert!(FileType::is_suffix_match("testing.pdf"));+ assert!(FileType::is_suffix_match("testing.md"));+ assert!(FileType::is_suffix_match("testing.canvas"));+ assert!(FileType::is_suffix_match("testing.coffee"));+ assert!(FileType::is_suffix_match("testing.cson"));+ assert!(FileType::is_suffix_match("testing.iced"));+ assert!(FileType::is_suffix_match("testing.c"));+ assert!(FileType::is_suffix_match("testing.i"));+ assert!(FileType::is_suffix_match("testing.cpp"));+ assert!(FileType::is_suffix_match("testing.c++m"));+ assert!(FileType::is_suffix_match("testing.cppm"));+ assert!(FileType::is_suffix_match("testing.cc"));+ assert!(FileType::is_suffix_match("testing.ccm"));+ assert!(FileType::is_suffix_match("testing.cxx"));+ assert!(FileType::is_suffix_match("testing.cxxm"));+ assert!(FileType::is_suffix_match("testing.zip"));+ assert!(FileType::is_suffix_match("testing.js.map"));+ assert!(FileType::is_suffix_match("testing.docx.zip"));+ assert!(FileType::is_suffix_match("testing.tar.gz"));+ assert!(FileType::is_suffix_match(".pdf"));+}++#[test]+fn test_is_suffix_match_false() {+ assert!(!FileType::is_suffix_match("testing.cp"));+ assert!(!FileType::is_suffix_match("testing.cpm"));+ assert!(!FileType::is_suffix_match("testing."));+ assert!(!FileType::is_suffix_match(".testing"));+}++#[test]+fn test_split_suffix_match() {+ assert_eq!(FileType::split_suffix_match("testing"), None);+ assert_eq!(FileType::split_suffix_match("testing."), None);+ assert_eq!(FileType::split_suffix_match(".testing"), None);+ assert_eq!(+ FileType::split_suffix_match("testing.docx"),+ Some(("testing", "docx"))+ );+ assert_eq!(+ FileType::split_suffix_match("testing.pdf"),+ Some(("testing", "pdf"))+ );+ assert_eq!(+ FileType::split_suffix_match("testing.md"),+ Some(("testing", "md"))+ );+ assert_eq!(+ FileType::split_suffix_match("testing.canvas"),+ Some(("testing", "canvas"))+ );+ assert_eq!(+ FileType::split_suffix_match("testing.coffee"),+ Some(("testing", "coffee"))+ );+ assert_eq!(+ FileType::split_suffix_match("testing.cson"),+ Some(("testing", "cson"))+ );+ assert_eq!(+ FileType::split_suffix_match("testing.iced"),+ Some(("testing", "iced"))+ );+ assert_eq!(+ FileType::split_suffix_match("testing.c"),+ Some(("testing", "c"))+ );+ assert_eq!(+ FileType::split_suffix_match("testing.i"),+ Some(("testing", "i"))+ );+ assert_eq!(+ FileType::split_suffix_match("testing.1.5.0.tar.gz"),+ Some(("testing.1.5.0", "tar.gz"))+ );+}diff --git a/rust/cloud-storage/model/src/document/response/location.rs b/rust/cloud-storage/model/src/document/response/location.rsindex 334ebdc332..e187374ac7 100644--- a/rust/cloud-storage/model/src/document/response/location.rs+++ b/rust/cloud-storage/model/src/document/response/location.rs@@ -2,6 +2,7 @@ use crate::document::{DocumentBasic, FileType};use crate::response::PresignedUrl;use crate::sync_service::DocumentMetadata as SyncServiceMetadata;use anyhow::Result;+use std::str::FromStr;use utoipa::ToSchema;#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema, Clone)]@@ -46,7 +47,8 @@ impl LocationResponseV3 {self.metadata().file_type.as_deref()- .and_then(FileType::from_str)+ .map(FileType::from_str)+ .and_then(Result::ok).ok_or_else(|| anyhow::anyhow!("unxpected file type {:?}", self.file_type()))}}diff --git a/rust/cloud-storage/model_file_type/Cargo.toml b/rust/cloud-storage/model_file_type/Cargo.tomlnew file mode 100644index 0000000000..129adf9eb5--- /dev/null+++ b/rust/cloud-storage/model_file_type/Cargo.toml@@ -0,0 +1,13 @@+[package]+edition = "2024"+name = "model_file_type"+publish = false+version = "0.1.0"++[features]+utoipa = ["dep:utoipa"]++[dependencies]+serde = { workspace = true }+thiserror = { workspace = true }+utoipa = { workspace = true, optional = true }diff --git a/rust/cloud-storage/model_file_type/src/lib.rs b/rust/cloud-storage/model_file_type/src/lib.rsnew file mode 100644index 0000000000..790e0e7e9a--- /dev/null+++ b/rust/cloud-storage/model_file_type/src/lib.rs@@ -0,0 +1,681 @@+#![deny(missing_docs)]++//! This crate is used to define an enumeration of all the [FileType] and [ContentType] that are compatible with Macro++use serde::{Deserialize, Serialize};+use std::borrow::Cow;+use std::marker::PhantomData;+use std::str::FromStr;+use thiserror::Error;++/// Indicates we eoncountered an unknown string value while attempting to construct type T+#[derive(Debug, Error)]+#[error("{0} is not a supported {t}", t = std::any::type_name::<T>())]+pub struct ValueError<T>(String, PhantomData<T>);++struct Lowercase<'a>(Cow<'a, str>);++impl<'a> Lowercase<'a> {+ fn new(s: &'a str) -> Self {+ Self(match s.chars().any(|c| c.is_ascii_uppercase()) {+ true => {+ let mut string = s.to_string();+ string.make_ascii_lowercase();+ Cow::Owned(string)+ }+ false => Cow::Borrowed(s),+ })+ }+}++macro_rules! generate_file_types {+ ($(($variant:ident, $str_name:expr, $mime_type:expr, $app_path:expr)),* $(,)?) => {+ /// Generates a FileType enum and associated ContentType enum with their implementations.+ ///+ /// This macro takes a list of tuples in the format:+ /// (Variant, "extension", "mime_type", CONTENT_TYPE_VARIANT)+ ///+ /// For each tuple it generates:+ /// - A variant in the FileType enum+ /// - A variant in the ContentType enum+ /// - Implementations for:+ /// - FileType::to_str() - Converts FileType to extension string+ /// - FileType::from_str() - Converts extension string to FileType+ /// - From<FileType> for ContentType - Maps FileType to ContentType+ /// - ContentType::mime_type() - Gets MIME type for ContentType+ ///+ #[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Copy, Clone)]+ #[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]+ #[serde(rename_all = "lowercase")]+ pub enum FileType {+ $(+ #[expect(missing_docs)]+ $variant,+ )*+ }++ impl FromStr for FileType {+ type Err = ValueError<Self>;+ fn from_str(file_type: &str) -> Result<Self, Self::Err> {++ let lowercase = Lowercase::new(file_type.trim_start_matches('.')); // remove leading dot++ match lowercase.0.as_ref() {+ $(+ $str_name => Ok(FileType::$variant),+ )*+ _ => {+ Err(ValueError(lowercase.0.into_owned(), PhantomData))+ }+ }+ }+ }++ impl FileType {+ /// return the file extension as a string slice+ pub fn as_str(&self) -> &'static str {+ match self {+ $(+ FileType::$variant => $str_name,+ )*+ }+ }++ /// return the mime type as a string slice+ pub fn mime_type(&self) -> &'static str {+ match self {+ $(+ FileType::$variant => $mime_type,+ )*+ }+ }++ /// return the app path for the file type+ pub fn macro_app_path(&self) -> String {+ match self {+ $(+ FileType::$variant => $app_path.to_string(),+ )*+ }+ }++ /// return all possible values as a slice+ pub fn all() -> &'static [FileType] {+ &[+ $(+ FileType::$variant,+ )*+ ]+ }+ }++ impl std::fmt::Display for FileType {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ $(+ FileType::$variant => write!(f, "{}", $str_name),+ )*+ }+ }+ }+++ /// the possible content types that are associated with macro+ #[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone)]+ pub enum ContentType {+ $(+ #[expect(missing_docs)]+ $variant,+ )*+ /// the default content type of application/octet-stream+ Default,+ }++ impl From<FileType> for ContentType {+ fn from(file_type: FileType) -> Self {+ match file_type {+ $(+ FileType::$variant => ContentType::$variant,+ )*+ }+ }+ }++ impl From<Option<FileType>> for ContentType {+ fn from(file_type: Option<FileType>) -> Self {+ match file_type {+ Some(file_type) => file_type.into(),+ None => ContentType::Default,+ }+ }+ }++ impl FromStr for ContentType {+ type Err = ValueError<Self>;+ fn from_str(mime_type: &str) -> Result<Self, Self::Err> {+ let cleaned = mime_type.to_ascii_lowercase();++ // there can be multiple variants for the same mime type+ // but it does not matter for the purposes of this function+ #[expect(unreachable_patterns)]+ match cleaned.as_str() {+ $(+ $mime_type => Ok(ContentType::$variant),+ )*+ _ => {+ Err(ValueError(cleaned, PhantomData))+ }+ }+ }++ }++ impl ContentType {+ /// return the mime type of self as a string slice+ pub fn mime_type(&self) -> &'static str {+ match self {+ $(+ ContentType::$variant => $mime_type,+ )*+ ContentType::Default => "application/octet-stream",+ }+ }+ }+ };+}++generate_file_types!(+ (+ Docx,+ "docx",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ "write"+ ),+ (Pdf, "pdf", "application/pdf", "pdf"),+ (Md, "md", "text/markdown", "md"),+ (Canvas, "canvas", "application/x-macro-canvas", "canvas"),+ // Code block: generated from VS Code extensions {+ (Coffee, "coffee", "text/plain", "code"),+ (Cson, "cson", "text/plain", "code"),+ (Iced, "iced", "text/plain", "code"),+ (C, "c", "text/plain", "code"),+ (I, "i", "text/plain", "code"),+ (Cpp, "cpp", "text/plain", "code"),+ (Cppm, "cppm", "text/plain", "code"),+ (Cc, "cc", "text/plain", "code"),+ (Ccm, "ccm", "text/plain", "code"),+ (Cxx, "cxx", "text/plain", "code"),+ (Cxxm, "cxxm", "text/plain", "code"),+ (CPlusPlus, "c++", "text/plain", "code"),+ (CPlusPlusm, "c++m", "text/plain", "code"),+ (Hpp, "hpp", "text/plain", "code"),+ (Hh, "hh", "text/plain", "code"),+ (Hxx, "hxx", "text/plain", "code"),+ (HPlusPlus, "h++", "text/plain", "code"),+ (H, "h", "text/plain", "code"),+ (Ii, "ii", "text/plain", "code"),+ (Ino, "ino", "text/plain", "code"),+ (Inl, "inl", "text/plain", "code"),+ (Ipp, "ipp", "text/plain", "code"),+ (Ixx, "ixx", "text/plain", "code"),+ (Tpp, "tpp", "text/plain", "code"),+ (Txx, "txx", "text/plain", "code"),+ (HppIn, "hpp.in", "text/plain", "code"),+ (HIn, "h.in", "text/plain", "code"),+ (Cu, "cu", "text/plain", "code"),+ (Cuh, "cuh", "text/plain", "code"),+ (Cs, "cs", "text/plain", "code"),+ (Csx, "csx", "text/plain", "code"),+ (Cake, "cake", "text/plain", "code"),+ (Css, "css", "text/plain", "code"),+ (Dart, "dart", "text/plain", "code"),+ (Diff, "diff", "text/plain", "code"),+ (Patch, "patch", "text/plain", "code"),+ (Rej, "rej", "text/plain", "code"),+ (Dockerfile, "dockerfile", "text/plain", "code"),+ (Containerfile, "containerfile", "text/plain", "code"),+ (Go, "go", "text/plain", "code"),+ (Handlebars, "handlebars", "text/plain", "code"),+ (Hbs, "hbs", "text/plain", "code"),+ (Hjs, "hjs", "text/plain", "code"),+ (Hlsl, "hlsl", "text/plain", "code"),+ (Hlsli, "hlsli", "text/plain", "code"),+ (Fx, "fx", "text/plain", "code"),+ (Fxh, "fxh", "text/plain", "code"),+ (Vsh, "vsh", "text/plain", "code"),+ (Psh, "psh", "text/plain", "code"),+ (Cginc, "cginc", "text/plain", "code"),+ (Compute, "compute", "text/plain", "code"),+ (Html, "html", "text/plain", "code"),+ (Htm, "htm", "text/plain", "code"),+ (Shtml, "shtml", "text/plain", "code"),+ (Xhtml, "xhtml", "text/plain", "code"),+ (Xht, "xht", "text/plain", "code"),+ (Mdoc, "mdoc", "text/plain", "code"),+ (Jsp, "jsp", "text/plain", "code"),+ (Asp, "asp", "text/plain", "code"),+ (Aspx, "aspx", "text/plain", "code"),+ (Jshtm, "jshtm", "text/plain", "code"),+ (Volt, "volt", "text/plain", "code"),+ (Ejs, "ejs", "text/plain", "code"),+ (Rhtml, "rhtml", "text/plain", "code"),+ (Ini, "ini", "text/plain", "code"),+ (Conf, "conf", "text/plain", "code"),+ (Properties, "properties", "text/plain", "code"),+ (Cfg, "cfg", "text/plain", "code"),+ (Directory, "directory", "text/plain", "code"),+ (Gitattributes, "gitattributes", "text/plain", "code"),+ (Gitconfig, "gitconfig", "text/plain", "code"),+ (Gitmodules, "gitmodules", "text/plain", "code"),+ (Editorconfig, "editorconfig", "text/plain", "code"),+ (Repo, "repo", "text/plain", "code"),+ (Java, "java", "text/plain", "code"),+ (Jav, "jav", "text/plain", "code"),+ (Jsx, "jsx", "text/plain", "code"),+ (Js, "js", "text/plain", "code"),+ (Es6, "es6", "text/plain", "code"),+ (Mjs, "mjs", "text/plain", "code"),+ (Cjs, "cjs", "text/plain", "code"),+ (Pac, "pac", "text/plain", "code"),+ (Json, "json", "text/plain", "code"),+ (Bowerrc, "bowerrc", "text/plain", "code"),+ (Jscsrc, "jscsrc", "text/plain", "code"),+ (Webmanifest, "webmanifest", "text/plain", "code"),+ (JsMap, "js.map", "text/plain", "code"),+ (CssMap, "css.map", "text/plain", "code"),+ (TsMap, "ts.map", "text/plain", "code"),+ (Har, "har", "text/plain", "code"),+ (Jslintrc, "jslintrc", "text/plain", "code"),+ (Jsonld, "jsonld", "text/plain", "code"),+ (Geojson, "geojson", "text/plain", "code"),+ (Ipynb, "ipynb", "text/plain", "code"),+ (Vuerc, "vuerc", "text/plain", "code"),+ (Jsonc, "jsonc", "text/plain", "code"),+ (Eslintrc, "eslintrc", "text/plain", "code"),+ (EslintrcJson, "eslintrc.json", "text/plain", "code"),+ (Jsfmtrc, "jsfmtrc", "text/plain", "code"),+ (Jshintrc, "jshintrc", "text/plain", "code"),+ (Swcrc, "swcrc", "text/plain", "code"),+ (Hintrc, "hintrc", "text/plain", "code"),+ (Babelrc, "babelrc", "text/plain", "code"),+ (Jsonl, "jsonl", "text/plain", "code"),+ (Ndjson, "ndjson", "text/plain", "code"),+ (CodeSnippets, "code-snippets", "text/plain", "code"),+ (Jl, "jl", "text/plain", "code"),+ (Jmd, "jmd", "text/plain", "code"),+ (Sty, "sty", "text/plain", "code"),+ (Cls, "cls", "text/plain", "code"),+ (Bbx, "bbx", "text/plain", "code"),+ (Cbx, "cbx", "text/plain", "code"),+ (Tex, "tex", "text/plain", "code"),+ (Ltx, "ltx", "text/plain", "code"),+ (Ctx, "ctx", "text/plain", "code"),+ (Bib, "bib", "text/plain", "code"),+ (Less, "less", "text/plain", "code"),+ (Log, "log", "text/plain", "code"),+ (Lua, "lua", "text/plain", "code"),+ (Mak, "mak", "text/plain", "code"),+ (Mk, "mk", "text/plain", "code"),+ (Mkd, "mkd", "text/plain", "code"),+ (Mdwn, "mdwn", "text/plain", "code"),+ (Mdown, "mdown", "text/plain", "code"),+ (Markdown, "markdown", "text/plain", "code"),+ (Markdn, "markdn", "text/plain", "code"),+ (Mdtxt, "mdtxt", "text/plain", "code"),+ (Mdtext, "mdtext", "text/plain", "code"),+ (Workbook, "workbook", "text/plain", "code"),+ (M, "m", "text/plain", "code"),+ (Mm, "mm", "text/plain", "code"),+ (Pl, "pl", "text/plain", "code"),+ (Pm, "pm", "text/plain", "code"),+ (Pod, "pod", "text/plain", "code"),+ (T, "t", "text/plain", "code"),+ (Psgi, "psgi", "text/plain", "code"),+ (Raku, "raku", "text/plain", "code"),+ (Rakumod, "rakumod", "text/plain", "code"),+ (Rakutest, "rakutest", "text/plain", "code"),+ (Rakudoc, "rakudoc", "text/plain", "code"),+ (Nqp, "nqp", "text/plain", "code"),+ (P6, "p6", "text/plain", "code"),+ (Pl6, "pl6", "text/plain", "code"),+ (Pm6, "pm6", "text/plain", "code"),+ (Php, "php", "text/plain", "code"),+ (Php4, "php4", "text/plain", "code"),+ (Php5, "php5", "text/plain", "code"),+ (Phtml, "phtml", "text/plain", "code"),+ (Ctp, "ctp", "text/plain", "code"),+ (Ps1, "ps1", "text/plain", "code"),+ (Psm1, "psm1", "text/plain", "code"),+ (Psd1, "psd1", "text/plain", "code"),+ (Pssc, "pssc", "text/plain", "code"),+ (Psrc, "psrc", "text/plain", "code"),+ (Py, "py", "text/plain", "code"),+ (Rpy, "rpy", "text/plain", "code"),+ (Pyw, "pyw", "text/plain", "code"),+ (Cpy, "cpy", "text/plain", "code"),+ (Gyp, "gyp", "text/plain", "code"),+ (Gypi, "gypi", "text/plain", "code"),+ (Pyi, "pyi", "text/plain", "code"),+ (Ipy, "ipy", "text/plain", "code"),+ (Pyt, "pyt", "text/plain", "code"),+ (R, "r", "text/plain", "code"),+ (Rhistory, "rhistory", "text/plain", "code"),+ (Rprofile, "rprofile", "text/plain", "code"),+ (Rt, "rt", "text/plain", "code"),+ (Cshtml, "cshtml", "text/plain", "code"),+ (Razor, "razor", "text/plain", "code"),+ (Rb, "rb", "text/plain", "code"),+ (Rbx, "rbx", "text/plain", "code"),+ (Rjs, "rjs", "text/plain", "code"),+ (Gemspec, "gemspec", "text/plain", "code"),+ (Rake, "rake", "text/plain", "code"),+ (Ru, "ru", "text/plain", "code"),+ (Erb, "erb", "text/plain", "code"),+ (Podspec, "podspec", "text/plain", "code"),+ (Rbi, "rbi", "text/plain", "code"),+ (Rs, "rs", "text/plain", "code"),+ (Scss, "scss", "text/plain", "code"),+ (Shader, "shader", "text/plain", "code"),+ (Sh, "sh", "text/plain", "code"),+ (Bash, "bash", "text/plain", "code"),+ (Bashrc, "bashrc", "text/plain", "code"),+ (BashAliases, "bash_aliases", "text/plain", "code"),+ (BashProfile, "bash_profile", "text/plain", "code"),+ (BashLogin, "bash_login", "text/plain", "code"),+ (Ebuild, "ebuild", "text/plain", "code"),+ (Eclass, "eclass", "text/plain", "code"),+ (Profile, "profile", "text/plain", "code"),+ (BashLogout, "bash_logout", "text/plain", "code"),+ (Xprofile, "xprofile", "text/plain", "code"),+ (Xsession, "xsession", "text/plain", "code"),+ (Xsessionrc, "xsessionrc", "text/plain", "code"),+ (Zsh, "zsh", "text/plain", "code"),+ (Zshrc, "zshrc", "text/plain", "code"),+ (Zprofile, "zprofile", "text/plain", "code"),+ (Zlogin, "zlogin", "text/plain", "code"),+ (Zlogout, "zlogout", "text/plain", "code"),+ (Zshenv, "zshenv", "text/plain", "code"),+ (ZshTheme, "zsh-theme", "text/plain", "code"),+ (Fish, "fish", "text/plain", "code"),+ (Ksh, "ksh", "text/plain", "code"),+ (Csh, "csh", "text/plain", "code"),+ (Cshrc, "cshrc", "text/plain", "code"),+ (Tcshrc, "tcshrc", "text/plain", "code"),+ (Yashrc, "yashrc", "text/plain", "code"),+ (YashProfile, "yash_profile", "text/plain", "code"),+ (Sql, "sql", "text/plain", "code"),+ (Dsql, "dsql", "text/plain", "code"),+ (Swift, "swift", "text/plain", "code"),+ (Ts, "ts", "text/plain", "code"),+ (Cts, "cts", "text/plain", "code"),+ (Mts, "mts", "text/plain", "code"),+ (Tsx, "tsx", "text/plain", "code"),+ (Tsbuildinfo, "tsbuildinfo", "text/plain", "code"),+ (Xml, "xml", "text/plain", "code"),+ (Xsd, "xsd", "text/plain", "code"),+ (Ascx, "ascx", "text/plain", "code"),+ (Atom, "atom", "text/plain", "code"),+ (Axml, "axml", "text/plain", "code"),+ (Axaml, "axaml", "text/plain", "code"),+ (Bpmn, "bpmn", "text/plain", "code"),+ (Cpt, "cpt", "text/plain", "code"),+ (Csl, "csl", "text/plain", "code"),+ (Csproj, "csproj", "text/plain", "code"),+ (CsprojUser, "csproj.user", "text/plain", "code"),+ (Dita, "dita", "text/plain", "code"),+ (Ditamap, "ditamap", "text/plain", "code"),+ (Dtd, "dtd", "text/plain", "code"),+ (Ent, "ent", "text/plain", "code"),+ (Mod, "mod", "text/plain", "code"),+ (Dtml, "dtml", "text/plain", "code"),+ (Fsproj, "fsproj", "text/plain", "code"),+ (Fxml, "fxml", "text/plain", "code"),+ (Iml, "iml", "text/plain", "code"),+ (Isml, "isml", "text/plain", "code"),+ (Jmx, "jmx", "text/plain", "code"),+ (Launch, "launch", "text/plain", "code"),+ (Menu, "menu", "text/plain", "code"),+ (Mxml, "mxml", "text/plain", "code"),+ (Nuspec, "nuspec", "text/plain", "code"),+ (Opml, "opml", "text/plain", "code"),+ (Owl, "owl", "text/plain", "code"),+ (Proj, "proj", "text/plain", "code"),+ (Props, "props", "text/plain", "code"),+ (Pt, "pt", "text/plain", "code"),+ (Publishsettings, "publishsettings", "text/plain", "code"),+ (Pubxml, "pubxml", "text/plain", "code"),+ (PubxmlUser, "pubxml.user", "text/plain", "code"),+ (Rbxlx, "rbxlx", "text/plain", "code"),+ (Rbxmx, "rbxmx", "text/plain", "code"),+ (Rdf, "rdf", "text/plain", "code"),+ (Rng, "rng", "text/plain", "code"),+ (Rss, "rss", "text/plain", "code"),+ (Shproj, "shproj", "text/plain", "code"),+ (Storyboard, "storyboard", "text/plain", "code"),+ (Targets, "targets", "text/plain", "code"),+ (Tld, "tld", "text/plain", "code"),+ (Tmx, "tmx", "text/plain", "code"),+ (Vbproj, "vbproj", "text/plain", "code"),+ (VbprojUser, "vbproj.user", "text/plain", "code"),+ (Vcxproj, "vcxproj", "text/plain", "code"),+ (VcxprojFilters, "vcxproj.filters", "text/plain", "code"),+ (Wsdl, "wsdl", "text/plain", "code"),+ (Wxi, "wxi", "text/plain", "code"),+ (Wxl, "wxl", "text/plain", "code"),+ (Wxs, "wxs", "text/plain", "code"),+ (Xaml, "xaml", "text/plain", "code"),+ (Xbl, "xbl", "text/plain", "code"),+ (Xib, "xib", "text/plain", "code"),+ (Xlf, "xlf", "text/plain", "code"),+ (Xliff, "xliff", "text/plain", "code"),+ (Xpdl, "xpdl", "text/plain", "code"),+ (Xul, "xul", "text/plain", "code"),+ (Xoml, "xoml", "text/plain", "code"),+ (Xsl, "xsl", "text/plain", "code"),+ (Xslt, "xslt", "text/plain", "code"),+ (Yaml, "yaml", "text/plain", "code"),+ (Yml, "yml", "text/plain", "code"),+ (Eyaml, "eyaml", "text/plain", "code"),+ (Eyml, "eyml", "text/plain", "code"),+ (Cff, "cff", "text/plain", "code"),+ (YamlTmlanguage, "yaml-tmlanguage", "text/plain", "code"),+ (+ YamlTmpreferences,+ "yaml-tmpreferences",+ "text/plain",+ "code"+ ),+ (YamlTmtheme, "yaml-tmtheme", "text/plain", "code"),+ (Winget, "winget", "text/plain", "code"),+ (Txt, "txt", "text/plain", "code"),+ (Csv, "csv", "text/plain", "code"),+ (Tsv, "tsv", "text/plain", "code"),+ // } Code block+ // images+ (Jpeg, "jpeg", "image/jpeg", "image"),+ (Jpg, "jpg", "image/jpeg", "image"),+ (Png, "png", "image/png", "image"),+ (Gif, "gif", "image/gif", "image"),+ (Svg, "svg", "image/svg+xml", "image"),+ (Webp, "webp", "image/webp", "image"),+ (Avif, "avif", "image/avif", "image"),+ (Bmp, "bmp", "image/bmp", "image"),+ (Ico, "ico", "image/x-icon", "image"),+ (Tiff, "tiff", "image/tiff", "image"),+ (Tif, "tif", "image/tiff", "image"),+ (Heic, "heic", "image/heic", "image"),+ (Heif, "heif", "image/heif", "image"),+ // NOT SUPPORTED BLOCKS++ // Archives and compressed files+ (Tar, "tar", "application/x-tar", "archive"),+ (TarGz, "tar.gz", "application/gzip", "archive"),+ (Tgz, "tgz", "application/gzip", "archive"),+ (Gz, "gz", "application/gzip", "archive"),+ (Bz2, "bz2", "application/x-bzip2", "archive"),+ (TarBz2, "tar.bz2", "application/x-bzip2", "archive"),+ (Tbz2, "tbz2", "application/x-bzip2", "archive"),+ (Z, "z", "application/x-compress", "archive"),+ (TarZ, "tar.z", "application/x-compress", "archive"),+ (Lz, "lz", "application/x-lzip", "archive"),+ (TarLz, "tar.lz", "application/x-lzip", "archive"),+ (Xz, "xz", "application/x-xz", "archive"),+ (TarXz, "tar.xz", "application/x-xz", "archive"),+ (Txz, "txz", "application/x-xz", "archive"),+ (Lzma, "lzma", "application/x-lzma", "archive"),+ (TarLzma, "tar.lzma", "application/x-lzma", "archive"),+ (Rar, "rar", "application/vnd.rar", "archive"),+ (SevenZ, "7z", "application/x-7z-compressed", "archive"),+ (Zst, "zst", "application/zstd", "archive"),+ (TarZst, "tar.zst", "application/zstd", "archive"),+ (Tzst, "tzst", "application/zstd", "archive"),+ (Zip, "zip", "application/zip", "archive"),+ // Executable files+ (Exe, "exe", "application/x-msdownload", "executable"),+ (Msi, "msi", "application/x-msi", "executable"),+ (Dll, "dll", "application/x-msdownload", "executable"),+ (Bat, "bat", "application/x-bat", "executable"),+ (Cmd, "cmd", "application/x-cmd", "executable"),+ (Com, "com", "application/x-msdownload", "executable"),+ (+ AppImage,+ "appimage",+ "application/x-executable",+ "executable"+ ),+ (App, "app", "application/x-executable", "executable"),+ (Bin, "bin", "application/octet-stream", "executable"),+ (+ Deb,+ "deb",+ "application/vnd.debian.binary-package",+ "executable"+ ),+ (Rpm, "rpm", "application/x-rpm", "executable"),+ (+ Apk,+ "apk",+ "application/vnd.android.package-archive",+ "executable"+ ),+ (Dmg, "dmg", "application/x-apple-diskimage", "executable"),+ (+ Pkg,+ "pkg",+ "application/vnd.apple.installer+xml",+ "executable"+ ),+ (Crx, "crx", "application/x-chrome-extension", "executable"),+ (Xpi, "xpi", "application/x-xpinstall", "executable"),+ // Audio files+ (Mp3, "mp3", "audio/mpeg", "audio"),+ (Wav, "wav", "audio/wav", "audio"),+ (Ogg, "ogg", "audio/ogg", "audio"),+ (Flac, "flac", "audio/flac", "audio"),+ (Aac, "aac", "audio/aac", "audio"),+ (M4a, "m4a", "audio/mp4", "audio"),+ (Wma, "wma", "audio/x-ms-wma", "audio"),+ (Mid, "mid", "audio/midi", "audio"),+ (Midi, "midi", "audio/midi", "audio"),+ // Video files+ (Mp4, "mp4", "video/mp4", "video"),+ (Mkv, "mkv", "video/x-matroska", "video"),+ (Webm, "webm", "video/webm", "video"),+ (Avi, "avi", "video/x-msvideo", "video"),+ (Mov, "mov", "video/quicktime", "video"),+ (Wmv, "wmv", "video/x-ms-wmv", "video"),+ (Mpg, "mpg", "video/mpeg", "video"),+ (Mpeg, "mpeg", "video/mpeg", "video"),+ (M4v, "m4v", "video/mp4", "video"),+ (Flv, "flv", "video/x-flv", "video"),+ (F4v, "f4v", "video/mp4", "video"),+ (ThreeGp, "3gp", "video/3gpp", "video"),+ // Font files+ (Ttf, "ttf", "font/ttf", "font"),+ (Otf, "otf", "font/otf", "font"),+ (Woff, "woff", "font/woff", "font"),+ (Woff2, "woff2", "font/woff2", "font"),+ (Eot, "eot", "application/vnd.ms-fontobject", "font"),+ // Document formats+ (Rtf, "rtf", "application/rtf", "document"),+ (+ Odt,+ "odt",+ "application/vnd.oasis.opendocument.text",+ "document"+ ),+ (+ Ods,+ "ods",+ "application/vnd.oasis.opendocument.spreadsheet",+ "document"+ ),+ (+ Odp,+ "odp",+ "application/vnd.oasis.opendocument.presentation",+ "document"+ ),+ (+ Odg,+ "odg",+ "application/vnd.oasis.opendocument.graphics",+ "document"+ ),+ (+ Odf,+ "odf",+ "application/vnd.oasis.opendocument.formula",+ "document"+ ),+ (Epub, "epub", "application/epub+zip", "document"),+ (Mobi, "mobi", "application/x-mobipocket-ebook", "document"),+ (Azw, "azw", "application/vnd.amazon.ebook", "document"),+ (Azw3, "azw3", "application/vnd.amazon.ebook", "document"),+ (Djvu, "djvu", "image/vnd.djvu", "document"),+ (Xls, "xls", "application/vnd.ms-excel", "document"),+ (Ppt, "ppt", "application/vnd.ms-powerpoint", "document"),+ (Pptx, "pptx", "application/xml", "document"),+ (Xlsx, "xlsx", "application/xml", "document"),+ // Database files+ (Db, "db", "application/octet-stream", "database"),+ (Sqlite, "sqlite", "application/vnd.sqlite3", "database"),+ (Sqlite3, "sqlite3", "application/vnd.sqlite3", "database"),+ (Mdb, "mdb", "application/vnd.ms-access", "database"),+ (Accdb, "accdb", "application/vnd.ms-access", "database"),+ (Dbf, "dbf", "application/x-dbf", "database"),+ // Data and config files+ (Plist, "plist", "application/xml", "data"),+ (Toml, "toml", "application/toml", "data"),+ (Env, "env", "text/plain", "data"),+ (Dot, "dot", "text/vnd.graphviz", "data"),+ (Gv, "gv", "text/vnd.graphviz", "data"),+ (Torrent, "torrent", "application/x-bittorrent", "data"),+ (Ics, "ics", "text/calendar", "data"),+ (Vcf, "vcf", "text/vcard", "data"),+ // Vector graphics+ (Ai, "ai", "application/postscript", "vector"),+ (Eps, "eps", "application/postscript", "vector"),+ (Ps, "ps", "application/postscript", "vector"),+ (Dxf, "dxf", "image/vnd.dxf", "vector"),+ (Dwg, "dwg", "image/vnd.dwg", "vector"),+ // 3D files+ (Stl, "stl", "model/stl", "3d"),+ (Obj, "obj", "model/obj", "3d"),+ (Fbx, "fbx", "application/octet-stream", "3d"),+ (Blend, "blend", "application/x-blender", "3d"),+ (Dae, "dae", "model/vnd.collada+xml", "3d"),+ (ThreeDs, "3ds", "application/x-3ds", "3d"),+ (Gltf, "gltf", "model/gltf+json", "3d"),+ (Glb, "glb", "model/gltf-binary", "3d"),+ // Virtual machine and container files+ (Vhd, "vhd", "application/x-virtualbox-vhd", "vm"),+ (Vhdx, "vhdx", "application/x-virtualbox-vhdx", "vm"),+ (Vmdk, "vmdk", "application/x-vmdk", "vm"),+ (Ova, "ova", "application/x-virtualbox-ova", "vm"),+ (Ovf, "ovf", "application/x-virtualbox-ovf", "vm"),+ (Iso, "iso", "application/x-iso9660-image", "vm"),+ (Img, "img", "application/octet-stream", "vm"),+ // Miscellaneous+ (Swf, "swf", "application/x-shockwave-flash", "media"),+);diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rsindex 319522e691..6702712b25 100644--- a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs+++ b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs@@ -1,7 +1,7 @@use crate::config::APPLE_BUNDLE_ID;use anyhow::Context;use aws_sdk_sns::types::MessageAttributeValue;-use model::document::FileType;+use model::document::{FileType, FileTypeExt};use model_notifications::NotificationWithRecipient;use model_notifications::{APNSPushNotification, ChannelInviteMetadata, ChannelMentionMetadata,@@ -9,6 +9,7 @@ use model_notifications::{NotificationEventType, PushNotificationData,};use models_comms::ChannelType;+use std::str::FromStr;use std::{collections::HashMap,hash::{DefaultHasher, Hash, Hasher},@@ -236,10 +237,7 @@ pub fn generate_push_notification("{} mentioned you in {}.{}",email, metadata.document_name, file_type);- let file_type: FileType = file_type- .as_str()- .try_into()- .context("file type is not a valid file type")?;+ let file_type = FileType::from_str(file_type.as_str())?;let block_route = if file_type.is_image() {"image"diff --git a/rust/cloud-storage/scribe/src/document/fetcher.rs b/rust/cloud-storage/scribe/src/document/fetcher.rsindex da776c8cc3..95e728d4b3 100644--- a/rust/cloud-storage/scribe/src/document/fetcher.rs+++ b/rust/cloud-storage/scribe/src/document/fetcher.rs@@ -2,6 +2,7 @@ use crate::document::types::{Data, DocumentContent};use anyhow::{Context, Error};use document_storage_service_client::DocumentStorageServiceClient;use lexical_client::LexicalClient;+use model::document::FileTypeExt;use model::document::{DocumentBasic, FileType, response::LocationResponseV3};use std::fmt::Debug;use std::sync::Arc;diff --git a/rust/cloud-storage/scribe/src/document/types.rs b/rust/cloud-storage/scribe/src/document/types.rsindex 60b71cac73..30faf9a98c 100644--- a/rust/cloud-storage/scribe/src/document/types.rs+++ b/rust/cloud-storage/scribe/src/document/types.rs@@ -3,7 +3,7 @@ use base64::{Engine as _, engine::general_purpose};use bytes::Bytes;use lexical_client::types::CognitionResponseData;use model::document::response::LocationResponseV3;-use model::document::{DocumentBasic, FileType};+use model::document::{DocumentBasic, FileType, FileTypeExt};#[derive(Debug, Clone)]pub struct DocumentContent {diff --git a/rust/cloud-storage/scribe/src/static_file/fetcher.rs b/rust/cloud-storage/scribe/src/static_file/fetcher.rsindex ce5f411e3f..f221df4ae7 100644--- a/rust/cloud-storage/scribe/src/static_file/fetcher.rs+++ b/rust/cloud-storage/scribe/src/static_file/fetcher.rs@@ -1,9 +1,10 @@use crate::static_file::types::{StaticFileContent, StaticFileData};use anyhow::{Context, Error};-use model::document::ContentType;+use model::document::{ContentType, ContentTypeExt};use models_sfs::FileMetadata;use static_file_service_client::StaticFileServiceClient;use std::fmt::Debug;+use std::str::FromStr;use std::sync::Arc;pub type NoData = ();@@ -78,7 +79,7 @@ impl<T> StaticFileFetcher<Fetched<FileMetadata>, T> {pub fn content_type(&self) -> Result<ContentType, Error> {ContentType::from_str(&self.metadata.content_type)- .ok_or_else(|| anyhow::anyhow!("Invalid content type: {}", self.metadata.content_type))+ .map_err(|_| anyhow::anyhow!("Invalid content type: {}", self.metadata.content_type))}}diff --git a/rust/cloud-storage/scribe/src/static_file/types.rs b/rust/cloud-storage/scribe/src/static_file/types.rsindex 5cb88edd64..f4f53b11b2 100644--- a/rust/cloud-storage/scribe/src/static_file/types.rs+++ b/rust/cloud-storage/scribe/src/static_file/types.rs@@ -1,7 +1,7 @@use anyhow::Error;use base64::{Engine as _, engine::general_purpose};use bytes::Bytes;-use model::document::ContentType;+use model::document::{ContentType, ContentTypeExt};use models_sfs::FileMetadata;#[derive(Debug, Clone)]diff --git a/rust/cloud-storage/search_processing_service/src/process/document/mod.rs b/rust/cloud-storage/search_processing_service/src/process/document/mod.rsindex 8ab8a7de4b..e37c3268e7 100644--- a/rust/cloud-storage/search_processing_service/src/process/document/mod.rs+++ b/rust/cloud-storage/search_processing_service/src/process/document/mod.rs@@ -1,4 +1,5 @@use anyhow::Context;+use model::document::FileTypeExt;use opensearch_client::OpensearchClient;use sqs_client::search::document::{DocumentId, SearchExtractorMessage};diff --git a/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs b/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rsindex dec24f17df..b641d863af 100644--- a/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs+++ b/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs@@ -1,3 +1,5 @@+use std::str::FromStr;+use anyhow::Context;use chrono::Utc;use model::document::{@@ -107,12 +109,12 @@ pub async fn update_search_with_raw_document(return Ok(());}- let file_type: FileType = document_info- .file_type- .context("expected a file type")?- .as_str()- .try_into()- .context("unable to parse file type")?;+ let file_type = FileType::from_str(+ document_info+ .file_type+ .context("expected a file type")?+ .as_str(),+ )?;// This is a check to see if the document version id in the message matches the document versionif let Some(search_message_document_version_id) =@@ -236,12 +238,12 @@ fn generate_upserts() -> anyhow::Result<Vec<UpsertDocumentArgs>> {let result = markdown_result;let updated_at = EpochSeconds::new(Utc::now().timestamp())?;- let file_type: FileType = document_info- .file_type- .context("expected a file type")?- .as_str()- .try_into()- .context("unable to parse file type")?;+ let file_type = FileType::from_str(+ document_info+ .file_type+ .context("expected a file type")?+ .as_str(),+ )?;let document_name = document_info.document_name;let upserts = resultdiff --git a/rust/cloud-storage/search_upload_handler/Cargo.toml b/rust/cloud-storage/search_upload_handler/Cargo.tomlindex 2bc125d847..a047fabe98 100644--- a/rust/cloud-storage/search_upload_handler/Cargo.toml+++ b/rust/cloud-storage/search_upload_handler/Cargo.toml@@ -11,6 +11,7 @@ aws-sdk-sqs = { workspace = true }aws_lambda_events = { workspace = true, features = ["eventbridge"] }lambda_runtime = { workspace = true }macro_entrypoint = { path = "../macro_entrypoint" }+model_file_type = { path = "../model_file_type" }openssl = { workspace = true }sqs_client = { path = "../sqs_client", default-features = false, features = ["search",diff --git a/rust/cloud-storage/search_upload_handler/src/handler.rs b/rust/cloud-storage/search_upload_handler/src/handler.rsindex fb19acf568..8cb08d204f 100644--- a/rust/cloud-storage/search_upload_handler/src/handler.rs+++ b/rust/cloud-storage/search_upload_handler/src/handler.rs@@ -1,9 +1,12 @@+use std::str::FromStr;+use anyhow::Context;use aws_lambda_events::event::eventbridge::EventBridgeEvent;use lambda_runtime::{Error, LambdaEvent,tracing::{self},};+use model_file_type::FileType;use sqs_client::search::{SearchQueueMessage, document::SearchExtractorMessage};#[derive(Debug)]@@ -82,10 +85,7 @@ pub async fn handler(tracing::trace!(document_key_parts=?document_key_parts, "processing document key");- let file_type = document_key_parts- .file_type- .as_str()- .try_into()+ let file_type = FileType::from_str(document_key_parts.file_type.as_str()).context("unable to parse file type")?;let search_extractor_message = SearchExtractorMessage {diff --git a/rust/cloud-storage/static_file_service/src/api/file/put_presigned_url.rs b/rust/cloud-storage/static_file_service/src/api/file/put_presigned_url.rsindex bd2410f484..24b1e3ada5 100644--- a/rust/cloud-storage/static_file_service/src/api/file/put_presigned_url.rs+++ b/rust/cloud-storage/static_file_service/src/api/file/put_presigned_url.rs@@ -1,3 +1,5 @@+use std::str::FromStr;+use crate::api::context::AppState;use crate::model::api::*;use crate::service::dynamodb::model::MetadataObject;@@ -33,7 +35,8 @@ pub async fn put_presigned_url(.file_name.split(".").last()- .and_then(FileType::from_str)+ .map(FileType::from_str)+ .and_then(Result::ok).map(|file_type| file_type.mime_type().to_string()).ok_or_else(|| {(diff --git a/rust/cloud-storage/target/lambda/dataloss_prevention_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/dataloss_prevention_handler/bootstrap.zipindex 2a5962b5a0..30fbae421b 100644Binary files a/rust/cloud-storage/target/lambda/dataloss_prevention_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/dataloss_prevention_handler/bootstrap.zip differdiff --git a/rust/cloud-storage/target/lambda/delete_chat_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/delete_chat_handler/bootstrap.zipindex abb50dd983..ed23ad19d4 100644Binary files a/rust/cloud-storage/target/lambda/delete_chat_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/delete_chat_handler/bootstrap.zip differdiff --git a/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zip b/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zipindex 63c029c930..ca2151e7aa 100644Binary files a/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zip and b/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zip differdiff --git a/rust/cloud-storage/target/lambda/document_text_extractor/bootstrap.zip b/rust/cloud-storage/target/lambda/document_text_extractor/bootstrap.zipnew file mode 100644index 0000000000..7d202388faBinary files /dev/null and b/rust/cloud-storage/target/lambda/document_text_extractor/bootstrap.zip differdiff --git a/rust/cloud-storage/target/lambda/docx_unzip_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/docx_unzip_handler/bootstrap.zipnew file mode 100644index 0000000000..5c221698adBinary files /dev/null and b/rust/cloud-storage/target/lambda/docx_unzip_handler/bootstrap.zip differdiff --git a/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zipindex 577f65da9c..5816a9aecf 100644Binary files a/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip differdiff --git a/rust/cloud-storage/target/lambda/email_suppression_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_suppression_handler/bootstrap.zipindex 9a3dae66cd..1511265e0b 100644Binary files a/rust/cloud-storage/target/lambda/email_suppression_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/email_suppression_handler/bootstrap.zip differdiff --git a/rust/cloud-storage/target/lambda/organization_retention_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/organization_retention_handler/bootstrap.zipindex a3647e06de..c2e9b55b0d 100644Binary files a/rust/cloud-storage/target/lambda/organization_retention_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/organization_retention_handler/bootstrap.zip differdiff --git a/rust/cloud-storage/target/lambda/organization_retention_trigger/bootstrap.zip b/rust/cloud-storage/target/lambda/organization_retention_trigger/bootstrap.zipindex e160d58b0b..04e2d9c0d0 100644Binary files a/rust/cloud-storage/target/lambda/organization_retention_trigger/bootstrap.zip and b/rust/cloud-storage/target/lambda/organization_retention_trigger/bootstrap.zip differdiff --git a/rust/cloud-storage/target/lambda/search_upload_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/search_upload_handler/bootstrap.zipindex 3194e8a15e..23390e763a 100644Binary files a/rust/cloud-storage/target/lambda/search_upload_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/search_upload_handler/bootstrap.zip differdiff --git a/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zipindex 8ea92db63a..278db119fc 100644Binary files a/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip differdiff --git a/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip b/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zipindex 48a7b1f3e9..054628855a 100644Binary files a/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip and b/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip differdiff --git a/rust/cloud-storage/target/lambda/user_link_cleanup_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/user_link_cleanup_handler/bootstrap.zipindex feba864d72..5c8cf8846b 100644Binary files a/rust/cloud-storage/target/lambda/user_link_cleanup_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/user_link_cleanup_handler/bootstrap.zip differdiff --git a/rust/cloud-storage/target/lambda/worker_trigger/bootstrap.zip b/rust/cloud-storage/target/lambda/worker_trigger/bootstrap.zipnew file mode 100644index 0000000000..9c61fc33dfBinary files /dev/null and b/rust/cloud-storage/target/lambda/worker_trigger/bootstrap.zip differdiff --git a/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs b/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rsindex 627adde29d..165d73c563 100644--- a/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs+++ b/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs@@ -15,15 +15,15 @@ use lambda_runtime::{};use macro_entrypoint::MacroEntrypoint;use model::{- document::FileType,+ document::{FileType, FileTypeExt},folder::{FileSystemNodeWithIds, FolderItem, S3Destination, S3DestinationMap},};use model_entity::EntityType;use models_bulk_upload::{UploadDocumentStatus, UploadFolderStatus, UploadFolderStatusUpdate};use sha2::{Digest, Sha256};use sqs_client::upload_extractor::UploadExtractQueueMessage;-use std::fs;use std::path::Path;+use std::{fs, str::FromStr};use std::{path::PathBuf, sync::Arc};use tempfile::tempdir;use tokio::fs::File;@@ -525,7 +525,7 @@ async fn build_file_system(extract_dir: &Path) -> Result<Vec<FolderItem>, Error>let (file_name, file_type) = match FileType::split_suffix_match(full_name) {Some((file, extension)) => {- let file_type: Option<FileType> = extension.try_into().ok();+ let file_type = FileType::from_str(extension).ok();(file, file_type)}None => (full_name, None),