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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
//! 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: [*Apache-2.0*](https://github.com/wojciechkepka/mobi-rs/blob/master/license)
//!
//!## Examples
//!### Print the whole book into stdout
//!```rust,ignore
//!use mobi::Mobi;
//!fn main() {
//!    let m = Mobi::init("/home/wojtek/Downloads/lotr.mobi").unwrap();
//!    println!("{}", m.content_raw().unwrap());
//!}
//!```
//!### Access basic info
//!- `src/main.rs`
//!```rust,ignore
//!use mobi::Mobi;
//!fn main() {
//!    let m = Mobi::init("/home/wojtek/Downloads/lotr.mobi").unwrap();
//!    let title = m.title().unwrap();
//!    let author = m.author().unwrap();
//!    let publisher = m.publisher().unwrap();
//!    let desc = m.description().unwrap();
//!    let isbn = m.isbn().unwrap();
//!    let pub_date = m.publish_date().unwrap();
//!    let contributor = m.contributor().unwrap();
//!    println!("{}\n{}\n{}\n{}\n{}\n{}\n{}\n", title, author, publisher, isbn, pub_date, desc, contributor);
//!    // 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
//!}
//!```
//!### Print all info
//!- `src/main.rs`
//!```rust,ignore
//!use mobi::Mobi;
//!
//!fn main() {
//!    let m = Mobi::init("/home/wojtek/Downloads/lotr.mobi").unwrap();
//!    println!("{}", m)
//!}
//!```
mod lz77;
pub mod exth;
pub mod mobih;
pub mod palmdoch;
pub mod header;
use crate::header::Header;
use crate::palmdoch::{Compression, PalmDocHeader};
use crate::exth::{ExtHeader, BookInfo};
use crate::mobih::MobiHeader;
use byteorder::{BigEndian, ReadBytesExt};
use chrono::prelude::*;
use std::collections::HashMap;
use std::fmt;
use std::fs;
use std::io::Cursor;
use std::path::Path;
macro_rules! return_or_err {
    ($x:expr) => {
        match $x {
            Ok(data) => data,
            Err(e) => return Err(e),
        }
    };
}
#[derive(Debug, Default)]
/// Structure that holds parsed ebook information and contents
pub struct Mobi {
    pub contents: 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 passed file path
    /// Returns std::io::Error if there is a problem with the provided path
    pub fn init<P: AsRef<Path>>(file_path: P) -> Result<Mobi, std::io::Error> {
        let contents = return_or_err!(fs::read(file_path));
        let header = return_or_err!(Header::parse(&contents));
        let palmdoc = return_or_err!(PalmDocHeader::parse(&contents, header.num_of_records));
        let mobi = return_or_err!(MobiHeader::parse(&contents, header.num_of_records));
        let exth = {
            if mobi.has_exth_header {
                return_or_err!(ExtHeader::parse(&contents, header.num_of_records))
            } else {
                ExtHeader::default()
            }
        };
        let records = return_or_err!(Record::parse_records(
            &contents,
            header.num_of_records,
            mobi.extra_bytes,
            palmdoc.compression_en()
        ));
        Ok(Mobi {
            contents,
            header,
            palmdoc,
            mobi,
            exth,
            records,
        })
    }
    /// Returns author record if such exists
    pub fn author(&self) -> Option<&String> {
        self.exth.get_book_info(BookInfo::Author)
    }
    /// Returns publisher record if such exists
    pub fn publisher(&self) -> Option<&String> {
        self.exth.get_book_info(BookInfo::Publisher)
    }
    /// Returns description record if such exists
    pub fn description(&self) -> Option<&String> {
        self.exth.get_book_info(BookInfo::Description)
    }
    /// Returns isbn record if such exists
    pub fn isbn(&self) -> Option<&String> {
        self.exth.get_book_info(BookInfo::Isbn)
    }
    /// Returns publish_date record if such exists
    pub fn publish_date(&self) -> Option<&String> {
        self.exth.get_book_info(BookInfo::PublishDate)
    }
    /// Returns contributor record if such exists
    pub fn contributor(&self) -> Option<&String> {
        self.exth.get_book_info(BookInfo::Contributor)
    }
    /// Returns title record if such exists
    pub fn title(&self) -> Option<&String> {
        self.exth.get_book_info(BookInfo::Title)
    }
    /// Returns text encoding used in ebook
    pub fn text_encoding(&self) -> Option<String> {
        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()
    }
    /// Returns creation datetime
    pub fn created_datetime(&self) -> NaiveDateTime {
        self.header.created_datetime()
    }
    /// Returns modification datetime
    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_raw(&self) -> Option<String> {
        let mut content = String::new();
        for i in 1..self.palmdoc.record_count - 1 {
            let s = &self.records[i as usize].to_string().replace("â", "").replace("€", "");

            content.push_str(s);
        }
        Some(content)
    }
    /// Returns a slice of the content where b is beginning index and e is ending index.
    /// Usually readable indexes are between 1-300(+-50)
    pub fn content_slice(&self, b: usize, e: usize) -> Option<String> {
        let mut content = String::new();
        if (b >= 1) && (b <= e) && (e < (self.palmdoc.record_count - 1) as usize) {
            for i in b..e {
                content.push_str(&self.records[i as usize].to_string());
            }
        }
        Some(content)
    }
}
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,
        )
    }
}
#[derive(Debug, Clone)]
/// A "cell" in the whole books content
pub struct Record {
    record_data_offset: u32,
    id: u32,
    pub record_data: String,
}
impl fmt::Display for Record {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.record_data)
    }
}
impl Record {
    #[allow(dead_code)]
    fn new() -> Record {
        Record {
            record_data_offset: 0,
            id: 0,
            record_data: String::new(),
        }
    }
    /// Reads into a string the record data based on record_data_offset
    fn record_data(
        record_data_offset: u32,
        next_record_data_offset: u32,
        extra_bytes: u32,
        compression_type: &Compression,
        content: &[u8],
    ) -> Result<String, std::io::Error> {
        match compression_type {
            Compression::No => Ok(String::from_utf8_lossy(
                &content
                    [record_data_offset as usize..next_record_data_offset as usize],
            )
            .to_owned()
            .to_string()),
            Compression::PalmDoc => {
                if record_data_offset < content.len() as u32 {
                    if record_data_offset < next_record_data_offset - extra_bytes {
                        let s = &content[record_data_offset as usize
                            ..(next_record_data_offset - extra_bytes) as usize];
                        lz77::decompress_lz77(s)
                    } else {
                        Ok(String::from(""))
                    }
                } else {
                    Ok(String::from(""))
                }
            }
            Compression::Huff => Ok(String::from("")),
        }
    }
    /// Parses a record from the reader at current position
    fn parse_record(reader: &mut Cursor<&[u8]>) -> Result<Record, std::io::Error> {
        let record_data_offset = return_or_err!(reader.read_u32::<BigEndian>());
        let id = return_or_err!(reader.read_u32::<BigEndian>());
        let record = Record {
            record_data_offset,
            id,
            record_data: String::new(),
        };
        Ok(record)
    }
    /// Gets all records in the specified content
    fn parse_records(
        content: &[u8],
        num_of_records: u16,
        _extra_bytes: u32,
        compression_type: Compression,
    ) -> Result<Vec<Record>, std::io::Error> {
        let mut records_content = vec![];
        let mut reader = Cursor::new(content);
        reader.set_position(78);
        for _i in 0..num_of_records {
            let record = return_or_err!(Record::parse_record(&mut reader));
            records_content.push(record);
        }
        for i in 0..records_content.len() {
            let mut current_rec = records_content[i].clone();
            if i != records_content.len() - 1 {
                let next_offset = records_content[i + 1].record_data_offset;
                if _extra_bytes < next_offset {
                    current_rec.record_data = match Record::record_data(
                        current_rec.record_data_offset,
                        next_offset,
                        _extra_bytes,
                        &compression_type,
                        content,
                    ) {
                        Ok(n) => n,
                        Err(e) => panic!(e),
                    };
                }
                records_content.insert(i, current_rec);
                records_content.remove(i + 1);
            }
        }
        Ok(records_content)
    }
}