forked from ecmadao/hacknical
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdownloads.js
72 lines (59 loc) · 1.66 KB
/
downloads.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
import phantom from 'phantom';
import path from 'path';
import fs from 'fs-extra';
import klawSync from 'klaw-sync';
import config from 'config';
import logger from '../utils/logger';
const sourcePath = config.get('downloads');
const waitUntil = asyncFunc => new Promise((resolve, reject) => {
const wait = () => {
asyncFunc().then((value) => {
if (value === true) {
resolve();
} else {
setTimeout(wait, 100);
}
}).catch((e) => {
reject(e);
});
}
wait();
});
const clearFolder = folder =>
process.nextTick(() => {
const files = klawSync(folder, { nodir: true });
for (const file of files) {
fs.removeSync(file.path);
}
});
const renderScreenshot = async (input, output) => {
const instance = await phantom.create();
const page = await instance.createPage();
await page.property('viewportSize', { width: 1024, height: 600 });
await page.open(input);
await waitUntil(() => page.evaluate(() => window.done));
await page.render(output);
await instance.exit();
};
const downloadResume = async (url, options = {}) => {
const {
title,
folder
} = options;
const resultFloder = path.resolve(__dirname, sourcePath, folder);
// makesure folder exist
await fs.ensureDirSync(sourcePath);
await fs.ensureDir(resultFloder);
const filePath = path.resolve(resultFloder, title);
const resultPath = `/downloads/${folder}/${title}`;
logger.info(`[RESUME:DOWNLOAD:RENDER-PATH] ${filePath}`);
if (fs.existsSync(filePath)) {
return resultPath;
}
clearFolder(resultFloder);
await renderScreenshot(url, filePath);
return resultPath;
};
export default {
resume: downloadResume
};