forked from opq-osc/OPQBot
/
getQrcode.go
88 lines (81 loc) · 1.72 KB
/
getQrcode.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package apiBuilder
import (
"bytes"
"encoding/base64"
"github.com/cross10/OPQBot/v2/errors"
"github.com/imroc/req/v3"
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/qrcode"
"github.com/mdp/qrterminal/v3"
"image"
_ "image/png"
"io"
"regexp"
)
func (b *Builder) Qrcode() IQrcode {
return &QrcodeStruct{url: b.url}
}
type IQrcode interface {
Get() error
GetUrl() *string
PrintTerminal(io.Writer) error
GetImageBytes() []byte
}
type QrcodeStruct struct {
url string
loginUrl *string
imgByte []byte
}
func (q *QrcodeStruct) GetImageBytes() []byte {
return q.imgByte
}
func (q *QrcodeStruct) GetUrl() *string {
return q.loginUrl
}
func (q *QrcodeStruct) PrintTerminal(writer io.Writer) error {
if q.loginUrl == nil {
return errors.ErrorData
}
qrterminal.GenerateWithConfig(*q.loginUrl, qrterminal.Config{
Level: qrterminal.L,
Writer: writer,
BlackChar: qrterminal.BLACK,
WhiteChar: qrterminal.WHITE,
QuietZone: 0,
})
return nil
}
func (q *QrcodeStruct) Get() error {
resp, err := req.R().Get(q.url + "/v1/login/getqrcode")
if err != nil {
return err
}
rgx := regexp.MustCompile(`data:image/png;base64,(.*?)"`)
data := rgx.FindSubmatch(resp.Bytes())
if len(data) != 2 {
return errors.ErrorData
}
img := string(data[1])
imgByte, err := base64.StdEncoding.DecodeString(img)
if err != nil {
return err
}
q.imgByte = imgByte
buf := bytes.NewBuffer(imgByte)
png, _, err := image.Decode(buf)
if err != nil {
return err
}
p, err := gozxing.NewBinaryBitmapFromImage(png)
if err != nil {
return err
}
qrReader := qrcode.NewQRCodeReader()
result, err := qrReader.Decode(p, nil)
if err != nil {
return err
}
loginUrl := result.String()
q.loginUrl = &loginUrl
return nil
}