-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
262 lines (211 loc) · 6.53 KB
/
index.js
File metadata and controls
262 lines (211 loc) · 6.53 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
import yargs from 'yargs';
import PromptSync from 'prompt-sync';
import fetch from 'node-fetch';
import yauzl from 'yauzl';
import { PDFDocument } from 'pdf-lib';
import fs from 'fs';
import fsExtra from 'fs-extra';
import path from 'path';
import { spawn } from 'child_process';
import { pipeline } from 'stream';
const argv = yargs(process.argv)
.option('id', {
alias: 'i',
type: 'string',
description: 'user id (email)',
})
.option('password', {
alias: 'p',
type: 'string',
description: 'user password',
})
.option('gedi', {
alias: 'g',
type: 'string',
description: 'book\'s gedi',
})
.option('output', {
alias: 'o',
type: 'string',
description: 'Output file',
})
.option('download', {
type: 'boolean',
description: 'Download the book',
default: true,
hidden: true,
})
.option('no-download', {
type: 'boolean',
description: 'Skip downloading the book and try to extract the zip file that is already in the temp folder',
default: false,
})
.option('clean', {
type: 'boolean',
description: 'Clean up the temp folder after finishing',
default: true,
hidden: true,
})
.option('no-clean', {
type: 'boolean',
description: 'Don\'t clean up the temp folder after finishing',
default: false,
})
.help()
.argv;
const prompt = PromptSync({ sigint: true });
function promisify(api) {
return function (...args) {
return new Promise(function (resolve, reject) {
api(...args, function (err, response) {
if (err) return reject(err);
resolve(response);
});
});
};
}
const yauzlFromFile = promisify(yauzl.open);
(async () => {
await fsExtra.ensureDir('tmp');
let book;
if (argv.download) {
let folder = await fs.promises.readdir('tmp');
if (folder.length > 0) {
console.log('Temp folder is not empty, make sure to delete the tmp folder if you want to download the book');
process.exit(1);
}
let id = argv.id;
let password = argv.password;
console.log('Warning: this script might log you out of your other devices');
while (!id)
id = prompt('Enter account email: ');
while (!password)
password = prompt('Enter account password: ');
let userAuth = await fetch('https://npmoffline.sanoma.it/mcs/api/v1/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Timezone-Offset': '+0200', // this is required for whatever reason
},
body: JSON.stringify({
id: id,
password: password,
}),
}).then((res) => res.json()).catch((err) => {
console.error('Failed to log in');
process.exit(1);
});
if (userAuth.code != 0) {
console.error('Failed to log in', userAuth.message);
process.exit(1);
}
await fetch(`https://npmoffline.sanoma.it/mcs/users/${id}/products/`, {
headers: {
'X-Auth-Token': 'Bearer ' + userAuth.result.data.access_token,
}
})
console.log('Fetching book list');
let books = {};
let pages = 1;
for (let i = 1; i <= pages; i++) {
let newBooks = await fetch(`https://npmoffline.sanoma.it/mcs/api/v1/books?app=true`, {
headers: {
'X-Auth-Token': 'Bearer ' + userAuth.result.data.access_token,
}
}).then((res) => res.json());
pages = newBooks.result.total_size / newBooks.result.page_size;
for (let book of newBooks.result.data) {
books[book.gedi] = book;
}
}
console.log('Books:');
console.table(Object.fromEntries(Object.entries(books).map(([id, book]) => [id, book.name])));
let gedi = argv.gedi;
while (!gedi)
gedi = prompt('Enter the book\'s gedi: ');
book = books[gedi];
console.log('Downloading "' + book.name + '"');
let zip = await fetch(book.url_download);
if (!zip.ok) {
console.error('Failed to download zip');
process.exit(1);
}
await promisify(pipeline)(zip.body, fs.createWriteStream('tmp/book.zip'));
} else {
console.log('Skipping download');
let stats = await fs.promises.stat('tmp/book.zip');
if (!stats.isFile()) {
console.error('No zip file found in the tmp folder');
process.exit(1);
}
}
console.log('Extracting zip');
let zipFile = await yauzlFromFile('tmp/book.zip');
let openReadStream = promisify(zipFile.openReadStream.bind(zipFile));
zipFile.on('entry', async (entry) => {
console.log('Entry: ' + entry.fileName);
if (!entry.fileName.startsWith("pages") || entry.fileName.endsWith('/')) return;
let filePath = entry.fileName.slice(5);
console.log('Extracting ' + filePath);
let folder = path.dirname(filePath);
await fsExtra.ensureDir(`tmp/pages/${folder}`);
let page = await openReadStream(entry);
let file = fs.createWriteStream(`tmp/pages/${filePath}`);
page.pipe(file);
});
zipFile.on('end', async () => {
await fs.promises.mkdir('tmp/output', { recursive: true });
let folders = (await fs.promises.readdir('tmp/pages')).filter((file) => /^\d+$/g.test(file));
let total = folders.length;
for (let i = 0; i < total; i++) {
console.log('Converting page ' + (i + 1) + ' of ' + total);
await convertPage(`tmp/pages/${i+1}/${i+1}.svg`, `tmp/output/${i+1}.pdf`);
}
console.log('Merging pages');
let pdf = await PDFDocument.create();
for (let i = 0; i < total; i++) {
let file = await fs.promises.readFile(`tmp/output/${i+1}.pdf`);
let page = await PDFDocument.load(file);
let [copiedPage] = await pdf.copyPages(page, [0]);
pdf.addPage(copiedPage);
}
console.log('Saving PDF');
let name = argv.output;
if (argv.download && !name) {
name = book.name.replace(/[\\/:*?"<>|]/g, '') + '.pdf';
} else if (!name) {
name = 'output.pdf';
}
await fs.promises.writeFile(name, await pdf.save());
if (argv.clean) {
console.log('Cleaning up');
await fsExtra.remove('tmp');
} else {
console.log('Skipping clean up, make sure to delete the temp folder when you are done');
}
console.log('Done');
});
})();
let inkscapeVersion; // old = 0.92 or older, new = anything after
async function getInkscapeVersion() {
return new Promise((resolve, reject) => {
let convert = spawn('inkscape', ['--version']);
convert.stdout.on("data", data => {
const version = data.toString();
const [_, major, minor ] = version.match(/(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)/);
if (major == 0 && minor <= 92) inkscapeVersion = "old";
else inkscapeVersion = "new";
resolve();
});
});
}
async function convertPage(input, output) {
return new Promise(async (resolve, reject) => {
if (!inkscapeVersion) await getInkscapeVersion();
let convert = spawn('inkscape', [(inkscapeVersion == "old" ? '--export-pdf=' : '--export-filename=') +output, input]);
convert.on('close', (code) => {
if (code == 0) resolve();
else reject(code);
});
});
}