2020-04-29 16:44:27 +01:00
|
|
|
const Promise = require('bluebird');
|
|
|
|
const crypto = require('crypto');
|
2022-05-09 12:44:04 +01:00
|
|
|
const tpl = require('@tryghost/tpl');
|
2016-02-12 20:04:26 +00:00
|
|
|
|
2020-12-09 13:19:22 +01:00
|
|
|
class Gravatar {
|
|
|
|
constructor({config, request}) {
|
|
|
|
this.config = config;
|
|
|
|
this.request = request;
|
2017-12-14 10:51:05 +01:00
|
|
|
}
|
|
|
|
|
2022-05-09 12:44:04 +01:00
|
|
|
url(email, options) {
|
|
|
|
if (options.default) {
|
|
|
|
// tpl errors on token `{default}` so we use `{_default}` instead
|
|
|
|
// but still allow the option to be passed as `default`
|
|
|
|
options._default = options.default;
|
|
|
|
}
|
|
|
|
const defaultOptions = {
|
|
|
|
size: 250,
|
|
|
|
_default: 'blank',
|
|
|
|
rating: 'g'
|
|
|
|
};
|
|
|
|
const emailHash = crypto.createHash('md5').update(email.toLowerCase().trim()).digest('hex');
|
|
|
|
const gravatarUrl = this.config.get('gravatar').url;
|
|
|
|
return tpl(gravatarUrl, Object.assign(defaultOptions, options, {hash: emailHash}));
|
|
|
|
}
|
|
|
|
|
2020-12-09 13:19:22 +01:00
|
|
|
lookup(userData, timeout) {
|
|
|
|
if (this.config.isPrivacyDisabled('useGravatar')) {
|
|
|
|
return Promise.resolve();
|
|
|
|
}
|
2022-05-09 12:44:04 +01:00
|
|
|
|
|
|
|
// test existence using a default 404, but return a different default
|
|
|
|
// so we still have a fallback if the image gets removed from Gravatar
|
|
|
|
const testUrl = this.url(userData.email, {default: 404, rating: 'x'});
|
|
|
|
const imageUrl = this.url(userData.email, {default: 'mp', rating: 'x'});
|
|
|
|
|
|
|
|
return Promise.resolve(this.request(testUrl, {timeout: timeout || 2 * 1000}))
|
2020-12-09 13:19:22 +01:00
|
|
|
.then(function () {
|
|
|
|
return {
|
2022-05-09 12:44:04 +01:00
|
|
|
image: imageUrl
|
2020-12-09 13:19:22 +01:00
|
|
|
};
|
|
|
|
})
|
|
|
|
.catch({statusCode: 404}, function () {
|
|
|
|
return {
|
|
|
|
image: undefined
|
|
|
|
};
|
|
|
|
})
|
|
|
|
.catch(function () {
|
|
|
|
// ignore error, just resolve with no image url
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2017-12-14 10:51:05 +01:00
|
|
|
|
2020-12-09 13:19:22 +01:00
|
|
|
module.exports = Gravatar;
|