forked from DeuxHuitHuit/algolia-webcrawler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
385 lines (351 loc) · 9.5 KB
/
app.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
#!/usr/bin/env node
/**
* App
*/
'use strict';
const argv = require('optimist').argv;
const pack = require('./package.json');
const path = require('path');
const u = require('url');
const _ = require('lodash');
const algoliasearch = require('algoliasearch');
const updateNotifier = require('update-notifier');
const chalk = require('chalk');
const processOne = require('./lib/process');
const sitemap = require('./lib/sitemap');
require('./lib/dns-cache');
let sitemapProcessed = 0;
let sitemapCount = 0;
let urlCount = 0;
const ERROR_EXIT_CODE = 10;
let returnCode = 0;
process.on('exit', (r) => {
process.nextTick(() => process.exit(returnCode || r));
});
const configFile = argv.config ? path.resolve(argv.config) : './config.json';
let config = {};
try {
config = require(configFile);
} catch (ex) {
config = null;
}
updateNotifier({pkg: pack}).notify();
if (!_.isObject(config)) {
console.error('Invalid configuration');
process.exit(1);
}
if (!_.isObject(config.cred)) {
console.error('Invalid credentials');
process.exit(2);
}
if (!_.isObject(config.index)) {
console.error('Invalid index configuration');
process.exit(4);
}
if (!_.isArray(config.sitemaps)) {
console.error('Invalid sitemaps configuration');
process.exit(8);
}
// Process map static selectors into their object equivalent
config.selectors = _.map(config.selectors, (selector, key) => {
if (!_.isObject(selector)) {
selector = {selector};
}
return {
key,
attributes: selector.attributes,
selector: selector.selector,
limit: selector.limit,
exclude: config.exclusions && config.exclusions[key]
};
});
const plugins = require('./lib/plugins')(__dirname, config.plugins);
const pingback = require('./lib/pingback')({url: config.pingbackUrl});
const client = algoliasearch(config.cred.appid, config.cred.apikey);
const pages = client.initIndex(config.index.name);
const errors = [];
// Welcome
console.log('Welcome to "%s" %s v%s', config.app, pack.name, pack.version);
console.log();
console.log('Loaded "%s" configuration', configFile);
console.log();
//Show info about pingback configuration
if (pingback.ok) {
console.log('Ping back url configured with: %s', config.pingbackUrl);
console.log();
}
// Launch sitemap crawling
sitemap(config, (sitemap, urls) => {
sitemapProcessed++;
console.log('Parsing Sitemap %s', sitemap.url);
if (!urls.length) {
errors.push({
ok: 'warn',
message: 'Sitemap ' + sitemap.url + ' does not contain any urls',
sitemap
});
console.log('Sitemap %s does not contain any urls', sitemap.url);
} else {
console.log('Sitemap %s contains %d urls', sitemap.url, urls.length);
}
const totalCount = urls.length;
if (_.isArray(config.blacklist)) {
urls = _.filter(urls, (url) => {
return _.every(_.map(
config.blacklist,
(bl) => url.url !== bl && u.parse(url.url).path !== bl
));
});
if (totalCount != urls.length) {
console.log('%s blacklisted %d urls', sitemap.url, totalCount - urls.length);
}
}
sitemapCount += urls.length;
// All sitemaps have failed
if (sitemapProcessed === config.sitemaps.length && sitemapCount === 0) {
console.log('All Sitemaps do not contain any urls');
process.exit(16);
// All sitemaps are parsed, kick in the process
} else if (sitemapProcessed === config.sitemaps.length) {
processOne.start();
}
if (!urls.length) {
// Current sitemap failed, exit
return;
}
const results = _.map(urls, (url, index) => {
console.log('Registered ' + url.url);
const processResults = processOne({
config,
url,
index,
plugins
}, function processOneCallback(error, record) {
const id = urlCount + 1;
if (!!error || !record) {
console.error('%d - Error! %s', id, error.message);
if (!!error && !error.retry) {
errors.push(error);
}
if ((!!error.pageNotFound || !!error.pageRedirected) && !!record) {
pages.deleteObject(record.objectID, (error, result) => {
console.log('%d - Deleted %s:%s (%s)', id, record.objectID, record.lang, record.url);
//Ping back delete
pingbackUrl({
id,
result: 'success',
action: 'delete',
url: url.url,
callback: tearDown
});
});
} else if (!!error.retry) {
console.error('%d - Retry url %s', id, url.url);
const retryResult = processOne({
config,
url,
index,
plugins,
isRetry: true
}, processOneCallback);
if (!retryResult.ok) {
console.error('%d - Error! %s', id, retryResult.message);
errors.push(retryResult);
}
processOne.resume();
} else {
//Ping back delete
pingbackUrl({
id,
result: 'success',
action: 'delete',
url: url.url,
callback: tearDown
});
}
return;
}
if (record.action === 'delete') {
console.error('%d - About to delete! %s', id, record.objectID);
pages.deleteObject(record.objectID, (error, result) => {
if (!!error) {
console.log();
if (!!result && !!result.message) {
console.error('%d - Error! %s', id, result.message);
errors.push(result);
}
if (!!error && !!error.message) {
console.error('%d - Error! %s', id, error.message);
errors.push(error);
}
//Ping back delete
pingbackUrl({
id, id,
result: 'error',
action: 'delete',
url: url.url,
callback: tearDown
});
} else {
console.log('%d - Deleted %s:%s (%s)', id, record.objectID, record.lang, record.url);
//Ping back delete
pingbackUrl({
id, id,
result: 'success',
action: 'delete',
url: url.url,
callback: tearDown
});
}
});
} else {
console.log('%d - About to save! %s:%s (%s)', id, record.objectID, record.lang, record.url);
pages.saveObject(record, (error, result) => {
if (!!error) {
console.log();
if (!!result && !!result.message) {
console.error('%d - Error! %s', id, result.message);
errors.push(result);
}
if (!!error && !!error.message) {
console.error('%d - Error! %s', id, error.message);
errors.push(error);
}
console.log();
//Ping back error
//Post error to ping back url if configured
pingbackUrl({
id: id,
result: 'error',
action: 'update',
url: url.url,
callback: tearDown
});
} else if (record.objectID !== result.objectID) {
console.log();
console.error('%d - Error! Object ID mismatch!', id);
console.log();
errors.push({
ok: false,
message: 'Object ID mismatch!'
});
//Ping back error
pingbackUrl({
id: id,
result: 'error',
action: 'update',
url: url.url,
callback: tearDown
});
} else {
console.log('%d - Saved %s:%s (%s)', id, record.objectID, record.lang, record.url);
//Ping back saved
pingbackUrl({
id: id,
result: 'success',
action: 'update',
url: url.url,
lastModified: record.http.lastModified,
callback: tearDown
});
}
});
}
});
if (processResults.ok !== true) {
errors.push(processResults);
console.error(processResults.message || 'Error!');
}
});
console.log('Sitemap %s registered %s / %s urls', sitemap.url, results.length, urls.length);
});
const pingbackUrl = (data) => {
//Process pingBack
if (pingback.ok) {
pingback.send({
result: data.result,
action: data.action,
url: data.url,
lastModified: data.lastModified
}, (data2) => {
if (data2.ok) {
console.log('%d - Ping back executed: %s :%s', data.id, data.action, data.url);
} else {
console.log('%d - Ping back error: ', data.id);
if (data2.err) {
console.dir(data2.err);
} else {
console.log(data2.message);
}
}
data.callback();
});
} else {
data.callback();
}
};
// Configure index
if (_.isObject(config.index.settings)) {
console.log('Configuring your index %s', config.index.name);
pages.setSettings(config.index.settings, (error, result) => {
if (!!error) {
console.log();
if (!!result && !!result.message) {
console.error('Error! ' + result.message);
}
if (!!error && !!error.message) {
console.error('Error! ' + error.message);
}
} else {
console.log('Configured index properly');
console.log();
}
});
}
const removeOldEntries = () => {
if (_.isInteger(config.oldentries) && config.oldentries > 0) {
console.log();
console.log('Removing old entries...');
console.log();
const deleteQuery = {
numericFilters: ['timestamp<' + (new Date().getTime() - config.oldentries)]
};
if (!!config.oldentriesfilters) {
deleteQuery.filters = config.oldentriesfilters;
}
pages.deleteBy(deleteQuery, (error, content) => {
if (!!error) {
console.error(chalk.red('Error deleting entries. ' + error.message));
return;
}
console.log(chalk.green('Deleting old entries done.'));
});
}
};
const displayErrorReport = () => {
console.log();
if (!errors.length) {
console.log(chalk.green('No problem were reported during the crawl!'));
} else {
console.log(chalk.yellow('%d problems occurred during the crawl'), errors.length);
_.forEach(errors, (e) => {
const isWarn = e.ok === 'warn';
const fx = isWarn ? 'warn' : 'error';
const c = isWarn ? chalk.yellow: chalk.red;
console[fx](c(e.message || e));
if (!isWarn) {
returnCode = ERROR_EXIT_CODE;
}
});
}
};
const tearDown = () => {
urlCount++;
if (urlCount === sitemapCount) {
processOne.stop();
removeOldEntries();
displayErrorReport();
} else {
processOne.resume();
}
};