-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
295 lines (270 loc) · 11 KB
/
content.js
File metadata and controls
295 lines (270 loc) · 11 KB
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
async function createWorker() {
const workerUrl = chrome.runtime.getURL("worker.js");
const response = await fetch(workerUrl);
let code = await response.text();
const libs = [
"libs/pdfkit.standalone.js",
"libs/blob-stream.min.js",
"libs/SVG-to-PDFKit.js",
"libs/jszip.min.js"
].map(l => chrome.runtime.getURL(l));
const header = `importScripts(${libs.map(u => `"${u}"`).join(", ")});\n`;
const blob = new Blob([header + code], { type: "application/javascript" });
return new Worker(URL.createObjectURL(blob));
}
function getDecryptionKey() {
const renderVerInput = document.querySelector('#render-ver');
return renderVerInput.value.split(':')[0];
}
async function getBookMetadata(bookId) {
const response = await fetch(`https://znanium.ru/catalog/document?id=${bookId}`, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}
});
if (!response.ok) {
console.error('Ошибка загрузки страницы');
return { author: 'Неизвестный автор', toc: null };
}
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
let author = 'Неизвестный автор';
const authorDiv = doc.querySelector('.book-link.qa_booklist_autors');
if (authorDiv) {
const firstAuthor = authorDiv.querySelector('a');
if (firstAuthor) {
author = firstAuthor.textContent.trim();
}
}
let toc = null;
const tocContainer = doc.querySelector('.book-single__headers-wrap');
if (tocContainer) {
toc = parseTableOfContents(tocContainer);
}
return { author, toc };
}
function parseTableOfContents(container) {
function parseItems(parentElement) {
let items = [];
parentElement.querySelectorAll(":scope > .book-single__header-item").forEach((item) => {
const titleElement = item.querySelector(".title");
const pageElement = item.querySelector(".page-number");
const subItemsContainer = item.querySelector(".subitems");
if (titleElement && pageElement) {
let tocItem = {
title: titleElement.textContent.trim(),
page: parseInt(pageElement.textContent.trim(), 10),
link: titleElement.getAttribute("href"),
subitems: subItemsContainer ? parseItems(subItemsContainer) : []
};
items.push(tocItem);
}
});
return items;
}
return parseItems(container);
}
async function requestPage(pageNumber, bookId, format) {
return new Promise((resolve, reject) => {
function messageHandler(event) {
if (event.source !== window) return;
if (event.data.action === "pageResponse") {
window.removeEventListener("message", messageHandler);
resolve(event.data.page);
} else if (event.data.action === "pageError") {
window.removeEventListener("message", messageHandler);
reject(new Error(event.data.error));
}
}
window.addEventListener("message", messageHandler);
window.postMessage({
action: "getPage",
pageNumber: pageNumber,
bookId: bookId,
format: format
}, "*");
});
}
async function fetchPage(bookId, pageNumber, format) {
let attempts = 0;
const maxAttempts = 25;
while (attempts < maxAttempts) {
try {
let pageContent = await requestPage(pageNumber, bookId, format);
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(pageContent, "text/xml");
if (format === 'epub') {
let pageTextElement = xmlDoc.querySelector("page_text");
if (!pageTextElement?.textContent?.trim()) {
throw new Error("Текст страницы не найден");
}
return pageTextElement.textContent.trim();
} else {
let bookpageElement = xmlDoc.querySelector("bookpage");
if (!bookpageElement?.textContent?.trim()) {
throw new Error("SVG не найден");
}
return bookpageElement.textContent.trim();
}
} catch (error) {
console.log(`Ошибка при загрузке страницы ${pageNumber}, попытка ${attempts + 1}/${maxAttempts}:`, error);
attempts++;
if (attempts >= maxAttempts) {
alert(`Не удалось загрузить страницу ${pageNumber} после ${maxAttempts} попыток`);
setError(`Не удалось загрузить страницу ${pageNumber} после ${maxAttempts} попыток`);
return;
}
await new Promise(resolve => setTimeout(resolve, 2500));
}
}
}
async function downloadEPUB(startPage, endPage, bookTitle, bookId, totalPages, worker, processedPages) {
const { author, toc } = await getBookMetadata(bookId);
worker.postMessage({
action: "initEPUB",
bookTitle,
bookId,
author,
toc
});
let downloadStopped = false;
let allPagesQueued = false;
let finalizeRequested = false;
let pagesQueuedCount = 0;
const tryFinalizeEPUB = () => {
if (!finalizeRequested && allPagesQueued && !downloadStopped && processedPages === pagesQueuedCount) {
if (pagesQueuedCount === 0) {
chrome.runtime.sendMessage({ action: "stopDownload" });
worker.terminate();
return;
}
finalizeRequested = true;
worker.postMessage({ action: "finalizeEPUB" });
}
};
worker.onmessage = (e) => {
if (e.data.action === "pageAdded") {
processedPages++;
updateProgress(Math.round((processedPages / totalPages) * 100));
tryFinalizeEPUB();
} else if (e.data.action === "done") {
const blob = e.data.blob;
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `${bookTitle}.epub`;
link.click();
chrome.runtime.sendMessage({ action: "stopDownload" });
finalizeRequested = true;
worker.terminate();
} else if (e.data.action === "error") {
setError(`Ошибка в воркере EPUB`);
chrome.runtime.sendMessage({ action: "stopDownload" });
downloadStopped = true;
finalizeRequested = true;
worker.terminate();
}
};
for (let page = startPage; page <= endPage; page++) {
if (downloadStopped) break;
let pageContent = await fetchPage(bookId, page, "epub");
if (pageContent === undefined) {
setError(`Скачивание прервано на странице ${page}`);
break;
}
worker.postMessage({ action: "addPageEPUB", text: pageContent });
pagesQueuedCount++;
}
allPagesQueued = true;
tryFinalizeEPUB();
}
async function downloadPDF(startPage, endPage, bookTitle, bookId, totalPages, worker, processedPages) {
const decryptionKey = getDecryptionKey();
worker.postMessage({ action: "initPDF", bookTitle, wasmUrl: chrome.runtime.getURL("decryptSVG.wasm") });
let downloadStopped = false;
let allPagesQueued = false;
let finalizeRequested = false;
let pagesQueuedCount = 0;
const tryFinalizePDF = () => {
if (!finalizeRequested && allPagesQueued && !downloadStopped && processedPages === pagesQueuedCount) {
if (pagesQueuedCount === 0) {
chrome.runtime.sendMessage({ action: "stopDownload" });
worker.terminate();
return;
}
finalizeRequested = true;
worker.postMessage({ action: "finalizePDF" });
}
};
worker.onmessage = (e) => {
if (e.data.action === "pageAdded") {
processedPages++;
updateProgress(Math.round((processedPages / totalPages) * 100));
tryFinalizePDF();
} else if (e.data.action === "done") {
finalizeRequested = true;
const dataBuffer = e.data.buffer;
const blob = dataBuffer ? new Blob([dataBuffer], { type: 'application/pdf' }) : e.data.blob;
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `${bookTitle}.pdf`;
link.click();
chrome.runtime.sendMessage({ action: "stopDownload" });
worker.terminate();
} else if (e.data.action === "error") {
setError(`Ошибка при скачивании страницы`);
chrome.runtime.sendMessage({ action: "stopDownload" });
downloadStopped = true;
finalizeRequested = true;
worker.terminate();
}
};
for (let page = startPage; page <= endPage; page++) {
if (downloadStopped) break;
let pageContent = await fetchPage(bookId, page, "pdf");
if (pageContent === undefined) {
setError(`Скачивание прервано на странице ${page}`);
break;
}
worker.postMessage({
action: "addPagePDF",
svgData: pageContent,
key: decryptionKey,
pageNumber: page
});
pagesQueuedCount++;
}
allPagesQueued = true;
tryFinalizePDF();
}
async function startDownload(startPage, endPage, format) {
const bookTitle = document.querySelector('p.book__name a')?.textContent.trim() || "Книга";
const bookId = getBookIdFromURL();
if (!bookId) {
alert('Номер книги не найден в ссылке.');
setError('Номер книги не найден в ссылке.');
return;
}
const totalPages = endPage - startPage + 1;
const worker = await createWorker();
if (format === "epub") {
await downloadEPUB(startPage, endPage, bookTitle, bookId, totalPages, worker, 0);
} else {
if (!document.querySelector('#render-ver')) {
alert('Не найден ключ расшифровки.');
setError('Не найден ключ расшифровки.');
return;
}
await downloadPDF(startPage, endPage, bookTitle, bookId, totalPages, worker, 0);
}
}
function updateProgress(percentage) {
chrome.runtime.sendMessage({ action: 'updateProgress', percentage });
}
function getBookIdFromURL() {
return new URLSearchParams(window.location.search).get('id');
}
function setError(text) {
chrome.runtime.sendMessage({ action: 'setError', text });
}
window.startDownload = startDownload;