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
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
//! An implementation of [MOBI](https://wiki.mobileread.com/wiki/MOBI) format data parsing and manipulation, written in Rust.
//!
//! The code is available on [GitHub](https://github.com/wojciechkepka/mobi-rs)
//!
//! License: [*MIT*](https://github.com/wojciechkepka/mobi-rs/blob/master/license)
//!
//! ## Examples
//! ### Access basic info
//! ```no_run
//! use mobi::Mobi;
//! fn main() -> Result<(), std::io::Error> {
//!     let book = vec![0, 0, 0];
//!     // You can either create a Mobi struct from a slice
//!     let m = Mobi::new(&book)?;
//!     // Or from an instance of io::Read
//!     let stdin = std::io::stdin();
//!     let mut handle = stdin.lock();
//!     let m = Mobi::from_read(&mut handle)?;
//!     // Or from filesystem
//!     let m = Mobi::from_path("/some/path/to/book.mobi")?;
//!
//!     let empty = "".to_string();
//!     // Access metadata
//!     let title = m.title().unwrap_or(&empty);
//!     let author = m.author().unwrap_or(&empty);
//!     let publisher = m.publisher().unwrap_or(&empty);
//!     let desc = m.description().unwrap_or(&empty);
//!     let isbn = m.isbn().unwrap_or(&empty);
//!     let pub_date = m.publish_date().unwrap_or(&empty);
//!     let contributor = m.contributor().unwrap_or(&empty);
//!
//!     // Access Headers
//!     let header = &m.header; // Normal Header
//!     let pdheader = &m.palmdoc; // PalmDOC Header
//!     let mheader = &m.mobi; // MOBI Header
//!     let exth = &m.exth; // Extra Header
//!
//!     // Access content
//!     let content = m.content_as_string();
//!
//!     Ok(())
//! }
//! ```
pub(crate) mod book;
#[cfg(feature = "fmt")]
mod display;
/// Module with headers from book containg more extracted data not
/// available through public API.
pub mod headers;
pub(crate) mod lz77;
pub(crate) mod reader;
pub(crate) mod record;
#[cfg(feature = "time")]
use chrono::prelude::*;
use headers::{exth, ExtHeader, Header, MobiHeader, PalmDocHeader, TextEncoding};
pub(crate) use reader::Reader;
pub use record::Record;
use std::{fs, io, io::Read, path::Path};

#[derive(Debug, Default)]
/// Structure that holds parsed ebook information and contents
pub struct Mobi {
    pub content: Vec<u8>,
    pub header: Header,
    pub palmdoc: PalmDocHeader,
    pub mobi: MobiHeader,
    pub exth: ExtHeader,
    pub records: Vec<Record>,
}
impl Mobi {
    /// Construct a Mobi object from a slice
    pub fn new<B: AsRef<Vec<u8>>>(bytes: B) -> io::Result<Mobi> {
        Mobi::from_reader(Reader::new(bytes.as_ref()))
    }
    /// Construct a Mobi object from passed file path
    pub fn from_path<P: AsRef<Path>>(file_path: P) -> io::Result<Mobi> {
        Mobi::new(&fs::read(file_path)?)
    }
    /// Construct a Mobi object from an object that implements a Read trait
    pub fn from_read<R: Read>(reader: R) -> io::Result<Mobi> {
        // Temporary solution
        let mut content = Vec::new();
        for byte in reader.bytes() {
            content.push(byte?);
        }
        Mobi::from_reader(Reader::new(&content))
    }

    fn from_reader(mut reader: Reader) -> io::Result<Mobi> {
        let header = Header::parse(&mut reader)?;
        reader.set_num_of_records(header.num_of_records);

        let palmdoc = PalmDocHeader::parse(&mut reader)?;
        let mobi = MobiHeader::parse(&mut reader)?;
        let exth = {
            if mobi.has_exth_header {
                ExtHeader::parse(&mut reader)?
            } else {
                ExtHeader::default()
            }
        };
        let records = Record::parse_records(
            reader.content_ref(),
            header.num_of_records,
            mobi.extra_bytes,
            palmdoc.compression_en(),
            mobi.text_encoding(),
        )?;
        Ok(Mobi {
            content: reader.content(),
            header,
            palmdoc,
            mobi,
            exth,
            records,
        })
    }

    /// Returns author record if such exists
    pub fn author(&self) -> Option<&String> {
        self.exth.get_book_info(exth::BookInfo::Author)
    }
    /// Returns publisher record if such exists
    pub fn publisher(&self) -> Option<&String> {
        self.exth.get_book_info(exth::BookInfo::Publisher)
    }
    /// Returns description record if such exists
    pub fn description(&self) -> Option<&String> {
        self.exth.get_book_info(exth::BookInfo::Description)
    }
    /// Returns isbn record if such exists
    pub fn isbn(&self) -> Option<&String> {
        self.exth.get_book_info(exth::BookInfo::Isbn)
    }
    /// Returns publish_date record if such exists
    pub fn publish_date(&self) -> Option<&String> {
        self.exth.get_book_info(exth::BookInfo::PublishDate)
    }
    /// Returns contributor record if such exists
    pub fn contributor(&self) -> Option<&String> {
        self.exth.get_book_info(exth::BookInfo::Contributor)
    }
    /// Returns title record if such exists
    pub fn title(&self) -> Option<&String> {
        self.exth.get_book_info(exth::BookInfo::Title)
    }
    /// Returns text encoding used in ebook
    pub fn text_encoding(&self) -> TextEncoding {
        self.mobi.text_encoding()
    }
    /// Returns type of this ebook
    pub fn mobi_type(&self) -> Option<String> {
        self.mobi.mobi_type()
    }
    /// Returns language of the ebook
    pub fn language(&self) -> Option<String> {
        self.mobi.language()
    }
    #[cfg(feature = "time")]
    /// Returns creation datetime
    /// This field is only available using `time` feature
    pub fn created_datetime(&self) -> NaiveDateTime {
        self.header.created_datetime()
    }
    #[cfg(feature = "time")]
    /// Returns modification datetime
    /// This field is only available using `time` feature
    pub fn mod_datetime(&self) -> NaiveDateTime {
        self.header.mod_datetime()
    }
    /// Returns compression method used on this file
    pub fn compression(&self) -> Option<String> {
        self.palmdoc.compression()
    }
    /// Returns encryption method used on this file
    pub fn encryption(&self) -> Option<String> {
        self.palmdoc.encryption()
    }
    /// Returns the whole content as String
    pub fn content_as_string(&self) -> String {
        (1..self.palmdoc.record_count - 1)
            .map(|i| self.records[i as usize].to_string())
            .collect()
    }
    /// Returns last readable index of the book
    pub fn last_index(&self) -> usize {
        (self.palmdoc.record_count - 1) as usize
    }
    /// Returns a slice of the content where b is beginning index and e is ending index.
    /// Use `last_index` function to find out the last readable index
    pub fn content_slice(&self, b: usize, e: usize) -> Option<String> {
        if (b >= 1) && (b <= e) && (e < self.last_index()) {
            Some((b..e).map(|i| self.records[i as usize].to_string()).collect())
        } else {
            None
        }
    }
}
#[cfg(feature = "fmt")]
impl fmt::Display for Mobi {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let empty_str = String::from("");
        write!(
            f,
            "
------------------------------------------------------------------------------------
Title:                  {}
Author:                 {}
Publisher:              {}
Description:            {}
ISBN:                   {}
Publish Date:           {}
Contributor:            {}
------------------------------------------------------------------------------------
{}
------------------------------------------------------------------------------------
{}
------------------------------------------------------------------------------------
{}
------------------------------------------------------------------------------------
{}
------------------------------------------------------------------------------------",
            self.title().unwrap_or(&empty_str),
            self.author().unwrap_or(&empty_str),
            self.publisher().unwrap_or(&empty_str),
            self.description().unwrap_or(&empty_str),
            self.isbn().unwrap_or(&empty_str),
            self.publish_date().unwrap_or(&empty_str),
            self.contributor().unwrap_or(&empty_str),
            self.header,
            self.palmdoc,
            self.mobi,
            self.exth,
        )
    }
}

/// Helper trait to group all enums containing header fields corresponding to each possible header
/// (MobiHeaderData, ExtHeaderData, PalmDocHeaderData, HeaderData)
pub(crate) trait FieldHeaderEnum {}
/// Trait allowing generic reading of header fields
pub(crate) trait HeaderField<T: FieldHeaderEnum> {
    /// Returns a position in the text where this field can be read
    fn position(self) -> u16;
}