diff --git a/Cargo.lock b/Cargo.lock index dbd6c42..1a4471f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -384,6 +384,7 @@ dependencies = [ "lru 0.18.0", "mail-parser", "mail-send", + "memmap2", "murmur3", "num_cpus", "oauth2", @@ -437,6 +438,7 @@ dependencies = [ "bichon-smtp", "chrono", "email_address", + "futures", "governor", "http", "poem", diff --git a/crates/cli/src/mbox/mod.rs b/crates/cli/src/mbox/mod.rs index 4ed48c0..68396ff 100644 --- a/crates/cli/src/mbox/mod.rs +++ b/crates/cli/src/mbox/mod.rs @@ -21,7 +21,7 @@ use std::path::PathBuf; use crate::api::sender::send_batch_request; use crate::mbox::gmail::determine_folder; -use crate::mbox::reader::MboxFile; +use bichon_core::import::reader::MboxFile; use crate::BichonCliConfig; use bichon_core::base64_encode_url_safe; use bichon_core::envelope::meta::{parse_bichon_metadata, BichonMetadata}; @@ -37,7 +37,6 @@ const MAX_EMAIL_BYTES: usize = 100 * 1024 * 1024; const MAX_BUFFER_BYTES: usize = 200 * 1024 * 1024; pub mod gmail; -pub mod reader; pub async fn handle_mbox_single_file_import( config: &BichonCliConfig, diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 5e76afd..f90da35 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -72,3 +72,4 @@ scopeguard = "1.2.0" cron = "0.15" quick-xml = { version = "0.40.0", features = ["serialize"] } hickory-resolver = "0.26.0-alpha.1" +memmap2 = "0.9.10" diff --git a/crates/core/src/import/history.rs b/crates/core/src/import/history.rs new file mode 100644 index 0000000..a17d0b1 --- /dev/null +++ b/crates/core/src/import/history.rs @@ -0,0 +1,127 @@ +// +// Copyright (c) 2025-2026 rustmailer.com (https://rustmailer.com) +// +// This file is part of the Bichon Email Archiving Project + +use crate::database::MemDbModel; +use crate::import::{ImportProgress, ImportStatus}; +use serde::{Deserialize, Serialize}; + +/// Maximum number of import history entries to keep per user. +pub const MAX_HISTORY_PER_USER: usize = 5; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "web-api", derive(poem_openapi::Object))] +pub struct ImportHistory { + /// Composite key: "{user_id}:{import_id}" + pub id: String, + pub user_id: u64, + pub import_id: String, + pub account_id: u64, + pub folder: String, + pub format: String, + pub status: String, + pub total: usize, + pub success: usize, + pub duplicates: usize, + pub failed: usize, + pub failed_details: Vec, + /// Unix timestamp in milliseconds. + pub created_at: i64, +} + +impl MemDbModel for ImportHistory { + fn collection() -> &'static str { + "import_history" + } + fn key(&self) -> String { + self.id.clone() + } +} + +impl ImportHistory { + pub fn from_progress( + user_id: u64, + import_id: &str, + account_id: u64, + folder: &str, + progress: &ImportProgress, + ) -> Self { + Self { + id: format!("{}:{}", user_id, import_id), + user_id, + import_id: import_id.to_string(), + account_id, + folder: folder.to_string(), + format: progress.format.clone(), + status: match progress.status { + ImportStatus::Pending => "pending", + ImportStatus::Processing => "processing", + ImportStatus::Completed => "completed", + ImportStatus::Failed => "failed", + } + .to_string(), + total: progress.total, + success: progress.success, + duplicates: progress.duplicates, + failed: progress.failed, + failed_details: progress.failed_details.clone(), + created_at: crate::utc_now!(), + } + } +} + +/// Prune old entries for a user so only the latest `MAX_HISTORY_PER_USER` remain. +pub fn prune_user_history(user_id: u64) -> crate::error::BichonResult<()> { + use crate::database::manager::DB_MANAGER; + use crate::database::batch_delete_impl; + use crate::raise_error; + use crate::error::code::ErrorCode; + let db = DB_MANAGER.db(); + let coll = db.collection(ImportHistory::collection()); + let prefix = format!("{}:", user_id); + + let mut entries: Vec = coll + .scan_prefix(&prefix) + .map_err(|e| raise_error!(format!("{:#?}", e), ErrorCode::InternalError))?; + if entries.len() <= MAX_HISTORY_PER_USER { + return Ok(()); + } + + // Sort by created_at descending (newest first), keep the first N + entries.sort_by(|a, b| b.created_at.cmp(&a.created_at)); + let to_delete: Vec = entries + .iter() + .skip(MAX_HISTORY_PER_USER) + .map(|e| e.id.clone()) + .collect(); + + if !to_delete.is_empty() { + batch_delete_impl::(db, to_delete)?; + } + + Ok(()) +} + +/// Save an import history record and prune old entries for the user. +pub fn save_import_history( + user_id: u64, + account_id: u64, + folder: &str, + progress: &ImportProgress, +) { + use crate::database::manager::DB_MANAGER; + use crate::database::upsert_impl; + + let entry = ImportHistory::from_progress(user_id, &progress.import_id, account_id, folder, progress); + let db = DB_MANAGER.db(); + + if let Err(e) = upsert_impl::(db, entry) { + tracing::error!("Failed to save import history: {:?}", e); + return; + } + + if let Err(e) = prune_user_history(user_id) { + tracing::warn!("Failed to prune import history: {:?}", e); + } +} diff --git a/crates/core/src/import/mod.rs b/crates/core/src/import/mod.rs index 13d85b0..c98c6a7 100644 --- a/crates/core/src/import/mod.rs +++ b/crates/core/src/import/mod.rs @@ -18,7 +18,15 @@ //use poem_openapi::Object; +pub mod history; +pub mod reader; +pub use history::ImportHistory; use serde::{Deserialize, Serialize}; +use std::{ + collections::HashMap, + path::Path, + sync::RwLock, +}; use crate::{ base64_decode_url_safe, @@ -27,15 +35,20 @@ use crate::{ cache::imap::mailbox::{Attribute, AttributeEnum, MailBox}, envelope::extractor::extract_envelope_from_eml, error::{BichonResult, code::ErrorCode}, + settings::dir::DATA_DIR_MANAGER, utils::create_hash, }, raise_error, }; -/// Skip individual emails larger than this after decoding (100 MB). +/// Maximum byte size of an individual email message after splitting (100 MB). const MAX_SINGLE_EML_BYTES: usize = 100 * 1024 * 1024; -#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize)] +/// Max file size accepted via the web upload endpoint. +pub const MAX_WEB_EML_BYTES: usize = 100 * 1024 * 1024; // 100 MB +pub const MAX_WEB_MBOX_BYTES: usize = 1024 * 1024 * 1024; // 1 GB + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[cfg_attr(feature = "web-api", derive(poem_openapi::Object))] pub struct BatchEmlRequest { pub account_id: u64, @@ -46,24 +59,26 @@ pub struct BatchEmlRequest { #[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "web-api", derive(poem_openapi::Object))] -pub struct FailedEmlDetail { - /// The 0-based index of the failed EML in the request list +pub struct FailedItemDetail { + /// The index (0-based) of the failed item. pub index: usize, - /// The error message that caused the import to fail + /// The error message that caused the import to fail. pub error_message: String, } #[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "web-api", derive(poem_openapi::Object))] pub struct BatchEmlResult { - /// Total number of emails processed + /// Total number of emails processed. pub total: usize, - /// Number of emails successfully imported + /// Number of emails successfully imported. pub success: usize, - /// Number of emails failed to import + /// Number of duplicate emails skipped (content hash already existed). + pub duplicates: usize, + /// Number of emails failed to import. pub failed: usize, - /// A list of details for failed imports - pub failed_details: Vec, + /// A list of details for failed imports. + pub failed_details: Vec, } pub struct ImportEmls; @@ -116,7 +131,7 @@ impl ImportEmls { let account_id = account.id; let mut success_count = 0; - let mut failed_details: Vec = Vec::new(); // Store failure details + let mut failed_details: Vec = Vec::new(); // Store failure details let total = request.emls.len(); let mut index: usize = 0; @@ -127,7 +142,7 @@ impl ImportEmls { let error_msg = format!("Failed to decode base64 EML at index {}: {:?}", index, e); tracing::error!("{}", error_msg); - failed_details.push(FailedEmlDetail { + failed_details.push(FailedItemDetail { index, error_message: error_msg, }); @@ -144,7 +159,7 @@ impl ImportEmls { index, size_mb, ); tracing::warn!("{}", error_msg); - failed_details.push(FailedEmlDetail { + failed_details.push(FailedItemDetail { index, error_message: error_msg, }); @@ -162,7 +177,7 @@ impl ImportEmls { index, e ); tracing::error!("{}", error_msg); - failed_details.push(FailedEmlDetail { + failed_details.push(FailedItemDetail { index, error_message: error_msg, }); @@ -178,8 +193,529 @@ impl ImportEmls { Ok(BatchEmlResult { total, success: success_count, + duplicates: 0, failed: failed_count, failed_details, // Return the list of failure details }) } } + +// ── File upload import ────────────────────────────────────────────── + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[cfg_attr(feature = "web-api", derive(poem_openapi::Enum))] +pub enum ImportStatus { + Pending, + Processing, + Completed, + Failed, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "web-api", derive(poem_openapi::Object))] +pub struct ImportProgress { + pub import_id: String, + pub status: ImportStatus, + pub format: String, + pub total: usize, + pub success: usize, + pub duplicates: usize, + pub failed: usize, + pub failed_details: Vec, +} + +static PROGRESS_STORE: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| RwLock::new(HashMap::new())); + +pub fn get_import_progress(import_id: &str) -> Option { + PROGRESS_STORE.read().ok()?.get(import_id).cloned() +} + +pub fn update_progress(import_id: &str, progress: ImportProgress) { + if let Ok(mut store) = PROGRESS_STORE.write() { + store.insert(import_id.to_string(), progress); + } +} + +/// Check free disk space (in bytes) on the temp directory's filesystem. +pub fn check_temp_disk_space() -> BichonResult { + use sysinfo::Disks; + let disks = Disks::new_with_refreshed_list(); + let temp_path = &DATA_DIR_MANAGER.temp_dir; + // Use the canonical path so we can match mount points + let canonical = std::fs::canonicalize(temp_path).unwrap_or_else(|_| temp_path.clone()); + for disk in disks.list() { + if canonical.starts_with(disk.mount_point()) { + return Ok(disk.available_space()); + } + } + // Fallback: if we can't find the mount point, report plenty of space + Ok(u64::MAX) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FileFormat { + Eml, + Mbox, +} + +pub fn detect_format(bytes: &[u8], file_name: &str) -> Option { + // MBOX files start with "From " (note the trailing space after From) + if bytes.starts_with(b"From ") { + // Double-check: look for a valid date after the first "From " line + // MBOX format: "From sender@host DayOfWeek Mon DD HH:MM:SS YYYY" + if let Some(first_newline) = bytes.iter().position(|&b| b == b'\n') { + let from_line = std::str::from_utf8(&bytes[..first_newline]).unwrap_or(""); + let parts: Vec<&str> = from_line.split_whitespace().collect(); + if parts.len() >= 7 { + return Some(FileFormat::Mbox); + } + } + } + // EML: starts with a header line or "Return-Path:", "Received:", "From:", "Date:", etc. + // Or check extension + if bytes.starts_with(b"Return-Path:") + || bytes.starts_with(b"Received:") + || bytes.starts_with(b"Date:") + || bytes.starts_with(b"From:") + || bytes.starts_with(b"Subject:") + || bytes.starts_with(b"To:") + || bytes.starts_with(b"Message-ID:") + { + return Some(FileFormat::Eml); + } + // Fallback: check file extension + let lower = file_name.to_lowercase(); + if lower.ends_with(".eml") { + Some(FileFormat::Eml) + } else if lower.ends_with(".mbox") { + Some(FileFormat::Mbox) + } else { + None + } +} + +/// Check whether `bytes` looks like a text file by inspecting the first chunk. +/// Returns `true` if it passes, `false` if it appears to be binary (video, executable, etc.). +/// +/// Email files (EML/MBOX) are text-based with printable ASCII, whitespace, and +/// optional UTF-8. Binary files like video contain null bytes and high ratios of +/// non-printable control characters. +pub fn detect_text_file(bytes: &[u8]) -> bool { + let check_len = bytes.len().min(8192); + if check_len == 0 { + return false; + } + let sample = &bytes[..check_len]; + + // Null bytes are a strong binary indicator + if sample.contains(&0x00) { + return false; + } + + let mut printable = 0usize; + let mut total = 0usize; + + let mut i = 0; + while i < sample.len() { + total += 1; + let b = sample[i]; + + if b.is_ascii_graphic() || b.is_ascii_whitespace() { + // Printable ASCII + whitespace (space, tab, CR, LF) + printable += 1; + } else if b == 0x1b { + // ESC — common in terminal sequences, rare in email + // Count as printable to avoid false positives + printable += 1; + } else if b >= 0x80 { + // UTF-8 continuation or multi-byte lead byte — allow. + // Check that we have a valid UTF-8 sequence ahead. + let seq_len = match b { + b if b & 0xE0 == 0xC0 => 2, + b if b & 0xF0 == 0xE0 => 3, + b if b & 0xF8 == 0xF0 => 4, + _ => 0, + }; + if seq_len > 0 && i + seq_len <= sample.len() { + let valid = std::str::from_utf8(&sample[i..i + seq_len]).is_ok(); + if valid { + printable += 1; + i += 1; // lead byte counted, continuations counted in loop + } + // if invalid, don't count as printable + } + // standalone continuation byte — not printable + } + // Other control characters (0x01-0x1F except whitespace/Esc) are not counted as printable + + i += 1; + } + + // Require at least 90% printable characters + printable as f64 / total as f64 >= 0.90 +} + +/// Validate that the target account exists, is enabled, and is NoSync type. +fn validate_import_account(account_id: u64) -> BichonResult { + let account = AccountModel::check_account_exists(account_id)?; + if !account.enabled { + return Err(raise_error!( + "The account is disabled.".into(), + ErrorCode::InvalidParameter + )); + } + if !matches!(account.account_type, AccountType::NoSync) { + return Err(raise_error!( + "Import is only allowed for NoSync accounts. IMAP accounts sync from the server.".into(), + ErrorCode::InvalidParameter + )); + } + Ok(account) +} + +/// Resolve or create a mailbox/folder for the given account. +fn resolve_mailbox(account: &AccountModel, folder: &str) -> BichonResult { + match account.account_type { + AccountType::IMAP => { + // Shouldn't reach here (validated above), but handle gracefully + let all_mailboxes = MailBox::list_all(account.id)?; + let mailbox = all_mailboxes.into_iter().find(|m| m.name == folder); + match mailbox { + Some(m) => Ok(m.id), + None => Err(raise_error!( + format!("Mail folder '{}' not found.", folder).into(), + ErrorCode::ResourceNotFound + )), + } + } + AccountType::NoSync => { + let mailbox = MailBox { + id: create_hash(account.id, folder), + account_id: account.id, + name: folder.to_string(), + delimiter: Some("/".to_string()), + attributes: vec![Attribute { + attr: AttributeEnum::Extension, + extension: Some("CreatedByBichon".into()), + }], + exists: 0, + unseen: None, + uid_next: None, + uid_validity: None, + highest_uid: None, + }; + let mailbox_id = mailbox.id; + MailBox::batch_upsert(&[mailbox])?; + Ok(mailbox_id) + } + } +} + +/// Process an uploaded file (EML or MBOX) and import into the given account/folder. +/// This runs synchronously and should be spawned on a background thread. +/// +/// For MBOX files, the file is memory-mapped via `memmap2` and messages are yielded +/// one at a time — the full file is never loaded into RAM. Individual messages +/// exceeding `MAX_SINGLE_EML_BYTES` (100 MB) are skipped. +pub fn process_uploaded_file( + import_id: &str, + file_path: &Path, + file_name: &str, + account_id: u64, + folder: &str, + user_id: u64, +) { + let account = match validate_import_account(account_id) { + Ok(a) => a, + Err(e) => { + let progress = ImportProgress { + import_id: import_id.to_string(), + status: ImportStatus::Failed, + format: "unknown".to_string(), + total: 0, + success: 0, + duplicates: 0, + failed: 0, + failed_details: vec![FailedItemDetail { + index: 0, + error_message: format!("Account validation failed: {:?}", e), + }], + }; + update_progress(import_id, progress.clone()); + history::save_import_history(user_id, account_id, folder, &progress); + return; + } + }; + + let mailbox_id = match resolve_mailbox(&account, folder) { + Ok(id) => id, + Err(e) => { + let progress = ImportProgress { + import_id: import_id.to_string(), + status: ImportStatus::Failed, + format: "unknown".to_string(), + total: 0, + success: 0, + duplicates: 0, + failed: 0, + failed_details: vec![FailedItemDetail { + index: 0, + error_message: format!("Mailbox resolution failed: {:?}", e), + }], + }; + update_progress(import_id, progress.clone()); + history::save_import_history(user_id, account_id, folder, &progress); + return; + } + }; + + // Read a small prefix for format detection + let format = match detect_format_from_file(file_path, file_name) { + Ok(f) => f, + Err(e) => { + let progress = ImportProgress { + import_id: import_id.to_string(), + status: ImportStatus::Failed, + format: "unknown".to_string(), + total: 0, + success: 0, + duplicates: 0, + failed: 0, + failed_details: vec![FailedItemDetail { + index: 0, + error_message: format!("{:?}", e), + }], + }; + update_progress(import_id, progress.clone()); + history::save_import_history(user_id, account_id, folder, &progress); + let _ = std::fs::remove_file(file_path); + return; + } + }; + + match format { + FileFormat::Eml => process_eml_file(import_id, file_path, account_id, mailbox_id, user_id, folder), + FileFormat::Mbox => process_mbox_file(import_id, file_path, account_id, mailbox_id, user_id, folder), + } +} + +/// Detect format from a file by reading only the first few KB. +fn detect_format_from_file(file_path: &Path, file_name: &str) -> BichonResult { + use std::io::Read; + let mut file = std::fs::File::open(file_path).map_err(|e| { + raise_error!(format!("Failed to open file: {}", e), ErrorCode::InternalError) + })?; + let mut buf = vec![0u8; 8192]; + let n = file.read(&mut buf).unwrap_or(0); + buf.truncate(n); + + detect_format(&buf, file_name).ok_or_else(|| { + raise_error!( + "Unknown file format. Supported: .eml, .mbox".into(), + ErrorCode::InvalidParameter + ) + }) +} + +/// Process a single EML file. The file is at most `MAX_WEB_EML_BYTES` (100 MB), +/// so reading it entirely is safe. +fn process_eml_file( + import_id: &str, + file_path: &Path, + account_id: u64, + mailbox_id: u64, + user_id: u64, + folder: &str, +) { + let file_bytes = match std::fs::read(file_path) { + Ok(b) => b, + Err(e) => { + fail_progress(import_id, "eml", &format!("Failed to read file: {}", e), user_id, account_id, folder); + let _ = std::fs::remove_file(file_path); + return; + } + }; + + let total = 1; + update_progress(import_id, ImportProgress { + import_id: import_id.to_string(), + status: ImportStatus::Processing, + format: "eml".to_string(), + total, + success: 0, + duplicates: 0, + failed: 0, + failed_details: vec![], + }); + + let (success_count, failed_details) = process_single_eml(&file_bytes, 0, account_id, mailbox_id); + + // Clean up + let _ = std::fs::remove_file(file_path); + + let final_progress = ImportProgress { + import_id: import_id.to_string(), + status: ImportStatus::Completed, + format: "eml".to_string(), + total, + success: success_count, + duplicates: 0, + failed: failed_details.len(), + failed_details, + }; + history::save_import_history(user_id, account_id, folder, &final_progress); + update_progress(import_id, final_progress); +} + +/// Process an MBOX file using memory-mapped I/O. Messages are yielded one at a +/// time by `MboxReader` — the full file is never loaded into RAM. +fn process_mbox_file( + import_id: &str, + file_path: &Path, + account_id: u64, + mailbox_id: u64, + user_id: u64, + folder: &str, +) { + let mbox = match reader::MboxFile::from_file(file_path) { + Ok(m) => m, + Err(e) => { + fail_progress(import_id, "mbox", &format!("Failed to open MBOX file: {}", e), user_id, account_id, folder); + let _ = std::fs::remove_file(file_path); + return; + } + }; + + // First pass: count total messages (MboxReader is lazy, so this is O(n) but cheap) + let total = mbox.iter().count(); + + update_progress(import_id, ImportProgress { + import_id: import_id.to_string(), + status: ImportStatus::Processing, + format: "mbox".to_string(), + total, + success: 0, + duplicates: 0, + failed: 0, + failed_details: vec![], + }); + + let mut success_count = 0usize; + let mut failed_details: Vec = Vec::new(); + + for (index, entry) in mbox.iter().enumerate() { + let eml_bytes = entry.data; + + if eml_bytes.len() > MAX_SINGLE_EML_BYTES { + let size_mb = eml_bytes.len() as f64 / 1024.0 / 1024.0; + failed_details.push(FailedItemDetail { + index, + error_message: format!( + "Email at index {} is {:.1} MB (limit {} MB). Skipping.", + index, + size_mb, + MAX_SINGLE_EML_BYTES / 1024 / 1024 + ), + }); + continue; + } + + match futures::executor::block_on(extract_envelope_from_eml(eml_bytes, account_id, mailbox_id)) { + Ok(_) => { + success_count += 1; + } + Err(e) => { + failed_details.push(FailedItemDetail { + index, + error_message: format!("{:?}", e), + }); + } + }; + + // Update progress every 100 items + if index % 100 == 0 || index == total - 1 { + update_progress(import_id, ImportProgress { + import_id: import_id.to_string(), + status: ImportStatus::Processing, + format: "mbox".to_string(), + total, + success: success_count, + duplicates: 0, + failed: failed_details.len(), + failed_details: failed_details.clone(), + }); + } + } + + // Clean up temp file (drop the mmap first — MboxFile owns it) + drop(mbox); + let _ = std::fs::remove_file(file_path); + + let final_progress = ImportProgress { + import_id: import_id.to_string(), + status: ImportStatus::Completed, + format: "mbox".to_string(), + total, + success: success_count, + duplicates: 0, + failed: failed_details.len(), + failed_details, + }; + history::save_import_history(user_id, account_id, folder, &final_progress); + update_progress(import_id, final_progress); +} + +/// Process a single EML byte slice and return (success_count, failed_details). +fn process_single_eml( + eml_bytes: &[u8], + index: usize, + account_id: u64, + mailbox_id: u64, +) -> (usize, Vec) { + if eml_bytes.len() > MAX_SINGLE_EML_BYTES { + let size_mb = eml_bytes.len() as f64 / 1024.0 / 1024.0; + return (0, vec![FailedItemDetail { + index, + error_message: format!( + "Email is {:.1} MB (limit {} MB). Skipping.", + size_mb, + MAX_SINGLE_EML_BYTES / 1024 / 1024 + ), + }]); + } + + match futures::executor::block_on(extract_envelope_from_eml(eml_bytes, account_id, mailbox_id)) { + Ok(_) => (1, vec![]), + Err(e) => (0, vec![FailedItemDetail { + index, + error_message: format!("{:?}", e), + }]), + } +} + +/// Record a fatal failure and save history. +fn fail_progress( + import_id: &str, + format: &str, + message: &str, + user_id: u64, + account_id: u64, + folder: &str, +) { + let progress = ImportProgress { + import_id: import_id.to_string(), + status: ImportStatus::Failed, + format: format.to_string(), + total: 0, + success: 0, + duplicates: 0, + failed: 0, + failed_details: vec![FailedItemDetail { + index: 0, + error_message: message.to_string(), + }], + }; + update_progress(import_id, progress.clone()); + history::save_import_history(user_id, account_id, folder, &progress); +} diff --git a/crates/cli/src/mbox/reader.rs b/crates/core/src/import/reader.rs similarity index 88% rename from crates/cli/src/mbox/reader.rs rename to crates/core/src/import/reader.rs index b5e2730..b2b6aa3 100644 --- a/crates/cli/src/mbox/reader.rs +++ b/crates/core/src/import/reader.rs @@ -21,6 +21,8 @@ use std::fs; use std::io; use std::path::Path; +/// Memory-mapped MBOX file. Messages are yielded one at a time without +/// loading the entire file into RAM. pub struct MboxFile { map: Mmap, } @@ -127,10 +129,6 @@ impl<'a> Iterator for MboxReader<'a> { #[cfg(test)] mod tests { - use mail_parser::MessageParser; - - use crate::mbox::gmail::determine_folder; - use super::*; fn collect_entries(data: &[u8]) -> Vec<&[u8]> { @@ -144,6 +142,7 @@ mod tests { let e = collect_entries(data); assert_eq!(e, vec![b"mail1\n", b"mail2\n"]); } + #[test] fn no_trailing_newline() { let data = b"From a\nmail1"; @@ -204,22 +203,4 @@ mod tests { let e = collect_entries(&data); assert_eq!(e.len(), 1000); } - - #[test] - fn test11() { - let mbox = MboxFile::from_file(Path::new("e:\\test.mbox")).unwrap(); - - for e in mbox.iter() { - let body = e.data; - - let message = MessageParser::new().parse(body).unwrap(); - let labels = message.header("X-Gmail-Labels").unwrap().as_text().unwrap(); - //println!("offset={} X-Gmail-Labels={:?}", e.offset, labels); - println!( - "X-Gmail-Labels={:?}, determine_folder={}", - labels, - determine_folder(labels) - ) - } - } } diff --git a/crates/core/src/settings/cli.rs b/crates/core/src/settings/cli.rs index 627aa5b..0dcc472 100644 --- a/crates/core/src/settings/cli.rs +++ b/crates/core/src/settings/cli.rs @@ -328,6 +328,17 @@ pub struct Settings { /// OIDC redirect URI (must match what's registered with the IdP). #[clap(long, env, help = "OpenID Connect redirect URI")] pub bichon_oidc_redirect_uri: Option, + + /// Maximum HTTP request body size in MB for file uploads (default: 1100 MB). + /// Requests exceeding this limit are rejected at the framework level before + /// the application reads the body, preventing memory exhaustion attacks. + #[clap( + long, + default_value = "1100", + env, + help = "Maximum HTTP request body size in MB for file uploads" + )] + pub bichon_upload_body_limit_mb: u64, } impl Settings { diff --git a/crates/core/src/settings/mod.rs b/crates/core/src/settings/mod.rs index 7d4e203..e2a3d5c 100644 --- a/crates/core/src/settings/mod.rs +++ b/crates/core/src/settings/mod.rs @@ -65,6 +65,8 @@ pub struct SystemConfigurations { pub bichon_oidc_issuer_url: Option, pub bichon_oidc_client_id: Option, pub bichon_oidc_redirect_uri: Option, + + pub bichon_upload_body_limit_mb: u64, } impl From<&Settings> for SystemConfigurations { @@ -103,6 +105,7 @@ impl From<&Settings> for SystemConfigurations { bichon_oidc_issuer_url: s.bichon_oidc_issuer_url.clone(), bichon_oidc_client_id: s.bichon_oidc_client_id.clone(), bichon_oidc_redirect_uri: s.bichon_oidc_redirect_uri.clone(), + bichon_upload_body_limit_mb: s.bichon_upload_body_limit_mb, } } } diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 26d6eef..4d854e3 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -31,6 +31,7 @@ timeago.workspace = true chrono.workspace = true tracing.workspace = true tokio.workspace = true +futures.workspace = true http.workspace = true urlencoding.workspace = true diff --git a/crates/server/src/rest/api/import.rs b/crates/server/src/rest/api/import.rs index 4be7e3b..622cf2a 100644 --- a/crates/server/src/rest/api/import.rs +++ b/crates/server/src/rest/api/import.rs @@ -16,14 +16,32 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . +use std::time::{SystemTime, UNIX_EPOCH}; + use crate::common::auth::WrappedContext; use crate::rest::api::ApiTags; use crate::rest::ApiResult; -use bichon_core::import::BatchEmlResult; -use bichon_core::import::{BatchEmlRequest, ImportEmls}; +use bichon_core::account::migration::AccountModel; +use bichon_core::database::manager::DB_MANAGER; +use bichon_core::database::MemDbModel; +use bichon_core::import::{ + check_temp_disk_space, get_import_progress, process_uploaded_file, update_progress, + BatchEmlRequest, BatchEmlResult, ImportEmls, ImportHistory, ImportProgress, ImportStatus, + MAX_WEB_EML_BYTES, MAX_WEB_MBOX_BYTES, +}; +use bichon_core::import::history::{save_import_history, MAX_HISTORY_PER_USER}; +use bichon_core::raise_error; +use bichon_core::error::code::ErrorCode; +use bichon_core::settings::dir::DATA_DIR_MANAGER; use bichon_core::users::permissions::Permission; -use poem_openapi::payload::Json; +use bichon_core::import::detect_text_file; +use bichon_core::import::FileFormat; +use futures::StreamExt; +use poem::Body; +use poem_openapi::param::{Path, Query}; +use poem_openapi::payload::{Json, Binary}; use poem_openapi::OpenApi; +use tokio::io::AsyncWriteExt; pub struct ImportApi; @@ -44,7 +62,331 @@ impl ImportApi { payload: Json, context: WrappedContext, ) -> ApiResult> { - context.require_permission(Some(payload.0.account_id), Permission::DATA_IMPORT_BATCH)?; - Ok(Json(ImportEmls::do_import(payload.0).await?)) + let account_id = payload.0.account_id; + let folder = payload.0.mail_folder.clone(); + context.require_permission(Some(account_id), Permission::DATA_IMPORT_BATCH)?; + let result = ImportEmls::do_import(payload.0).await?; + + // Save import history + let progress = ImportProgress { + import_id: format!( + "batch_{:x}", + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + ), + status: if result.failed == 0 { + ImportStatus::Completed + } else if result.success == 0 { + ImportStatus::Failed + } else { + ImportStatus::Completed + }, + format: "eml".to_string(), + total: result.total, + success: result.success, + duplicates: result.duplicates, + failed: result.failed, + failed_details: result.failed_details.clone(), + }; + save_import_history(context.user.id, account_id, &folder, &progress); + + Ok(Json(result)) + } + + /// Upload an EML or MBOX file for import into a NoSync account. + /// + /// The file is sent as the raw request body. Both `account_id` and `mail_folder` + /// must be provided as query parameters, along with the original `file_name` for + /// extension validation. + /// + /// Returns an `import_id` to poll for progress via `/import-progress/:import_id`. + #[oai(path = "/upload-import", method = "post", operation_id = "upload_import")] + async fn upload_import( + &self, + /// Target account ID (must be NoSync type). + account_id: Query, + /// Target mail folder name. + mail_folder: Query, + /// Original file name, used for extension validation (e.g. "export.eml"). + file_name: Query, + /// The raw file bytes (.eml or .mbox). + data: Binary, + context: WrappedContext, + ) -> ApiResult> { + let account_id = account_id.0; + context.require_permission(Some(account_id), Permission::DATA_IMPORT_BATCH)?; + + // Basic account validation (fails fast) + AccountModel::check_account_exists(account_id)?; + + let folder = mail_folder.0.trim().to_string(); + if folder.is_empty() { + return Err(raise_error!( + "mail_folder is required.".into(), + ErrorCode::InvalidParameter + ))?; + } + + let file_name = file_name.0.trim().to_string(); + if file_name.is_empty() { + return Err(raise_error!( + "file_name is required.".into(), + ErrorCode::InvalidParameter + ))?; + } + + // Validate file extension + let ext_lower = std::path::Path::new(&file_name) + .extension() + .and_then(|e| e.to_str()) + .map(|e| e.to_lowercase()) + .unwrap_or_default(); + let is_mbox_ext = ext_lower == "mbox"; + let is_eml_ext = ext_lower == "eml"; + if !is_mbox_ext && !is_eml_ext { + return Err(raise_error!( + format!( + "Unsupported file type '.{}'. Only .eml and .mbox files are allowed.", + ext_lower + ), + ErrorCode::InvalidParameter + ))?; + } + + // Check disk space (fail fast before streaming) + let min_required = if is_mbox_ext { MAX_WEB_MBOX_BYTES } else { MAX_WEB_EML_BYTES }; + let free = check_temp_disk_space()?; + if free < min_required as u64 * 2 { + let free_gb = free as f64 / 1024.0 / 1024.0 / 1024.0; + let need_gb = (min_required as f64 * 2.0) / 1024.0 / 1024.0 / 1024.0; + return Err(raise_error!( + format!( + "Insufficient disk space. Free: {:.1} GB. Need at least {:.1} GB.", + free_gb, need_gb + ), + ErrorCode::InvalidParameter + ))?; + } + + // Stream body to temp file, enforcing size limits and validating content + let import_id = format!( + "imp_{:x}", + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + ); + let temp_path = DATA_DIR_MANAGER.temp_dir.join(format!("import_{}.tmp", import_id)); + + let (format_detected, file_len) = stream_body_to_temp( + data.0, + &temp_path, + is_mbox_ext, + ).await?; + + let format = format_detected.unwrap_or_else(|| { + if is_mbox_ext { FileFormat::Mbox } else { FileFormat::Eml } + }); + + let format_str = match format { + FileFormat::Mbox => "mbox".to_string(), + FileFormat::Eml => "eml".to_string(), + }; + + let max_size = match format { + FileFormat::Mbox => MAX_WEB_MBOX_BYTES, + FileFormat::Eml => MAX_WEB_EML_BYTES, + }; + if file_len > max_size { + let _ = std::fs::remove_file(&temp_path); + let max_mb = max_size as f64 / 1024.0 / 1024.0; + let actual_mb = file_len as f64 / 1024.0 / 1024.0; + return Err(raise_error!( + format!( + "File too large ({:.1} MB). Maximum for {} is {:.0} MB. Use the CLI for larger files.", + actual_mb, format_str.to_uppercase(), max_mb + ), + ErrorCode::InvalidParameter + ))?; + } + + // Record initial progress + let initial = ImportProgress { + import_id: import_id.clone(), + status: ImportStatus::Pending, + format: format_str.clone(), + total: 0, + success: 0, + duplicates: 0, + failed: 0, + failed_details: vec![], + }; + + // Store initial progress so polling can find it immediately + update_progress(&import_id, initial.clone()); + + // Spawn background processing + let id = import_id.clone(); + let folder_clone = folder.clone(); + let user_id = context.user.id; + tokio::task::spawn_blocking(move || { + process_uploaded_file(&id, &temp_path, &file_name, account_id, &folder_clone, user_id); + }); + + Ok(Json(initial)) + } + + /// Poll import progress by import ID. + #[oai( + path = "/import-progress/:import_id", + method = "get", + operation_id = "get_import_progress" + )] + async fn get_import_progress( + &self, + import_id: Path, + context: WrappedContext, + ) -> ApiResult> { + let _ = context; // progress queries don't need per-account auth + match get_import_progress(&import_id.0) { + Some(progress) => Ok(Json(progress)), + None => Err(raise_error!( + format!("Import {} not found.", import_id.0), + ErrorCode::ResourceNotFound + ))?, + } + } + + /// Check available disk space on the server's temp directory. + #[oai( + path = "/check-disk-space", + method = "get", + operation_id = "check_disk_space" + )] + async fn check_disk_space(&self, _context: WrappedContext) -> ApiResult> { + let free = check_temp_disk_space()?; + Ok(Json(free)) + } + + /// List import history for the current user (latest first, up to 5 entries). + #[oai( + path = "/import-history", + method = "get", + operation_id = "list_import_history" + )] + async fn list_import_history( + &self, + context: WrappedContext, + ) -> ApiResult>> { + let prefix = format!("{}:", context.user.id); + let coll = DB_MANAGER.db().collection(ImportHistory::collection()); + let mut entries: Vec = coll + .scan_prefix(&prefix) + .map_err(|e| raise_error!(format!("{:#?}", e), ErrorCode::InternalError))?; + // Sort by created_at descending (newest first), keep at most N per user + entries.sort_by(|a, b| b.created_at.cmp(&a.created_at)); + entries.truncate(MAX_HISTORY_PER_USER); + Ok(Json(entries)) } } + +/// Stream a poem `Body` to a temp file while enforcing size limits and +/// validating that the content looks like a text-based email file. +/// +/// Returns the detected format (if any) and the total bytes written. +async fn stream_body_to_temp( + body: Body, + temp_path: &std::path::Path, + is_mbox_ext: bool, +) -> ApiResult<(Option, usize)> { + let max_stream = if is_mbox_ext { MAX_WEB_MBOX_BYTES } else { MAX_WEB_EML_BYTES }; + + let mut file = tokio::fs::File::create(temp_path).await.map_err(|e| { + raise_error!( + format!("Failed to create temp file: {}", e), + ErrorCode::InternalError + ) + })?; + + let mut body_stream = body.into_bytes_stream(); + let mut total: usize = 0; + let mut first_chunk: Vec = Vec::new(); + let mut format_detected: Option = None; + let mut text_checked = false; + + while let Some(chunk_result) = body_stream.next().await { + let chunk = chunk_result.map_err(|e| { + raise_error!( + format!("Failed to read request body: {}", e), + ErrorCode::InternalError + ) + })?; + + total += chunk.len(); + + // Enforce size limit during streaming + if total > max_stream { + // Clean up partial temp file + drop(file); + let _ = tokio::fs::remove_file(temp_path).await; + let max_mb = max_stream as f64 / 1024.0 / 1024.0; + return Err(raise_error!( + format!( + "Upload exceeds maximum size of {:.0} MB. Use the CLI for larger files.", + max_mb + ), + ErrorCode::InvalidParameter + ))?; + } + + // Accumulate first ~8 KB for format & text detection + if first_chunk.len() < 8192 { + let remaining = 8192 - first_chunk.len(); + first_chunk.extend_from_slice(&chunk[..chunk.len().min(remaining)]); + } + + // Once we have enough data, validate format and text + if first_chunk.len() >= 512 && !text_checked { + text_checked = true; + format_detected = bichon_core::import::detect_format(&first_chunk, "upload"); + + // If extension is .eml but content looks like MBOX (or vice versa), that's OK. + // But if content doesn't look like either, reject. + if !detect_text_file(&first_chunk) { + drop(file); + let _ = tokio::fs::remove_file(temp_path).await; + return Err(raise_error!( + "The uploaded file appears to be binary (not a valid email file). Only .eml and .mbox text files are accepted.".into(), + ErrorCode::InvalidParameter + ))?; + } + } + + file.write_all(&chunk).await.map_err(|e| { + raise_error!( + format!("Failed to write temp file: {}", e), + ErrorCode::InternalError + ) + })?; + } + + file.flush().await.map_err(|e| { + raise_error!( + format!("Failed to flush temp file: {}", e), + ErrorCode::InternalError + ) + })?; + + // If file is empty, reject + if total == 0 { + let _ = tokio::fs::remove_file(temp_path).await; + return Err(raise_error!( + "Empty file is not allowed.".into(), + ErrorCode::InvalidParameter + ))?; + } + + Ok((format_detected, total)) +} diff --git a/web/src/api/import/api.ts b/web/src/api/import/api.ts new file mode 100644 index 0000000..48e5f11 --- /dev/null +++ b/web/src/api/import/api.ts @@ -0,0 +1,82 @@ +// +// Copyright (c) 2025-2026 rustmailer.com (https://rustmailer.com) +// +// This file is part of the Bichon Email Archiving Project + +import axiosInstance from '@/api/axiosInstance'; +import { list_accounts } from '@/api/account/api'; +import type { AccountModel } from '@/api/account/api'; + +export interface ImportProgress { + import_id: string; + status: 'Pending' | 'Processing' | 'Completed' | 'Failed'; + format: string; + total: number; + success: number; + duplicates: number; + failed: number; + failed_details: { index: number; error_message: string }[]; +} + +export const upload_import = async ( + accountId: number, + mailFolder: string, + fileName: string, + file: File, + onProgress?: (pct: number) => void +): Promise => { + const response = await axiosInstance.post( + `api/v1/upload-import`, + file, + { + params: { account_id: accountId, mail_folder: mailFolder, file_name: fileName }, + headers: { 'Content-Type': 'application/octet-stream' }, + onUploadProgress: (e) => { + if (e.total && onProgress) onProgress(Math.round((e.loaded / e.total) * 100)); + }, + } + ); + return response.data; +}; + +export const get_import_progress = async (importId: string): Promise => { + const response = await axiosInstance.get( + `api/v1/import-progress/${importId}` + ); + return response.data; +}; + +export const check_disk_space = async (): Promise => { + const response = await axiosInstance.get('api/v1/check-disk-space'); + return response.data; +}; + +export const get_nosync_accounts = async (): Promise => { + const data = await list_accounts(); + return (data.items || []).filter( + (a) => a.account_type === 'NoSync' && a.enabled + ); +}; + +// ── Import history ──────────────────────────────────────────────── + +export interface ImportHistory { + id: string; + user_id: number; + import_id: string; + account_id: number; + folder: string; + format: string; + status: 'pending' | 'processing' | 'completed' | 'failed'; + total: number; + success: number; + duplicates: number; + failed: number; + failed_details: { index: number; error_message: string }[]; + created_at: number; +} + +export const list_import_history = async (): Promise => { + const response = await axiosInstance.get('api/v1/import-history'); + return response.data; +}; diff --git a/web/src/components/layout/data/sidebar-data.ts b/web/src/components/layout/data/sidebar-data.ts index 2012f48..ff9bcb4 100644 --- a/web/src/components/layout/data/sidebar-data.ts +++ b/web/src/components/layout/data/sidebar-data.ts @@ -22,7 +22,7 @@ import { IconLayoutDashboard, IconSettings } from '@tabler/icons-react' -import { IdCard, Inbox, Paperclip, Search, Users2 } from 'lucide-react' +import { IdCard, Inbox, Paperclip, Search, Upload, Users2 } from 'lucide-react' import { type SidebarData } from '../types' import { useTranslation } from 'react-i18next' import { useCurrentUser } from '@/hooks/use-current-user' @@ -57,6 +57,12 @@ export function useSidebarData(): SidebarData { url: '/search', icon: Search, }, + { + title: t('import.title', 'Import'), + url: '/import', + icon: Upload, + visible: require_any_permission(['data:import:batch']), + }, { title: t('navigation.attachment'), url: '/attachment', diff --git a/web/src/features/import/folder-hint.ts b/web/src/features/import/folder-hint.ts new file mode 100644 index 0000000..1f34a8b --- /dev/null +++ b/web/src/features/import/folder-hint.ts @@ -0,0 +1,146 @@ +// +// Copyright (c) 2025-2026 rustmailer.com (https://rustmailer.com) +// +// This file is part of the Bichon Email Archiving Project + +/** + * Parse raw EML/MBOX headers from the first few KB of a file and return a + * suggested folder name, or null if nothing useful was found. + * + * Mirrors the CLI logic in crates/cli/src/mbox/gmail.rs (determine_folder). + */ + +const HEADER_READ_BYTES = 64 * 1024; // read first 64 KB to get headers + +/** RFC 2047 encoded-word prefix. We do a best-effort decode. */ +function decodeRfc2047(raw: string): string { + return raw.replace(/=\?[^?]+\?[BbQq]\?[^?]*\?=/gi, (match) => { + try { + const parts = match.split('?'); + const charset = parts[1]; + const encoding = parts[2].toUpperCase(); + const encoded = parts[3]; + let bytes: Uint8Array; + if (encoding === 'B') { + const bin = atob(encoded); + bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); + } else { + // Q-encoding + const hex = encoded.replace(/_/g, ' ').replace(/=([0-9A-Fa-f]{2})/g, (_, h) => + String.fromCharCode(parseInt(h, 16)), + ); + bytes = new TextEncoder().encode(hex); + } + return new TextDecoder(charset).decode(bytes); + } catch { + return match; + } + }); +} + +/** Extract a single header value from raw email text. Case-insensitive. */ +function getHeader(raw: string, name: string): string | null { + const re = new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*:\\s*(.+)$`, 'im'); + const m = raw.match(re); + if (!m) return null; + // Unfold continuation lines (leading whitespace) + let val = m[1].trim(); + const startIdx = m.index! + m[0].length; + const rest = raw.slice(startIdx); + const contRe = /^\s+(.+)$/gm; + let cm: RegExpExecArray | null; + while ((cm = contRe.exec(rest)) !== null) { + val += ' ' + cm[1].trim(); + } + return decodeRfc2047(val); +} + +/** Determine folder from X-Gmail-Labels, mirroring the CLI's determine_folder(). */ +function folderFromGmailLabels(raw: string): string | null { + const labelsRaw = getHeader(raw, 'X-Gmail-Labels'); + if (!labelsRaw) return null; + + const statusBlacklist = new Set(['Opened', 'Unread', 'Archived']); + const allLabels = labelsRaw.split(',').map((s) => s.trim()).filter(Boolean); + if (allLabels.length === 0) return null; + + const filtered = allLabels.filter((l) => !statusBlacklist.has(l)); + if (filtered.length === 0) return allLabels[0]; + if (filtered.length === 1) return filtered[0]; + + // Prefer business labels over generic Inbox/Sent + const business = filtered.find((l) => l !== 'Inbox' && l !== 'Sent'); + return business ?? filtered[0]; +} + +/** Try to read mailbox_name from X-Bichon-Metadata JSON header. */ +function folderFromBichonMetadata(raw: string): string | null { + const metaRaw = getHeader(raw, 'X-Bichon-Metadata'); + if (!metaRaw) return null; + try { + const meta = JSON.parse(metaRaw); + if (meta?.mailbox_name && typeof meta.mailbox_name === 'string') { + return meta.mailbox_name; + } + } catch { + // ignore parse errors + } + return null; +} + +/** Derive a folder from the file name (e.g. "Inbox.mbox" → "Inbox"). */ +function folderFromFileName(fileName: string): string | null { + const base = fileName.replace(/\.[^.]+$/, ''); // strip extension + if (!base || base === fileName) return null; + // Common patterns + if (/^[a-zA-Z0-9_/\-.\s]+$/.test(base) && base.length > 0 && base.length < 128) { + return base; + } + return null; +} + +export interface FolderHint { + /** The suggested folder name. */ + name: string; + /** Where the hint came from. */ + source: 'gmail-labels' | 'bichon-metadata' | 'filename' | 'mbox-filename'; +} + +/** + * Read the first chunk of a File and return folder hints extracted from headers. + * Returns null if no hint could be extracted. + */ +export async function extractFolderHint(file: File): Promise { + const ext = file.name.split('.').pop()?.toLowerCase(); + const isMbox = ext === 'mbox'; + + // Read first 64 KB — enough for headers of the first message + const chunk = new Uint8Array(await file.slice(0, HEADER_READ_BYTES).arrayBuffer()); + const raw = new TextDecoder('utf-8', { fatal: false }).decode(chunk); + + // MBOX: the first line is "From ...", headers start after the first newline + const headers = isMbox + ? raw.replace(/^From [^\n]*\n/, '') // strip MBOX "From " separator + : raw; + + // 1. X-Bichon-Metadata (highest priority, explicit) + const bichonFolder = folderFromBichonMetadata(headers); + if (bichonFolder) return { name: bichonFolder, source: 'bichon-metadata' }; + + // 2. X-Gmail-Labels + const gmailFolder = folderFromGmailLabels(headers); + if (gmailFolder) return { name: gmailFolder, source: 'gmail-labels' }; + + // 3. For MBOX files, use the filename + if (isMbox) { + const fnFolder = folderFromFileName(file.name); + if (fnFolder) return { name: fnFolder, source: 'mbox-filename' }; + } + + // 4. For EML files, try the filename + const fnFolder = folderFromFileName(file.name); + if (fnFolder) return { name: fnFolder, source: 'filename' }; + + return null; +} diff --git a/web/src/features/import/index.tsx b/web/src/features/import/index.tsx new file mode 100644 index 0000000..9ae7ea9 --- /dev/null +++ b/web/src/features/import/index.tsx @@ -0,0 +1,819 @@ +// +// Copyright (c) 2025-2026 rustmailer.com (https://rustmailer.com) +// +// This file is part of the Bichon Email Archiving Project + +import { useState, useRef, useCallback, useEffect } from 'react'; +import { useTranslation } from 'react-i18next'; +import { useMutation, useQuery } from '@tanstack/react-query'; +import { + Upload, FileText, X, CheckCircle2, AlertTriangle, + Sparkles, PenLine, ListTree, ChevronsUpDown, Check, + Clock, ChevronRight, +} from 'lucide-react'; + +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Progress } from '@/components/ui/progress'; +import { ScrollArea } from '@/components/ui/scroll-area'; +import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'; +import { cn } from '@/lib/utils'; +import { Main } from '@/components/layout/main'; +import { FixedHeader } from '@/components/layout/fixed-header'; +import { useToast } from '@/hooks/use-toast'; +import { Badge } from '@/components/ui/badge'; +import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList, +} from '@/components/ui/command'; + +import { + upload_import, + get_import_progress, + get_nosync_accounts, + list_import_history, + type ImportProgress, + type ImportHistory, +} from '@/api/import/api'; +import { list_mailboxes } from '@/api/mailbox/api'; +import { extractFolderHint, type FolderHint } from './folder-hint'; + +const MAX_EML = 100 * 1024 * 1024; // 100 MB +const MAX_MBOX = 1024 * 1024 * 1024; // 1 GB + +// MIME types that are clearly NOT email files — reject these upfront. +const BLOCKED_MIME_PREFIXES = [ + 'video/', 'audio/', 'image/', 'font/', + 'application/zip', 'application/gzip', 'application/x-tar', + 'application/x-7z', 'application/x-rar', + 'application/vnd.', 'application/pdf', + 'application/x-msdownload', 'application/x-executable', +]; + +function isValidFileType(file: File, ext: string): boolean { + // Check MIME type: reject known binary types + const mime = file.type.toLowerCase(); + if (mime) { + for (const prefix of BLOCKED_MIME_PREFIXES) { + if (mime.startsWith(prefix)) return false; + } + } + // Check extension + return ext === 'eml' || ext === 'mbox'; +} + +type FolderMode = 'header' | 'existing' | 'custom'; + +interface QueuedFile { + file: File; + sizeOk: boolean; + typeOk: boolean; +} + +function formatSize(bytes: number) { + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; + return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`; +} + +function folderHintLabel(hint: FolderHint): string { + switch (hint.source) { + case 'gmail-labels': return 'X-Gmail-Labels'; + case 'bichon-metadata': return 'X-Bichon-Metadata'; + case 'filename': return 'filename'; + case 'mbox-filename': return 'mbox filename'; + } +} + +export default function ImportPage() { + const { t } = useTranslation(); + const { toast } = useToast(); + + const [accountId, setAccountId] = useState(''); + const [folderMode, setFolderMode] = useState('header'); + const [folder, setFolder] = useState('INBOX'); + const [files, setFiles] = useState([]); + const [dragging, setDragging] = useState(false); + // const [importId, setImportId] = useState(null); + const [progress, setProgress] = useState(null); + const [uploadPct, setUploadPct] = useState(0); + const [phase, setPhase] = useState<'idle' | 'uploading' | 'processing' | 'done'>('idle'); + const [folderHint, setFolderHint] = useState(null); + const [headerFolder, setHeaderFolder] = useState('INBOX'); + + // Combobox state for existing mailbox selection + const [mailboxOpen, setMailboxOpen] = useState(false); + // Combobox state for account selection + const [accountOpen, setAccountOpen] = useState(false); + + const pollRef = useRef | null>(null); + + const { data: accounts = [] } = useQuery({ + queryKey: ['nosync-accounts'], + queryFn: get_nosync_accounts, + staleTime: 30_000, + }); + + const { data: mailboxData } = useQuery({ + queryKey: ['account-mailboxes', accountId], + queryFn: () => list_mailboxes(Number(accountId), false), + enabled: !!accountId, + staleTime: 60_000, + }); + const mailboxes = mailboxData?.mailboxes ?? []; + + // Import history + const { data: history = [], refetch: refetchHistory } = useQuery({ + queryKey: ['import-history'], + queryFn: list_import_history, + staleTime: 10_000, + }); + + // Resolve the effective folder based on current mode + const effectiveFolder = (() => { + switch (folderMode) { + case 'header': + return headerFolder; + case 'existing': + case 'custom': + return folder; + } + })(); + + const startPolling = useCallback((id: string) => { + if (pollRef.current) clearInterval(pollRef.current); + let retries = 0; + pollRef.current = setInterval(async () => { + try { + const p = await get_import_progress(id); + setProgress(p); + retries = 0; + if (p.status === 'Completed' || p.status === 'Failed') { + if (pollRef.current) clearInterval(pollRef.current); + setPhase('done'); + refetchHistory(); + } + } catch { + retries++; + if (retries > 5) { + if (pollRef.current) clearInterval(pollRef.current); + setPhase('idle'); + } + } + }, 1000); + }, [refetchHistory]); + + useEffect(() => { + return () => { if (pollRef.current) clearInterval(pollRef.current); }; + }, []); + + const handleFiles = useCallback(async (newFiles: FileList | File[]) => { + const arr = Array.from(newFiles) as File[]; + const queued: QueuedFile[] = arr.map((f) => { + const ext = f.name.split('.').pop()?.toLowerCase() || ''; + const isMbox = ext === 'mbox'; + const max = isMbox ? MAX_MBOX : MAX_EML; + const typeOk = isValidFileType(f, ext); + return { file: f, sizeOk: f.size <= max, typeOk }; + }); + + setFiles(queued); + setPhase('idle'); + setProgress(null); + //setImportId(null); + + // Extract folder hint from the first valid file + const firstOk = queued.find((q) => q.sizeOk && q.typeOk); + if (firstOk) { + try { + const hint = await extractFolderHint(firstOk.file); + if (hint) { + setFolderHint(hint); + setHeaderFolder(hint.name); + } + } catch { + // ignore + } + } + }, []); + + const removeFile = (idx: number) => { + setFiles((prev) => prev.filter((_, i) => i !== idx)); + if (files.length <= 1) { + setFolderHint(null); + setHeaderFolder('INBOX'); + } + }; + + const handleAccountChange = (v: string) => { + setAccountId(v); + setFiles([]); + setFolderHint(null); + setHeaderFolder('INBOX'); + }; + + const handleModeChange = (mode: FolderMode) => { + setFolderMode(mode); + // When switching to header mode, re-detect from files if available + if (mode === 'header' && files.length > 0) { + const firstOk = files.find((q) => q.sizeOk && q.typeOk); + if (firstOk) { + extractFolderHint(firstOk.file).then((hint) => { + if (hint) { + setFolderHint(hint); + setHeaderFolder(hint.name); + } + }); + } + } + }; + + const importMutation = useMutation({ + mutationFn: async () => { + if (!accountId || !files.length) return; + const file = files[0].file; + setPhase('uploading'); + setUploadPct(0); + const result = await upload_import( + Number(accountId), + effectiveFolder, + file.name, + file, + (pct) => setUploadPct(pct), + ); + //setImportId(result.import_id); + setProgress(result); + setPhase('processing'); + startPolling(result.import_id); + }, + onError: (err: any) => { + setPhase('idle'); + toast({ + title: t('common.failed'), + description: err?.response?.data?.message || err.message, + variant: 'destructive', + }); + }, + }); + + const canImport = + accountId && effectiveFolder.trim() && files.length > 0 && files.every((f) => f.sizeOk && f.typeOk) && phase === 'idle'; + + return ( + <> + +
+
+
+

+ {t('import.title', 'Import EML / MBOX')} +

+

+ {t('import.description', 'Import email files into a NoSync account. For larger files, use the CLI.')} +

+
+ + {/* Step 1: Target account */} + + + + {t('import.target', '1. Select target account')} + + + +
+ + + + + + + + + + + {t('import.noAccountFound', 'No account found.')} + + + {accounts.map((a) => ( + { + handleAccountChange(String(a.id)); + setAccountOpen(false); + }} + className='text-xs' + > + + {a.account_name || a.email} + + ))} + + + + + +
+
+
+ + {/* Step 2: Folder determination mode */} + + + + {t('import.folderMethod', '2. Choose folder method')} + + + {t('import.folderMethodDesc', 'How should the target mail folder be determined?')} + + + + handleModeChange(v as FolderMode)} + className="gap-3" + > + {/* Mode 1: Auto-detect from headers */} + + + {/* Mode 2: Pick from existing mailboxes */} + + + {/* Mode 3: Manual input */} + + + + + + {/* Step 3: File upload */} + + + + {t('import.chooseFiles', '3. Choose files')} + + + {t('import.limits', 'Max: EML 100 MB · MBOX 1 GB. Larger files → CLI.')} + + + +
{ e.preventDefault(); setDragging(true); }} + onDragLeave={() => setDragging(false)} + onDrop={(e) => { e.preventDefault(); setDragging(false); handleFiles(e.dataTransfer.files); }} + onClick={() => { + const input = document.createElement('input'); + input.type = 'file'; + input.accept = '.eml,.mbox,message/rfc822,application/mbox,text/plain'; + input.multiple = true; + input.onchange = () => input.files && handleFiles(input.files); + input.click(); + }} + > + +

