aboutsummaryrefslogtreecommitdiff
path: root/src/epub.rs
blob: d86fa35f2167a3db8328c68d1550bfcfa5bd48e3 (plain) (blame)
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
use crate::models::FileEntry;
use anyhow::Result;
use reqwest::Client;
use std::path::Path;
use tokio::{
    fs::{self, File},
    io::AsyncWriteExt,
};

/// Creates and writes container.xml.
pub async fn write_container_xml(dest_root: &Path, opf_full_path: &str) -> Result<()> {
    // Create destination directory.
    let dest_dir = dest_root.join("META-INF");
    fs::create_dir_all(&dest_dir).await?;

    // Create distination file.
    let dest_path = dest_dir.join("container.xml");
    let mut file = File::create(dest_path).await?;

    // Prepare file contents.
    let contents = format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
  <rootfiles>
    <rootfile full-path="{opf_full_path}" media-type="application/oebps-package+xml"/>
  </rootfiles>
</container>
"#
    );

    // Write down the file.
    file.write_all(contents.as_bytes()).await?;
    Ok(())
}

pub async fn download_all_files(
    client: &Client,
    file_entries: &[FileEntry],
    dest_root: &Path,
) -> Result<()> {
    for entry in file_entries {
        let dest_path = dest_root.join(&entry.full_path);

        if let Some(parent_dir) = dest_path.parent() {
            fs::create_dir_all(parent_dir).await?;
        }

        let mut file = File::create(dest_path).await?;
        let bytes = client
            .get(&entry.url)
            .send()
            .await?
            .error_for_status()?
            .bytes()
            .await?;

        file.write_all(&bytes).await?;
    }
    Ok(())
}