2022-06-24 23:09:46 +04:00
|
|
|
package captcha
|
|
|
|
|
|
|
|
import (
|
|
|
|
"image"
|
2022-06-26 23:53:52 +04:00
|
|
|
"justcaptcha/pkg/captcha"
|
2022-06-27 20:48:39 +04:00
|
|
|
"math/rand"
|
2022-06-24 23:09:46 +04:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/fogleman/gg"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
dwImageWidth = 160
|
|
|
|
dwImageHeight = 40
|
|
|
|
)
|
|
|
|
|
|
|
|
type DwellingCaptcha struct {
|
2022-07-30 15:33:34 +04:00
|
|
|
captcha.BaseCaptcha
|
2022-06-24 23:09:46 +04:00
|
|
|
}
|
|
|
|
|
2022-06-26 20:51:04 +04:00
|
|
|
func NewDwellingCaptcha(expiry time.Duration) *DwellingCaptcha {
|
2022-06-24 23:09:46 +04:00
|
|
|
return &DwellingCaptcha{
|
2022-07-30 15:33:34 +04:00
|
|
|
BaseCaptcha: captcha.BaseCaptcha{
|
2022-06-26 23:53:52 +04:00
|
|
|
ExpireIn: captcha.ExpiryDate(expiry)}}
|
2022-06-24 23:09:46 +04:00
|
|
|
}
|
|
|
|
|
2022-08-17 21:47:27 +04:00
|
|
|
func (c *DwellingCaptcha) Image(style string) *image.Image {
|
2022-06-27 03:03:22 +04:00
|
|
|
isDark := style == "dark"
|
2022-06-24 23:09:46 +04:00
|
|
|
ctx := gg.NewContext(dwImageWidth, dwImageHeight)
|
|
|
|
|
|
|
|
// fill background
|
2022-06-27 03:03:22 +04:00
|
|
|
if isDark {
|
2022-06-27 01:30:28 +04:00
|
|
|
ctx.SetRGB255(0x0a, 0x0a, 0x0a)
|
|
|
|
} else {
|
|
|
|
ctx.SetRGB255(0xf5, 0xf5, 0xf5)
|
|
|
|
}
|
2022-06-24 23:09:46 +04:00
|
|
|
ctx.Clear()
|
|
|
|
|
|
|
|
// draw text
|
2022-06-27 03:03:22 +04:00
|
|
|
if isDark {
|
2022-06-27 01:30:28 +04:00
|
|
|
ctx.SetRGB255(0xf5, 0xf5, 0xf5)
|
|
|
|
} else {
|
|
|
|
ctx.SetRGB255(0x0a, 0x0a, 0x0a)
|
|
|
|
}
|
2022-06-24 23:09:46 +04:00
|
|
|
ctx.Scale(4.0, 2.7)
|
|
|
|
ctx.DrawStringAnchored(string(c.GetAnswer()), 20, 5, .5, .5)
|
|
|
|
|
|
|
|
// draw lines and points
|
2022-06-27 20:48:39 +04:00
|
|
|
h := float64(ctx.Height())
|
2022-06-24 23:09:46 +04:00
|
|
|
|
2022-06-27 20:48:39 +04:00
|
|
|
for i := 0; i < 24; i++ {
|
|
|
|
x0 := rand.Float64() * h
|
|
|
|
x1 := rand.Float64() * h
|
|
|
|
x2 := rand.Float64() * h
|
|
|
|
x3 := rand.Float64() * h
|
|
|
|
ctx.DrawLine(x0, 0, h, x1)
|
|
|
|
ctx.DrawLine(0, x2, x3, h)
|
|
|
|
r := rand.Intn(256)
|
|
|
|
g := rand.Intn(256)
|
|
|
|
b := rand.Intn(256)
|
|
|
|
ctx.SetRGB255(r, g, b)
|
|
|
|
lw := float64(rand.Float32() * 4.0)
|
|
|
|
if lw == 0 {
|
|
|
|
lw = 0.1
|
|
|
|
}
|
|
|
|
ctx.SetLineWidth(lw)
|
2022-06-24 23:09:46 +04:00
|
|
|
ctx.Stroke()
|
|
|
|
}
|
|
|
|
|
2022-08-17 21:47:27 +04:00
|
|
|
i := ctx.Image()
|
|
|
|
return &i
|
2022-06-24 23:09:46 +04:00
|
|
|
}
|