This repository has been archived by the owner on May 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
mirror.js
87 lines (82 loc) · 2.39 KB
/
mirror.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
'use strict';
var fs = require('co-fs');
var path = require('path');
var utilities = require('./utilities');
var Writer = require('./writer');
/**
* Mirror the chapter.
* @param {!Series} series
* @param {!Chapter} chapter Requires to be populated.
* @param {string=} extension
* @return {boolean}
*/
module.exports = function *(series, chapter, extension) {
var pathToBook = utilities.createPathToBook(series, chapter, extension);
if (pathToBook) {
var tempPathToBook = pathToBook + '.mrdownload';
yield ensure(tempPathToBook);
yield publish(new Writer(tempPathToBook), series, chapter);
yield fs.rename(tempPathToBook, pathToBook);
return true;
}
return false;
};
/**
* Ensures the directory to contain the book exists.
* @param {string} pathToBook
*/
function *ensure(pathToBook) {
var pathToDirectory = path.dirname(pathToBook);
if (!(yield fs.exists(pathToDirectory))) {
yield fs.mkdir(pathToDirectory);
}
}
/**
* Publish the chapter.
* @param {!Writer} writer
* @param {!Series} series
* @param {!Chapter} chapter
*/
function *publish(writer, series, chapter) {
yield publishPreviewImage(writer, series);
for (var i = 0; i < chapter.children.length; i += 1) {
var page = chapter.children[i];
yield utilities.request(page);
yield publishPage(writer, page, i + 1);
}
writer.publish();
}
/**
* Publish the preview image.
* @param {!Writer} writer
* @param {!Series} series
*/
function *publishPreviewImage(writer, series) {
if (series.imageAddress) {
var imageAddresses = [].concat(series.imageAddress);
for (var i = 0; i < imageAddresses.length; i += 1) {
var imageAddress = imageAddresses[i];
var image = yield utilities.request(imageAddress, 'binary');
if (image) {
writer.add(series.imageAddress, 0, image);
}
}
}
}
/**
* Publish the page
* @param {!Writer} writer
* @param {!Page} page
* @param {number} number
*/
function *publishPage(writer, page, number) {
var imageAddresses = [].concat(page.imageAddress);
for (var i = 0; i < imageAddresses.length; i += 1) {
var imageAddress = imageAddresses[i];
var image = yield utilities.request(imageAddress, 'binary');
if (image) {
writer.add(imageAddress, number, image);
return;
}
}
}