Skip to content

Commit

Permalink
feat: add avatarUrl to custom avatar url fix #607
Browse files Browse the repository at this point in the history
  • Loading branch information
lizheming committed Oct 30, 2021
1 parent 6296fe5 commit a473ecb
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 8 deletions.
11 changes: 5 additions & 6 deletions packages/server/src/controller/comment.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,19 @@ async function formatCmt(
comment.type = user.type;
}

comment.mail = helper.md5(
comment.mail ? comment.mail.toLowerCase() : comment.mail
);

const avatarUrl =
user && user.avatar
? user.avatar
: `https://seccdn.libravatar.org/avatar/${comment.mail}`;

: await think.service('avatar').stringify(comment);
comment.avatar =
avatarProxy && !avatarUrl.includes(avatarProxy)
? avatarProxy + '?url=' + encodeURIComponent(avatarUrl)
: avatarUrl;

comment.mail = helper.md5(
comment.mail ? comment.mail.toLowerCase() : comment.mail
);

return comment;
}

Expand Down
8 changes: 6 additions & 2 deletions packages/server/src/logic/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,20 @@ module.exports = class extends think.Logic {
}

const userInfo = user[0];
userInfo.mailMd5 = helper.md5(userInfo.email);

let avatarUrl = userInfo.avatar
? userInfo.avatar
: `https://seccdn.libravatar.org/avatar/${userInfo.mailMd5}`;
: await think.service('avatar').stringify({
mail: userInfo.email,
nick: userInfo.display_name,
link: userInfo.url,
});
const { avatarProxy } = think.config();
if (avatarProxy) {
avatarUrl = avatarProxy + '?url=' + encodeURIComponent(avatarUrl);
}
userInfo.avatar = avatarUrl;
userInfo.mailMd5 = helper.md5(userInfo.email);
this.ctx.state.userInfo = userInfo;
}
};
22 changes: 22 additions & 0 deletions packages/server/src/service/avatar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const nunjucks = require('nunjucks');
const helper = require('think-helper');
const { GRAVATAR_STR } = process.env;

const env = new nunjucks.Environment();
env.addFilter('md5', (str) => helper.md5(str));

module.exports = class extends think.Service {
async stringify(comment) {
const fn = think.config('avatarUrl');
if (think.isFunction(fn)) {
const ret = await fn(comment);
if (think.isString(ret) && ret) {
return ret;
}
}

const gravatarStr =
GRAVATAR_STR || 'https://seccdn.libravatar.org/avatar/{{mail|md5}}';
return env.renderString(gravatarStr, comment);
}
};

0 comments on commit a473ecb

Please sign in to comment.