Compare commits

..

No commits in common. "defeb9b3b19f73d7c09f472721a12d1a1526e02a" and "332d992d05ecbe0868d2d8f45627aec43936e07c" have entirely different histories.

3 changed files with 133 additions and 187 deletions

View File

@ -170,7 +170,6 @@ func (d *Discord) convertUser(u *discordgo.User) *user.User {
ID: u.ID, ID: u.ID,
Name: u.Username, Name: u.Username,
Admin: false, Admin: false,
Icon: d.client.State.User.AvatarURL("64"),
IconImg: img, IconImg: img,
} }
} }

View File

@ -16,6 +16,7 @@ import (
"time" "time"
"github.com/fogleman/gg" "github.com/fogleman/gg"
"github.com/google/uuid"
"github.com/nfnt/resize" "github.com/nfnt/resize"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
@ -44,23 +45,6 @@ type memeText struct {
Caps bool `json:"c"` Caps bool `json:"c"`
} }
type specification struct {
ImageURL string
StampURL string
Configs []memeText
}
func (s specification) toJSON() string {
out, _ := json.Marshal(s)
return string(out)
}
func SpecFromJSON(input []byte) (specification, error) {
out := specification{}
err := json.Unmarshal(input, &out)
return out, err
}
var horizon = 24 * 7 var horizon = 24 * 7
type cachedImages map[string]*cachedImage type cachedImages map[string]*cachedImage
@ -112,13 +96,13 @@ func (p *MemePlugin) help(c bot.Connector, kind bot.Kind, message msg.Message, a
return true return true
} }
func (p *MemePlugin) stamp(c bot.Connector, format, id string) string { func (p *MemePlugin) bully(c bot.Connector, format, id string) (image.Image, string) {
iconURL := "" bullyIcon := ""
for _, bully := range p.c.GetArray("meme.bully", []string{}) { for _, bully := range p.c.GetArray("meme.bully", []string{}) {
if format == bully { if format == bully {
if u, err := c.Profile(bully); err == nil { if u, err := c.Profile(bully); err == nil {
iconURL = u.Icon bullyIcon = u.Icon
} else { } else {
log.Debug().Err(err).Msgf("could not get profile for %s", format) log.Debug().Err(err).Msgf("could not get profile for %s", format)
} }
@ -129,11 +113,22 @@ func (p *MemePlugin) stamp(c bot.Connector, format, id string) string {
} }
} }
if u, err := c.Profile(id); iconURL == "" && err == nil { if u, err := c.Profile(id); bullyIcon == "" && err == nil {
iconURL = u.Icon if u.IconImg != nil {
return u.IconImg, format
}
bullyIcon = u.Icon
} }
return iconURL u, err := url.Parse(bullyIcon)
if err != nil {
log.Error().Err(err).Msg("error with bully URL")
}
bullyImg, err := DownloadTemplate(u)
if err != nil {
log.Error().Err(err).Msg("error downloading bully icon")
}
return bullyImg, format
} }
func (p *MemePlugin) sendMeme(c bot.Connector, channel, channelName, msgID string, from *user.User, text string) { func (p *MemePlugin) sendMeme(c bot.Connector, channel, channelName, msgID string, from *user.User, text string) {
@ -148,103 +143,88 @@ func (p *MemePlugin) sendMeme(c bot.Connector, channel, channelName, msgID strin
log.Debug().Strs("parts", parts).Msgf("Meme:\n%+v", text) log.Debug().Strs("parts", parts).Msgf("Meme:\n%+v", text)
var config []memeText go func() {
var config []memeText
message = strings.TrimPrefix(message, "`") message = strings.TrimPrefix(message, "`")
message = strings.TrimSuffix(message, "`") message = strings.TrimSuffix(message, "`")
err := json.Unmarshal([]byte(message), &config) err := json.Unmarshal([]byte(message), &config)
if err == nil { if err == nil {
message = "" message = ""
for _, c := range config { for _, c := range config {
message += c.Text + "\n" message += c.Text + "\n"
} }
} else {
if strings.Contains(message, "||") {
parts = strings.Split(message, "||")
} else { } else {
parts = strings.Split(message, "\n") if strings.Contains(message, "||") {
} parts = strings.Split(message, "||")
} else {
parts = strings.Split(message, "\n")
}
allConfigs := p.c.GetMap("meme.memeconfigs", map[string]string{}) allConfigs := p.c.GetMap("meme.memeconfigs", map[string]string{})
configtxt, ok := allConfigs[format] configtxt, ok := allConfigs[format]
if !ok { if !ok {
config = defaultFormatConfig()
log.Debug().Msgf("Did not find %s in %+v", format, allConfigs)
} else {
err = json.Unmarshal([]byte(configtxt), &config)
if err != nil {
log.Error().Err(err).Msgf("Could not parse config for %s:\n%s", format, configtxt)
config = defaultFormatConfig() config = defaultFormatConfig()
} log.Debug().Msgf("Did not find %s in %+v", format, allConfigs)
} } else {
err = json.Unmarshal([]byte(configtxt), &config)
j := 0 if err != nil {
for i := range config { log.Error().Err(err).Msgf("Could not parse config for %s:\n%s", format, configtxt)
if len(parts) > i { config = defaultFormatConfig()
if parts[j] != "_" { }
config[i].Text = parts[j] }
j := 0
for i := range config {
if len(parts) > i {
if parts[j] != "_" {
config[i].Text = parts[j]
}
j++
} }
j++
} }
} }
}
formats := p.c.GetMap("meme.memes", defaultFormats) bullyImg, format := p.bully(c, format, from.ID)
imgURL, ok := formats[format]
if !ok {
imgURL = format
}
stampURL := p.stamp(c, format, from.ID) id, w, h, err := p.genMeme(format, bullyImg, config)
if err != nil {
msg := fmt.Sprintf("Hey %v, I couldn't download that image you asked for.", from.Name)
p.bot.Send(c, bot.Ephemeral, channel, from.ID, msg)
return
}
baseURL := p.c.Get("BaseURL", ``)
u, _ := url.Parse(baseURL)
u.Path = path.Join(u.Path, "meme", "img", id)
spec := specification{ log.Debug().Msgf("image is at %s", u.String())
ImageURL: imgURL, _, err = p.bot.Send(c, bot.Message, channel, "", bot.ImageAttachment{
StampURL: stampURL, URL: u.String(),
Configs: config, AltTxt: fmt.Sprintf("%s: %s", from.Name, message),
} Width: w,
Height: h,
})
encodedSpec, _ := json.Marshal(spec) if err == nil && msgID != "" {
p.bot.Send(c, bot.Delete, channel, msgID)
}
w, h, err := p.checkMeme(imgURL) m := msg.Message{
if err != nil { User: &user.User{
msg := fmt.Sprintf("Hey %v, I couldn't download that image you asked for.", from.Name) ID: from.ID,
p.bot.Send(c, bot.Ephemeral, channel, from.ID, msg) Name: from.Name,
return Admin: false,
} },
baseURL := p.c.Get("BaseURL", ``) Channel: channel,
u, _ := url.Parse(baseURL) ChannelName: channelName,
u.Path = path.Join(u.Path, "meme", "img") Body: message,
q := u.Query() Command: isCmd,
q.Add("spec", string(encodedSpec)) Time: time.Now(),
u.RawQuery = q.Encode() }
log.Debug().Msgf("image is at %s", u.String()) p.bot.Receive(c, bot.Message, m)
_, err = p.bot.Send(c, bot.Message, channel, "", bot.ImageAttachment{ }()
URL: u.String(),
AltTxt: fmt.Sprintf("%s: %s", from.Name, message),
Width: w,
Height: h,
})
if err == nil && msgID != "" {
p.bot.Send(c, bot.Delete, channel, msgID)
}
m := msg.Message{
User: &user.User{
ID: from.ID,
Name: from.Name,
Admin: false,
},
Channel: channel,
ChannelName: channelName,
Body: message,
Command: isCmd,
Time: time.Now(),
}
p.bot.Receive(c, bot.Message, m)
} }
@ -294,13 +274,13 @@ func DownloadTemplate(u *url.URL) (image.Image, error) {
} }
var defaultFormats = map[string]string{ var defaultFormats = map[string]string{
"fry": "https://imgflip.com/s/meme/Futurama-Fry.jpg", "fry": "Futurama-Fry.jpg",
"aliens": "https://imgflip.com/s/meme/Ancient-Aliens.jpg", "aliens": "Ancient-Aliens.jpg",
"doge": "https://imgflip.com/s/meme/Doge.jpg", "doge": "Doge.jpg",
"simply": "https://imgflip.com/s/meme/One-Does-Not-Simply.jpg", "simply": "One-Does-Not-Simply.jpg",
"wonka": "https://imgflip.com/s/meme/Creepy-Condescending-Wonka.jpg", "wonka": "Creepy-Condescending-Wonka.jpg",
"grumpy": "https://imgflip.com/s/meme/Grumpy-Cat.jpg", "grumpy": "Grumpy-Cat.jpg",
"raptor": "https://imgflip.com/s/meme/Philosoraptor.jpg", "raptor": "Philosoraptor.jpg",
} }
func (p *MemePlugin) findFontSize(config []memeText, w, h int, sizes []float64) float64 { func (p *MemePlugin) findFontSize(config []memeText, w, h int, sizes []float64) float64 {
@ -353,31 +333,23 @@ func defaultFormatConfigJSON() string {
return string(c) return string(c)
} }
func (p *MemePlugin) checkMeme(imgURL string) (int, int, error) { func (p *MemePlugin) genMeme(meme string, bully image.Image, config []memeText) (string, int, int, error) {
u, err := url.Parse(imgURL)
if err != nil || u.Scheme == "" {
log.Debug().Err(err).Str("imgName", imgURL).Msgf("url not detected")
return 0, 0, fmt.Errorf("URL not valid (%s): %w", imgURL, err)
}
img, err := DownloadTemplate(u)
return img.Bounds().Dx(), img.Bounds().Dy(), err
}
func (p *MemePlugin) genMeme(spec specification) ([]byte, error) {
fontSizes := []float64{48, 36, 24, 16, 12} fontSizes := []float64{48, 36, 24, 16, 12}
formats := p.c.GetMap("meme.memes", defaultFormats)
jsonSpec := spec.toJSON() path := uuid.New().String()
if cached, ok := p.images[jsonSpec]; ok {
log.Debug().Msgf("Returning cached image for %s", jsonSpec) imgName, ok := formats[meme]
return cached.repr, nil if !ok {
imgName = meme
} }
u, err := url.Parse(spec.ImageURL) u, err := url.Parse(imgName)
if err != nil || u.Scheme == "" { if err != nil || u.Scheme == "" {
log.Debug().Err(err).Str("imgName", spec.ImageURL).Msgf("url not detected") log.Debug().Err(err).Str("imgName", imgName).Msgf("url not detected")
return nil, fmt.Errorf("Error with meme URL: %w", err) if u, err = url.Parse("https://imgflip.com/s/meme/" + imgName); err != nil {
return "", 0, 0, err
}
} }
log.Debug().Msgf("Attempting to download url: %s", u.String()) log.Debug().Msgf("Attempting to download url: %s", u.String())
@ -385,13 +357,15 @@ func (p *MemePlugin) genMeme(spec specification) ([]byte, error) {
img, err := DownloadTemplate(u) img, err := DownloadTemplate(u)
if err != nil { if err != nil {
log.Debug().Msgf("failed to download image: %s", err) log.Debug().Msgf("failed to download image: %s", err)
return nil, err return "", 0, 0, err
} }
r := img.Bounds() r := img.Bounds()
w := r.Dx() w := r.Dx()
h := r.Dy() h := r.Dy()
// /meme2 5guys [{"x": 0.1, "y": 0.1, "t": "test"}]
maxSz := p.c.GetFloat64("maxImgSz", 750.0) maxSz := p.c.GetFloat64("maxImgSz", 750.0)
if w > h { if w > h {
@ -411,24 +385,18 @@ func (p *MemePlugin) genMeme(spec specification) ([]byte, error) {
h = r.Dy() h = r.Dy()
log.Debug().Msgf("resized to %v, %v", w, h) log.Debug().Msgf("resized to %v, %v", w, h)
if spec.StampURL != "" { if bully != nil {
img, err = p.applyStamp(img, spec.StampURL) img = p.applyBully(img, bully)
if err != nil {
log.Error().
Err(err).
Interface("spec", spec).
Msg("could not apply stamp")
}
} }
m := gg.NewContext(w, h) m := gg.NewContext(w, h)
m.DrawImage(img, 0, 0) m.DrawImage(img, 0, 0)
fontLocation := p.c.Get("meme.font", "impact.ttf") fontLocation := p.c.Get("meme.font", "impact.ttf")
m.LoadFontFace(fontLocation, p.findFontSize(spec.Configs, w, h, fontSizes)) m.LoadFontFace(fontLocation, p.findFontSize(config, w, h, fontSizes))
for i, c := range spec.Configs { for i, c := range config {
if c.Caps { if c.Caps {
spec.Configs[i].Text = strings.ToUpper(c.Text) config[i].Text = strings.ToUpper(c.Text)
} }
} }
@ -441,7 +409,7 @@ func (p *MemePlugin) genMeme(spec specification) ([]byte, error) {
if dx*dx+dy*dy >= strokeSize*strokeSize { if dx*dx+dy*dy >= strokeSize*strokeSize {
continue continue
} }
for _, c := range spec.Configs { for _, c := range config {
x := float64(w)*c.XPerc + float64(dx) x := float64(w)*c.XPerc + float64(dx)
y := float64(h)*c.YPerc + float64(dy) y := float64(h)*c.YPerc + float64(dy)
m.DrawStringAnchored(c.Text, x, y, 0.5, 0.5) m.DrawStringAnchored(c.Text, x, y, 0.5, 0.5)
@ -451,7 +419,7 @@ func (p *MemePlugin) genMeme(spec specification) ([]byte, error) {
// Apply white fill // Apply white fill
m.SetHexColor("#FFF") m.SetHexColor("#FFF")
for _, c := range spec.Configs { for _, c := range config {
x := float64(w) * c.XPerc x := float64(w) * c.XPerc
y := float64(h) * c.YPerc y := float64(h) * c.YPerc
m.DrawStringAnchored(c.Text, x, y, 0.5, 0.5) m.DrawStringAnchored(c.Text, x, y, 0.5, 0.5)
@ -459,23 +427,18 @@ func (p *MemePlugin) genMeme(spec specification) ([]byte, error) {
i := bytes.Buffer{} i := bytes.Buffer{}
png.Encode(&i, m.Image()) png.Encode(&i, m.Image())
p.images[jsonSpec] = &cachedImage{time.Now(), i.Bytes()} p.images[path] = &cachedImage{time.Now(), i.Bytes()}
log.Debug().Msgf("Saved to %s\n", jsonSpec) log.Debug().Msgf("Saved to %s\n", path)
return p.images[jsonSpec].repr, nil return path, w, h, nil
} }
func (p *MemePlugin) applyStamp(img image.Image, bullyURL string) (image.Image, error) { func (p *MemePlugin) applyBully(img, bullyImg image.Image) image.Image {
u, _ := url.Parse(bullyURL)
bullyImg, err := DownloadTemplate(u)
if err != nil {
return nil, err
}
dst := image.NewRGBA(img.Bounds()) dst := image.NewRGBA(img.Bounds())
scaleFactor := p.c.GetFloat64("meme.stampScale", 0.1) scaleFactor := p.c.GetFloat64("meme.bullyScale", 0.1)
position := p.c.GetString("meme.stampPosition", "botright") position := p.c.GetString("meme.bullyPosition", "botright")
scaleFactor = float64(img.Bounds().Max.X) * scaleFactor / float64(bullyImg.Bounds().Max.X) scaleFactor = float64(img.Bounds().Max.X) * scaleFactor / float64(bullyImg.Bounds().Max.X)
@ -501,7 +464,7 @@ func (p *MemePlugin) applyStamp(img image.Image, bullyURL string) (image.Image,
rect := image.Rect(pt.X, pt.Y, srcSz.X, srcSz.Y) rect := image.Rect(pt.X, pt.Y, srcSz.X, srcSz.Y)
draw.DrawMask(dst, rect, bullyImg, image.Point{}, &circle{image.Point{w / 2, h / 2}, w / 2}, image.Point{}, draw.Over) draw.DrawMask(dst, rect, bullyImg, image.Point{}, &circle{image.Point{w / 2, h / 2}, w / 2}, image.Point{}, draw.Over)
return dst, nil return dst
} }
// the following is ripped off of https://blog.golang.org/image-draw // the following is ripped off of https://blog.golang.org/image-draw

View File

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"net/url" "net/url"
"path"
"sort" "sort"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
@ -50,9 +51,12 @@ func (p *MemePlugin) all(w http.ResponseWriter, r *http.Request) {
} }
realURL, err := url.Parse(u) realURL, err := url.Parse(u)
if err != nil || realURL.Scheme == "" { if err != nil || realURL.Scheme == "" {
values = append(values, webResp{n, "404.png", config}) realURL, err = url.Parse("https://imgflip.com/s/meme/" + u)
log.Error().Err(err).Msgf("invalid URL") if err != nil {
continue values = append(values, webResp{n, "404.png", config})
log.Error().Err(err).Msgf("invalid URL")
continue
}
} }
values = append(values, webResp{n, realURL.String(), config}) values = append(values, webResp{n, realURL.String(), config})
} }
@ -133,31 +137,11 @@ func (p *MemePlugin) webRoot(w http.ResponseWriter, r *http.Request) {
} }
func (p *MemePlugin) img(w http.ResponseWriter, r *http.Request) { func (p *MemePlugin) img(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query() _, file := path.Split(r.URL.Path)
spec := q.Get("spec") id := file
if spec == "" { if img, ok := p.images[id]; ok {
log.Debug().Msgf("No spec found for img") w.Write(img.repr)
w.WriteHeader(404)
w.Write([]byte{})
return
}
s, err := SpecFromJSON([]byte(spec))
if err != nil {
w.WriteHeader(400)
w.Write([]byte(err.Error()))
return
}
img, err := p.genMeme(s)
if err == nil {
w.Write(img)
} else { } else {
log.Error().
Err(err).
Interface("spec", s).
Msg("Unable to generate meme image")
w.WriteHeader(404) w.WriteHeader(404)
w.Write([]byte("not found")) w.Write([]byte("not found"))
} }