mirror of https://github.com/velour/catbase.git
meme: rm images after a while
This commit is contained in:
parent
a5f0380585
commit
bcb5d43ea6
|
@ -25,16 +25,35 @@ type MemePlugin struct {
|
||||||
bot bot.Bot
|
bot bot.Bot
|
||||||
c *config.Config
|
c *config.Config
|
||||||
|
|
||||||
images map[string][]byte
|
images cachedImages
|
||||||
|
}
|
||||||
|
|
||||||
|
type cachedImage struct {
|
||||||
|
created time.Time
|
||||||
|
repr []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
var horizon = 24 * 7
|
||||||
|
|
||||||
|
type cachedImages map[string]*cachedImage
|
||||||
|
|
||||||
|
func (ci cachedImages) cleanup() {
|
||||||
|
for key, img := range ci {
|
||||||
|
if time.Now().After(img.created.Add(time.Hour * time.Duration(horizon))) {
|
||||||
|
delete(ci, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(b bot.Bot) *MemePlugin {
|
func New(b bot.Bot) *MemePlugin {
|
||||||
mp := &MemePlugin{
|
mp := &MemePlugin{
|
||||||
bot: b,
|
bot: b,
|
||||||
c: b.Config(),
|
c: b.Config(),
|
||||||
images: make(map[string][]byte),
|
images: make(cachedImages),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
horizon = mp.c.GetInt("meme.horizon", horizon)
|
||||||
|
|
||||||
b.Register(mp, bot.Message, mp.message)
|
b.Register(mp, bot.Message, mp.message)
|
||||||
b.Register(mp, bot.Help, mp.help)
|
b.Register(mp, bot.Help, mp.help)
|
||||||
mp.registerWeb(b.DefaultConnector())
|
mp.registerWeb(b.DefaultConnector())
|
||||||
|
@ -101,8 +120,13 @@ func (p *MemePlugin) registerWeb(c bot.Connector) {
|
||||||
http.HandleFunc("/meme/img/", func(w http.ResponseWriter, r *http.Request) {
|
http.HandleFunc("/meme/img/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
_, file := path.Split(r.URL.Path)
|
_, file := path.Split(r.URL.Path)
|
||||||
id := file
|
id := file
|
||||||
img := p.images[id]
|
if img, ok := p.images[id]; ok {
|
||||||
w.Write(img)
|
w.Write(img.repr)
|
||||||
|
} else {
|
||||||
|
w.WriteHeader(404)
|
||||||
|
w.Write([]byte("not found"))
|
||||||
|
}
|
||||||
|
p.images.cleanup()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -183,7 +207,7 @@ func (p *MemePlugin) genMeme(meme, text string) string {
|
||||||
|
|
||||||
i := bytes.Buffer{}
|
i := bytes.Buffer{}
|
||||||
png.Encode(&i, m.Image())
|
png.Encode(&i, m.Image())
|
||||||
p.images[path] = i.Bytes()
|
p.images[path] = &cachedImage{time.Now(), i.Bytes()}
|
||||||
|
|
||||||
log.Debug().Msgf("Saved to %s\n", path)
|
log.Debug().Msgf("Saved to %s\n", path)
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue