-
Notifications
You must be signed in to change notification settings - Fork 0
/
gather-scraped-data.js
182 lines (149 loc) · 5.2 KB
/
gather-scraped-data.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
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var async = require('async');
var request = require('requestretry');
var SEARCH_API_KEY = 'AIzaSyCT8bmjc-fjWT7KC-pAoccnO_Qvk-1GFbU';
var RESULTS_PER_PAGE = 10;
var MALARIA_TRANS = '"malaria" "paludisme" "ملاريا" "malária" "малярия" "疟疾" "maliarija" "sıtma" "ম্যালেরিয়া" "малария" "มาลาเรีย" "bệnh sốt rét" "ወባ" "малярія" "ملیریا" "bezgak"';
var SERVICED_NEWSPAPERS_FILE = './serviced-newspapers.json';
var SERVICED_QUERIES_PREFIX = './serviced-queries';
var LAST_SAVED_UID = './serviced-queries-final-040418';
var YEAR_START = 2000;
var YEAR_END = 2016;
var searchRequest = request.defaults({
url: 'https://www.googleapis.com/customsearch/v1',
json: true,
retryStrategy: function(err, res, body) {
var retryRequest = err || request.RetryStrategies.HTTPOrNetworkError(err, res, body) || res.statusCode !== 200;
if (retryRequest) {
console.log('Retrying request');
if (res) {
console.log(res.statusCode);
console.log(res.body);
}
}
return retryRequest;
},
qs: {
'key': SEARCH_API_KEY,
'num': RESULTS_PER_PAGE
}
});
var newspapers = JSON.parse(fs.readFileSync('./newspapers.json', 'utf8'));
var servicedQueries;
var servicedQueriesFile = path.join(SERVICED_QUERIES_PREFIX, LAST_SAVED_UID + '.json');
if (servicedQueriesFile != '') {
servicedQueries = JSON.parse(fs.readFileSync(servicedQueriesFile, 'utf8'));
} else {
servicedQueries = {};
}
var servicedNewspapers;
if (fs.existsSync(SERVICED_NEWSPAPERS_FILE)) {
servicedNewspapers = JSON.parse(fs.readFileSync(SERVICED_NEWSPAPERS_FILE, 'utf8'));
} else {
servicedNewspapers = {};
}
newspapers.forEach(function (newspaper) {
if (!(newspaper.uid in servicedQueries)) {
servicedQueries[newspaper.uid] = {
'pepfar': {},
'pmi': {}
};
for (var i = YEAR_START; i <= YEAR_END; i++) {
servicedQueries[newspaper.uid]['pepfar'][i] = [];
servicedQueries[newspaper.uid]['pmi'][i] = [];
}
}
});
var servicedNewspapersSet = new Set(Object.keys(servicedNewspapers));
var unservicedNewspapers = newspapers.filter(e => !(servicedNewspapersSet.has(e.uid)));
function processNewspaper(newspaper, cb1) {
function processNewspaperAndQuery(queryMeta, cb2) {
var queryReadable = `${queryMeta.year} ${queryMeta.q} query for ${newspaper.uid}`;
if (servicedQueries[newspaper.uid][queryMeta.q][queryMeta.year].length > 0) {
console.log(`Already serviced ${queryReadable}`);
return cb2();
}
console.log(`Servicing ${queryReadable}`);
var startIndex = 1;
var morePages = true;
var searchQueryResults = [];
async.until(
function() { return !morePages; },
function (cb3) {
var searchOptions = {
qs: {
'q': queryMeta.q,
'cx': newspaper['cse id'],
'filter': 1,
'sort': `date:r:${queryMeta.year}0101:${queryMeta.year}1231`,
'start': startIndex
}
};
if (queryMeta.q === 'pmi') {
searchOptions['qs']['orTerms'] = MALARIA_TRANS;
}
searchRequest(searchOptions, function (err, res, body) {
if (err) {
return cb3(err);
}
if (res.statusCode !== 200) {
console.log(`Received response with status code ${res.statusCode} for ${queryReadable}`);
process.exit(1);
}
searchQueryResults.push(body);
morePages = 'nextPage' in body.queries;
if (morePages) {
console.log('total estimated results: ' + body.searchInformation.totalResults);
console.log('current start index: ' + startIndex);
console.log('number of results on this page: ' + body.queries.request[0].count);
}
startIndex += RESULTS_PER_PAGE;
cb3();
});
}, function (err) {
if (err) {
return cb2(err);
}
assert(queryMeta.year in servicedQueries[newspaper.uid][queryMeta.q], `Missing support for year ${queryMeta.year}`);
servicedQueries[newspaper.uid][queryMeta.q][queryMeta.year] = searchQueryResults;
cb2();
}
);
}
var queriesMeta = [];
for (var i = YEAR_START; i <= YEAR_END; i++) {
queriesMeta.push({
q: 'pepfar',
year: i
});
queriesMeta.push({
q: 'pmi',
year: i
});
}
process.nextTick(function() {
// Queries loop
async.forEachSeries(queriesMeta, processNewspaperAndQuery, function (err) {
if (err) {
return cb1(err);
}
fs.writeFileSync(path.join(SERVICED_QUERIES_PREFIX, newspaper.uid + '.json'), JSON.stringify(servicedQueries), 'utf8');
servicedNewspapers[newspaper.uid] = true;
fs.writeFileSync(SERVICED_NEWSPAPERS_FILE, JSON.stringify(servicedNewspapers), 'utf8');
console.log('Finished processing newspaper: ' + newspaper.uid);
cb1();
});
});
}
// Main loop
async.forEachSeries(unservicedNewspapers, processNewspaper, function (err) {
if (err) {
console.log('Error during op');
console.log(err);
return;
}
console.log('Success');
});