2018-04-22 21:46:14 +00:00
|
|
|
'use strict';
|
|
|
|
|
2018-05-05 15:08:40 +00:00
|
|
|
const config = require('config');
|
2019-11-05 03:52:17 +00:00
|
|
|
const bhttp = require('bhttp');
|
|
|
|
const blake2 = require('blake2');
|
2018-04-22 21:46:14 +00:00
|
|
|
|
2021-12-17 01:04:25 +00:00
|
|
|
const logger = require('../logger')(__filename);
|
|
|
|
const limiter = require('../limiter').items;
|
|
|
|
|
2019-11-12 02:38:26 +00:00
|
|
|
async function fetchItem(url, attempt, post, host) {
|
2019-11-01 03:22:36 +00:00
|
|
|
async function retry(error) {
|
2021-12-17 01:04:25 +00:00
|
|
|
logger.warn(`Failed to fetch '${url}', ${attempt < config.fetch.retries ? 'retrying' : 'giving up'}: ${error.message} (${post ? post.permalink : 'no post'})`);
|
2018-04-22 21:46:14 +00:00
|
|
|
|
2019-11-01 03:22:36 +00:00
|
|
|
if (attempt < config.fetch.retries) {
|
|
|
|
return fetchItem(url, attempt + 1, post);
|
2018-04-22 21:46:14 +00:00
|
|
|
}
|
2018-05-05 15:08:40 +00:00
|
|
|
|
|
|
|
return null;
|
2019-11-01 03:22:36 +00:00
|
|
|
}
|
2018-04-22 21:46:14 +00:00
|
|
|
|
2019-11-01 03:22:36 +00:00
|
|
|
try {
|
2021-12-17 01:04:25 +00:00
|
|
|
const res = await limiter.schedule(async () => bhttp.get(url));
|
2019-11-01 03:22:36 +00:00
|
|
|
|
2019-11-05 03:52:17 +00:00
|
|
|
if (!res.statusCode === 200) {
|
2018-05-05 15:08:40 +00:00
|
|
|
throw new Error(`Response not OK for '${url}', HTTP code '${res.status}'`);
|
|
|
|
}
|
|
|
|
|
2021-12-17 01:04:25 +00:00
|
|
|
if (!Buffer.isBuffer(res.body)) {
|
|
|
|
throw new Error(`Unexpected response for '${url}' (${res.status}): ${res.body}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.debug(`Fetched '${host ? host.url : url}' (${post ? post.permalink : 'no post'})`);
|
2018-04-22 21:46:14 +00:00
|
|
|
|
2019-11-05 03:52:17 +00:00
|
|
|
const hash = blake2.createHash('blake2b', { digestLength: 24 });
|
|
|
|
hash.update(res.body);
|
|
|
|
const contentHash = hash.digest('hex');
|
|
|
|
|
|
|
|
return Object.assign(res.body, { hash: contentHash });
|
2019-11-01 03:22:36 +00:00
|
|
|
} catch (error) {
|
|
|
|
return retry(error);
|
|
|
|
}
|
|
|
|
}
|
2018-04-22 21:46:14 +00:00
|
|
|
|
|
|
|
module.exports = fetchItem;
|