#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;
use std::path::PathBuf;
use serde::Serialize;
use crate::document_core::DocumentCore;
use crate::model::document::Document;
use crate::parser::FileFormat;
use crate::service::error::ServiceError;
pub const DEFAULT_MAX_BYTES: usize = 256 * 1024 * 1024;
const TITLE_SCAN_PAGES: u32 = 3;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocumentService {
max_bytes: Option<usize>,
title_scan: bool,
}
impl Default for DocumentService {
fn default() -> Self {
DocumentService {
max_bytes: Some(DEFAULT_MAX_BYTES),
title_scan: true,
}
}
}
impl DocumentService {
pub fn new() -> Self {
DocumentService::default()
}
pub fn with_max_bytes(mut self, max_bytes: Option<usize>) -> Self {
self.max_bytes = max_bytes;
self
}
pub fn with_title_scan(mut self, title_scan: bool) -> Self {
self.title_scan = title_scan;
self
}
pub fn max_bytes(&self) -> Option<usize> {
self.max_bytes
}
pub fn open_bytes(
&self,
bytes: &[u8],
opts: &OpenOptions,
) -> Result<OpenedDocument, ServiceError> {
self.open_inner(bytes, opts, DocumentSource::Bytes)
}
#[cfg(not(target_arch = "wasm32"))]
pub fn open_path(
&self,
path: &Path,
opts: &OpenOptions,
) -> Result<OpenedDocument, ServiceError> {
let bytes = match std::fs::read(path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Err(ServiceError::NotFound {
path: path.to_path_buf(),
})
}
Err(error) => {
return Err(ServiceError::Io {
path: path.to_path_buf(),
kind: error.kind(),
})
}
};
self.open_inner(&bytes, opts, DocumentSource::Path(path.to_path_buf()))
}
fn open_inner(
&self,
bytes: &[u8],
opts: &OpenOptions,
source: DocumentSource,
) -> Result<OpenedDocument, ServiceError> {
if let Some(limit) = opts.max_bytes.or(self.max_bytes) {
if bytes.len() > limit {
return Err(ServiceError::TooLarge {
size_bytes: bytes.len(),
limit_bytes: limit,
});
}
}
let format = crate::parser::detect_format(bytes);
if !is_openable(format) {
return Err(ServiceError::UnsupportedFormat { detected: format });
}
let mut core = DocumentCore::new_empty();
let loaded = core.load_bytes(bytes, opts.password.as_deref().map(str::as_bytes));
loaded.map_err(|error| ServiceError::from_open_failure(&error, opts.password.is_some()))?;
Ok(OpenedDocument {
core,
format,
size_bytes: bytes.len(),
source,
title_scan: self.title_scan,
})
}
}
#[derive(Clone, Default, PartialEq, Eq)]
pub struct OpenOptions {
pub password: Option<String>,
pub max_bytes: Option<usize>,
}
impl std::fmt::Debug for OpenOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OpenOptions")
.field("password", &self.password.as_ref().map(|_| "[redacted]"))
.field("max_bytes", &self.max_bytes)
.finish()
}
}
impl OpenOptions {
pub fn new() -> Self {
OpenOptions::default()
}
pub fn with_password(mut self, password: impl Into<String>) -> Self {
self.password = Some(password.into());
self
}
pub fn with_max_bytes(mut self, max_bytes: usize) -> Self {
self.max_bytes = Some(max_bytes);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DocumentSource {
Path(PathBuf),
Bytes,
}
pub struct OpenedDocument {
pub(crate) core: DocumentCore,
format: FileFormat,
size_bytes: usize,
source: DocumentSource,
title_scan: bool,
}
impl std::fmt::Debug for OpenedDocument {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OpenedDocument")
.field("format", &self.format)
.field("size_bytes", &self.size_bytes)
.field("source", &self.source)
.field("page_count", &self.core.page_count())
.finish()
}
}
impl OpenedDocument {
pub fn format(&self) -> FileFormat {
self.format
}
pub fn size_bytes(&self) -> usize {
self.size_bytes
}
pub fn source(&self) -> &DocumentSource {
&self.source
}
pub fn core(&self) -> &DocumentCore {
&self.core
}
pub fn document(&self) -> &Document {
&self.core.document
}
pub fn page_count(&self) -> u32 {
self.core.page_count()
}
pub fn into_core(self) -> DocumentCore {
self.core
}
pub fn info(&self) -> DocumentInfo {
let document = self.document();
let version = if matches!(self.format, FileFormat::Hml | FileFormat::Pdf) {
None
} else {
Some(format!(
"{}.{}.{}.{}",
document.header.version.major,
document.header.version.minor,
document.header.version.build,
document.header.version.revision,
))
};
let fonts: Vec<String> = document
.doc_info
.font_faces
.iter()
.flatten()
.map(|face| face.name.clone())
.collect();
let para_count: usize = document.sections.iter().map(|s| s.paragraphs.len()).sum();
DocumentInfo {
format: format_token(self.format),
size_bytes: self.size_bytes,
version,
sections: document.sections.len(),
page_count: self.core.page_count(),
para_count,
encrypted: document.header.encrypted,
fonts,
title: if self.title_scan {
self.guess_title()
} else {
None
},
}
}
fn guess_title(&self) -> Option<String> {
for page in 0..self.core.page_count().min(TITLE_SCAN_PAGES) {
let Ok(text) = self.core.extract_page_text_native(page) else {
continue;
};
if let Some(line) = text.lines().map(str::trim).find(|l| !l.is_empty()) {
return Some(line.to_string());
}
}
None
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DocumentInfo {
pub format: &'static str,
pub size_bytes: usize,
pub version: Option<String>,
pub sections: usize,
pub page_count: u32,
pub para_count: usize,
pub encrypted: bool,
pub fonts: Vec<String>,
pub title: Option<String>,
}
pub fn format_token(format: FileFormat) -> &'static str {
match format {
FileFormat::Hwp => "hwp5",
FileFormat::Hwpx => "hwpx",
FileFormat::Hwp3 => "hwp3",
FileFormat::Hml => "hml",
FileFormat::Pdf => "pdf",
FileFormat::DrmProtected => "drm-protected",
FileFormat::Empty => "empty",
FileFormat::Unknown => "unknown",
}
}
fn is_openable(format: FileFormat) -> bool {
(format == FileFormat::Pdf && cfg!(feature = "pdf-import"))
|| matches!(
format,
FileFormat::Hwp | FileFormat::Hwpx | FileFormat::Hwp3 | FileFormat::Hml
)
}