-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
130 lines (102 loc) · 3.03 KB
/
index.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
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
const startTime = process.uptime();
const fs = require('fs');
const http = require('http');
const https = require('https');
const input_path = './input/';
const output_path = `./output/${Date.now()}`;
/**
* Check if directories exists
*/
if (!fs.existsSync('./input/')) {
fs.mkdirSync('./input/');
}
if (!fs.existsSync('./output/')) {
fs.mkdirSync('./output');
}
/**
* File reader
*/
const files = fs.readdirSync(input_path);
files.forEach(filename => {
try {
if (filename.endsWith('.har')) {
parseHar(filename);
}
} catch (error) {
console.error(error);
}
});
/**
* .har parser
*/
function parseHar(filename) {
fs.readFile(input_path + filename, async (err, data) => {
const entries = JSON.parse(new TextDecoder().decode(data)).log.entries;
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
if (entry.request.url.startsWith('http')) {
const correct = i + 1;
if (!await parseEntry(filename, entry)) {
console.log(`Downloading.. | Progress: ${correct}/${entries.length}`);
}
console.log((parseEntry(filename, entry)
? `file not cached, downloading..`
: `file is cached, copying..`) + ` | ${correct}/${entries.length}`)
}
}
console.log('Finished at ' + (process.uptime() - startTime).toFixed(2) + ' second(s)');
});
}
async function parseEntry(fn, entry) {
const _domain = fn.split('.har')[0]
const domain = entry.request.url.split('/')[2];
if (domain != _domain) {
console.log(domain + ' ' + _domain);
return;
}
const __split = entry.request.url.split(_domain);
const path = output_path + __split[1].split('?')[0];
const _filename = path.split('/')[path.split('/').length - 1];
const _dir = path.split(_filename)[0];
const __path = path.split('/');
let _path = "";
_dir.split('/').forEach(dir => {
if (dir.length > 0) {
const count = __path.length;
const element = __path[count];
if (element != _filename) {
_path += dir + "/";
if (!fs.existsSync(_path)) {
fs.mkdirSync(_path);
}
}
}
});
let content = await download(entry.request.url);
console.log(_path + _filename);
fs.writeFile(_path + _filename, content, (err) => {
if (err)
throw err;
});
}
/**
* Download func.
*/
function download(url) {
return new Promise((resolve, reject) => {
let client = http;
if (url.startsWith('https'))
client = https;
client.get(url, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve(data);
});
}).on('error', (err) => {
resolve(false);
});
})
}