cowboy: add cache

This commit is contained in:
Chris Sexton 2022-07-22 17:06:55 -04:00 committed by Chris Sexton
parent ba99b2113c
commit 112ccea89a
2 changed files with 42 additions and 3 deletions

View File

@ -2,9 +2,10 @@ package cowboy
import (
"fmt"
"github.com/velour/catbase/connectors/discord"
"regexp"
"github.com/velour/catbase/connectors/discord"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot"
"github.com/velour/catbase/config"
@ -38,6 +39,15 @@ func New(b bot.Bot) *Cowboy {
func (p *Cowboy) register() {
tbl := bot.HandlerTable{
{
Kind: bot.Message, IsCmd: true,
Regex: regexp.MustCompile(`(?i)^:cowboy_clear_cache:$`),
Handler: func(r bot.Request) bool {
cowboyClearCache()
p.b.Send(r.Conn, bot.Ephemeral, r.Msg.Channel, r.Msg.User.ID, ":cowboy_cache_cleared:")
return true
},
},
{
Kind: bot.Message, IsCmd: false,
Regex: regexp.MustCompile(`(?i)^:cowboy_(?P<what>.+):$`),
@ -51,6 +61,14 @@ func (p *Cowboy) register() {
}
func (p *Cowboy) makeCowboy(r bot.Request) {
what := r.Values["what"]
// This'll add the image to the cowboy_cache before discord tries to access it over http
_, err := cowboy(p.c, p.emojyPath, p.baseEmojyURL, what)
if err != nil {
log.Error().Err(err).Msg(":cowboy_fail:")
p.b.Send(r.Conn, bot.Ephemeral, r.Msg.Channel, r.Msg.User.ID, "Hey cowboy, that image wasn't there.")
return
}
log.Debug().Msgf("makeCowboy: %s", r.Values["what"])
base := p.c.Get("baseURL", "http://127.0.0.1:1337")
u := base + "/cowboy/img/" + r.Values["what"]

View File

@ -9,12 +9,19 @@ import (
"math"
"os"
"path"
"sync"
"github.com/nfnt/resize"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/config"
"github.com/velour/catbase/plugins/emojy"
)
var (
cowboyCache = map[string][]byte{}
cowboyMutex = sync.Mutex{}
)
func getEmojy(emojyPath, baseEmojyURL, name string) (image.Image, error) {
files, _, err := emojy.AllFiles(emojyPath, baseEmojyURL)
if err != nil {
@ -66,11 +73,18 @@ func cowboyifyImage(c *config.Config, emojyPath string, input image.Image) (imag
}
func cowboy(c *config.Config, emojyPath, baseEmojyURL, name string) ([]byte, error) {
emojy, err := getEmojy(emojyPath, baseEmojyURL, name)
cowboyMutex.Lock()
defer cowboyMutex.Unlock()
if img, ok := cowboyCache[name]; ok {
log.Debug().Msgf(":cowboy_using_cached_image: %s", name)
return img, nil
}
log.Debug().Msgf(":cowboy_generating_image: %s", name)
emjy, err := getEmojy(emojyPath, baseEmojyURL, name)
if err != nil {
return nil, err
}
img, err := cowboyifyImage(c, emojyPath, emojy)
img, err := cowboyifyImage(c, emojyPath, emjy)
if err != nil {
return nil, err
}
@ -79,5 +93,12 @@ func cowboy(c *config.Config, emojyPath, baseEmojyURL, name string) ([]byte, err
if err != nil {
return nil, err
}
cowboyCache[name] = w.Bytes()
return w.Bytes(), nil
}
func cowboyClearCache() {
cowboyMutex.Lock()
defer cowboyMutex.Unlock()
cowboyCache = map[string][]byte{}
}