use std::env;
use std::path::Path;
use std::process::Stdio;
use tempfile::TempDir;
use tokio::fs::{self, File};
use tokio::io::AsyncWriteExt;
use tokio::process::Command;
use url::Url;
mod error;
pub use error::{ConvertError, ConvertResult};
#[derive(Debug, Clone)]
pub struct ConvertOptions {
pub async_times: u32,
pub async_interval: u64,
pub tmp_prefix: Option<String>,
pub soffice_binary_paths: Option<Vec<String>>,
pub input_format: Option<String>,
}
impl Default for ConvertOptions {
fn default() -> Self {
Self {
async_times: 3,
async_interval: 200,
tmp_prefix: Some("libreoffice_convert_".to_string()),
soffice_binary_paths: None,
input_format: None,
}
}
}
impl ConvertOptions {
pub fn new() -> Self {
Self::default()
}
pub fn with_async_times(mut self, times: u32) -> Self {
self.async_times = times;
self
}
pub fn with_async_interval(mut self, interval_ms: u64) -> Self {
self.async_interval = interval_ms;
self
}
pub fn with_tmp_prefix<S: Into<String>>(mut self, prefix: S) -> Self {
self.tmp_prefix = Some(prefix.into());
self
}
pub fn with_soffice_paths(mut self, paths: Vec<String>) -> Self {
self.soffice_binary_paths = Some(paths);
self
}
pub fn add_soffice_path<S: Into<String>>(mut self, path: S) -> Self {
let mut paths = self.soffice_binary_paths.unwrap_or_default();
paths.push(path.into());
self.soffice_binary_paths = Some(paths);
self
}
pub fn with_input_format<S: Into<String>>(mut self, format: S) -> Self {
self.input_format = Some(format.into());
self
}
}
fn is_image_file(path: &str) -> bool {
let path_lower = path.to_lowercase();
let image_extensions = [
".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".tif",
".svg", ".webp", ".ico", ".raw", ".cr2", ".nef", ".arw"
];
image_extensions.iter().any(|ext| path_lower.ends_with(ext))
}
pub fn find_soffice(options: &ConvertOptions) -> ConvertResult<String> {
let mut paths = options.soffice_binary_paths.clone().unwrap_or_default();
if let Ok(lo_exe) = env::var("LIBRE_OFFICE_EXE") {
paths.push(lo_exe);
}
#[cfg(target_os = "macos")]
{
paths.extend(vec![
"/Applications/LibreOffice.app/Contents/MacOS/soffice".to_string(),
"/Applications/LibreOffice.app/Contents/MacOS/soffice.bin".to_string(),
]);
}
#[cfg(target_os = "linux")]
{
paths.extend(vec![
"/usr/bin/libreoffice".to_string(),
"/usr/bin/soffice".to_string(),
"/snap/bin/libreoffice".to_string(),
"/opt/libreoffice/program/soffice".to_string(),
"/usr/local/lib/libreoffice/program/soffice".to_string(),
]);
}
#[cfg(windows)]
{
let program_files = env::var("PROGRAMFILES")
.unwrap_or_else(|_| "C:\\Program Files".to_string());
let program_files_x86 = env::var("PROGRAMFILES(X86)")
.or_else(|_| env::var("PROGRAMFILES_X86"))
.unwrap_or_else(|_| "C:\\Program Files (x86)".to_string());
let local_app_data = env::var("LOCALAPPDATA")
.unwrap_or_else(|_| "C:\\Users\\Public\\AppData\\Local".to_string());
paths.extend(vec![
format!("{}\\LibreOffice\\program\\soffice.exe", program_files),
format!("{}\\LibreOffice\\program\\soffice.exe", program_files_x86),
"C:\\Program Files\\LibreOffice\\program\\soffice.exe".to_string(),
"C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe".to_string(),
format!("{}\\Programs\\soffice.exe", local_app_data),
]);
}
for path in paths {
if Path::new(&path).exists() {
return Ok(path);
}
}
Err(ConvertError::SofficeNotFound)
}
pub async fn convert_with_options(
document: &[u8],
format: &str,
filter: Option<&str>,
options: ConvertOptions,
) -> ConvertResult<Vec<u8>> {
if document.is_empty() {
return Err(ConvertError::InvalidInput("Document data is empty".to_string()));
}
if format.is_empty() {
return Err(ConvertError::InvalidInput("Format is empty".to_string()));
}
let temp_dir = TempDir::with_prefix(
options.tmp_prefix.as_deref().unwrap_or("libreoffice_convert_")
).map_err(|e| ConvertError::TempDirCreationFailed(e.to_string()))?;
let install_dir = TempDir::with_prefix("soffice_user_profile_")
.map_err(|e| ConvertError::TempDirCreationFailed(e.to_string()))?;
let soffice_path = find_soffice(&options)?;
let input_format = options.input_format.as_deref().unwrap_or("docx");
let file_name = format!("source.{}", input_format);
let input_path = temp_dir.path().join(&file_name);
let mut source_file = File::create(&input_path).await
.map_err(|e| ConvertError::FileWriteFailed(e.to_string()))?;
source_file.write_all(document).await
.map_err(|e| ConvertError::FileWriteFailed(e.to_string()))?;
source_file.flush().await
.map_err(|e| ConvertError::FileWriteFailed(e.to_string()))?;
let user_install_url = Url::from_directory_path(install_dir.path())
.map_err(|_| ConvertError::InvalidPath("Invalid path for URL conversion".to_string()))?;
let filter_param = filter.map(|f| format!(":{}", f)).unwrap_or_default();
let fmt_str = if filter.map(|f| f.contains(' ')).unwrap_or(false) {
format!("\"{}{}\"", format, filter_param)
} else {
format!("{}{}", format, filter_param)
};
let input_path_str = input_path.to_string_lossy().to_string();
let output_dir_str = temp_dir.path().to_string_lossy().to_string();
let output = Command::new(&soffice_path)
.arg(format!("-env:UserInstallation={}", user_install_url))
.arg("--headless")
.arg("--convert-to")
.arg(&fmt_str)
.arg("--outdir")
.arg(&output_dir_str)
.arg(&input_path_str)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.await
.map_err(|e| ConvertError::ProcessExecutionFailed(e.to_string()))?;
let stderr = String::from_utf8_lossy(&output.stderr);
if !output.status.success() {
return Err(ConvertError::ProcessFailed {
code: output.status.code(),
stderr: stderr.to_string(),
});
}
let output_path = temp_dir.path().join(format!("source.{}", format.split(':').next().unwrap_or(format)));
let mut retry_count = 0;
let max_times = options.async_times;
let interval_ms = options.async_interval;
let buffer = loop {
match fs::read(&output_path).await {
Ok(buf) => break buf,
Err(e) if retry_count < max_times => {
retry_count += 1;
tokio::time::sleep(tokio::time::Duration::from_millis(interval_ms)).await;
}
Err(e) => {
return Err(ConvertError::FileReadFailed(
format!("Failed to read output file after {} retries: {}", retry_count, e)
));
}
}
};
Ok(buffer)
}
pub async fn convert(
document: &[u8],
format: &str,
filter: Option<&str>,
) -> ConvertResult<Vec<u8>> {
convert_with_options(document, format, filter, ConvertOptions::default()).await
}
pub async fn convert_file(
input_path: &str,
output_path: &str,
format: &str,
filter: Option<&str>,
) -> ConvertResult<()> {
if is_image_file(input_path) {
return Err(ConvertError::InvalidInput(format!(
"Image conversion is not supported. Cannot convert '{}' to '{}'.\n\n\
This tool uses LibreOffice's --convert-to command which is designed for document formats \
(like .docx, .xlsx, .pptx, .odt, etc.), not for image files.\n\n\
For converting images to PDF, consider using:\n\
- ImageMagick: magick input.png output.pdf\n\
- ImageMagick: convert input.png output.pdf\n\
- Online tools or dedicated image-to-PDF converters\n\
- LibreOffice Draw (manually open image and export as PDF)",
input_path, format
)));
}
let document = fs::read(input_path).await
.map_err(|e| ConvertError::FileReadFailed(e.to_string()))?;
let input_ext = Path::new(input_path)
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("docx");
let options = ConvertOptions::default()
.with_input_format(input_ext);
let result = convert_with_options(&document, format, filter, options).await?;
fs::write(output_path, result).await
.map_err(|e| ConvertError::FileWriteFailed(e.to_string()))?;
Ok(())
}
pub async fn convert_file_with_options(
input_path: &str,
output_path: &str,
format: &str,
filter: Option<&str>,
mut options: ConvertOptions,
) -> ConvertResult<()> {
if is_image_file(input_path) {
return Err(ConvertError::InvalidInput(format!(
"Image conversion is not supported. Cannot convert '{}' to '{}'.\n\n\
This tool uses LibreOffice's --convert-to command which is designed for document formats \
(like .docx, .xlsx, .pptx, .odt, etc.), not for image files.\n\n\
For converting images to PDF, consider using:\n\
- ImageMagick: magick input.png output.pdf\n\
- ImageMagick: convert input.png output.pdf\n\
- Online tools or dedicated image-to-PDF converters\n\
- LibreOffice Draw (manually open image and export as PDF)",
input_path, format
)));
}
let document = fs::read(input_path).await
.map_err(|e| ConvertError::FileReadFailed(e.to_string()))?;
if options.input_format.is_none() {
let input_ext = Path::new(input_path)
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("docx");
options.input_format = Some(input_ext.to_string());
}
let result = convert_with_options(&document, format, filter, options).await?;
fs::write(output_path, result).await
.map_err(|e| ConvertError::FileWriteFailed(e.to_string()))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_convert_options_default() {
let options = ConvertOptions::default();
assert_eq!(options.async_times, 3);
assert_eq!(options.async_interval, 200);
}
#[test]
fn test_convert_options_builder() {
let options = ConvertOptions::new()
.with_async_times(5)
.with_async_interval(300)
.with_tmp_prefix("test_");
assert_eq!(options.async_times, 5);
assert_eq!(options.async_interval, 300);
assert_eq!(options.tmp_prefix, Some("test_".to_string()));
}
#[test]
fn test_find_soffice() {
let options = ConvertOptions::default();
let result = find_soffice(&options);
println!("find_soffice result: {:?}", result);
}
}