moto/internal/organize/avatar.go

57 lines
1.3 KiB
Go

package organize
import (
"context"
"git.nobla.cn/golang/moto/common/db"
"git.nobla.cn/golang/moto/models"
"github.com/disintegration/letteravatar"
"image"
"image/png"
"mime"
"net/http"
"os"
"path"
"strings"
"time"
"unicode/utf8"
)
func Avatar(ctx context.Context, dirname, userid string, r *http.Request, w http.ResponseWriter) {
var (
fs os.FileInfo
fp *os.File
err error
img image.Image
modTime time.Time
)
tx := db.DB().WithContext(ctx)
extName := ".png"
if dirname != "" {
filename := path.Join(dirname, userid+extName)
if fp, err = os.Open(filename); err == nil {
defer fp.Close()
if fs, err = os.Stat(filename); err == nil {
modTime = fs.ModTime()
}
http.ServeContent(w, r, userid+extName, modTime, fp)
return
}
}
userModel := &models.User{}
if err = tx.Where("uid=?", userid).First(userModel).Error; err != nil {
return
}
firstLetter, _ := utf8.DecodeRuneInString(strings.ToUpper(userModel.Username))
if img, err = letteravatar.Draw(64, firstLetter, nil); err == nil {
w.Header().Set("Content-Type", mime.TypeByExtension(extName))
if dirname != "" {
filename := path.Join(dirname, userid+extName)
if fp, err = os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644); err == nil {
err = png.Encode(fp, img)
err = fp.Close()
}
}
err = png.Encode(w, img)
}
}