-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
util.js
286 lines (199 loc) · 6.99 KB
/
util.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
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
const fs = require(`fs`);
const { createGzip } = require('zlib');
const pipe = require(`util`).promisify(require(`stream`).pipeline);
const markdownLinkExtractor = require('markdown-link-extractor');
const fetch = require(`node-fetch`);
const FormData = require(`form-data`);
const odd = require(`open-directory-downloader`);
const { ScanError } = require(`./errors`)
const indexer = new odd.OpenDirectoryDownloader();
module.exports.scanUrls = async function scanUrls(urls) {
let scanResults = {
successful: [],
failed: [],
};
for (let url of urls) {
console.info(`Starting scan of '${url}'...`)
try {
scanResults.successful.push(await indexer.scanUrl(url, {
keepJsonFile: true,
performSpeedtest: true,
uploadUrlFile: true,
fastScan: true,
threads: 4,
timeout: 30,
}));
} catch (err) {
console.warn(`Failed to scan '${url}':`, err);
scanResults.failed.push({
url,
reason: err[0] instanceof odd.ODDError ? err[0].message : `Internal Error`, // TODO once Google Drive errors are supported in `open-directory-downloader`, detect them (via string matching) and provide an appropriate error message
reddit: err[1]?.reddit,
missingFileSizes: err[1]?.missingFileSizes
})
}
}
scanResults.successful.forEach(result => saveScanResults(result.jsonFile, result.scannedUrl));
console.debug(`scanResults:`, scanResults);
if (scanResults.successful.length === 0 && urls.length > 0) {
throw new ScanError(scanResults.failed.length === 1 ? scanResults.failed[0].reason : `Couldn't scan any of the provided ODs`)
}
if (scanResults.successful.length === 0 && urls.length > 0) {
throw new Error(scanResults.failed.length === 1 ? scanResults.failed[0].reason : `Couldn't scan any of the provided ODs`)
}
return scanResults;
}
module.exports.urlsFromText = function urlsFromText(text) {
// return matches = text.match(urlRegexSafe({
// strict: true,
// exact: false,
// ipv4: true,
// ipv6: true,
// localhost: false,
// parens: false, // don't include markdown's trainling parentheses in URL
// }))
return markdownLinkExtractor(text);
}
module.exports.extractUrls = async function extractUrls(submissionOrComment, isComment = false) {
const excludedDomains = JSON.parse(process.env.DOMAINS_EXCLUDED_FROM_SCANNING)
let matches;
if (isComment) {
matches = module.exports.urlsFromText(submissionOrComment.body);
} else {
if (!(await submissionOrComment.is_self)) {
matches = [await submissionOrComment.url];
} else {
let submissionText = await (submissionOrComment.selftext);
matches = module.exports.urlsFromText(submissionText);
}
}
// filter out duplicate URLs as well as URLs from excluded domains
let filteredUrls = []
for (const url of matches) {
if (
!filteredUrls.some(x => x === url) &&
!excludedDomains.includes(new URL(url).hostname)
) {
filteredUrls.push(url)
}
}
return filteredUrls;
}
async function saveScanResults(scanPath, scannedUrl) {
let fileToUpload
try {
fileToUpload = await compressFile(scanPath)
if (scanPath !== fileToUpload) {
fs.unlinkSync(scanPath)
}
} catch (err) {
console.warn(`Couldn't compress file '${scanPath}':`, err)
fileToUpload = scanPath
}
try {
let db = JSON.parse(fs.readFileSync(process.env.DB_FILE_PATH, {
encoding: `utf-8`,
}))
db.push({
scannedUrl,
pathToScanFile: fileToUpload,
})
fs.writeFileSync(process.env.DB_FILE_PATH, JSON.stringify(db))
console.log(`Saved scan result to db file`)
} catch (err) {
console.error(`Error while saving scan results to db file:`, err);
}
}
async function checkDiscoveryServerReachable() {
while (true) {
console.debug(`Checking if discovery server is reachable...`);
let res = await fetch(process.env.ODCRAWLER_DISCOVERY_ENDPOINT, {
method: `head`,
})
if (res.ok) {
console.debug(`Discovery server is online!`);
await tryToUploadScansFromDB()
} else {
console.warn(`Discovery server appears to be offline.`);
}
let sleepMinutes = Number(process.env.ODCRAWLER_DISCOVERY_UPLOAD_FREQUENCY)
console.debug(`Waiting ${sleepMinutes} second${sleepMinutes > 1 ? `s` : ``} before trying again`)
await sleep(sleepMinutes*1000)
}
}
module.exports.checkDiscoveryServerReachable = checkDiscoveryServerReachable
async function tryToUploadScansFromDB() {
console.debug(`Trying to upload saved scans to the discovery server...`)
try {
let db = JSON.parse(fs.readFileSync(process.env.DB_FILE_PATH, {
encoding: `utf-8`,
}))
let failed = []
if (db.length == 0) {
console.debug(`No scans left to upload!`)
return
}
for (const scanResult of db) {
try {
if (fs.existsSync(scanResult.pathToScanFile)) {
await uploadScan(scanResult.pathToScanFile)
fs.unlinkSync(scanResult.pathToScanFile)
console.log(`Scan file deleted!`)
} else {
console.warn(`Scan file doesn't exist anymore, removing from DB...`)
}
} catch (err) {
console.error(`Error while uploading scan:`, err)
failed.push(scanResult)
}
}
fs.writeFileSync(process.env.DB_FILE_PATH, JSON.stringify(failed))
} catch (err) {
console.error(`Error while trying to upload scans:`, err)
}
}
async function uploadScan(scanPath) {
console.log(`Uploading scan...`)
const form = new FormData();
form.append(`file`, fs.createReadStream(scanPath))
let res = await fetch(`${process.env.ODCRAWLER_DISCOVERY_ENDPOINT}/upload`, {
method: `POST`,
headers: {
Authorization: 'Basic ' + Buffer.from(process.env.ODCRAWLER_DISCOVERY_UPLOAD_USERNAME + ":" + process.env.ODCRAWLER_DISCOVERY_UPLOAD_PASSWORD).toString('base64'),
},
body: form,
timeout: 0,
compress: true,
});
let jsonResponse;
try {
jsonResponse = await res.json();
} catch (err) {
throw new Error(`Failed to upload scan to discovery server: ${err}`);
}
if (res.ok && jsonResponse.ok) {
console.log(`Scan uploaded successfully! Path: ${jsonResponse.path}`);
} else {
throw new Error(`Failed to upload scan: ${jsonResponse.error}`)
}
}
/**
* Compresses a file using gzip
* @param {String} input The path to the input file
* @param {String} [output] The path to the output file. Can't exist yet.
* @returns {String} The path to the output file
*/
async function compressFile(input, output) {
const outputName = output || `${input}.gz`;
const gzip = createGzip();
const source = fs.createReadStream(input);
const destination = fs.createWriteStream(outputName);
await pipe(source, gzip, destination);
return outputName
}
function sleep(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms);
})
}
module.exports.sleep = sleep