-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch.js
334 lines (286 loc) · 9.79 KB
/
fetch.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/**
* This crawler crawls Wikipedia to rip the currency
* denominations from the pages.
*
* Based on
* @see https://github.com/bda-research/node-crawler
*
*
* Strange things:
*
* Currency pages
* - Sometimes, Banknotes and Coins are without freq. used and rarely used. In this case, it is on the same line.
*
* Main page
* - Countries with multiple pages, first currency is 6 cells wide, all the others are 5.
* - Zimbabwe has bond coins without a 'real' name, resulting in the row with all (none)'s
*
* Todo:
* - Tidy up
* - Better error handling
*/
var showdown = require('showdown');
var Crawler = require("crawler");
var fs = require('fs');
var foundCurrencies = {};
var drainEventActive = false;
var debugMaxCurrencies = 0;
var urlsCrawled = [];
var debug = false;
// Create the Crawler
var c = new Crawler({
maxConnections : 1,
rateLimit: 1000, // 1 every second
callback : function (error, res, done) {
handleError(error);
if(res.options.type === 'base') {
parseBasePage(error, res, done)
} else if(res.options.type === 'currency') {
parseCurrencyPage(error, res, done)
}
}
});
/**
* Parse Wikipedia's detail page on the currency.
*
* @param {*} error
* @param {*} res
* @param {*} done
*/
function parseCurrencyPage(error, res, done) {
drainEventActive = true;
var $ = res.$;
var rows = $('.infobox').find('tbody').find('tr');
console.log(`Parsing ${res.options.iso}`);
var isInBankNotes = false;
var isInCoins = false;
rows.each((i, element) => {
var e = $(element);
const tdText = parseDenominations(trimText(e.find('td').text()));
var tableHeader = e.find('th');
var t = $(tableHeader).text();
if($(tableHeader).text() === 'Banknotes') {
// If there also is a td in the row, it is directly used
if(tdText != null && tdText != '') {
foundCurrencies[res.options.iso]['banknotes']['frequently'] = tdText;
if(debug) { console.log(`Found Single Banknotes ${tdText}`); }
return;
}
if(debug) { console.log('Found Banknotes'); }
isInBankNotes = true;
isInCoins = false;
}
else if($(tableHeader).text() === 'Coins') {
// If there also is a td in the row, it is directly used
if(tdText != null && tdText != '') {
foundCurrencies[res.options.iso]['coins']['frequently'] = tdText;
if(debug) {
console.log(`Found single Coins ${tdText}`);
}
return;
}
if(debug) { console.log('Found Coins'); }
isInBankNotes = false;
isInCoins = true;
} else if($(tableHeader).text() === ' Freq. used' && isInBankNotes) {
// Freq. used for Banknotes
if(debug) { console.log('Found Freq. used'); }
foundCurrencies[res.options.iso]['banknotes']['frequently'] = tdText;
} else if($(tableHeader).text() === ' Freq. used' && isInCoins) {
// Freq. used for Coins
if(debug) { console.log('Found Freq. used'); }
foundCurrencies[res.options.iso]['coins']['frequently'] = tdText;
} else if($(tableHeader).text() === ' Rarely used' && isInBankNotes) {
// Rarely used for Banknotes
if(debug) { console.log('Found Rarely used'); }
foundCurrencies[res.options.iso]['banknotes']['rarely'] = tdText;
} else if($(tableHeader).text() === ' Rarely used' && isInCoins) {
// Rarely used for Coins
if(debug) { console.log('Found Rarely used'); }
foundCurrencies[res.options.iso]['coins']['rarely'] = tdText;
}
});
// Check for empty data
var currencySum = foundCurrencies[res.options.iso]['banknotes']['frequently'].length +
foundCurrencies[res.options.iso]['banknotes']['rarely'].length +
foundCurrencies[res.options.iso]['coins']['frequently'].length +
foundCurrencies[res.options.iso]['coins']['rarely'].length;
if(currencySum === 0) {
console.error(`No denominations found for ${res.options.country} ${res.options.iso}!`);
}
if(debug) { console.log('\n'); }
done();
}
/**
* Parse the currencies base listing from Wikipedia
*
* @param {*} error
* @param {*} res
* @param {*} done
*/
function parseBasePage(error, res, done) {
var $ = res.$;
// Find all rows
var rows = $('.wikitable').find('tbody').find('tr');
// Foreach Rows
var previousCountry = null;
rows.each((i, element) => {
var e = $(element);
// Check if it has a first td with a rowspan=2
var cells = e.find('td');
if(cells.length == 0) {
return;
}
var url = false;
var iso = null;
// See note [1]
if(cells.length == 5) {
iso = trimText(cells.eq(2).text());
} else {
iso = trimText(cells.eq(3).text());
}
if(typeof foundCurrencies.iso === "undefined") {
foundCurrencies[iso] = createBaseCurrencyObject();
}
// If there are only 5 cells, this currency belongs to the previous country
// See note [1]
if(cells.length == 5) {
if(foundCurrencies[iso].countries.indexOf(previousCountry) === -1) {
foundCurrencies[iso].countries.push(previousCountry);
}
foundCurrencies[iso].name = trimText(cells.first().text());
foundCurrencies[iso].symbols = trimText(cells.eq(1).text()).split(' or ');
foundCurrencies[iso].iso = iso;
foundCurrencies[iso].fractionalUnit = trimText(cells.eq(3).text());
foundCurrencies[iso].numberToBasic = trimText(cells.eq(4).text());
url = parseUrl(cells.first().find('a').attr('href'));
} else {
previousCountry = trimText(cells.first().text());
if(foundCurrencies[iso].countries.indexOf(previousCountry) === -1) {
foundCurrencies[iso].countries.push(previousCountry);
}
foundCurrencies[iso].name = trimText(cells.eq(1).text());
foundCurrencies[iso].symbols = trimText(cells.eq(2).text()).split(' or ');
foundCurrencies[iso].iso = iso;
foundCurrencies[iso].fractionalUnit = trimText(cells.eq(4).text());
foundCurrencies[iso].numberToBasic = trimText(cells.eq(5).text());
url = parseUrl(cells.eq(1).find('a').attr('href'));
}
// Queue the url, but don't parse twice
if(url !== false && ~urlsCrawled.indexOf(url) == false && debugMaxCurrencies < 5) {
urlsCrawled.push(url);
// Dont parse twice
c.queue({
uri: url,
iso: iso,
type: 'currency',
});
if(debug) {
debugMaxCurrencies = debugMaxCurrencies + 1;
}
}
});
done();
}
function createBaseCurrencyObject() {
return {
'name': null,
'symbols': [],
'iso': null,
'countries': [],
'fractionalUnit': null,
'numberToBasic': null,
'banknotes': {
'rarely': [],
'frequently': []
},
'coins': {
'rarely': [],
'frequently': []
}
};
}
/**
* Separate demonimations into an array of numbers
*
* Example string:
* 50₽, 100₽, 200₽, 500₽, 1,000₽, 2,000₽, 5,000₽, 1.00e
*
* @param {*} str
* @returns
*/
function parseDenominations(str) {
return str.match(/([0-9]((,|\.)[0-9]+)*)+/g, '');
}
/**
* Parse and validate the url
*
* @param {*} url
* @returns
*/
function parseUrl(url) {
var base = 'https://en.wikipedia.org';
if(url === undefined) {
return false;
}
if(url.charAt(0) === '#') {
return false;
}
return `${base}/${url}`;
}
/**
* Handle errors during crawling
*
* @param {*} error
*/
function handleError(error) {
if(error) {
console.log(error);
throw "Error during crawling";
}
}
/**
* Trim a label from newlines and [] annotations
*
* @param {*} text
*/
function trimText(text) {
return text.replace(/[\n\t\r]/g,"").trim().replace(/(\[.*\])/g,"");
}
// Start at the "Circulating Currencies" page
urlsCrawled.push('https://en.wikipedia.org/wiki/List_of_circulating_currencies');
c.queue({
uri: 'https://en.wikipedia.org/wiki/List_of_circulating_currencies',
type: 'base',
});
/**
* Whenever the queue is empty, drain the thing.
*/
c.on('drain',function() {
if(!drainEventActive) {
return;
}
// Write json files
const prettyCurrencyJson = JSON.stringify(foundCurrencies, null, 2);
fs.writeFile('./public/currencies.json', prettyCurrencyJson, 'utf8', () => { return; });
const currencyJson = JSON.stringify(foundCurrencies);
fs.writeFile('./public/currencies.min.json', currencyJson, 'utf8', () => { return; });
var urlsJson = JSON.stringify(urlsCrawled, null, 2);
fs.writeFile('./public/urls.json', urlsJson, 'utf8', () => { return; });
// Write the readme
var readme = fs.readFileSync('README.md', 'utf8');
let date = new Date();
let options = {
weekday: "long", year: "numeric", month: "short",
day: "numeric", hour: "2-digit", minute: "2-digit"
};
readme = readme + `\n### Crawled URLS\n\nLast crawl date: _${date.toLocaleTimeString('en-us', options)}_`;
readme = readme + '\n```\n';
urlsCrawled.forEach(url => {
readme = readme + `\n- ${url}`;
});
readme = readme + '\n```\n';
var converter = new showdown.Converter({completeHTMLDocument: true});
var html = converter.makeHtml(readme);
fs.writeFile('./public/index.html', html, 'utf8', () => { return; });
});