forked from Sneezry/Kepler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
426 lines (385 loc) · 13.4 KB
/
background.js
File metadata and controls
426 lines (385 loc) · 13.4 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
"use strict";
let busy = false;
function httpRequest(url, isBlob){
console.log(`Getting ${url}...`);
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(isBlob ? xhr.response : xhr.responseText);
} else {
reject(new Error(`Error code: ${xhr.status}`));
}
return;
}
}
xhr.onerror = error => {
reject(error);
return;
}
if (isBlob) {
xhr.responseType = 'blob';
}
xhr.send();
});
}
function getBookInfo(url) {
const matches = url.match(/learning\.oreilly\.com\/library\/view\/(.*?)\/(\d+)[\/$]/);
if (matches && matches.length > 2) {
return {
title: matches[1],
id: matches[2]
};
}
return null;
}
function generateTOC(toc) {
let depth = 0;
let root = {
children: []
};
let indexes = [];
let lastDepth = null;
toc.items.forEach(item => {
depth = Math.max(depth, item.depth);
let _depth = item.depth - 1;
indexes[_depth] = indexes[_depth] || 0;
if (lastDepth === null || lastDepth < item.depth) {
indexes[_depth] = 0;
} else {
indexes[_depth]++;
}
let _point = root;
for (let i = 0; i <= _depth; i++) {
_point.children[indexes[i]] = _point.children[indexes[i]] || {
label: null,
order: null,
id: null,
href: null,
children: []
};
_point = _point.children[indexes[i]];
}
_point.label = item.label;
_point.order = item.order;
_point.id = item.id;
_point.src = item.href;
lastDepth = item.depth;
});
let navMap = getMap(root.children);
let ncx = `<?xml version="1.0" encoding="utf-8" standalone="no"?>
<ncx xmlns:ncx="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">
<head>
<meta name="cover" content="cover"/>
<meta name="dtb:uid" content="isbn:${toc.book_id}"/>
<meta name="dtb:depth" content="${depth}"/>
<meta name="dtb:totalPageCount" content="0"/>
<meta name="dtb:maxPageNumber" content="0"/>
</head>
<docTitle>
<text>${toc.title}</text>
</docTitle>
<docAuthor>
<text>${toc.authors}</text>
</docAuthor>
<navMap>
${navMap}
</navMap>
</ncx>`;
let opfItems = '';
let xmlItems = '';
toc.items.forEach(item => {
opfItems = `${opfItems}
<item id="${item.id}" href="${item.href.split('#')[0]}" media-type="${item.media_type}"/>
`;
if (item.media_type === 'application/xhtml+xml') {
xmlItems = `${xmlItems}
<itemref idref="${item.id}"/>
`;
}
});
let opf = `<?xml version="1.0" encoding="utf-8" standalone="no"?>
<package xmlns:epub="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="bookid">
<metadata>
<dc:identifier xmlns:dc="http://purl.org/dc/elements/1.1/" id="bookid">urn:isbn:${toc.book_id}</dc:identifier>
<dc:title xmlns:dc="http://purl.org/dc/elements/1.1/">${toc.title}</dc:title>
<!-- <dc:rights xmlns:dc="http://purl.org/dc/elements/1.1/"></dc:rights> -->
<dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">${toc.publisher.name}</dc:publisher>
<!-- <dc:subject xmlns:dc="http://purl.org/dc/elements/1.1/"></dc:subject> -->
<dc:date xmlns:dc="http://purl.org/dc/elements/1.1/">${toc.pub_date}</dc:date>
<!-- <dc:description xmlns:dc="http://purl.org/dc/elements/1.1/"></dc:description> -->
<dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf" opf:file-as="Douglas Crockford">${toc.authors}</dc:creator>
<dc:language xmlns:dc="http://purl.org/dc/elements/1.1/">en</dc:language>
<meta name="cover" content="cover-image"/>
</metadata>
<manifest>
<item id="ncxtoc" media-type="application/x-dtbncx+xml" href="toc.ncx"/>
<item id="cover-image" href="cover-image.jpg" media-type="image/jpeg"/>
${opfItems}
</manifest>
<spine toc="ncxtoc">
<itemref idref="cover-image" linear="no"/>
${xmlItems}
</spine>
</package>`;
return {ncx, opf};
}
function getMap(points) {
let map = '';
points.forEach(point => {
map = `${map}
<navPoint id="${point.id}" playOrder="${point.order}">
<navLabel>
<text>${point.label}</text>
</navLabel>
<content src="${point.src.split('#')[0]}"/>
${point.children ? getMap(point.children) : ''}
</navPoint>`;
});
return map;
}
function Kepler(info) {
this.id = info.id;
this.title = info.title;
this.pages = [];
this.gotItem = 0;
}
Kepler.prototype.INTERVAL = 1000;
Kepler.prototype.getBook = function() {
chrome.browserAction.setBadgeText({text: '0'});
return new Promise((resolve, reject) => {
const url = `https://learning.oreilly.com/nest/epub/toc/?book_id=${this.id}`;
httpRequest(url).then(res => {
try {
const toc = JSON.parse(res);
this.totalItem = toc.items.length;
this.toc = generateTOC(toc);
this.parseTOC(toc).then(() => {
this.getSingleImageData(`https://learning.oreilly.com/library/cover/${this.id}/720h/`, 'cover-image.jpg')
.then(() => {
this.save().then(resolve, reject);
}, reject);
}, reject);
} catch(error) {
reject(error);
}
}, reject);
});
}
Kepler.prototype.parseTOC = function(toc) {
return new Promise((resolve, reject) => {
const items = toc.items;
const itemPromises = [];
let currentIndex = 0;
const queue = setInterval(() => {
if (currentIndex < items.length) {
itemPromises.push(this.getSingleItem(items[currentIndex++]));
} else {
clearInterval(queue);
Promise.all(itemPromises).then(resolve, reject);
}
}, this.INTERVAL);
});
}
Kepler.prototype.getSingleItem = function(item) {
return new Promise((resolve, reject) => {
const url = `https://learning.oreilly.com${item.url}`;
httpRequest(url).then(res => {
try {
const page = JSON.parse(res);
this.getSinglePage(item, page).then(() => {
this.gotItem++;
const process = Math.floor(this.gotItem / this.totalItem * 100);
chrome.browserAction.setBadgeText({text: process.toString()});
resolve();
}, reject);
return;
} catch(error) {
reject(error);
return;
}
}, reject);
});
}
Kepler.prototype.getSinglePage = function(item, page) {
return new Promise((resolve, reject) => {
const url = page.content;
const name = page.full_path;
httpRequest(url).then(res => {
const content = `<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:epub="http://www.idpf.org/2007/ops">
<head>
<title>${page.title}</title>
</head>
<body>
${res}
</body>
</html>`;
const _page = {
name: name,
label: item.label,
order: item.order,
depth: item.depth,
base64: false,
content: content.replace(/ /g, ' ')
.replace(/<hr>/g, '<hr/>')
.replace(/<br>/g, '<br/>')
.replace(/(<img[^>]*[^\/>])>/g, '$1/>')
};
this.pages.push(_page);
this.getImages(page.images, page.full_path).then(resolve, reject);
}, reject);
});
}
Kepler.prototype.getImages = function(imagePaths, pagePath) {
return new Promise((resolve, reject) => {
const imagePromises = [];
let currentIndex = 0;
const queue = setInterval(() => {
if (currentIndex < imagePaths.length) {
if (pagePath.indexOf('/') === -1) {
pagePath = '';
} else {
pagePath = pagePath.substr(0, pagePath.lastIndexOf('/'));
}
let path = joinPath([pagePath, imagePaths[currentIndex++]]);
let url = `https://learning.oreilly.com/library/view/${this.title}/${this.id}/${path}`;
imagePromises.push(this.getSingleImageData(url, path));
} else {
clearInterval(queue);
Promise.all(imagePromises).then(resolve, reject);
}
}, this.INTERVAL);
});
}
Kepler.prototype.getSingleImageData = function(url, name) {
return new Promise((resolve, reject) => {
httpRequest(url, true).then(res => {
name = name || url.match(/([^\/]+)$/)[1];
const reader = new FileReader();
reader.onload = () => {
try {
const content = reader.result;
const image = {
name: name,
base64: true,
content: content.split(',')[1]
};
this.pages.push(image);
resolve();
return;
} catch(error) {
reject(error);
return;
}
};
reader.readAsDataURL(res);
}, reject);
});
}
Kepler.prototype.save = function() {
return new Promise((resolve, reject) => {
try {
chrome.browserAction.setBadgeText({text: '...'});
const title = this.title;
const toc = this.toc;
const zip = new JSZip();
zip.file('mimetype', 'application/epub+zip');
const meta = zip.folder('META-INF');
meta.file('container.xml', `<?xml version="1.0" encoding="utf-8" standalone="no"?>
<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">
<rootfiles>
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>`);
const OEBPS = zip.folder('OEBPS');
OEBPS.file('toc.ncx', toc.ncx);
OEBPS.file('content.opf', toc.opf);
this.pages.forEach(page => {
let current = OEBPS;
if (page.name.indexOf('/') !== -1) {
let path = joinPath(['OEBPS', page.name.substr(0, page.name.lastIndexOf('/'))]);
current = zip.folder(path);
page.name = page.name.substr(page.name.lastIndexOf('/') + 1);
}
current.file(page.name, page.content, {base64: page.base64});
});
zip.generateAsync({type:'blob'})
.then(function(content) {
saveAs(content, `${title}.epub`);
resolve();
}, reject);
} catch(error) {
reject(error);
}
});
}
function setBusy(_busy) {
busy = _busy;
const icon = _busy ? 'kepler-busy.png' : 'kepler.png';
chrome.browserAction.setIcon({
path: {
'19': icon,
'38': icon
}
});
if (!_busy) {
chrome.browserAction.setBadgeText({text: ''});
}
}
chrome.browserAction.setBadgeBackgroundColor({color: '#000'});
chrome.browserAction.onClicked.addListener((tab) => {
if (busy) {
return;
}
setBusy(true);
const url = tab.url;
if (!/:\/\/learning\.oreilly\.com/.test(url)) {
setBusy(false);
return;
}
const info = getBookInfo(url);
if (!info) {
setBusy(false);
return;
}
const kepler = new Kepler(info);
kepler.getBook().then(() => {
setBusy(false);
}, error => {
setBusy(false);
throw error;
});
});
function joinPath(paths) {
let path = [];
paths.forEach(_path => {
if (!_path) {
return;
}
let _paths = _path.split('/');
// _path start with /
if (_paths[0] === '') {
path = [];
for (let i = 1; i < _paths.length; i++) {
path.push(_paths[i]);
}
} else {
for (let i = 0; i < _paths.length; i++) {
// ignore // and ./
if (!_paths[i] || _paths[i] === '.') {
continue;
}
if (_paths[i] === '..') {
path.length = path.length - 1;
} else {
path.push(_paths[i]);
}
}
}
});
return path.join('/');
}