aboutsummaryrefslogtreecommitdiff
path: root/src/xml.rs
blob: 277f12a519d63e316ba26fad267d985aee94ad6e (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
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
use anyhow::{Context, Result};
use ogrim::{Document, xml};
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use quick_xml::{Reader, Writer};
use relative_path::{RelativePath, RelativePathBuf};
use std::collections::HashMap;
use std::io::{BufRead, Write};
use url::Url;

use crate::models::{Chapter, EpubResponse, FileEntry};

/// Checks if a tag is a standard HTML void element that shouldn't have a closing tag.
fn is_html_void_tag(name: &[u8]) -> bool {
    matches!(
        name,
        b"area"
            | b"base"
            | b"br"
            | b"col"
            | b"embed"
            | b"hr"
            | b"img"
            | b"input"
            | b"link"
            | b"meta"
            | b"param"
            | b"source"
            | b"track"
            | b"wbr"
    )
}

/// Processes the fragment and outputs a complete, EPUB-ready XHTML document.
pub fn build_epub_chapter<R: BufRead, W: Write>(
    epub_data: &EpubResponse,
    chapter: &Chapter,
    chapter_dir: &RelativePath,
    fragment_input: R,
    url_to_file: &HashMap<&Url, &FileEntry>,
    url_path_to_local: &HashMap<&str, &RelativePathBuf>,
    mut out: &mut W,
) -> Result<()> {
    // EPUB XHTML Boilerplate wrapper.
    // EPUBs strictly require the w3 and idpf namespaces to validate properly.
    let wrapper_xhtml = xml!(
        <?xml version="1.0" encoding="UTF-8"?>
        <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"
            lang={epub_data.language} xml:lang={epub_data.language}>
        <head>
            <title>{chapter.title}</title>
            {|doc| make_stylesheet_links(doc, chapter, chapter_dir, url_to_file)}
        </head>
        <body>
        </body>
        </html>
    );
    let wrapper_suffix = "</body></html>";
    let wrapper_prefix = wrapper_xhtml
        .as_str()
        .strip_suffix(wrapper_suffix)
        .context("Wrapper must end with </body></html>")?;

    // Write wrapper prefix to output first.
    out.write_all(wrapper_prefix.as_bytes())?;
    out.write_all(b"\n")?;

    // Setup the XML Reader and Writer.
    let mut reader = Reader::from_reader(fragment_input);
    // Preserve spacing for EPUB text formatting.
    reader.config_mut().trim_text(false);
    // Fragments could have unmatched tags - tell the parser not to panic if so.
    reader.config_mut().check_end_names = false;
    let mut writer = Writer::new(&mut out);

    // Loop through the XML events and rewrite tags.
    let mut buffer = Vec::new();
    loop {
        match reader.read_event_into(&mut buffer) {
            Ok(Event::Start(tag_data)) => {
                // If it is a void tag, convert it to a self-closing XML tag.
                let tag_type = if is_html_void_tag(tag_data.name().as_ref()) {
                    Event::Empty
                } else {
                    Event::Start
                };
                writer.write_event(tag_type(rewrite_attributes(
                    &tag_data,
                    url_path_to_local,
                    chapter_dir,
                )))?;
            }
            Ok(Event::Empty(tag_data)) => {
                // If tags are already empty, leave them as-is.
                writer.write_event(Event::Empty(rewrite_attributes(
                    &tag_data,
                    url_path_to_local,
                    chapter_dir,
                )))?;
            }
            Ok(Event::End(tag_data)) => {
                // Silently drop closing tags for void elements if they exist (e.g. <img></img>).
                if !is_html_void_tag(tag_data.name().as_ref()) {
                    writer.write_event(Event::End(tag_data))?;
                }
            }
            Ok(Event::Eof) => break,
            Ok(tag_data) => writer.write_event(tag_data)?, // Pass through text, comments, etc. unmodified.
            Err(e) => anyhow::bail!(e),
        }
    }

    // Finish by flushing wrapper suffix to output.
    out.write_all(b"\n")?;
    out.write_all(wrapper_suffix.as_bytes())?;

    Ok(())
}

/// Processes the fragment and outputs a complete, EPUB-ready XHTML document.
pub fn write_modified_opf<R: BufRead, W: Write>(
    opf_input: R,
    mut out: &mut W,
    description: &str,
) -> Result<()> {
    // Setup the XML Reader and Writer.
    let mut reader = Reader::from_reader(opf_input);
    // Preserve spacing for easier diffs.
    reader.config_mut().trim_text(false);
    let mut writer = Writer::new(&mut out);

    // Loop through the XML events and check tags.
    let mut buffer = Vec::new();
    let mut desc_found = false;
    loop {
        match reader.read_event_into(&mut buffer) {
            Ok(Event::Start(tag_data)) => {
                // Simply record if dc:description found.
                if tag_data.name().as_ref() == b"dc:description" {
                    desc_found = true;
                }
                // Then pass through unmodified.
                writer.write_event(Event::Start(tag_data))?;
            }
            Ok(Event::End(tag_data)) => {
                // Write description if end of metadata is reached without finding one.
                if tag_data.name().as_ref() == b"metadata" && !desc_found {
                    writer.write_event(Event::Start(BytesStart::new("dc:description")))?;
                    writer.write_event(Event::Text(BytesText::new(description)))?;
                    writer.write_event(Event::End(BytesEnd::new("dc:description")))?;
                }
                // Pass through unmodified.
                writer.write_event(Event::End(tag_data))?;
            }
            Ok(Event::Eof) => break,
            Ok(tag_data) => writer.write_event(tag_data)?, // Pass through text, comments, etc. unmodified.
            Err(e) => anyhow::bail!(e),
        }
    }

    Ok(())
}

/// Helper function add link elements for stylesheets to an xml Document.
fn make_stylesheet_links(
    doc: &mut Document,
    chapter: &Chapter,
    chapter_dir: &RelativePath,
    url_to_file: &HashMap<&Url, &FileEntry>,
) {
    chapter
        .related_assets
        .stylesheets
        .iter()
        .filter_map(|u| url_to_file.get(u))
        .for_each(|e| {
            let rel_path = chapter_dir.relative(&e.full_path);
            xml!(doc,
                <link rel="stylesheet" type={e.media_type} href={rel_path} />
            );
        })
}

/// Helper function to inspect tags and rewrite the elements' attributes.
fn rewrite_attributes<'a>(
    tag_data: &BytesStart<'a>,
    url_path_to_local: &HashMap<&str, &RelativePathBuf>,
    chapter_dir: &RelativePath,
) -> BytesStart<'static> {
    let name = String::from_utf8_lossy(tag_data.name().as_ref()).into_owned();
    let mut new_elem = BytesStart::new(name);

    for attr in tag_data.attributes().filter_map(Result::ok) {
        let key = attr.key.as_ref();

        // Intercept element attributes which could contain links to resources.
        if matches!(
            (tag_data.name().as_ref(), key),
            (b"img", b"src")
                | (b"source", b"src")
                | (b"video", b"src")
                | (b"audio", b"src")
                | (b"a", b"href")
                | (b"link", b"href")
                | (b"object", b"data")
                | (b"embed", b"src")
                | (b"iframe", b"src")
                | (b"track", b"src")
        ) {
            let url = String::from_utf8_lossy(&attr.value);

            // If we have a local path, inject it instead of the absolute URL.
            if let Some(local_path) = url_path_to_local.get(url.as_ref()) {
                let key = String::from_utf8_lossy(key);
                new_elem.push_attribute((key.as_ref(), chapter_dir.relative(local_path).as_str()));
                continue;
            }
        }

        // Keep all other attributes intact.
        new_elem.push_attribute(attr);
    }

    new_elem
}