+ {t('import.dropHere', 'Drop .eml / .mbox files here')} +

+

+ {t('import.orClick', 'or click to browse')} +

+
+ + {files.length > 0 && ( +
+ {files.map((qf, i) => ( +
+ + {qf.file.name} + + {formatSize(qf.file.size)} + + {!qf.typeOk && ( + Invalid type + )} + {!qf.sizeOk && qf.typeOk && ( + Too large + )} + {qf.sizeOk && qf.typeOk ? ( + + ) : ( + + )} + {phase === 'idle' && ( + + )} +
+ ))} +
+ )} +
+
+ + {/* Step 4: Progress & Results */} + {(phase !== 'idle' || progress) && ( + + + + {phase === 'uploading' && t('import.uploading', 'Uploading…')} + {phase === 'processing' && t('import.processing', 'Processing…')} + {phase === 'done' && (progress?.status === 'Completed' ? t('import.completed', 'Import complete') : t('import.failed', 'Import failed'))} + + + + {phase === 'uploading' && ( +
+
+ {t('import.uploadingFile')} + {uploadPct}% +
+ +
+ )} + + {progress && progress.total > 0 && ( +
+
+ + {t('import.processed', { current: progress.success + progress.failed, total: progress.total })} + + + {progress.total > 0 + ? Math.round(((progress.success + progress.failed) / progress.total) * 100) + : 0}% + +
+ 0 ? ((progress.success + progress.failed) / progress.total) * 100 : 0} + className="h-2" + /> +
+ )} + + {progress && progress.total > 0 && ( +
+ + + {t('import.successCount', { count: progress.success })} + + + + {t('import.failedCount', { count: progress.failed })} + +
+ )} + + {progress && progress.failed_details.length > 0 && ( +
+ + {t('import.failedDetails', 'Failed items')} ({progress.failed_details.length}) + + +
+ {progress.failed_details.map((d, i) => ( +
+ #{d.index}: {d.error_message} +
+ ))} +
+
+
+ )} +
+
+ )} + + {/* Import button */} +
+
+ {t('import.willImportTo', 'Will import to')}: {effectiveFolder} +
+ +
+ + {/* Import history */} + {history.length > 0 && ( + + accounts.find((a) => a.id === id)?.account_name + || accounts.find((a) => a.id === id)?.email + || String(id) + } + /> + )} +
+
+ + ); +} + +// ─── Import history collapsible ────────────────────────────────────────── + +function statusColor(status: string) { + switch (status) { + case 'completed': return 'text-green-600'; + case 'failed': return 'text-destructive'; + case 'processing': return 'text-amber-600'; + default: return 'text-muted-foreground'; + } +} + +function statusLabel(status: string) { + switch (status) { + case 'completed': return 'Completed'; + case 'failed': return 'Failed'; + case 'processing': return 'Processing'; + case 'pending': return 'Pending'; + default: return status; + } +} + +function timeAgo(ts: number) { + const seconds = Math.floor((Date.now() - ts) / 1000); + if (seconds < 60) return `${seconds}s ago`; + if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`; + if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`; + return new Date(ts).toLocaleDateString(); +} + +function CollapsibleHistory({ + history, + t, + accountLabel, +}: { + history: ImportHistory[]; + t: (key: string) => string; + accountLabel: (id: number) => string; +}) { + const [open, setOpen] = useState(false); + + return ( +
+ + {open && ( +
+
+ {history.map((h) => ( +
+
+
+ + {statusLabel(h.status)} + + + {accountLabel(h.account_id)} / {h.folder} + +
+ {timeAgo(h.created_at)} +
+
+ {h.format.toUpperCase()} + {h.success} success + {h.duplicates > 0 && {h.duplicates} dup} + {h.failed > 0 && {h.failed} failed} + {h.total} total +
+ {h.failed_details.length > 0 && ( +
+ + {t('import.failedDetails')} ({h.failed_details.length}) + +
+ {h.failed_details.map((d, i) => ( +
+ #{d.index}: {d.error_message} +
+ ))} +
+
+ )} +
+ ))} +
+
+ )} +
+ ); +} diff --git a/web/src/hooks/use-current-user.ts b/web/src/hooks/use-current-user.ts index 125bcb2..ae5fcde 100644 --- a/web/src/hooks/use-current-user.ts +++ b/web/src/hooks/use-current-user.ts @@ -64,6 +64,9 @@ export function useCurrentUser() { if (accountId !== undefined) { return accountMap.get(accountId)?.has(perm) ?? false } + for (const perms of accountMap.values()) { + if (perms.has(perm)) return true + } return false }) } diff --git a/web/src/locales/ar.json b/web/src/locales/ar.json index 57369c5..d41fca0 100644 --- a/web/src/locales/ar.json +++ b/web/src/locales/ar.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "يرجى تسجيل الدخول ببيانات الاعتماد المناسبة للوصول إلى هذا المورد.", "unauthorizedTitle": "وصول غير مصرح به" }, + "import": { + "account": "الحساب", + "chooseFiles": "3. اختر الملفات", + "completed": "اكتمل الاستيراد", + "description": "استيراد ملفات البريد إلى حساب محلي (NoSync). للملفات الكبيرة، استخدم CLI.", + "detectedFolder": "مكتشف", + "detectedFrom": "مكتشف من", + "dropHere": "أفلت ملفات .eml / .mbox هنا", + "failed": "فشل الاستيراد", + "failedCount": "{{count}} فشل", + "failedDetails": "العناصر الفاشلة", + "folder": "المجلد", + "folderMethod": "2. اختر طريقة تحديد المجلد", + "folderMethodDesc": "كيف سيتم تحديد مجلد البريد المستهدف؟", + "importHistory": "سجل الاستيراد", + "limits": "الحد الأقصى: EML 100 م.ب · MBOX 1 غ.ب. للملفات الأكبر ← CLI.", + "modeCustom": "أدخل اسم مجلد مخصص", + "modeCustomDesc": "اكتب اسم مجلد البريد المستهدف يدويًا.", + "modeExisting": "اختر من صناديق البريد الحالية", + "modeExistingDesc": "حدد أحد صناديق البريد الموجودة بالفعل في هذا الحساب.", + "modeHeader": "كشف تلقائي من ترويسات البريد", + "modeHeaderDesc": "قراءة X-Gmail-Labels / X-Bichon-Metadata من الملف. يعتمد على اسم الملف كبديل.", + "noAccountFound": "لم يتم العثور على حساب.", + "noFileYet": "لم يتم اختيار أي ملف بعد", + "noMailboxFound": "لم يتم العثور على صندوق بريد.", + "noMailboxes": "لم يتم العثور على صناديق بريد في هذا الحساب.", + "orClick": "أو انقر للتصفح", + "processed": "تم معالجة {{current}} / {{total}}", + "processing": "جاري المعالجة…", + "searchAccount": "البحث عن الحسابات...", + "searchMailbox": "البحث عن صناديق البريد...", + "selectAccount": "اختر حسابًا", + "selectAccountFirst": "يرجى اختيار حساب أولاً.", + "selectMailbox": "اختر صندوق بريد...", + "source": "المصدر", + "startImport": "استيراد", + "successCount": "تم استيراد {{count}}", + "target": "1. اختر الحساب المستهدف", + "title": "استيراد", + "uploading": "جاري الرفع…", + "uploadingFile": "جاري رفع الملف", + "willImportTo": "سيتم الاستيراد إلى" + }, "mail": { "account": "الحساب", "attachments": "المرفقات", diff --git a/web/src/locales/da.json b/web/src/locales/da.json index bb80623..353eb89 100644 --- a/web/src/locales/da.json +++ b/web/src/locales/da.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "Log venligst ind med passende legitimationsoplysninger for at få adgang til denne ressource.", "unauthorizedTitle": "Uautoriseret adgang" }, + "import": { + "account": "Konto", + "chooseFiles": "3. Vælg filer", + "completed": "Import fuldført", + "description": "Importer e-mailfiler til en lokal konto (NoSync). Brug CLI til større filer.", + "detectedFolder": "Registreret", + "detectedFrom": "Registreret fra", + "dropHere": "Slip .eml / .mbox-filer her", + "failed": "Import mislykkedes", + "failedCount": "{{count}} fejlet", + "failedDetails": "Fejlede elementer", + "folder": "Mappe", + "folderMethod": "2. Vælg mappemetode", + "folderMethodDesc": "Hvordan skal destinationsmappen bestemmes?", + "importHistory": "Importhistorik", + "limits": "Maks: EML 100 MB · MBOX 1 GB. Større filer → CLI.", + "modeCustom": "Indtast et brugerdefineret mappenavn", + "modeCustomDesc": "Skriv navnet på destinationsmappen manuelt.", + "modeExisting": "Vælg fra eksisterende postkasser", + "modeExistingDesc": "Vælg en af de postkasser, der allerede findes på denne konto.", + "modeHeader": "Registrer automatisk fra e-mailheadere", + "modeHeaderDesc": "Læs X-Gmail-Labels / X-Bichon-Metadata fra filen. Falder tilbage til filnavn.", + "noAccountFound": "Ingen konto fundet.", + "noFileYet": "Ingen fil valgt endnu", + "noMailboxFound": "Ingen postkasse fundet.", + "noMailboxes": "Ingen postkasser fundet på denne konto.", + "orClick": "eller klik for at gennemse", + "processed": "{{current}} / {{total}} behandlet", + "processing": "Behandler…", + "searchAccount": "Søg efter konti...", + "searchMailbox": "Søg efter postkasser...", + "selectAccount": "Vælg en konto", + "selectAccountFirst": "Vælg en konto først.", + "selectMailbox": "Vælg en postkasse...", + "source": "kilde", + "startImport": "Importer", + "successCount": "{{count}} importeret", + "target": "1. Vælg målkonto", + "title": "Import", + "uploading": "Uploader…", + "uploadingFile": "Uploader fil", + "willImportTo": "Vil blive importeret til" + }, "mail": { "account": "Konto", "attachments": "Vedhæftninger", diff --git a/web/src/locales/de.json b/web/src/locales/de.json index 52d9ed4..cb67d32 100644 --- a/web/src/locales/de.json +++ b/web/src/locales/de.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "Bitte melden Sie sich mit gültigen Anmeldeinformationen an, um auf diese Ressource zuzugreifen.", "unauthorizedTitle": "Nicht autorisierter Zugriff" }, + "import": { + "account": "Konto", + "chooseFiles": "3. Dateien auswählen", + "completed": "Import abgeschlossen", + "description": "E-Mail-Dateien in ein lokales Konto (NoSync) importieren. Für größere Dateien CLI nutzen.", + "detectedFolder": "Erkannt", + "detectedFrom": "Erkannt aus", + "dropHere": ".eml / .mbox-Dateien hierher ziehen", + "failed": "Import fehlgeschlagen", + "failedCount": "{{count}} fehlgeschlagen", + "failedDetails": "Fehlgeschlagene Elemente", + "folder": "Ordner", + "folderMethod": "2. Ordnermethode wählen", + "folderMethodDesc": "Wie soll der Zielordner bestimmt werden?", + "importHistory": "Importverlauf", + "limits": "Max: EML 100 MB · MBOX 1 GB. Größere Dateien → CLI.", + "modeCustom": "Benutzerdefinierten Ordnernamen eingeben", + "modeCustomDesc": "Geben Sie den Namen des Zielordners manuell ein.", + "modeExisting": "Aus bestehenden Postfächern wählen", + "modeExistingDesc": "Wählen Sie ein bereits in diesem Konto vorhandenes Postfach aus.", + "modeHeader": "Automatisch aus E-Mail-Headern erkennen", + "modeHeaderDesc": "Liest X-Gmail-Labels / X-Bichon-Metadata aus der Datei. Fallback auf Dateiname.", + "noAccountFound": "Kein Konto gefunden.", + "noFileYet": "Noch keine Datei ausgewählt", + "noMailboxFound": "Kein Postfach gefunden.", + "noMailboxes": "Keine Postfächer in diesem Konto gefunden.", + "orClick": "oder zum Durchsuchen klicken", + "processed": "{{current}} / {{total}} verarbeitet", + "processing": "Verarbeitung…", + "searchAccount": "Konten suchen...", + "searchMailbox": "Postfächer suchen...", + "selectAccount": "Konto auswählen", + "selectAccountFirst": "Wählen Sie zuerst ein Konto aus.", + "selectMailbox": "Postfach auswählen...", + "source": "Quelle", + "startImport": "Importieren", + "successCount": "{{count}} importiert", + "target": "1. Zielkonto auswählen", + "title": "Import", + "uploading": "Hochladen…", + "uploadingFile": "Datei wird hochgeladen", + "willImportTo": "Wird importiert in" + }, "mail": { "account": "Konto", "attachments": "Anhänge", diff --git a/web/src/locales/en.json b/web/src/locales/en.json index 55da1ef..15aec34 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -591,6 +591,49 @@ "unauthorizedDesc": "Please log in with the appropriate credentials to access this resource.", "unauthorizedTitle": "Unauthorized Access" }, + "import": { + "account": "Account", + "chooseFiles": "3. Choose files", + "completed": "Import complete", + "description": "Import email files into a local account (NoSync). For larger files, use the CLI.", + "detectedFolder": "Detected", + "detectedFrom": "Detected from", + "dropHere": "Drop .eml / .mbox files here", + "failed": "Import failed", + "failedCount": "{{count}} failed", + "failedDetails": "Failed items", + "folder": "Folder", + "folderMethod": "2. Choose folder method", + "folderMethodDesc": "How should the target mail folder be determined?", + "importHistory": "Import History", + "limits": "Max: EML 100 MB · MBOX 1 GB. Larger files → CLI.", + "modeCustom": "Enter a custom folder name", + "modeCustomDesc": "Manually type the target mail folder name.", + "modeExisting": "Choose from existing mailboxes", + "modeExistingDesc": "Select one of the mailboxes already present in this account.", + "modeHeader": "Auto-detect from email headers", + "modeHeaderDesc": "Read X-Gmail-Labels / X-Bichon-Metadata from the uploaded file. Falls back to filename.", + "noAccountFound": "No account found.", + "noFileYet": "No file selected yet", + "noMailboxFound": "No mailbox found.", + "noMailboxes": "No mailboxes found in this account.", + "orClick": "or click to browse", + "processed": "{{current}} / {{total}} processed", + "processing": "Processing…", + "searchAccount": "Search accounts...", + "searchMailbox": "Search mailboxes...", + "selectAccount": "Select an account", + "selectAccountFirst": "Select an account first.", + "selectMailbox": "Select a mailbox...", + "source": "source", + "startImport": "Import", + "successCount": "{{count}} imported", + "target": "1. Select target account", + "title": "Import", + "uploading": "Uploading…", + "uploadingFile": "Uploading file", + "willImportTo": "Will import to" + }, "mail": { "account": "Account", "attachments": "Attachments", diff --git a/web/src/locales/es.json b/web/src/locales/es.json index 34e1e27..7b3c68f 100644 --- a/web/src/locales/es.json +++ b/web/src/locales/es.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "Inicia sesión con credenciales válidas para acceder a este recurso.", "unauthorizedTitle": "Acceso no autorizado" }, + "import": { + "account": "Cuenta", + "chooseFiles": "3. Seleccionar archivos", + "completed": "Importación completada", + "description": "Importar archivos de correo a una cuenta local (NoSync). Para archivos más grandes, use la CLI.", + "detectedFolder": "Detectado", + "detectedFrom": "Detectado de", + "dropHere": "Arrastre archivos .eml / .mbox aquí", + "failed": "Error al importar", + "failedCount": "{{count}} fallidos", + "failedDetails": "Elementos fallidos", + "folder": "Carpeta", + "folderMethod": "2. Elegir método de carpeta", + "folderMethodDesc": "¿Cómo se debe determinar la carpeta de correo de destino?", + "importHistory": "Historial de importación", + "limits": "Máx: EML 100 MB · MBOX 1 GB. Archivos más grandes → CLI.", + "modeCustom": "Ingresar un nombre de carpeta personalizado", + "modeCustomDesc": "Escriba manualmente el nombre de la carpeta de destino.", + "modeExisting": "Elegir de buzones existentes", + "modeExistingDesc": "Seleccione uno de los buzones ya presentes en esta cuenta.", + "modeHeader": "Detectar automáticamente de cabeceras", + "modeHeaderDesc": "Lee X-Gmail-Labels / X-Bichon-Metadata del archivo. Alternativa: nombre del archivo.", + "noAccountFound": "No se encontró ninguna cuenta.", + "noFileYet": "Ningún archivo seleccionado", + "noMailboxFound": "No se encontró ningún buzón.", + "noMailboxes": "No se encontraron buzones en esta cuenta.", + "orClick": "o haga clic para buscar", + "processed": "{{current}} / {{total}} procesados", + "processing": "Procesando…", + "searchAccount": "Buscar cuentas...", + "searchMailbox": "Buscar buzones...", + "selectAccount": "Seleccionar una cuenta", + "selectAccountFirst": "Seleccione una cuenta primero.", + "selectMailbox": "Seleccionar buzón...", + "source": "origen", + "startImport": "Importar", + "successCount": "{{count}} importados", + "target": "1. Seleccionar cuenta de destino", + "title": "Importar", + "uploading": "Subiendo…", + "uploadingFile": "Subiendo archivo", + "willImportTo": "Se importará a" + }, "mail": { "account": "Cuenta", "attachments": "Adjuntos", diff --git a/web/src/locales/fi.json b/web/src/locales/fi.json index 0222f11..4cbbf4a 100644 --- a/web/src/locales/fi.json +++ b/web/src/locales/fi.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "Kirjaudu sisään oikeilla tunnuksilla päästäksesi tähän resurssiin.", "unauthorizedTitle": "Luvaton pääsy" }, + "import": { + "account": "Tili", + "chooseFiles": "3. Valitse tiedostot", + "completed": "Tuonti valmis", + "description": "Tuo sähköpostitiedostoja paikalliselle tilille (NoSync). Käytä CLI:tä suuremmille tiedostoille.", + "detectedFolder": "Tunnistettu", + "detectedFrom": "Tunnistettu lähteestä", + "dropHere": "Pudota .eml / .mbox -tiedostot tähän", + "failed": "Tuonti epäonnistui", + "failedCount": "{{count}} epäonnistui", + "failedDetails": "Epäonnistuneet kohteet", + "folder": "Kansio", + "folderMethod": "2. Valitse kansiomenetelmä", + "folderMethodDesc": "Miten kohdekansio tulisi määrittää?", + "importHistory": "Tuontihistoria", + "limits": "Max: EML 100 MB · MBOX 1 GB. Suuremmat tiedostot → CLI.", + "modeCustom": "Syötä mukautettu kansion nimi", + "modeCustomDesc": "Kirjoita kohdekansion nimi manuaalisesti.", + "modeExisting": "Valitse olemassa olevista postilaatikoista", + "modeExistingDesc": "Valitse jokin tällä tilillä jo olevista postilaatikoista.", + "modeHeader": "Tunnista automaattisesti sähköpostiviestien otsakkeista", + "modeHeaderDesc": "Lue X-Gmail-Labels / X-Bichon-Metadata tiedostosta. Varajärjestelmänä tiedostonimi.", + "noAccountFound": "Tiliä ei löytynyt.", + "noFileYet": "Ei valittua tiedostoa", + "noMailboxFound": "Postilaatikkoa ei löytynyt.", + "noMailboxes": "Tältä tililtä ei löytynyt postilaatikoita.", + "orClick": "tai napsauta selataksesi", + "processed": "{{current}} / {{total}} käsitelty", + "processing": "Käsitellään…", + "searchAccount": "Etsi tilejä...", + "searchMailbox": "Etsi postilaatikoita...", + "selectAccount": "Valitse tili", + "selectAccountFirst": "Valitse ensin tili.", + "selectMailbox": "Valitse postilaatikko...", + "source": "lähde", + "startImport": "Tuo", + "successCount": "{{count}} tuotu", + "target": "1. Valitse kohdetili", + "title": "Tuonti", + "uploading": "Ladataan…", + "uploadingFile": "Ladataan tiedostoa", + "willImportTo": "Tuodaan kohteeseen" + }, "mail": { "account": "Tili", "attachments": "Liitteet", diff --git a/web/src/locales/fr.json b/web/src/locales/fr.json index 758f146..82a85a8 100644 --- a/web/src/locales/fr.json +++ b/web/src/locales/fr.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "Veuillez vous connecter avec les informations d'identification appropriées pour accéder à cette ressource.", "unauthorizedTitle": "Accès Non Autorisé" }, + "import": { + "account": "Compte", + "chooseFiles": "3. Choisir les fichiers", + "completed": "Importation terminée", + "description": "Importer des fichiers d'e-mails dans un compte local (NoSync). Pour les gros fichiers, utilisez le CLI.", + "detectedFolder": "Détecté", + "detectedFrom": "Détecté depuis", + "dropHere": "Déposez les fichiers .eml / .mbox ici", + "failed": "Échec de l'importation", + "failedCount": "{{count}} échoué(s)", + "failedDetails": "Éléments en échec", + "folder": "Dossier", + "folderMethod": "2. Choisir la méthode de dossier", + "folderMethodDesc": "Comment le dossier de destination doit-il être déterminé ?", + "importHistory": "Historique d'importation", + "limits": "Max : EML 100 MB · MBOX 1 GB. Fichiers plus volumineux → CLI.", + "modeCustom": "Saisir un nom de dossier personnalisé", + "modeCustomDesc": "Saisissez manuellement le nom du dossier de destination.", + "modeExisting": "Choisir parmi les boîtes existantes", + "modeExistingDesc": "Sélectionnez l'une des boîtes aux lettres déjà présentes dans ce compte.", + "modeHeader": "Détection auto depuis les en-têtes", + "modeHeaderDesc": "Lit X-Gmail-Labels / X-Bichon-Metadata depuis le fichier. Alternative : nom du fichier.", + "noAccountFound": "Aucun compte trouvé.", + "noFileYet": "Aucun fichier sélectionné", + "noMailboxFound": "Aucune boîte aux lettres trouvée.", + "noMailboxes": "Aucune boîte aux lettres trouvée dans ce compte.", + "orClick": "ou cliquez pour parcourir", + "processed": "{{current}} / {{total}} traités", + "processing": "Traitement…", + "searchAccount": "Rechercher des comptes...", + "searchMailbox": "Rechercher des boîtes...", + "selectAccount": "Sélectionner un compte", + "selectAccountFirst": "Sélectionnez d'abord un compte.", + "selectMailbox": "Sélectionner une boîte...", + "source": "source", + "startImport": "Importer", + "successCount": "{{count}} importé(s)", + "target": "1. Sélectionner le compte cible", + "title": "Importer", + "uploading": "Téléversement…", + "uploadingFile": "Téléversement du fichier", + "willImportTo": "Sera importé dans" + }, "mail": { "account": "Compte", "attachments": "Pièces jointes", diff --git a/web/src/locales/it.json b/web/src/locales/it.json index e54456c..b127b2b 100644 --- a/web/src/locales/it.json +++ b/web/src/locales/it.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "Accedi con le credenziali corrette per accedere a questa risorsa.", "unauthorizedTitle": "Accesso non Autorizzato" }, + "import": { + "account": "Account", + "chooseFiles": "3. Scegli i file", + "completed": "Importazione completata", + "description": "Importa file email in un account locale (NoSync). Per file più grandi, usa la CLI.", + "detectedFolder": "Rilevato", + "detectedFrom": "Rilevato da", + "dropHere": "Trascina i file .eml / .mbox qui", + "failed": "Importazione fallita", + "failedCount": "{{count}} falliti", + "failedDetails": "Elementi falliti", + "folder": "Cartella", + "folderMethod": "2. Scegli il metodo della cartella", + "folderMethodDesc": "Come determinare la cartella di posta di destinazione?", + "importHistory": "Cronologia importazioni", + "limits": "Max: EML 100 MB · MBOX 1 GB. File più grandi → CLI.", + "modeCustom": "Inserisci un nome cartella personalizzato", + "modeCustomDesc": "Digita manualmente il nome della cartella di destinazione.", + "modeExisting": "Scegli tra le caselle esistenti", + "modeExistingDesc": "Seleziona una delle caselle già presenti in questo account.", + "modeHeader": "Rilevamento automatico dagli header", + "modeHeaderDesc": "Legge X-Gmail-Labels / X-Bichon-Metadata dal file. Alternativa: nome del file.", + "noAccountFound": "Nessun account trovato.", + "noFileYet": "Nessun file selezionato", + "noMailboxFound": "Nessuna casella postale trouvata.", + "noMailboxes": "Nessuna casella postale trovata in questo account.", + "orClick": "o clicca per sfogliare", + "processed": "{{current}} / {{total}} elaborati", + "processing": "Elaborazione…", + "searchAccount": "Cerca account...", + "searchMailbox": "Cerca caselle postali...", + "selectAccount": "Seleziona un account", + "selectAccountFirst": "Seleziona prima un account.", + "selectMailbox": "Seleziona una casella...", + "source": "origine", + "startImport": "Importa", + "successCount": "{{count}} importati", + "target": "1. Seleziona account di destinazione", + "title": "Importa", + "uploading": "Caricamento…", + "uploadingFile": "Caricamento del file", + "willImportTo": "Sarà importato in" + }, "mail": { "account": "Account", "attachments": "Allegati", diff --git a/web/src/locales/jp.json b/web/src/locales/jp.json index 2895a0e..72755bd 100644 --- a/web/src/locales/jp.json +++ b/web/src/locales/jp.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "このリソースにアクセスするには、適切な資格情報でログインしてください。", "unauthorizedTitle": "不正アクセス" }, + "import": { + "account": "アカウント", + "chooseFiles": "3. ファイルを選択", + "completed": "インポート完了", + "description": "NoSyncローカルアカウントにメールファイルをインポートします。大容量ファイルはCLIを使用してください。", + "detectedFolder": "放出演出", + "detectedFrom": "検出元:", + "dropHere": "ここに .eml / .mbox ファイルをドロップ", + "failed": "インポート失敗", + "failedCount": "{{count}} 件の失敗", + "failedDetails": "失敗したアイテム", + "folder": "フォルダ", + "folderMethod": "2. フォルダ指定方法の選択", + "folderMethodDesc": "インポート先のフォルダをどのように決定しますか?", + "importHistory": "インポート履歴", + "limits": "上限: EML 100 MB · MBOX 1 GB。これ以上のサイズは → CLIへ。", + "modeCustom": "カスタムフォルダ名を入力", + "modeCustomDesc": "インポート先のフォルダ名を手動で入力します。", + "modeExisting": "既存のメールボックスから選択", + "modeExistingDesc": "このアカウントに既に存在するメールボックスから選択します。", + "modeHeader": "メールヘッダーから自动検出", + "modeHeaderDesc": "ファイルから X-Gmail-Labels / X-Bichon-Metadata を読み取ります。ない場合はファイル名を使用します。", + "noAccountFound": "アカウントが見つかりません。", + "noFileYet": "ファイルが選択されていません", + "noMailboxFound": "メールボックスが見つかりません。", + "noMailboxes": "このアカウントにメールボックスが見つかりません。", + "orClick": "またはクリックしてファイルを選択", + "processed": "{{current}} / {{total}} 件を処理済み", + "processing": "処理中…", + "searchAccount": "アカウントを検索...", + "searchMailbox": "メールボックスを検索...", + "selectAccount": "アカウントを選択", + "selectAccountFirst": "最初にアカウントを選択してください。", + "selectMailbox": "メールボックスを選択...", + "source": "ソース", + "startImport": "インポート", + "successCount": "{{current}} 件を処理済み", + "target": "1. 対象アカウントの選択", + "title": "インポート", + "uploading": "アップロード中…", + "uploadingFile": "ファイルをアップロード中", + "willImportTo": "インポート先:" + }, "mail": { "account": "アカウント", "attachments": "添付ファイル", diff --git a/web/src/locales/ko.json b/web/src/locales/ko.json index 373bf75..4b5c630 100644 --- a/web/src/locales/ko.json +++ b/web/src/locales/ko.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "이 리소스에 접근하려면 적절한 자격 증명으로 로그인하십시오.", "unauthorizedTitle": "승인되지 않은 접근" }, + "import": { + "account": "계정", + "chooseFiles": "3. 파일 선택", + "completed": "가져오기 완료", + "description": "로컬 계정(NoSync)으로 이메일 파일을 가져옵니다. 대용량 파일은 CLI를 사용하세요.", + "detectedFolder": "감지됨", + "detectedFrom": "감지 대상:", + "dropHere": "여기에 .eml / .mbox 파일 끌어놓기", + "failed": "가져오기 실패", + "failedCount": "{{count}}개 실패", + "failedDetails": "실패한 항목", + "folder": "폴더", + "folderMethod": "2. 폴더 지정 방식 선택", + "folderMethodDesc": "가져올 메일 폴더를 어떻게 결정하시겠습니까?", + "importHistory": "가져오기 기록", + "limits": "제한: EML 100 MB · MBOX 1 GB. 더 큰 파일은 → CLI 사용.", + "modeCustom": "사용자 지정 폴더 이름 입력", + "modeCustomDesc": "가져올 메일 폴더 이름을 수동으로 입력합니다.", + "modeExisting": "기존 편지함에서 선택", + "modeExistingDesc": "이 계정에 이미 존재하는 편지함 중 하나를 선택합니다.", + "modeHeader": "이메일 헤더에서 자동 감지", + "modeHeaderDesc": "파일에서 X-Gmail-Labels / X-Bichon-Metadata를 읽습니다. 없을 경우 파일명을 사용합니다.", + "noAccountFound": "계정을 찾을 수 없습니다.", + "noFileYet": "선택된 파일 없음", + "noMailboxFound": "편지함을 찾을 수 없습니다.", + "noMailboxes": "이 계정에서 편지함을 찾을 수 없습니다.", + "orClick": "또는 클릭하여 찾아보기", + "processed": "{{current}} / {{total}} 처리됨", + "processing": "처리 중…", + "searchAccount": "계정 검색...", + "searchMailbox": "편지함 검색...", + "selectAccount": "계정 선택", + "selectAccountFirst": "계정을 먼저 선택해 주세요.", + "selectMailbox": "편지함 선택...", + "source": "소스", + "startImport": "가져오기", + "successCount": "{{count}}개 가져옴", + "target": "1. 대상 계정 선택", + "title": "가져오기", + "uploading": "업로드 중…", + "uploadingFile": "파일 업로드 중", + "willImportTo": "가져올 위치:" + }, "mail": { "account": "계정", "attachments": "첨부 파일", diff --git a/web/src/locales/nl.json b/web/src/locales/nl.json index a2b5cc9..0fea311 100644 --- a/web/src/locales/nl.json +++ b/web/src/locales/nl.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "Log in met de juiste inloggegevens om deze bron te benaderen.", "unauthorizedTitle": "Ongeautoriseerde Toegang" }, + "import": { + "account": "Account", + "chooseFiles": "3. Kies bestanden", + "completed": "Import voltooid", + "description": "Importeer e-mailbestanden in een lokaal account (NoSync). Gebruik de CLI voor grotere bestanden.", + "detectedFolder": "Gedetecteerd", + "detectedFrom": "Gedetecteerd uit", + "dropHere": "Sleep .eml / .mbox bestanden hierheen", + "failed": "Import mislukt", + "failedCount": "{{count}} mislukt", + "failedDetails": "Mislukte items", + "folder": "Map", + "folderMethod": "2. Kies mapmethode", + "folderMethodDesc": "Hoe moet de doelmap voor e-mail worden bepaald?", + "importHistory": "Importgeschiedenis", + "limits": "Max: EML 100 MB · MBOX 1 GB. Grotere bestanden → CLI.", + "modeCustom": "Voer een aangepaste mapnaam in", + "modeCustomDesc": "Typ handmatig de naam van de doelmap.", + "modeExisting": "Kies uit bestaande mailboxen", + "modeExistingDesc": "Selecteer een van de mailboxen die al in dit account aanwezig zijn.", + "modeHeader": "Automatisch detecteren uit e-mailheaders", + "modeHeaderDesc": "Leest X-Gmail-Labels / X-Bichon-Metadata uit het bestand. Valt terug op bestandsnaam.", + "noAccountFound": "Geen account gevonden.", + "noFileYet": "Nog geen bestand geselecteerd", + "noMailboxFound": "Geen mailbox gevonden.", + "noMailboxes": "Geen mailboxen gevonden in dit account.", + "orClick": "of klik om te bladeren", + "processed": "{{current}} / {{total}} verwerkt", + "processing": "Verwerken…", + "searchAccount": "Accounts zoeken...", + "searchMailbox": "Mailboxen zoeken...", + "selectAccount": "Selecteer een account", + "selectAccountFirst": "Selecteer eerst een account.", + "selectMailbox": "Selecteer een mailbox...", + "source": "bron", + "startImport": "Importeren", + "successCount": "{{count}} geïmporteerd", + "target": "1. Selecteer doelaccount", + "title": "Importeren", + "uploading": "Uploaden…", + "uploadingFile": "Bestand uploaden", + "willImportTo": "Zal importeren naar" + }, "mail": { "account": "Account", "attachments": "Bijlagen", diff --git a/web/src/locales/no.json b/web/src/locales/no.json index c17f218..cca5032 100644 --- a/web/src/locales/no.json +++ b/web/src/locales/no.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "Vennligst logg inn med riktig legitimasjon for å få tilgang til denne ressursen.", "unauthorizedTitle": "Uautorisert tilgang" }, + "import": { + "account": "Konto", + "chooseFiles": "3. Velg filer", + "completed": "Import fullført", + "description": "Importer e-postfiler til en lokal konto (NoSync). Bruk CLI for større filer.", + "detectedFolder": "Registrert", + "detectedFrom": "Registrert fra", + "dropHere": "Slipp .eml / .mbox-filer her", + "failed": "Import mislyktes", + "failedCount": "{{count}} feilet", + "failedDetails": "Feilede elementer", + "folder": "Mappe", + "folderMethod": "2. Velg mappemetode", + "folderMethodDesc": "Hvordan skal målmappen for e-post bestemmes?", + "importHistory": "Importhistorikk", + "limits": "Maks: EML 100 MB · MBOX 1 GB. Større filer → CLI.", + "modeCustom": "Skriv inn et egendefinert mappenavn", + "modeCustomDesc": "Skriv inn navnet på målmappen manuelt.", + "modeExisting": "Velg fra eksisterende postbokser", + "modeExistingDesc": "Velg en av postboksene som allerede finnes på denne konto.", + "modeHeader": "Registrer automatisk fra e-postheadere", + "modeHeaderDesc": "Leser X-Gmail-Labels / X-Bichon-Metadata fra filen. Faller tillbaka til filnavn.", + "noAccountFound": "Ingen konto fundet.", + "noFileYet": "Ingen fil valgt ennå", + "noMailboxFound": "Ingen postboks funnet.", + "noMailboxes": "Ingen postbokser funnet på denne kontoen.", + "orClick": "eller klikk for å bla gjennom", + "processed": "{{current}} / {{total}} behandlet", + "processing": "Behandler…", + "searchAccount": "Søk etter kontoer...", + "searchMailbox": "Søk etter postbokser...", + "selectAccount": "Velg en konto", + "selectAccountFirst": "Velg en konto først.", + "selectMailbox": "Velg en postboks...", + "source": "kilde", + "startImport": "Importer", + "successCount": "{{count}} importert", + "target": "1. Velg målkonto", + "title": "Import", + "uploading": "Laster opp…", + "uploadingFile": "Laster opp fil", + "willImportTo": "Vil bli importert til" + }, "mail": { "account": "Konto", "attachments": "Vedlegg", diff --git a/web/src/locales/pl.json b/web/src/locales/pl.json index cd2adb6..8cf4420 100644 --- a/web/src/locales/pl.json +++ b/web/src/locales/pl.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "Aby uzyskać dostęp do tego zasobu, zaloguj się przy użyciu odpowiednich danych uwierzytelniających", "unauthorizedTitle": "Dostęp nieautoryzowany" }, + "import": { + "account": "Konto", + "chooseFiles": "3. Wybierz pliki", + "completed": "Import zakończony", + "description": "Importuj pliki e-mail do konta lokalnego (NoSync). W przypadku większych plików użyj CLI.", + "detectedFolder": "Wykryto", + "detectedFrom": "Wykryto z", + "dropHere": "Upuść pliki .eml / .mbox tutaj", + "failed": "Import nie powiódł się", + "failedCount": "Niepowodzenie: {{count}}", + "failedDetails": "Nieudane elementy", + "folder": "Folder", + "folderMethod": "2. Wybierz metodę folderu", + "folderMethodDesc": "Jak ma zostać określony docelowy folder poczty?", + "importHistory": "Historia importu", + "limits": "Maks: EML 100 MB · MBOX 1 GB. Większe pliki → CLI.", + "modeCustom": "Wprowadź własną nazwę folderu", + "modeCustomDesc": "Ręcznie wpisz nazwę docelowego folderu poczty.", + "modeExisting": "Wybierz z istniejących skrzynek", + "modeExistingDesc": "Wybierz jedną ze skrzynek pocztowych już istniejących na tym koncie.", + "modeHeader": "Automatyczne wykrywanie z nagłówków", + "modeHeaderDesc": "Odczytaj X-Gmail-Labels / X-Bichon-Metadata z pliku. W przypadku braku użyta zostanie nazwa pliku.", + "noAccountFound": "Nie znaleziono konta.", + "noFileYet": "Nie wybrano jeszcze żadnego pliku", + "noMailboxFound": "Nie znaleziono skrzynki pocztowej.", + "noMailboxes": "Nie znaleziono skrzynek pocztowych na tym koncie.", + "orClick": "lub kliknij, aby przeglądać", + "processed": "Przetworzono: {{current}} / {{total}}", + "processing": "Przetwarzanie…", + "searchAccount": "Szukaj kont...", + "searchMailbox": "Szukaj skrzynek...", + "selectAccount": "Wybierz konto", + "selectAccountFirst": "Najpierw wybierz konto.", + "selectMailbox": "Wybierz skrzynkę...", + "source": "źródło", + "startImport": "Importuj", + "successCount": "Zaimportowano: {{count}}", + "target": "1. Wybierz konto docelowe", + "title": "Import", + "uploading": "Przesyłanie…", + "uploadingFile": "Przesyłanie pliku", + "willImportTo": "Zostanie zaimportowane do" + }, "mail": { "account": "Konto", "attachments": "Załączniki", diff --git a/web/src/locales/pt.json b/web/src/locales/pt.json index 913cd24..6aa6dfb 100644 --- a/web/src/locales/pt.json +++ b/web/src/locales/pt.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "Por favor, faça login com as credenciais apropriadas para acessar este recurso.", "unauthorizedTitle": "Acesso Não Autorizado" }, + "import": { + "account": "Conta", + "chooseFiles": "3. Escolher arquivos", + "completed": "Importação concluída", + "description": "Importar arquivos de e-mail para uma conta local (NoSync). Para arquivos maiores, use a CLI.", + "detectedFolder": "Detectado", + "detectedFrom": "Detectado de", + "dropHere": "Solte arquivos .eml / .mbox aqui", + "failed": "Falha na importação", + "failedCount": "{{count}} falharam", + "failedDetails": "Itens com falha", + "folder": "Pasta", + "folderMethod": "2. Escolher método de pasta", + "folderMethodDesc": "Como a pasta de e-mail de destino deve ser determinada?", + "importHistory": "Histórico de importação", + "limits": "Máx: EML 100 MB · MBOX 1 GB. Arquivos maiores → CLI.", + "modeCustom": "Digitar um nome de pasta personalizado", + "modeCustomDesc": "Digite manualmente o nome da pasta de e-mail de destino.", + "modeExisting": "Escolher a partir de caixas existentes", + "modeExistingDesc": "Selecione uma das caixas de correio já presentes nesta conta.", + "modeHeader": "Detectar automaticamente dos cabeçalhos", + "modeHeaderDesc": "Lê X-Gmail-Labels / X-Bichon-Metadata do arquivo. Alternativa: nome do arquivo.", + "noAccountFound": "Nenhuma conta encontrada.", + "noFileYet": "Nenhum arquivo selecionado", + "noMailboxFound": "Nenhuma caixa de correio encontrada.", + "noMailboxes": "Nenhuma caixa de correio encontrada nesta conta.", + "orClick": "ou clique para navegar", + "processed": "{{current}} / {{total}} processados", + "processing": "Processando…", + "searchAccount": "Buscar contas...", + "searchMailbox": "Buscar caixas de correio...", + "selectAccount": "Selecionar uma conta", + "selectAccountFirst": "Selecione uma conta primeiro.", + "selectMailbox": "Selecionar caixa de correio...", + "source": "origem", + "startImport": "Importar", + "successCount": "{{count}} importados", + "target": "1. Selecionar conta de destino", + "title": "Importar", + "uploading": "Enviando…", + "uploadingFile": "Enviando arquivo", + "willImportTo": "Será importado para" + }, "mail": { "account": "Conta", "attachments": "Anexos", diff --git a/web/src/locales/ru.json b/web/src/locales/ru.json index a56e008..a9ef03c 100644 --- a/web/src/locales/ru.json +++ b/web/src/locales/ru.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "Пожалуйста, войдите с соответствующими учетными данными для доступа к этому ресурсу.", "unauthorizedTitle": "Несанкционированный доступ" }, + "import": { + "account": "Аккаунт", + "chooseFiles": "3. Выбрать файлы", + "completed": "Импорт завершен", + "description": "Импорт файлов писем в локальный аккаунт (NoSync). Для больших файлов используйте CLI.", + "detectedFolder": "Обнаружено", + "detectedFrom": "Обнаружено из", + "dropHere": "Перетащите файлы .eml / .mbox сюда", + "failed": "Ошибка импорта", + "failedCount": "Ошибок: {{count}}", + "failedDetails": "Неудачные элементы", + "folder": "Папка", + "folderMethod": "2. Выберите метод определения папки", + "folderMethodDesc": "Как следует определять целевую папку для писем?", + "importHistory": "История импорта", + "limits": "Макс: EML 100 МБ · MBOX 1 ГБ. Для больших файлов → CLI.", + "modeCustom": "Ввести имя папки вручную", + "modeCustomDesc": "Введите имя целевой папки вручную.", + "modeExisting": "Выбрать из существующих ящиков", + "modeExistingDesc": "Выберите один из почтовых ящиков, уже существующих в этом аккаунте.", + "modeHeader": "Автоопределение из заголовков писем", + "modeHeaderDesc": "Чтение X-Gmail-Labels / X-Bichon-Metadata из файла. Если их нет, используется имя файла.", + "noAccountFound": "Аккаунт не найден.", + "noFileYet": "Файл еще не выбран", + "noMailboxFound": "Почтовый ящик не найден.", + "noMailboxes": "В этом аккаунте не найдено почтовых ящиков.", + "orClick": "или нажмите для обзора", + "processed": "Обработано: {{current}} / {{total}}", + "processing": "Обработка…", + "searchAccount": "Поиск аккаунтов...", + "searchMailbox": "Поиск почтовых ящиков...", + "selectAccount": "Выберите аккаунт", + "selectAccountFirst": "Сначала выберите аккаунт.", + "selectMailbox": "Выберите почтовый ящик...", + "source": "источник", + "startImport": "Импортировать", + "successCount": "Импортировано: {{count}}", + "target": "1. Выберите целевой аккаунт", + "title": "Импорт", + "uploading": "Загрузка…", + "uploadingFile": "Загрузка файла", + "willImportTo": "Будет импортировано в" + }, "mail": { "account": "Аккаунт", "attachments": "Вложения", diff --git a/web/src/locales/sv.json b/web/src/locales/sv.json index d03460d..9632e8a 100644 --- a/web/src/locales/sv.json +++ b/web/src/locales/sv.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "Vänligen logga in med lämpliga uppgifter för att komma åt denna resurs.", "unauthorizedTitle": "Obehörig åtkomst" }, + "import": { + "account": "Konto", + "chooseFiles": "3. Välj filer", + "completed": "Import slutförd", + "description": "Importera e-postfiler till ett lokalt konto (NoSync). Använd CLI för större filer.", + "detectedFolder": "Identifierad", + "detectedFrom": "Identifierad från", + "dropHere": "Släpp .eml / .mbox-filer här", + "failed": "Import misslyckades", + "failedCount": "{{count}} misslyckades", + "failedDetails": "Misslyckade objekt", + "folder": "Mapp", + "folderMethod": "2. Välj mappemetod", + "folderMethodDesc": "Hur ska målmappen for e-post bestämmas?", + "importHistory": "Importhistorik", + "limits": "Max: EML 100 MB · MBOX 1 GB. Större filer → CLI.", + "modeCustom": "Ange ett anpassat mappnamn", + "modeCustomDesc": "Ange namnet på målmappen manuellt.", + "modeExisting": "Välj från befintliga brevlådor", + "modeExistingDesc": "Välj en av de brevlådor som redan finns på detta konto.", + "modeHeader": "Identifiera automatiskt från e-posthuvuden", + "modeHeaderDesc": "Läser X-Gmail-Labels / X-Bichon-Metadata från filen. Faller tillbaka på filnamn.", + "noAccountFound": "Inget konto hittades.", + "noFileYet": "Ingen fil har valts än", + "noMailboxFound": "Ingen brevlåda hittades.", + "noMailboxes": "Inga brevlådor hittades på detta konto.", + "orClick": "eller klicka för att bläddra", + "processed": "{{current}} / {{total}} behandlade", + "processing": "Behandlar…", + "searchAccount": "Sök konton...", + "searchMailbox": "Sök brevlådor...", + "selectAccount": "Välj ett konto", + "selectAccountFirst": "Välj ett konto först.", + "selectMailbox": "Välj en brevlåda...", + "source": "källa", + "startImport": "Importera", + "successCount": "{{count}} importerade", + "target": "1. Välj målkonto", + "title": "Import", + "uploading": "Laddar upp…", + "uploadingFile": "Laddar upp fil", + "willImportTo": "Kommer att importeras till" + }, "mail": { "account": "Konto", "attachments": "Bilagor", diff --git a/web/src/locales/zh-tw.json b/web/src/locales/zh-tw.json index 0544ced..437691a 100644 --- a/web/src/locales/zh-tw.json +++ b/web/src/locales/zh-tw.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "請使用正確的憑證登入,以存取此資源。", "unauthorizedTitle": "無權存取" }, + "import": { + "account": "帳戶", + "chooseFiles": "3. 選擇檔案", + "completed": "匯入完成", + "description": "將郵件檔案匯入至本地帳戶 (NoSync)。大檔案請使用 CLI 命令行工具。", + "detectedFolder": "已識別", + "detectedFrom": "識別自", + "dropHere": "將 .eml / .mbox 檔案拖曳到此處", + "failed": "匯入失敗", + "failedCount": "{{count}} 個失敗", + "failedDetails": "失敗詳情", + "folder": "資料夾", + "folderMethod": "2. 選擇資料夾比對策略", + "folderMethodDesc": "如何確定匯入 Target 郵件資料夾?", + "importHistory": "匯入歷史", + "limits": "限制:EML 100 MB · MBOX 1 GB。超過限制請使用 CLI。", + "modeCustom": "指定自訂資料夾名稱", + "modeCustomDesc": "手動輸入目標郵件資料夾的名稱。", + "modeExisting": "從現有郵箱中選擇", + "modeExistingDesc": "選擇該帳戶中已存在的郵箱資料夾。", + "modeHeader": "從郵件標頭自動識別", + "modeHeaderDesc": "讀取檔案中的 X-Gmail-Labels / X-Bichon-Metadata 標籤,未識別時預設使用檔案名稱。", + "noAccountFound": "未找到相關帳戶。", + "noFileYet": "尚未選擇任何檔案", + "noMailboxFound": "未找到郵箱。", + "noMailboxes": "該帳戶下未找到任何郵箱。", + "orClick": "或點擊瀏覽檔案", + "processed": "已處理 {{current}} / {{total}}", + "processing": "正在處理…", + "searchAccount": "搜尋帳戶...", + "searchMailbox": "搜尋郵箱...", + "selectAccount": "選擇帳戶", + "selectAccountFirst": "請先選擇一個帳戶。", + "selectMailbox": "選擇郵箱...", + "source": "來源", + "startImport": "開始匯入", + "successCount": "已成功匯入 {{count}} 封", + "target": "1. 選擇目標帳戶", + "title": "匯入郵件", + "uploading": "正在上傳…", + "uploadingFile": "正在上傳檔案", + "willImportTo": "將匯入至" + }, "mail": { "account": "帳號", "attachments": "附件", diff --git a/web/src/locales/zh.json b/web/src/locales/zh.json index 1cbb8b4..605c890 100644 --- a/web/src/locales/zh.json +++ b/web/src/locales/zh.json @@ -589,6 +589,49 @@ "unauthorizedDesc": "请使用适当的凭据登录以访问此资源。", "unauthorizedTitle": "未授权访问" }, + "import": { + "account": "账户", + "chooseFiles": "3. 选择文件", + "completed": "导入完成", + "description": "将邮件文件导入至本地账户 (NoSync)。大文件请使用 CLI 命令行工具。", + "detectedFolder": "已识别", + "detectedFrom": "识别自", + "dropHere": "将 .eml / .mbox 文件拖拽到此处", + "failed": "导入失败", + "failedCount": "{{count}} 个失败", + "failedDetails": "失败详情", + "folder": "文件夹", + "folderMethod": "2. 选择文件夹匹配策略", + "folderMethodDesc": "如何确定导入的目标邮件文件夹?", + "importHistory": "导入历史", + "limits": "限制:EML 100 MB · MBOX 1 GB。超过限制请使用 CLI。", + "modeCustom": "指定自定义文件夹名称", + "modeCustomDesc": "手动输入目标邮件文件夹的名称。", + "modeExisting": "从现有邮箱中选择", + "modeExistingDesc": "选择该账户中已存在的邮箱文件夹。", + "modeHeader": "从邮件标头自动识别", + "modeHeaderDesc": "读取文件中的 X-Gmail-Labels / X-Bichon-Metadata 标签,未识别时默认使用文件名。", + "noAccountFound": "未找到相关账户。", + "noFileYet": "尚未选择任何文件", + "noMailboxFound": "未找到邮箱。", + "noMailboxes": "该账户下未找到任何邮箱。", + "orClick": "或点击浏览文件", + "processed": "已处理 {{current}} / {{total}}", + "processing": "正在处理…", + "searchAccount": "搜索账户...", + "searchMailbox": "搜索邮箱...", + "selectAccount": "选择账户", + "selectAccountFirst": "请先选择一个账户。", + "selectMailbox": "选择邮箱...", + "source": "来源", + "startImport": "开始导入", + "successCount": "已成功导入 {{count}} 封", + "target": "1. 选择目标账户", + "title": "导入邮件", + "uploading": "正在上传…", + "uploadingFile": "正在上传文件", + "willImportTo": "将导入至" + }, "mail": { "account": "账户", "attachments": "附件", diff --git a/web/src/routeTree.gen.ts b/web/src/routeTree.gen.ts index 9feae38..64f735d 100644 --- a/web/src/routeTree.gen.ts +++ b/web/src/routeTree.gen.ts @@ -18,6 +18,7 @@ import { Route as AuthenticatedIndexImport } from './routes/_authenticated/index import { Route as authSignInImport } from './routes/(auth)/sign-in' import { Route as auth500Import } from './routes/(auth)/500' import { Route as AuthenticatedSearchIndexImport } from './routes/_authenticated/search/index' +import { Route as AuthenticatedImportIndexImport } from './routes/_authenticated/import/index' import { Route as AuthenticatedAttachmentIndexImport } from './routes/_authenticated/attachment/index' // Create Virtual Routes @@ -221,6 +222,12 @@ const AuthenticatedSearchIndexRoute = AuthenticatedSearchIndexImport.update({ getParentRoute: () => AuthenticatedRouteRoute, } as any) +const AuthenticatedImportIndexRoute = AuthenticatedImportIndexImport.update({ + id: '/import/', + path: '/import/', + getParentRoute: () => AuthenticatedRouteRoute, +} as any) + const AuthenticatedAttachmentIndexRoute = AuthenticatedAttachmentIndexImport.update({ id: '/attachment/', @@ -454,6 +461,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthenticatedAttachmentIndexImport parentRoute: typeof AuthenticatedRouteImport } + '/_authenticated/import/': { + id: '/_authenticated/import/' + path: '/import' + fullPath: '/import' + preLoaderRoute: typeof AuthenticatedImportIndexImport + parentRoute: typeof AuthenticatedRouteImport + } '/_authenticated/search/': { id: '/_authenticated/search/' path: '/search' @@ -561,6 +575,7 @@ interface AuthenticatedRouteRouteChildren { AuthenticatedUsersRouteLazyRoute: typeof AuthenticatedUsersRouteLazyRouteWithChildren AuthenticatedIndexRoute: typeof AuthenticatedIndexRoute AuthenticatedAttachmentIndexRoute: typeof AuthenticatedAttachmentIndexRoute + AuthenticatedImportIndexRoute: typeof AuthenticatedImportIndexRoute AuthenticatedSearchIndexRoute: typeof AuthenticatedSearchIndexRoute AuthenticatedAccountsIndexLazyRoute: typeof AuthenticatedAccountsIndexLazyRoute AuthenticatedApiDocsIndexLazyRoute: typeof AuthenticatedApiDocsIndexLazyRoute @@ -575,6 +590,7 @@ const AuthenticatedRouteRouteChildren: AuthenticatedRouteRouteChildren = { AuthenticatedUsersRouteLazyRouteWithChildren, AuthenticatedIndexRoute: AuthenticatedIndexRoute, AuthenticatedAttachmentIndexRoute: AuthenticatedAttachmentIndexRoute, + AuthenticatedImportIndexRoute: AuthenticatedImportIndexRoute, AuthenticatedSearchIndexRoute: AuthenticatedSearchIndexRoute, AuthenticatedAccountsIndexLazyRoute: AuthenticatedAccountsIndexLazyRoute, AuthenticatedApiDocsIndexLazyRoute: AuthenticatedApiDocsIndexLazyRoute, @@ -606,6 +622,7 @@ export interface FileRoutesByFullPath { '/users/api-tokens': typeof AuthenticatedUsersApiTokensLazyRoute '/users/roles': typeof AuthenticatedUsersRolesLazyRoute '/attachment': typeof AuthenticatedAttachmentIndexRoute + '/import': typeof AuthenticatedImportIndexRoute '/search': typeof AuthenticatedSearchIndexRoute '/accounts': typeof AuthenticatedAccountsIndexLazyRoute '/api-docs': typeof AuthenticatedApiDocsIndexLazyRoute @@ -632,6 +649,7 @@ export interface FileRoutesByTo { '/users/api-tokens': typeof AuthenticatedUsersApiTokensLazyRoute '/users/roles': typeof AuthenticatedUsersRolesLazyRoute '/attachment': typeof AuthenticatedAttachmentIndexRoute + '/import': typeof AuthenticatedImportIndexRoute '/search': typeof AuthenticatedSearchIndexRoute '/accounts': typeof AuthenticatedAccountsIndexLazyRoute '/api-docs': typeof AuthenticatedApiDocsIndexLazyRoute @@ -663,6 +681,7 @@ export interface FileRoutesById { '/_authenticated/users/api-tokens': typeof AuthenticatedUsersApiTokensLazyRoute '/_authenticated/users/roles': typeof AuthenticatedUsersRolesLazyRoute '/_authenticated/attachment/': typeof AuthenticatedAttachmentIndexRoute + '/_authenticated/import/': typeof AuthenticatedImportIndexRoute '/_authenticated/search/': typeof AuthenticatedSearchIndexRoute '/_authenticated/accounts/': typeof AuthenticatedAccountsIndexLazyRoute '/_authenticated/api-docs/': typeof AuthenticatedApiDocsIndexLazyRoute @@ -694,6 +713,7 @@ export interface FileRouteTypes { | '/users/api-tokens' | '/users/roles' | '/attachment' + | '/import' | '/search' | '/accounts' | '/api-docs' @@ -719,6 +739,7 @@ export interface FileRouteTypes { | '/users/api-tokens' | '/users/roles' | '/attachment' + | '/import' | '/search' | '/accounts' | '/api-docs' @@ -748,6 +769,7 @@ export interface FileRouteTypes { | '/_authenticated/users/api-tokens' | '/_authenticated/users/roles' | '/_authenticated/attachment/' + | '/_authenticated/import/' | '/_authenticated/search/' | '/_authenticated/accounts/' | '/_authenticated/api-docs/' @@ -807,6 +829,7 @@ export const routeTree = rootRoute "/_authenticated/users", "/_authenticated/", "/_authenticated/attachment/", + "/_authenticated/import/", "/_authenticated/search/", "/_authenticated/accounts/", "/_authenticated/api-docs/", @@ -897,6 +920,10 @@ export const routeTree = rootRoute "filePath": "_authenticated/attachment/index.tsx", "parent": "/_authenticated" }, + "/_authenticated/import/": { + "filePath": "_authenticated/import/index.tsx", + "parent": "/_authenticated" + }, "/_authenticated/search/": { "filePath": "_authenticated/search/index.tsx", "parent": "/_authenticated" diff --git a/web/src/routes/_authenticated/import/index.tsx b/web/src/routes/_authenticated/import/index.tsx new file mode 100644 index 0000000..8bc207a --- /dev/null +++ b/web/src/routes/_authenticated/import/index.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' +import ImportPage from '@/features/import' + +export const Route = createFileRoute('/_authenticated/import/')({ + component: ImportPage, +})