2022-02-17 11:53:37 +03:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"codeberg.org/Codeberg/avatars"
|
|
|
|
"github.com/gorilla/mux"
|
2022-02-17 12:34:33 +03:00
|
|
|
lru "github.com/hashicorp/golang-lru"
|
2022-02-17 11:53:37 +03:00
|
|
|
conf "github.com/muety/wakapi/config"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
type AvatarHandler struct {
|
|
|
|
config *conf.Config
|
2022-02-17 12:34:33 +03:00
|
|
|
cache *lru.Cache
|
2022-02-17 11:53:37 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewAvatarHandler() *AvatarHandler {
|
2022-02-17 12:34:33 +03:00
|
|
|
cache, err := lru.New(1 * 1000 * 64) // assuming an avatar is 1 kb, allocate up to 64 mb of memory for avatars cache
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &AvatarHandler{
|
|
|
|
config: conf.Get(),
|
|
|
|
cache: cache,
|
|
|
|
}
|
2022-02-17 11:53:37 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *AvatarHandler) RegisterRoutes(router *mux.Router) {
|
|
|
|
r := router.PathPrefix("/avatar/{hash}.svg").Subrouter()
|
|
|
|
r.Path("").Methods(http.MethodGet).HandlerFunc(h.Get)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *AvatarHandler) Get(w http.ResponseWriter, r *http.Request) {
|
2022-02-17 12:34:33 +03:00
|
|
|
hash := mux.Vars(r)["hash"]
|
2022-02-17 11:53:37 +03:00
|
|
|
|
2022-02-17 12:34:33 +03:00
|
|
|
if !h.cache.Contains(hash) {
|
|
|
|
h.cache.Add(hash, avatars.MakeMaleAvatar(hash))
|
2022-02-17 11:53:37 +03:00
|
|
|
}
|
2022-02-17 12:34:33 +03:00
|
|
|
data, _ := h.cache.Get(hash)
|
2022-02-17 11:53:37 +03:00
|
|
|
|
|
|
|
w.Header().Set("Content-Type", "image/svg+xml")
|
2022-02-17 12:34:33 +03:00
|
|
|
w.Header().Set("Cache-Control", "max-age=2592000")
|
2022-02-17 11:53:37 +03:00
|
|
|
w.WriteHeader(http.StatusOK)
|
2022-02-17 12:34:33 +03:00
|
|
|
w.Write([]byte(data.(string)))
|
2022-02-17 11:53:37 +03:00
|
|
|
}
|