-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscraper.js
99 lines (76 loc) · 2.32 KB
/
scraper.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
const logger = require('./logger').child('Scraper');
const { SeenURL, Coordinates, Country } = require('./db');
const parser = require('./parser');
const config = require('./config');
const cheerio = require('cheerio');
const geolite2 = require('geolite2-redist');
const maxmind = require('maxmind');
const fs = require('fs');
const axios = require('axios').default;
const lookup = geolite2.open('GeoLite2-City', path => new maxmind.Reader(fs.readFileSync(path)));
function toInt(x) {
return Math.round((x * (10 ** 5)));
}
async function getLinks(body) {
let $ = cheerio.load(body);
let links = [];
$("tbody").eq(1).find('a').each((index, element) => {
links.push($(element).attr('href'));
});
let unseenLinks = [];
for (let link of links) {
if (await SeenURL.count({ where: { url: link } })) continue;
unseenLinks.push(link);
}
return unseenLinks;
}
function parseLogs(logs) {
let lines = logs.split('\n');
let ips = []
for (let line of lines) {
for (let parse of Object.values(parser)) {
let res = parse(line);
if (res) {
ips.push(res);
break;
}
}
}
return ips;
}
async function scrape() {
logger.info('Starting sync');
logger.info('Looking for links');
let links = await getLinks((await axios.get(config.endpoint)).data);
let ips = new Set();
if (links.length == 0) return logger.info('No new links found')
for (let link of links) {
logger.info(`Fetching ${link}`);
let logs = (await axios.get(`${config.endpoint}${link}`)).data;
for (let ip of parseLogs(logs)) {
ips.add(ip);
}
await SeenURL.create({ url: link });
}
for (let ip of ips) {
let geo = lookup.get(ip);
if (!geo.registered_country) continue;
let country = geo.registered_country.iso_code;
let longitude = toInt(geo.location.longitude), latitude = toInt(geo.location.latitude);
if (await Country.count({ where: { name: country } })) {
await Country.increment({ count: 1 }, { where: { name: country } });
} else {
await Country.create({ name: country, count: 1 });
}
if (await Coordinates.count({ where: { longitude, latitude } })) {
await Coordinates.increment({ count: 1 }, { where: { longitude, latitude } });
} else {
await Coordinates.create({ longitude, latitude, count: 1 });
}
}
logger.info('Finished sync');
}
module.exports = () => {
scrape();
setInterval(scrape, config.interval)
}