-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathconvert.js
234 lines (193 loc) · 6.76 KB
/
convert.js
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
"use strict";
const path = require("path");
const fs = require("fs").promises;
const workerpool = require("workerpool");
const progressUtils = require("./progress-utils.js");
module.exports = async (
cachePath,
manifestPath,
chapterDataPath,
contentPath,
bookData,
substitutionsPath,
concurrentJobs,
chapterTitleStyle
) => {
const manifestChapters = JSON.parse(await fs.readFile(manifestPath, { encoding: "utf-8" }));
const chapterData = getChapterData(bookData.arcs, manifestChapters, chapterTitleStyle);
await fs.writeFile(chapterDataPath, JSON.stringify(chapterData, null, 2));
const flattenedChapters = chapterData.flatMap(arc => arc.chapters);
const substitutionsText = await fs.readFile(substitutionsPath, { encoding: "utf-8" });
const substitutions = parseSubstitutions(substitutionsText);
console.log("Converting raw downloaded HTML to EPUB chapters");
const progress = progressUtils.start(flattenedChapters.length);
const poolOptions = {};
if (concurrentJobs !== undefined) {
poolOptions.maxWorkers = concurrentJobs;
}
const pool = workerpool.pool(path.resolve(__dirname, "convert-worker.js"), poolOptions);
const warnings = [];
await Promise.all(flattenedChapters.map(async chapter => {
const inputPath = path.resolve(cachePath, chapter.inputFilename);
const outputPath = path.resolve(contentPath, chapter.outputFilename);
const chapterSubstitutions = substitutions.get(chapter.url) || [];
warnings.push(...await pool.exec("convertChapter", [
chapter,
bookData.title,
inputPath,
outputPath,
chapterSubstitutions
]));
progressUtils.increment(progress);
}));
pool.terminate();
for (const warning of warnings) {
console.warn(warning);
}
console.log(`All chapters converted in ${progressUtils.getTotalSeconds(progress)} seconds`);
};
function getChapterData(arcs, manifest, chapterTitleStyle) {
const manifestMap = new Map(manifest.map(entry => [entry.url, entry]));
const chapterData = structuredClone(arcs);
for (const arc of chapterData) {
for (const chapter of arc.chapters) {
const manifestEntry = manifestMap.get(chapter.url);
chapter.inputFilename = manifestEntry.filename;
chapter.outputFilename = `${path.basename(chapter.inputFilename, ".html")}.xhtml`;
chapter.originalTitle = manifestEntry.title;
chapter.usedTitle = chooseChapterTitle(chapter, chapterTitleStyle);
chapter.datePublished = manifestEntry.datePublished;
chapter.dateModified = manifestEntry.dateModified;
}
}
return chapterData;
}
function chooseChapterTitle(chapterData, chapterTitleStyle) {
if (chapterTitleStyle === "original") {
if (!chapterData.originalTitle) {
throw new Error(`originalTitle not found in chapter data for ${chapterData.url}`);
}
return chapterData.originalTitle;
}
if (chapterTitleStyle === "simplified") {
if (!chapterData.simplifiedTitle) {
throw new Error(`simplifiedTitle not found in chapter data for ${chapterData.url}`);
}
return chapterData.simplifiedTitle;
}
if (chapterTitleStyle === "character-names") {
if (!chapterData.characterNamesTitle) {
if (!chapterData.simplifiedTitle) {
throw new Error(`Neither characterNamesTitle nor simplifiedTitle found in chapter data for ${chapterData.url}`);
}
return chapterData.simplifiedTitle;
}
return chapterData.characterNamesTitle;
}
throw new Error(`Invalid chapter title style: ${chapterTitleStyle}`);
}
function parseSubstitutions(text) {
const lines = text.split("\n");
const result = new Map();
let currentChapter = null;
let currentBefore = null;
let currentRegExp = null;
for (const [lineNumber, line] of Object.entries(lines)) {
// Skip empty lines
if (!line.trim()) {
continue;
}
const errorPrefix = `Error in substitutions line "${line}" (line number ${Number(lineNumber) + 1}): `;
let sigil, content;
try {
[, sigil, content] = /(@ | {2}- | {2}\+ ?| {2}r | {2}s | {2}# )(.*)/u.exec(line);
} catch {
throw new Error(`${errorPrefix}invalid line format`);
}
switch (sigil) {
// New chapter
case "@ ": {
if (!isCanonicalizedURL(content)) {
throw new Error(`${errorPrefix}invalid chapter URL`);
}
currentChapter = content;
if (!result.has(currentChapter)) {
result.set(currentChapter, []);
}
currentBefore = null;
currentRegExp = null;
break;
}
// Before line
case " - ": {
if (!currentChapter) {
throw new Error(`${errorPrefix}missing previous current chapter (@) line`);
}
if (currentBefore) {
throw new Error(`${errorPrefix}appeared after a before (-) line`);
}
if (currentRegExp) {
throw new Error(`${errorPrefix}appeared after a regexp (r) line`);
}
currentBefore = content.replaceAll("\\n", "\n");
currentRegExp = null;
break;
}
// After line
case " +":
case " + ": {
if (!currentChapter || !currentBefore) {
throw new Error(`${errorPrefix}missing previous current chapter (@) or before (-) line`);
}
if (currentRegExp) {
throw new Error(`${errorPrefix}appeared after a regexp (r) line`);
}
const change = {
before: beforeAfterLineToString(currentBefore),
after: beforeAfterLineToString(content)
};
result.get(currentChapter).push(change);
currentBefore = null;
break;
}
// RegExp line
case " r ": {
if (!currentChapter) {
throw new Error(`${errorPrefix}missing previous current chapter (@) line`);
}
if (currentBefore) {
throw new Error(`${errorPrefix}appeared after a before (-) line`);
}
currentRegExp = new RegExp(content, "ug");
break;
}
// RegExp substitution
case " s ": {
if (!currentChapter || !currentRegExp) {
throw new Error(`${errorPrefix}missing previous current chapter (@) or regexp (r) line`);
}
const change = {
regExp: currentRegExp,
replacement: content.replaceAll("\\n", "\n")
};
result.get(currentChapter).push(change);
currentRegExp = null;
break;
}
// Comment
case " # ": {
if (!currentChapter) {
throw new Error(`${errorPrefix} missing previous current chapter (@) line`);
}
break;
}
}
}
return result;
}
function isCanonicalizedURL(urlString) {
return URL.parse(urlString).href === urlString;
}
function beforeAfterLineToString(line) {
return line.replaceAll("\\n", "\n").replace(/(?:\\s)+$/u, match => " ".repeat(match.length / 2));
}