Compare commits

..

No commits in common. "07c4950b2df3ad7938d54a51120043029dc7f75b" and "cee267dbb81afdb260d1a5da18c51a8307c726c3" have entirely different histories.

3 changed files with 23 additions and 252 deletions

View File

@ -14,7 +14,6 @@ import (
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
"github.com/velour/catbase/config" "github.com/velour/catbase/config"
@ -48,7 +47,6 @@ var forbiddenKeys = map[string]bool{
"twitch.clientid": true, "twitch.clientid": true,
"untappd.token": true, "untappd.token": true,
"slack.token": true, "slack.token": true,
"meme.memes": true,
} }
// Message responds to the bot hook on recieving messages. // Message responds to the bot hook on recieving messages.
@ -108,14 +106,8 @@ func (p *AdminPlugin) message(conn bot.Connector, k bot.Kind, message msg.Messag
return true return true
} }
verbs := map[string]bool{
"set": true,
"push": true,
"setkey": true,
}
parts := strings.Split(body, " ") parts := strings.Split(body, " ")
if verbs[parts[0]] && len(parts) > 2 && forbiddenKeys[parts[1]] { if parts[0] == "set" && len(parts) > 2 && forbiddenKeys[parts[1]] {
p.bot.Send(conn, bot.Message, message.Channel, "You cannot access that key") p.bot.Send(conn, bot.Message, message.Channel, "You cannot access that key")
return true return true
} else if parts[0] == "unset" && len(parts) > 1 { } else if parts[0] == "unset" && len(parts) > 1 {

View File

@ -2,15 +2,12 @@ package meme
import ( import (
"bytes" "bytes"
"encoding/json"
"fmt" "fmt"
"html/template"
"image" "image"
"image/png" "image/png"
"net/http" "net/http"
"net/url" "net/url"
"path" "path"
"sort"
"strings" "strings"
"time" "time"
@ -70,128 +67,29 @@ func (p *MemePlugin) message(c bot.Connector, kind bot.Kind, message msg.Message
} }
func (p *MemePlugin) help(c bot.Connector, kind bot.Kind, message msg.Message, args ...interface{}) bool { func (p *MemePlugin) help(c bot.Connector, kind bot.Kind, message msg.Message, args ...interface{}) bool {
webRoot := p.c.Get("BaseURL", "https://catbase.velour.ninja")
formats := p.c.GetMap("meme.memes", defaultFormats) formats := p.c.GetMap("meme.memes", defaultFormats)
msg := "Use `/meme [format] [text]` to create a meme.\nI know the following formats:" msg := "Use `/meme [format] [text]` to create a meme.\nI know the following formats:"
msg += "\n`[format]` can be a URL"
for k := range formats { for k := range formats {
msg += "\n" + k msg += "\n" + k
} }
msg += fmt.Sprintf("\nHead over to %s/meme to add new meme formats", webRoot)
p.bot.Send(c, bot.Message, message.Channel, msg) p.bot.Send(c, bot.Message, message.Channel, msg)
return true return true
} }
func (p *MemePlugin) registerWeb(c bot.Connector) { func (p *MemePlugin) registerWeb(c bot.Connector) {
http.HandleFunc("/slash/meme", p.slashMeme(c)) http.HandleFunc("/slash/meme", func(w http.ResponseWriter, r *http.Request) {
http.HandleFunc("/meme/img/", p.img)
http.HandleFunc("/meme/all", p.all)
http.HandleFunc("/meme/add", p.addMeme)
http.HandleFunc("/meme", p.webRoot)
p.bot.RegisterWeb("/meme", "Memes")
}
type webResp struct {
Name string `json:"name"`
URL string `json:"url"`
}
type webResps []webResp
func (w webResps) Len() int { return len(w) }
func (w webResps) Swap(i, j int) { w[i], w[j] = w[j], w[i] }
type ByName struct{ webResps }
func (s ByName) Less(i, j int) bool { return s.webResps[i].Name < s.webResps[j].Name }
func (p *MemePlugin) all(w http.ResponseWriter, r *http.Request) {
memes := p.c.GetMap("meme.memes", defaultFormats)
values := webResps{}
for n, u := range memes {
realURL, err := url.Parse(u)
if err != nil || realURL.Scheme == "" {
realURL, _ = url.Parse("https://imgflip.com/s/meme/" + u)
}
sort.Sort(ByName{values})
values = append(values, webResp{n, realURL.String()})
}
out, err := json.Marshal(values)
if err != nil {
w.WriteHeader(500)
log.Error().Err(err).Msgf("could not serve all memes route")
return
}
w.Write(out)
}
func (p *MemePlugin) addMeme(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(405)
fmt.Fprintf(w, "Incorrect HTTP method")
return
}
checkError := func(err error) bool {
if err != nil {
log.Error().Err(err).Msgf("addMeme failed")
w.WriteHeader(500)
e, _ := json.Marshal(err)
w.Write(e)
return true
}
return false
}
decoder := json.NewDecoder(r.Body)
values := webResp{}
err := decoder.Decode(&values)
if checkError(err) {
return
}
formats := p.c.GetMap("meme.memes", defaultFormats)
formats[values.Name] = values.URL
err = p.c.SetMap("meme.memes", formats)
checkError(err)
}
func (p *MemePlugin) webRoot(w http.ResponseWriter, r *http.Request) {
var tpl = template.Must(template.New("factoidIndex").Parse(string(memeIndex)))
tpl.Execute(w, struct{ Nav []bot.EndPoint }{p.bot.GetWebNavigation()})
}
func (p *MemePlugin) img(w http.ResponseWriter, r *http.Request) {
_, file := path.Split(r.URL.Path)
id := file
if img, ok := p.images[id]; ok {
w.Write(img.repr)
} else {
w.WriteHeader(404)
w.Write([]byte("not found"))
}
p.images.cleanup()
}
func (p *MemePlugin) slashMeme(c bot.Connector) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
r.ParseForm() r.ParseForm()
log.Debug().Msgf("Meme:\n%+v", r.PostForm.Get("text")) log.Debug().Msgf("Meme:\n%+v", r.PostForm.Get("text"))
channel := r.PostForm.Get("channel_id") channel := r.PostForm.Get("channel_id")
channelName := r.PostForm.Get("channel_name") channelName := r.PostForm.Get("channel_name")
from := r.PostForm.Get("user_name") from := r.PostForm.Get("user_name")
text := r.PostForm.Get("text")
log.Debug().Msgf("channel: %s", channel) log.Debug().Msgf("channel: %s", channel)
parts := strings.SplitN(text, " ", 2) parts := strings.SplitN(r.PostForm.Get("text"), " ", 2)
if len(parts) != 2 {
log.Debug().Msgf("Bad meme request: %s, %s", from, text)
p.bot.Send(c, bot.Message, channel, fmt.Sprintf("%s tried to send me a bad meme request.", from))
return
}
isCmd, message := bot.IsCmd(p.c, parts[1]) isCmd, message := bot.IsCmd(p.c, parts[1])
format := parts[0] format := parts[0]
log.Debug().Strs("parts", parts).Msgf("Meme:\n%+v", text) log.Debug().Strs("parts", parts).Msgf("Meme:\n%+v", r.PostForm.Get("text"))
w.WriteHeader(200) w.WriteHeader(200)
w.Write(nil) w.Write(nil)
@ -202,12 +100,7 @@ func (p *MemePlugin) slashMeme(c bot.Connector) http.HandlerFunc {
top, bottom = parts[0], parts[1] top, bottom = parts[0], parts[1]
} }
id, err := p.genMeme(format, top, bottom) id := p.genMeme(format, top, bottom)
if err != nil {
msg := fmt.Sprintf("Hey %s, I couldn't download that image you asked for.", from)
p.bot.Send(c, bot.Message, channel, msg)
return
}
baseURL := p.c.Get("BaseURL", `https://catbase.velour.ninja`) baseURL := p.c.Get("BaseURL", `https://catbase.velour.ninja`)
u, _ := url.Parse(baseURL) u, _ := url.Parse(baseURL)
u.Path = path.Join(u.Path, "meme", "img", id) u.Path = path.Join(u.Path, "meme", "img", id)
@ -232,22 +125,32 @@ func (p *MemePlugin) slashMeme(c bot.Connector) http.HandlerFunc {
p.bot.Receive(c, bot.Message, m) p.bot.Receive(c, bot.Message, m)
}() }()
} })
http.HandleFunc("/meme/img/", func(w http.ResponseWriter, r *http.Request) {
_, file := path.Split(r.URL.Path)
id := file
if img, ok := p.images[id]; ok {
w.Write(img.repr)
} else {
w.WriteHeader(404)
w.Write([]byte("not found"))
}
p.images.cleanup()
})
} }
func DownloadTemplate(u *url.URL) (image.Image, error) { func DownloadTemplate(u *url.URL) image.Image {
res, err := http.Get(u.String()) res, err := http.Get(u.String())
if err != nil { if err != nil {
log.Error().Msgf("template from %s failed because of %v", u.String(), err) log.Error().Msgf("template from %s failed because of %v", u.String(), err)
return nil, err
} }
defer res.Body.Close() defer res.Body.Close()
image, _, err := image.Decode(res.Body) image, _, err := image.Decode(res.Body)
if err != nil { if err != nil {
log.Error().Msgf("Could not decode %v because of %v", u, err) log.Error().Msgf("Could not decode %v because of %v", u, err)
return nil, err
} }
return image, nil return image
} }
var defaultFormats = map[string]string{ var defaultFormats = map[string]string{
@ -260,7 +163,7 @@ var defaultFormats = map[string]string{
"raptor": "Philosoraptor.jpg", "raptor": "Philosoraptor.jpg",
} }
func (p *MemePlugin) genMeme(meme, top, bottom string) (string, error) { func (p *MemePlugin) genMeme(meme, top, bottom string) string {
fontSizes := []float64{48, 36, 24, 16, 12} fontSizes := []float64{48, 36, 24, 16, 12}
fontSize := fontSizes[0] fontSize := fontSizes[0]
@ -281,11 +184,7 @@ func (p *MemePlugin) genMeme(meme, top, bottom string) (string, error) {
log.Debug().Msgf("Attempting to download url: %s", u.String()) log.Debug().Msgf("Attempting to download url: %s", u.String())
img, err := DownloadTemplate(u) img := DownloadTemplate(u)
if err != nil {
log.Debug().Msgf("failed to download image: %s", err)
return "", err
}
r := img.Bounds() r := img.Bounds()
w := r.Dx() w := r.Dx()
@ -354,5 +253,5 @@ func (p *MemePlugin) genMeme(meme, top, bottom string) (string, error) {
log.Debug().Msgf("Saved to %s\n", path) log.Debug().Msgf("Saved to %s\n", path)
return path, nil return path
} }

View File

@ -1,120 +0,0 @@
package meme
var memeIndex = `
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Load required Bootstrap and BootstrapVue CSS -->
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<!-- Load polyfills to support older browsers -->
<script src="//polyfill.io/v3/polyfill.min.js?features=es2015%2CMutationObserver"></script>
<!-- Load Vue followed by BootstrapVue -->
<script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<script src="https://unpkg.com/vue-router"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<meta charset="UTF-8">
<title>Memes</title>
</head>
<body>
<div id="app">
<b-navbar>
<b-navbar-brand>Memes</b-navbar-brand>
<b-navbar-nav>
<b-nav-item v-for="item in nav" :href="item.URL" :active="item.Name === 'Meme'">{{ "{{ item.Name }}" }}</b-nav-item>
</b-navbar-nav>
</b-navbar>
<b-alert
dismissable
variant="error"
v-if="err"
@dismissed="err = ''">
{{ "{{ err }}" }}
</b-alert>
<b-form @submit="addMeme">
<b-container>
<b-row>
<b-col cols="5">
<b-input v-model="name"></b-input>
</b-col>
<b-col cols="5">
<b-input v-model="url"></b-input>
</b-col>
<b-col cols="2">
<b-button type="submit">Add Meme</b-button>
</b-col>
</b-row>
<b-row>
<b-col>
<b-table
fixed
:items="results"
:fields="fields">
<template v-slot:cell(image)="data">
<b-img :src="data.item.url" rounded block fluid />
</template>
</b-table>
</b-col>
</b-row>
</b-container>
</b-form>
</div>
<script>
var router = new VueRouter({
mode: 'history',
routes: []
});
var app = new Vue({
el: '#app',
router,
data: {
err: '',
nav: {{ .Nav }},
name: "",
url: "",
results: [],
fields: [
{ key: 'name', sortable: true },
{ key: 'url', sortable: true },
{ key: 'image' }
]
},
mounted() {
this.refresh();
},
computed: {
},
methods: {
refresh: function() {
axios.get('/meme/all')
.catch(err => (this.err = err))
.then(resp => {
this.results = resp.data
})
},
addMeme: function(evt) {
if (evt) {
evt.preventDefault();
evt.stopPropagation()
}
if (this.name && this.url)
axios.post('/meme/add', {Name: this.name, URL: this.url})
.then(resp => {
this.results = resp.data;
this.name = "";
this.url = "";
this.refresh();
})
.catch(err => (this.err = err));
}
}
})
</script>
</body>
</html>
`