Add caching for upload avatars
This commit is contained in:
parent
878c171cef
commit
f85085271f
|
@ -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()
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue