Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Import .mobi books into Citadel #20

Merged
merged 3 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ calibre-db = "0.1.0"
chrono = { version = "0.4.31", features = ["serde"] }
diesel = { version = "2.1.0", features = ["sqlite", "chrono", "returning_clauses_for_sqlite_3_35"] }
epub = "2.1.1"
mobi = "0.8.0"
libcalibre = { path = "./libcalibre" }
regex = "1.10.2"
serde = { version = "1.0", features = ["derive"] }
Expand Down
1 change: 1 addition & 0 deletions src-tauri/libcalibre/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ chrono = { version = "0.4.31", features = ["serde"] }
diesel = { version = "2.1.0", features = ["sqlite", "chrono", "returning_clauses_for_sqlite_3_35"] }
diesel_migrations = { version = "2.1.0", features = ["sqlite"] }
epub = "2.1.1"
mobi = "0.8.0"
regex = "1.10.2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use std::error::Error;
use std::ffi::OsStr;
use std::path::Path;

use mobi::Mobi;

use crate::application::services::domain::file::dto::{NewFileDto, UpdateFileDto};
use crate::domain::book_file::entity::{BookFile, NewBookFile, UpdateBookFile};
use crate::domain::book_file::repository::Repository as BookFileRepository;
Expand All @@ -27,6 +29,16 @@ fn cover_data(path: &Path) -> Result<Option<Vec<u8>>, Box<dyn Error>> {
let mut doc = epub::doc::EpubDoc::new(path)?;
Ok(doc.get_cover().map(|(data, _id)| data))
}
Some(MIMETYPE::MOBI) => {
let m = Mobi::from_path(&path);
match m {
Err(_) => Err("Failed to read mobi file")?,
Ok(mobi) => {
let cover_data = mobi.image_records().last().map(|img| img.content.to_vec());
Ok(cover_data)
}
}
}
_ => Ok(None),
}
}
Expand Down
5 changes: 5 additions & 0 deletions src-tauri/libcalibre/src/mime_type.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub enum MIMETYPE {
EPUB,
MOBI,
UNKNOWN,
}

Expand All @@ -8,6 +9,7 @@ impl MIMETYPE {
pub fn as_str(&self) -> &'static str {
match *self {
MIMETYPE::EPUB => "application/epub+zip",
MIMETYPE::MOBI => "application/x-mobipocket-ebook",
MIMETYPE::UNKNOWN => "application/octet-stream",
}
}
Expand All @@ -16,6 +18,7 @@ impl MIMETYPE {
pub fn from_str(mimetype: &str) -> Option<Self> {
match mimetype {
"application/epub+zip" => Some(MIMETYPE::EPUB),
"application/x-mobipocket-ebook" => Some(MIMETYPE::MOBI),
"application/octet-stream" => Some(MIMETYPE::UNKNOWN),
_ => None,
}
Expand All @@ -24,13 +27,15 @@ impl MIMETYPE {
pub fn to_file_extension(&self) -> &'static str {
match *self {
MIMETYPE::EPUB => "epub",
MIMETYPE::MOBI => "mobi",
MIMETYPE::UNKNOWN => "",
}
}

pub fn from_file_extension(extension: &str) -> Option<Self> {
match extension.to_lowercase().as_str() {
"epub" => Some(MIMETYPE::EPUB),
"mobi" => Some(MIMETYPE::MOBI),
_ => None,
}
}
Expand Down
50 changes: 5 additions & 45 deletions src-tauri/src/libs/calibre/mod.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
use std::io::Error;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use std::sync::Mutex;

use crate::book::ImportableBookMetadata;
use crate::book::ImportableBookType;
use crate::book::LibraryAuthor;
use crate::book::LibraryBook;
use crate::libs::file_formats::read_epub_metadata;

use chrono::NaiveDate;
use chrono::NaiveDateTime;
Expand Down Expand Up @@ -41,11 +38,7 @@ use std::path::Path;

#[derive(Serialize, Deserialize, specta::Type, Debug)]
pub struct ImportableFile {
path: PathBuf,
}

fn get_supported_extensions() -> Vec<&'static str> {
vec!["epub", "mobi", "pdf"]
pub(crate) path: PathBuf,
}

#[derive(Serialize, specta::Type)]
Expand Down Expand Up @@ -75,49 +68,16 @@ pub fn calibre_list_all_authors(library_root: String) -> Vec<LibraryAuthor> {

#[tauri::command]
#[specta::specta]
pub fn check_file_importable(path_to_file: String) -> ImportableFile {
pub fn check_file_importable(path_to_file: String) -> Option<ImportableFile> {
let file_path = Path::new(&path_to_file);

if !file_path.exists() {
panic!("File does not exist at {}", path_to_file);
}

let file_extension = file_path.extension().and_then(|ext| ext.to_str());

match file_extension {
Some(extension) if get_supported_extensions().contains(&extension) => ImportableFile {
path: PathBuf::from(path_to_file),
},
Some(extension) => {
panic!("Unsupported file extension: {}", extension);
}
None => {
panic!("File does not have an extension");
}
}
super::file_formats::validate_file_importable(file_path)
}

#[tauri::command]
#[specta::specta]
pub fn get_importable_file_metadata(file: ImportableFile) -> ImportableBookMetadata {
// TODO Do not assume file is an EPUB
let res = read_epub_metadata(file.path.as_path());

ImportableBookMetadata {
file_type: ImportableBookType::EPUB,
title: res.title.unwrap_or("".to_string()),
author_names: res.creator_list,
language: res.language,
publisher: res.publisher,
identifier: res.identifier,
path: file.path,
file_contains_cover: res.cover_image_data.is_some(),
tags: res.subjects,
publication_date: NaiveDate::from_str(
res.publication_date.unwrap_or("".to_string()).as_str(),
)
.ok(),
}
pub fn get_importable_file_metadata(file: ImportableFile) -> Option<ImportableBookMetadata> {
super::file_formats::get_importable_file_metadata(file)
}

pub fn create_folder_for_author(
Expand Down
42 changes: 42 additions & 0 deletions src-tauri/src/libs/file_formats/epub.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use std::path::Path;

use epub::doc::EpubDoc;

pub struct EpubMetadata {
pub title: Option<String>,
pub creator_list: Option<Vec<String>>,
pub identifier: Option<String>,
pub publisher: Option<String>,
pub publication_date: Option<String>,
pub language: Option<String>,
pub cover_image_data: Option<Vec<u8>>,
pub subjects: Vec<String>,
}

pub fn read_metadata(path: &Path) -> Option<EpubMetadata> {
match EpubDoc::new(path) {
Err(_) => None,
Ok(mut doc) => {
let creators = doc
.metadata
.get("creator")
.map(|v| v.to_vec())
.unwrap_or(Vec::new());

Some(EpubMetadata {
title: doc.mdata("title"),
creator_list: Some(creators),
identifier: doc.mdata("identifier"),
publisher: doc.mdata("publisher"),
language: doc.mdata("language"),
cover_image_data: doc.get_cover().map(|(data, _id)| data),
publication_date: doc.mdata("date"),
subjects: doc
.metadata
.get("subject")
.map(|v| v.to_vec())
.unwrap_or(Vec::new()),
})
}
}
}
Loading
Loading