-
Notifications
You must be signed in to change notification settings - Fork 2
/
epub.ts
248 lines (226 loc) · 6.95 KB
/
epub.ts
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
import { JSZip, type JSZipGeneratorOptions } from "./deps.ts";
import { Image } from "./util/html.ts";
import {
validateAndNormalizeChapters,
validateAndNormalizeOptions,
} from "./util/mod.ts";
import {
fetchFileContent,
renderTemplate,
retryFetch,
uuid,
} from "./util/other.ts";
import { buildBundle } from "./util/bundle.ts";
import { Content, NormChapter, NormOptions, Options } from "./util/validate.ts";
// import ejs from "https://esm.sh/ejs@3.1.8";
export class EPub {
protected options: NormOptions;
protected content: NormChapter[];
protected uuid: string;
protected images: Image[] = [];
protected cover?: { extension: string; mediaType: string };
protected log: typeof console.log;
protected warn: typeof console.warn;
protected zip: InstanceType<typeof JSZip>;
constructor(options: Options, content: Content) {
this.options = validateAndNormalizeOptions(options);
switch (this.options.verbose) {
case true:
this.log = console.log.bind(console);
this.warn = console.warn.bind(console);
break;
case false:
this.log = this.warn = () => {};
break;
default:
this.log = this.options.verbose.bind(null, "log");
this.warn = this.options.verbose.bind(null, "warn");
break;
}
this.uuid = uuid();
this.content = validateAndNormalizeChapters.call(this, content);
this.zip = new JSZip();
this.zip.addFile("mimetype", "application/epub+zip", {
compression: "STORE",
});
if (this.options.cover) {
const mediaType = "image/jpeg";
const extension = "jpg";
if (mediaType && extension) {
this.cover = { mediaType, extension };
}
}
}
async render() {
this.log("Generating Template Files...");
await this.generateTemplateFiles();
this.log("Downloading fonts...");
await this.downloadAllFonts();
this.log("Downloading images...");
await this.downloadAllImages();
this.log("Making cover...");
await this.makeCover();
this.log("Finishing up...");
return this;
}
async genEpub() {
// if dev, generate bundle first
if (Deno.env.get("DEV") == "1") {
await buildBundle("./templates");
}
try {
await this.render();
const content = await this.zip.generateAsync({
type: "uint8array",
mimeType: "application/epub+zip",
compression: "DEFLATE",
compressionOptions: {
level: 9,
},
});
this.log("Done");
return content;
} catch (e) {
console.error(e);
throw e;
}
}
generateAsync(options: JSZipGeneratorOptions) {
return this.zip.generateAsync(options);
}
protected async generateTemplateFiles() {
const css = await fetchFileContent("template.css");
this.zip.addFile("OEBPS/style.css", css);
for (const chapter of this.content) {
const rendered = await renderTemplate("chapter.xhtml.ejs", {
lang: this.options.lang,
prependChapterTitles: this.options.prependChapterTitles,
...chapter,
});
this.zip.addFile(chapter.href, rendered);
}
this.zip.addFile(
"META-INF/container.xml",
`<?xml version="1.0" encoding="UTF-8" ?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles>
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>`,
);
const opt = {
...this.options,
id: this.uuid,
images: this.images,
cover: this.cover,
content: this.content,
};
// console.log("opt", opt);
await renderTemplate("content.opf.ejs", opt).then((content) => {
this.zip.addFile("OEBPS/content.opf", content);
});
await renderTemplate("toc.ncx.ejs", opt).then((toc) => {
this.zip.addFile("OEBPS/toc.ncx", toc);
});
await renderTemplate("toc.xhtml.ejs", opt).then((toc) => {
this.zip.addFile("OEBPS/toc.xhtml", toc);
});
if (this.cover) {
await renderTemplate("cover.xhtml.ejs", {
...this.options,
cover: this.cover,
}).then(
(cover) => {
this.zip.addFile("OEBPS/cover.xhtml", cover);
},
);
}
}
protected async downloadAllFonts() {
if (!this.options.fonts.length) return this.log("No fonts to download");
const fonts = this.zip.folder("OEBPS/fonts")!;
for (
let i = 0;
i < this.options.fonts.length;
i += this.options.batchSize
) {
const fontContents = await Promise.all(
this.options.fonts.slice(i, i + this.options.batchSize).map((font) => {
const d = retryFetch(
font.url,
this.options.fetchTimeout,
this.options.retryTimes,
this.log,
)
.then(
(
res,
) => (this.log(`Downloaded font ${font.url}`),
{ ...font, data: res }),
);
return this.options.ignoreFailedDownloads
? d.catch(
(reason) => (this.warn(
`Warning (font ${font.url}): Download failed`,
reason,
),
{ ...font, data: "" }),
)
: d;
}),
);
fontContents.forEach((font) => fonts.addFile(font.filename, font.data));
}
}
protected async downloadAllImages() {
if (!this.images.length) return this.log("No images to download");
const images = this.zip.folder("OEBPS/images");
for (let i = 0; i < this.images.length; i += this.options.batchSize) {
const imageContents = await Promise.all(
this.images.slice(i, i + this.options.batchSize).map((image) => {
const d = retryFetch(
image.url,
this.options.fetchTimeout,
this.options.retryTimes,
this.log,
)
.then(
(
res,
) => (this.log(`Downloaded image ${image.url}`),
{ ...image, data: res }),
);
return this.options.ignoreFailedDownloads
? d.catch(
(reason) => (this.warn(
`Warning (image ${image.url}): Download failed`,
reason,
),
{ ...image, data: "" }),
)
: d;
}),
);
imageContents.forEach((image) =>
images.addFile(`${image.id}.${image.extension}`, image.data)
);
}
}
protected async makeCover() {
if (!this.cover) return this.log("No cover to download");
const coverContent = await retryFetch(
this.options.cover,
this.options.fetchTimeout,
this.options.retryTimes,
this.log,
)
.catch(
(reason) => (this.warn(
`Warning (cover ${this.options.cover}): Download failed`,
reason,
),
""),
);
this.zip.addFile(`OEBPS/cover.${this.cover.extension}`, coverContent);
}
}