This repository has been archived on 2023-07-05. You can view files and clone it, but cannot push or open issues or pull requests.
clessy/mods/unsplash.go

220 lines
5.4 KiB
Go
Raw Normal View History

2016-06-20 15:38:00 +00:00
package main
import (
"bytes"
"image"
_ "image/gif"
"image/jpeg"
_ "image/png"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
2018-11-16 11:27:42 +00:00
"git.fromouter.space/crunchy-rocks/draw2d"
"git.fromouter.space/crunchy-rocks/draw2d/draw2dimg"
"git.fromouter.space/crunchy-rocks/freetype"
2018-11-08 18:55:34 +00:00
"git.fromouter.space/hamcha/tg"
2016-06-20 15:38:00 +00:00
"github.com/disintegration/imaging"
)
const unsplashUrl = "https://source.unsplash.com/random/1280x720"
var quoteFontData draw2d.FontData
2018-05-24 15:48:35 +00:00
func unsplash_init() {
2016-06-20 15:38:00 +00:00
fontfile, err := os.Open(*gillmt)
assert(err)
defer fontfile.Close()
bytes, err := ioutil.ReadAll(fontfile)
assert(err)
font, err := freetype.ParseFont(bytes)
assert(err)
quoteFontData = draw2d.FontData{"gillmt", draw2d.FontFamilySans, draw2d.FontStyleBold}
draw2d.RegisterFont(quoteFontData, font)
2017-03-15 20:20:07 +00:00
log.Println("[unsplash] Loaded!")
2016-06-20 15:38:00 +00:00
}
func stripUnreadable(r rune) rune {
if r == '\n' || r == '\t' {
return ' '
}
2018-11-16 16:02:48 +00:00
if r < 32 {
return -1
}
return r
}
2018-05-24 15:48:35 +00:00
func unsplash_message(broker *tg.Broker, update tg.APIMessage) {
2016-06-20 15:38:00 +00:00
if isCommand(update, "unsplash") {
text := ""
user := update.User
if update.ReplyTo != nil {
2018-06-18 17:26:22 +00:00
switch {
case update.ReplyTo.Text != nil:
text = *(update.ReplyTo.Text)
case update.ReplyTo.Caption != nil:
text = *(update.ReplyTo.Caption)
default:
2018-12-13 10:29:45 +00:00
broker.SendTextMessage(update.Chat, "Non c'e' niente di 'ispiratore' in questo..", &tg.MessageOptions{
ReplyID: &update.MessageID,
})
2016-06-20 15:57:26 +00:00
return
}
2018-06-18 17:26:22 +00:00
// For forwarded message take the original user
if update.FwdUser != nil {
user = update.FwdUser.Message.User
} else {
user = update.ReplyTo.User
}
2016-06-20 15:38:00 +00:00
} else {
2016-06-21 19:26:13 +00:00
if strings.Index(*(update.Text), " ") > 0 {
2016-06-21 15:51:11 +00:00
text = strings.TrimSpace(strings.SplitN(*(update.Text), " ", 2)[1])
}
2016-06-20 15:38:00 +00:00
}
// Cleanup chars
text = strings.Map(stripUnreadable, text)
2016-06-20 15:38:00 +00:00
author := user.FirstName
if user.LastName != "" {
author = user.FirstName + " " + user.LastName
}
author += " (" + user.Username + ")"
if strings.TrimSpace(text) == "" {
2018-12-13 10:29:45 +00:00
broker.SendTextMessage(update.Chat, "Non c'e' niente di 'ispiratore' in questo..", &tg.MessageOptions{
ReplyID: &update.MessageID,
})
2016-06-20 15:38:00 +00:00
return
}
resp, err := http.Get(unsplashUrl)
if err != nil {
2018-04-09 13:21:25 +00:00
log.Printf("[unsplash] HTTP request failed: %s\nOriginal URL: %s\n", err.Error(), unsplashUrl)
2018-12-13 10:29:45 +00:00
broker.SendTextMessage(update.Chat, "<b>ERRORE!</b> @hamcha controlla la console!", &tg.MessageOptions{
ReplyID: &update.MessageID,
})
2016-06-20 15:38:00 +00:00
return
}
defer resp.Body.Close()
img, _, err := image.Decode(resp.Body)
if err != nil {
2018-04-09 13:21:25 +00:00
log.Printf("[unsplash] Image decode error: %s\nOriginal URL: %s\n", err.Error(), unsplashUrl)
2018-12-13 10:29:45 +00:00
broker.SendTextMessage(update.Chat, "<b>ERRORE</b>: Non riesco a leggere l'immagine", &tg.MessageOptions{
ReplyID: &update.MessageID,
})
2016-06-20 15:38:00 +00:00
return
}
broker.SendChatAction(update.Chat, tg.ActionUploadingPhoto)
2016-06-20 15:38:00 +00:00
// Darken image
img = imaging.AdjustBrightness(imaging.AdjustGamma(imaging.AdjustSigmoid(img, 0.5, -6.0), 0.8), -20)
// Create target image
bounds := img.Bounds()
iwidth := float64(bounds.Size().X)
iheight := float64(bounds.Size().Y)
timg := image.NewRGBA(bounds)
gc := draw2dimg.NewGraphicContext(timg)
2018-11-16 11:27:42 +00:00
gc.Emojis = emojis
2016-06-20 15:44:46 +00:00
gc.SetFontData(quoteFontData)
2016-06-20 15:38:00 +00:00
gc.DrawImage(img)
gc.SetStrokeColor(image.Black)
gc.SetFillColor(image.White)
text = strings.ToUpper(strings.TrimSpace(text))
gc.Restore()
gc.Save()
// Detect appropriate font size
scale := iheight / iwidth * (iwidth / 10) * 0.8
gc.SetFontSize(scale)
gc.SetLineWidth(scale / 15)
// Get NEW bounds
left, top, right, bottom := gc.GetStringBounds(text)
width := right - left
texts := []string{text}
2016-06-21 12:32:31 +00:00
if width*1.2 > iwidth {
2016-06-20 15:38:00 +00:00
// Split text
texts = splitCenter(text)
// Get longest line
longer := float64(0)
longid := 0
widths := make([]float64, len(texts))
for id := range texts {
tleft, _, tright, _ := gc.GetStringBounds(texts[id])
widths[id] = tright - tleft
if width > longer {
longer = widths[id]
longid = id
}
}
// Still too big? Decrease font size again
iter := 0
2016-06-21 12:31:13 +00:00
for width*1.2 > iwidth && iter < 10 {
2016-06-21 19:30:10 +00:00
scale *= (0.9 - 0.05*float64(iter))
2016-06-20 15:38:00 +00:00
gc.SetFontSize(scale)
left, top, right, bottom = gc.GetStringBounds(texts[longid])
2016-06-20 15:38:00 +00:00
width = right - left
iter++
}
}
texts = append(texts, author)
2016-06-20 16:01:29 +00:00
height := bottom - top + 20
2016-06-20 15:38:00 +00:00
margin := float64(height / 50)
txtheight := (height + margin) * float64(len(texts))
gc.Save()
for id, txt := range texts {
gc.Save()
left, _, right, _ = gc.GetStringBounds(txt)
width = right - left
x := (iwidth - width) / 2
2016-06-20 15:53:25 +00:00
y := (iheight-txtheight)/2 + (height+margin*2)*float64(id+1)
2016-06-20 15:38:00 +00:00
if id == len(texts)-1 {
gc.SetFontSize(scale * 0.7)
left, _, right, _ = gc.GetStringBounds(txt)
width = right - left
x = (iwidth - width) / 1.5
y = (iheight-txtheight)/2 + (height+margin)*float64(id+1) + margin*6
}
gc.Translate(x, y)
gc.StrokeString(txt)
gc.FillString(txt)
gc.Restore()
}
buf := new(bytes.Buffer)
err = jpeg.Encode(buf, timg, &(jpeg.Options{Quality: 80}))
if err != nil {
log.Println("[unsplash] Image encode error: %s\n", err.Error())
2018-12-13 10:29:45 +00:00
broker.SendTextMessage(update.Chat, "<b>ERRORE!</b> @hamcha controlla la console!", &tg.MessageOptions{
ReplyID: &update.MessageID,
})
2016-06-20 15:38:00 +00:00
return
}
2018-12-13 10:29:45 +00:00
broker.SendPhoto(update.Chat, buf.Bytes(), "quote.jpg", "", &tg.MessageOptions{
ReplyID: &update.MessageID,
})
2016-06-20 15:38:00 +00:00
}
}