This commit is contained in:
桜華 2022-09-24 23:38:57 +08:00
parent 91b923ad46
commit 7dc2f78b47
4 changed files with 2053 additions and 1057 deletions

2032
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -7,6 +7,7 @@
"author": "satori <huan0016@gmail.com>", "author": "satori <huan0016@gmail.com>",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"axios": "^0.27.2",
"express": "^4.17.1", "express": "^4.17.1",
"express-session": "^1.17.2", "express-session": "^1.17.2",
"express-session-nedb": "^1.0.1", "express-session-nedb": "^1.0.1",
@ -17,7 +18,6 @@
"md5": "^2.3.0", "md5": "^2.3.0",
"md5-node": "^1.0.1", "md5-node": "^1.0.1",
"nedb": "^1.8.0", "nedb": "^1.8.0",
"request": "^2.88.2",
"string-random": "^0.1.3" "string-random": "^0.1.3"
}, },
"scripts": { "scripts": {

View File

@ -1,11 +1,7 @@
/** import fs from 'fs'
* Gravatar 头像缓存插件
*/
import md5 from 'md5'
import path from 'path' import path from 'path'
import request from 'request' import axios from 'axios'
import { createWriteStream, existsSync, mkdirSync } from 'fs' import crypto from 'crypto'
const 镜像站列表 = [ const 镜像站列表 = [
'gravatar.loli.net', // loli.net 'gravatar.loli.net', // loli.net
@ -19,30 +15,30 @@ const 镜像站列表 = [
var 头像来源 = 0 var 头像来源 = 0
function getGravatar(email, size) { function getGravatar(email, size=128) {
let str = email ? md5(email.toLowerCase()) : 'default' let str = email ? crypto.createHash('md5').update(email.toLowerCase()).digest('hex') : 'default'
let 本地路径 = './data/avatar/' + str + '.jpg' let 本地路径 = './data/avatar/' + str + '.jpg'
let 网络路径 = `https://${镜像站列表[头像来源]}/avatar/${str}.jpg?s=${size}&d=mm&r=g` let 网络路径 = `https://${镜像站列表[头像来源]}/avatar/${str}.jpg?s=${size}&d=mm&r=g`
if (!existsSync(本地路径)) { if (!fs.existsSync(本地路径)) {
request(网络路径).on('error', function (err) { axios({ url:网络路径, responseType: 'arraybuffer' }).then(({data}) => {
fs.writeFileSync(本地路径, data, 'binary')
}).catch(error => {
头像来源++ 头像来源++
if (镜像站列表.length <= 头像来源) { console.log(error)
return console.log("下载头像失败, 使用默认头像") if (头像来源 <= 镜像站列表.length) getGravatar(email, size)
} console.log("下载头像完毕")
getGravatar(email, size) })
}).pipe(createWriteStream(本地路径))
} }
} }
function 检查并创建目录(dirname) { function 检查并创建目录(dirname) {
if (existsSync(dirname)) { if (fs.existsSync(dirname)) {
return true return true
} else if (检查并创建目录(path.dirname(dirname))) { } else if (检查并创建目录(path.dirname(dirname))) {
mkdirSync(dirname) fs.mkdirSync(dirname)
return true return true
} }
return fasle return false
} }
export default { export default {
@ -59,3 +55,7 @@ export default {
// 向头像获取方法插入替换 // 向头像获取方法插入替换
getGravatar, // 获取头像(如果不存在自动从网络下载) getGravatar, // 获取头像(如果不存在自动从网络下载)
} }
// test
// 检查并创建目录('./data/avatar/')
// getGravatar('huan0016@gmail.com', 128)

1036
yarn.lock

File diff suppressed because it is too large Load Diff