diff --git a/api/chat.py b/api/chat.py index eb71a1f..470be83 100644 --- a/api/chat.py +++ b/api/chat.py @@ -434,7 +434,7 @@ class RoomInfoHandler(api.base.ApiHandler): class AvatarHandler(api.base.ApiHandler): async def get(self): - # uid基本是0了,现在这个接口唯一的作用是算用户名MD5,其实可以放到前端 + # uid基本是0了,现在都是前端计算默认头像URL,这个接口留着只是为了兼容旧版 uid = int(self.get_query_argument('uid')) username = self.get_query_argument('username', '') avatar_url = await services.avatar.get_avatar_url_or_none(uid) diff --git a/frontend/package.json b/frontend/package.json index 555bda3..712f262 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -10,6 +10,7 @@ "dependencies": { "axios": "^1.4.0", "core-js": "^3.8.3", + "crypto-js": "^4.2.0", "downloadjs": "^1.4.7", "element-ui": "^2.15.13", "lodash": "^4.17.21", diff --git a/frontend/src/api/chat/index.js b/frontend/src/api/chat/index.js index 195b59e..db2090d 100644 --- a/frontend/src/api/chat/index.js +++ b/frontend/src/api/chat/index.js @@ -1,4 +1,5 @@ import axios from 'axios' +import MD5 from 'crypto-js/md5' export function getDefaultMsgHandler() { let dummyFunc = () => {} @@ -27,6 +28,10 @@ export function processAvatarUrl(avatarUrl) { } export async function getAvatarUrl(uid, username) { + if (uid === 0) { + return getDefaultAvatarUrl(uid, username) + } + let res try { res = (await axios.get('/api/avatar_url', { params: { @@ -34,11 +39,24 @@ export async function getAvatarUrl(uid, username) { username: username } })).data } catch { - return DEFAULT_AVATAR_URL + return getDefaultAvatarUrl(uid, username) } return res.avatarUrl } +export function getDefaultAvatarUrl(uid, username) { + let strToHash + if (uid !== 0) { + strToHash = uid.toString() + } else if (username !== '') { + strToHash = username + } else { + return DEFAULT_AVATAR_URL + } + let idHash = MD5(strToHash).toString() + return `//cravatar.cn/avatar/${idHash}?s=256&d=robohash&f=y` +} + export async function getTextEmoticons() { let res try {