-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconverter.rs
More file actions
81 lines (74 loc) · 3.2 KB
/
converter.rs
File metadata and controls
81 lines (74 loc) · 3.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//! Модуль для перевода старых форматов документов Microsoft office в новые
//!
//! Используется cli утилита поставляемая libreoffice - soffice
use std::process::{Command, Stdio};
use crate::{
constants::{APPLICATION_DOC, APPLICATION_PPT, APPLICATION_RTF, APPLICATION_XLS},
errors::ParserError,
match_parsers::{define_mime_type, read_data_from_file},
};
type Result<T> = std::result::Result<T, ParserError>;
/// Поддерживаемые типы старых форматов Microsoft office
enum MSOfficeFormat {
/// doc like форматы
Doc,
/// xls like форматы
Xls,
/// ppt like форматы
Ppt,
}
/// Конвертер старых Microsoft office форматов в новые
///
/// Определяет формат и вызывает конвертацию файла
/// # Arguments
/// - `old_file_path` - путь по которому лежит файл старого формата
/// - `new_path` - путь по которому должен появить файл нового формата
///
/// # Errors
/// - [`ParserError::InvalidFormat`] - тип файла не поддерживается/не определен
/// - [`ParserError::IoError`] - проблемы с libreoffice
pub(crate) fn convert_to_new_format(old_file_path: &str, new_path: &str) -> Result<()> {
let file_data = read_data_from_file(old_file_path)?;
match define_mime_type(&file_data) {
Some(mime) if mime == APPLICATION_RTF || mime == APPLICATION_DOC => {
converter_files(MSOfficeFormat::Doc, old_file_path, new_path)
}
Some(mime) if mime == APPLICATION_XLS => {
converter_files(MSOfficeFormat::Xls, old_file_path, new_path)
}
Some(mime) if mime == APPLICATION_PPT => {
converter_files(MSOfficeFormat::Ppt, old_file_path, new_path)
}
Some(mime) => Err(ParserError::InvalidFormat(format!(
"Не поддерживается данный тип файла {mime}"
))),
None => Err(ParserError::InvalidFormat(
"Не получается определить данный тип файла ".to_string(),
)),
}
}
/// Конвертирует файл в новый формат в зависимости от типа
/// # Arguments
/// - `old_file_path` - путь по которому лежит файл старого формата
/// - `new_path` - путь по которому должен появить файл нового формата
///
/// # Errors
/// - [`ParserError::IoError`] - проблемы с libreoffice
fn converter_files(type_format: MSOfficeFormat, old_file_path: &str, new_path: &str) -> Result<()> {
let type_convert = match type_format {
MSOfficeFormat::Doc => "docx",
MSOfficeFormat::Xls => "xlsx",
MSOfficeFormat::Ppt => "pptx",
};
Command::new("soffice")
.arg("--headless")
.arg("--convert-to")
.arg(type_convert)
.arg(old_file_path)
.arg("--outdir")
.arg(new_path)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()?;
Ok(())
}