use crate::book::Book;
use crate::container;
use crate::error::{Error, ResolveError, Result};
use crate::format::{ANCHORS, CONTAINER_MAGIC, FORMAT, META, RESOURCES, SERVICE_COUNT, TOC};
use crate::id::{ChapterId, PictureId};
use crate::index::Index;
use crate::index::Resolved;
use crate::meta::Meta;
use crate::options::{Limits, ReadOptions};
use crate::types::{
Anchor, ChapterEntry, Destination, LandmarkEntry, PictureEntry, Position, Resource, TocEntry,
Version,
};
use mopenzl::TypedOutput;
use mopenzl::framing::{FramedDecompressor, FramedIndex};
use std::fs::File;
use std::io::{Cursor, Read, Seek, SeekFrom};
use std::path::Path;
#[derive(Debug)]
pub struct BookReader<R> {
source: R,
decoder: FramedDecompressor,
directory: FramedIndex,
index: Index,
limits: Limits,
}
impl BookReader<File> {
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
Self::new(File::open(path)?)
}
}
impl BookReader<Cursor<Vec<u8>>> {
pub fn buffered(mut reader: impl Read) -> Result<Self> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes)?;
Self::new(Cursor::new(bytes))
}
}
impl<R: Read + Seek> BookReader<R> {
pub fn new(source: R) -> Result<Self> {
Self::with_options(source, &ReadOptions::default())
}
pub fn with_options(mut source: R, options: &ReadOptions) -> Result<Self> {
let limits = options.limits;
check_signature(&mut source)?;
let mut decoder = container::decoder(&limits, u64::MAX)?;
let directory = decoder
.framed_index(&mut source)
.map_err(container::error)?;
let mut read = |number: u32| {
let at = usize::try_from(number).unwrap_or(usize::MAX);
decoder
.read_indexed_resource(&mut source, &directory, at)
.map_err(container::error)
};
if directory.is_empty() {
return Err(Error::NotMbook);
}
let version = container::header(&read(FORMAT)?.outputs)?;
if directory.len() < SERVICE_COUNT {
return Err(Error::Malformed {
resource: FORMAT,
reason: "the file has fewer than five resources",
});
}
let meta = read(META)?;
let resources = read(RESOURCES)?;
let toc = read(TOC)?;
let anchors = read(ANCHORS)?;
let decoded_lens: Vec<u64> = directory.iter().map(|info| info.decoded_size).collect();
let index = Index::from_outputs(
version,
[
&meta.outputs,
&resources.outputs,
&toc.outputs,
&anchors.outputs,
],
&decoded_lens,
)?;
Ok(Self {
source,
decoder,
directory,
index,
limits,
})
}
#[must_use]
pub fn version(&self) -> Version {
self.index.version()
}
#[must_use]
pub fn meta(&self) -> &Meta {
self.index.meta()
}
#[must_use]
pub fn toc(&self) -> &[TocEntry] {
self.index.toc()
}
pub fn chapters(&self) -> impl ExactSizeIterator<Item = ChapterEntry<'_>> {
self.index.chapters()
}
pub fn pictures(&self) -> impl ExactSizeIterator<Item = PictureEntry<'_>> {
self.index.pictures()
}
#[must_use]
pub fn chapter(&self, id: ChapterId) -> Option<ChapterEntry<'_>> {
self.index.chapter(id)
}
#[must_use]
pub fn picture(&self, id: PictureId) -> Option<PictureEntry<'_>> {
self.index.picture(id)
}
#[must_use]
pub fn find_chapter(&self, path: &str) -> Option<ChapterEntry<'_>> {
self.index.find_chapter(path)
}
#[must_use]
pub fn find_picture(&self, path: &str) -> Option<PictureEntry<'_>> {
self.index.find_picture(path)
}
#[must_use]
pub fn cover(&self) -> Option<PictureEntry<'_>> {
self.meta().cover().and_then(|path| self.find_picture(path))
}
#[must_use]
pub fn chapter_id(&self, number: u32) -> Option<ChapterId> {
self.index.chapter_id(number)
}
#[must_use]
pub fn picture_id(&self, number: u32) -> Option<PictureId> {
self.index.picture_id(number)
}
#[must_use]
pub fn anchors(&self, chapter: ChapterId) -> &[Anchor] {
self.index.anchors(chapter.number())
}
pub fn resolve(&self, from: ChapterId, destination: &str) -> Result<Destination, ResolveError> {
self.index.resolve(from, destination)
}
pub fn read_resolve(&mut self, from: ChapterId, destination: &str) -> Result<Destination> {
match self.index.resolve_named(from, destination)? {
Resolved::Known(destination) => Ok(destination),
Resolved::Extra { chapter, name } => {
let anchors = self.read_extra_anchors(chapter)?;
let anchor = anchors.iter().find(|anchor| anchor.name == name);
let offset = anchor.ok_or(ResolveError::UnknownAnchor)?.offset;
Ok(Destination::Chapter(Position { chapter, offset }))
}
}
}
pub fn resources(&self) -> impl ExactSizeIterator<Item = Resource<'_>> {
self.index.resources()
}
pub fn read_chapter(&mut self, id: ChapterId) -> Result<String> {
let number = id.number();
if self.index.chapter_id(number).is_none() {
return Err(Error::NoSuchResource(number));
}
let bytes = self.read_serial(number)?;
self.index.text(number, bytes)
}
pub fn read_extra_anchors(&mut self, chapter: ChapterId) -> Result<Vec<Anchor>> {
let number = chapter.number();
if self.index.chapter_id(number).is_none() {
return Err(Error::NoSuchResource(number));
}
let Some(table) = self.index.anchor_table(number) else {
return Ok(Vec::new());
};
let outputs = read_outputs(&mut self.decoder, &mut self.source, &self.directory, table)?;
self.index.read_extra_anchors(number, table, &outputs)
}
pub fn read_landmarks(&mut self) -> Result<Vec<LandmarkEntry>> {
let Some(table) = self.index.landmarks_table() else {
return Ok(Vec::new());
};
let outputs = read_outputs(&mut self.decoder, &mut self.source, &self.directory, table)?;
self.index.read_landmarks(table, &outputs)
}
pub fn read_picture(&mut self, id: PictureId) -> Result<Vec<u8>> {
let number = id.number();
if self.index.picture_id(number).is_none() {
return Err(Error::NoSuchResource(number));
}
self.read_serial(number)
}
pub fn read_cover(&mut self) -> Result<Option<Vec<u8>>> {
match self.cover().map(|cover| cover.id) {
Some(id) => self.read_picture(id).map(Some),
None => Ok(None),
}
}
pub fn load(&mut self) -> Result<Book> {
if self.index.content_len() > self.limits.max_file_bytes {
return Err(Error::Limit("the decoded book exceeds the file limit"));
}
let Self {
source,
decoder,
directory,
index,
..
} = self;
Book::assemble(index, |number| {
read_outputs(decoder, source, directory, number)
})
}
#[must_use]
pub fn into_inner(self) -> R {
self.source
}
fn read_serial(&mut self, number: u32) -> Result<Vec<u8>> {
let outputs = read_outputs(&mut self.decoder, &mut self.source, &self.directory, number)?;
container::serial(number, outputs)
}
}
fn read_outputs<R: Read + Seek>(
decoder: &mut FramedDecompressor,
source: &mut R,
directory: &FramedIndex,
number: u32,
) -> Result<Vec<TypedOutput>> {
let at = usize::try_from(number).unwrap_or(usize::MAX);
decoder
.read_indexed_resource(source, directory, at)
.map(|resource| resource.outputs)
.map_err(container::error)
}
fn check_signature<R: Read + Seek>(source: &mut R) -> Result<()> {
let start = source.stream_position()?;
let mut signature = [0; CONTAINER_MAGIC.len()];
let complete = match source.read_exact(&mut signature) {
Ok(()) => true,
Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => false,
Err(error) => return Err(error.into()),
};
source.seek(SeekFrom::Start(start))?;
if complete && signature == CONTAINER_MAGIC {
Ok(())
} else {
Err(Error::NotMbook)
}
}