Add caching for upload avatars

This commit is contained in:
kolaente 2020-08-02 15:15:04 +02:00
parent 878c171cef
commit f85085271f
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
1 changed files with 50 additions and 1 deletions

View File

@ -17,15 +17,45 @@
package upload
import (
"bytes"
"code.vikunja.io/api/pkg/files"
"code.vikunja.io/api/pkg/user"
"github.com/disintegration/imaging"
"image"
"image/png"
"io/ioutil"
"sync"
)
var (
// This is a map with a map so we're able to clear all cached avatar (in all sizes) for one user at once
// The first map has as key the user id, the second one has the size as key
resizedCache = map[int64]map[int64][]byte{}
resizedCacheLock = sync.Mutex{}
)
func init() {
resizedCache = make(map[int64]map[int64][]byte)
}
type Provider struct {
}
func (p *Provider) GetAvatar(u *user.User, size int64) (avatar []byte, mimeType string, err error) {
a, cached := resizedCache[u.ID]
if cached {
if a != nil && a[size] != nil {
return a[size], "", nil
}
if a == nil {
resizedCache[u.ID] = make(map[int64][]byte)
}
} else {
resizedCache[u.ID] = make(map[int64][]byte)
}
// If we get this far, the avatar is either not cached at all or not in this size
f := &files.File{ID: u.AvatarFileID}
if err := f.LoadFileByID(); err != nil {
return nil, "", err
@ -35,6 +65,25 @@ func (p *Provider) GetAvatar(u *user.User, size int64) (avatar []byte, mimeType
return nil, "", err
}
avatar, err = ioutil.ReadAll(f.File)
img, _, err := image.Decode(f.File)
if err != nil {
return nil, "", err
}
resizedImg := imaging.Resize(img, 0, int(size), imaging.Lanczos)
buf := &bytes.Buffer{}
if err := png.Encode(buf, resizedImg); err != nil {
return nil, "", err
}
avatar, err = ioutil.ReadAll(buf)
resizedCacheLock.Lock()
resizedCache[u.ID][size] = avatar
resizedCacheLock.Unlock()
return avatar, f.Mime, err
}
func InvalidateCache(u *user.User) {
resizedCacheLock.Lock()
delete(resizedCache, u.ID)
resizedCacheLock.Unlock()
}