-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch-epub.js
193 lines (165 loc) · 5.6 KB
/
search-epub.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
const { exec } = require("child_process");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
// Retrieve command-line arguments
const [, , epubFilePath, searchText] = process.argv;
if (!epubFilePath || !searchText) {
console.error("Usage: node searchEpub.js <path_to_epub> <search_text>");
process.exit(1);
}
if (!fs.existsSync(epubFilePath)) {
console.error(`Error: File not found at ${epubFilePath}`);
process.exit(1);
}
const outputJsonPath = path.join(__dirname, "cfi_output.json");
const cacheFilePath = path.join(__dirname, "cfi_cache.json");
const epubCfiGeneratorPath = path.join(
__dirname,
"node_modules",
".bin",
"epub-cfi-generator",
);
const generateFileHash = (filePath) => {
const hash = crypto.createHash("sha256");
const fileBuffer = fs.readFileSync(filePath);
hash.update(fileBuffer);
return hash.digest("hex");
};
const isCacheValid = () => {
if (!fs.existsSync(cacheFilePath)) {
return false;
}
const cacheData = JSON.parse(fs.readFileSync(cacheFilePath, "utf8"));
const epubHash = generateFileHash(epubFilePath);
return cacheData.epubHash === epubHash;
};
const getCfis = (callback) => {
if (isCacheValid()) {
const cachedData = JSON.parse(fs.readFileSync(cacheFilePath, "utf8"));
callback(null, cachedData.cfiData);
} else {
exec(
`"${epubCfiGeneratorPath}" "${epubFilePath}" "${outputJsonPath}"`,
(error, stdout, stderr) => {
if (error) {
console.error(`Error generating CFIs: ${stderr}`);
callback(error);
return;
}
fs.readFile(outputJsonPath, "utf8", (err, data) => {
if (err) {
console.error(`Error reading output JSON: ${err.message}`);
callback(err);
return;
}
const cfiData = JSON.parse(data);
const cacheData = {
epubHash: generateFileHash(epubFilePath),
cfiData,
};
fs.writeFileSync(cacheFilePath, JSON.stringify(cacheData, null, 2));
fs.unlinkSync(outputJsonPath);
callback(null, cfiData);
});
},
);
}
};
const normalizeWhitespace = (text) => {
return text.replace(/\s+/g, " ").trim();
};
const formatEpubCfi = (startCfi, endCfi, startOffset, endOffset) => {
// Extract the path and offset from both the start and end CFIs
const [startPath, startOffsetValue] = startCfi.split(":");
const [endPath, endOffsetValue] = endCfi.split(":");
// Remove the final segment (last /n) from both paths
const sanitizedStartPath = startPath.replace(/\/\d+$/, "");
const sanitizedEndPath = endPath.replace(/\/\d+$/, "");
// Find the common part of the path
let commonPart = "";
const startPathParts = sanitizedStartPath.split("/");
const endPathParts = sanitizedEndPath.split("/");
// Loop through both paths and find the common segment
let i = 0;
while (
i < startPathParts.length && i < endPathParts.length &&
startPathParts[i] === endPathParts[i]
) {
commonPart = `${commonPart}/${startPathParts[i]}`;
i++;
}
// Extract the last dissimilar segments (before the offsets)
const dissimilarStart = startPath.slice(commonPart.length);
const dissimilarEnd = endPath.slice(commonPart.length);
// Determine if we need to include the last segment in the dissimilar part
const startEntity = `/${dissimilarStart}:${startOffset}`;
const endEntity = `/${dissimilarEnd}:${endOffset}`;
// Format the result as epubcfi({common_part},{start_entity},{end_entity})
return `epubcfi(${commonPart.slice(1)},${startEntity},${endEntity})`;
};
const searchCfiData = (cfiData, searchText) => {
const normalizedSearchText = normalizeWhitespace(searchText);
let found = false;
const flattened = cfiData.flatMap((heading) =>
heading.content.map((section) => ({
node: normalizeWhitespace(section.node),
cfi: section.cfi,
}))
);
for (let i = 0; i < flattened.length; i++) {
let combinedText = "";
let charMap = [];
let startCfi = "";
let endCfi = "";
let startOffset = -1;
let endOffset = -1;
for (let j = i; j < flattened.length; j++) {
const currentNode = flattened[j];
const currentText = currentNode.node;
const currentTextLength = currentText.length;
charMap.push({
cfi: currentNode.cfi,
start: combinedText.length,
end: combinedText.length + currentTextLength,
});
combinedText += (j > i ? " " : "") + currentText;
if (combinedText.includes(normalizedSearchText)) {
console.log("Current Node:", currentNode.node);
console.log("Lenght of the combinedText:", combinedText.length);
const startIdx = combinedText.indexOf(normalizedSearchText) - 1;
const endIdx = startIdx + normalizedSearchText.length;
for (const map of charMap) {
if (startIdx >= map.start && startIdx < map.end) {
startCfi = map.cfi;
startOffset = startIdx - map.start;
}
if (endIdx > map.start && endIdx <= map.end) {
endCfi = map.cfi;
endOffset = endIdx - map.start;
}
}
// Format and output the result with EPUB CFI format
console.log(
formatEpubCfi(startCfi, endCfi, startOffset, endOffset),
);
found = true;
break;
}
if (combinedText.length > normalizedSearchText.length * 2) {
break;
}
}
if (found) break;
}
if (!found) {
//console.log("Text not found in the EPUB.");
process.exit(1);
}
};
getCfis((error, cfiData) => {
if (error) {
process.exit(1);
}
searchCfiData(cfiData, searchText);
});