This repository has been archived by the owner on Feb 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
captcha.go
173 lines (160 loc) · 4.63 KB
/
captcha.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package captcha
import (
"context"
"encoding/base64"
"fmt"
"image"
"image/jpeg"
"math"
"math/rand"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"github.com/zhulingbiezhi/go12306/pkg/common"
"github.com/zhulingbiezhi/go12306/tools/errors"
"github.com/zhulingbiezhi/go12306/tools/logger"
"github.com/zhulingbiezhi/go12306/tools/rest"
"github.com/zhulingbiezhi/go12306/tools/utils"
)
type Captcha struct {
CookieMap map[string]*http.Cookie
}
type imageResponse struct {
Image string `json:"image"`
ResultMessage string `json:"result_message"`
ResultCode string `json:"result_code"`
}
func GetAuthCode(ctx context.Context, vals url.Values, cookieMap map[string]*http.Cookie) (string, error) {
if len(vals) == 0 {
return "", errors.Errorf(nil, "data is empty")
}
c := Captcha{
CookieMap: cookieMap,
}
resp, err := c.generatorCodeImage(ctx, vals)
if err != nil {
return "", errors.Errorf(err, "generatorCodeImage err")
}
//save picture
if false {
if err := saveImage(resp.Image); err != nil {
return "", errors.Errorf(err, "saveImage err")
}
}
//image recognition
ret, err := getVerifyCode(resp.Image)
if err != nil {
return "", errors.Errorf(err, "GetVerifyCode err")
}
//check auth code
answer := strings.Join(getImagePositionByOffset(ret), ",")
success, err := c.checkAuthCode(ctx, answer)
if err != nil {
return "", errors.Errorf(err, "CheckAuthCode err")
}
if !success {
return "", errors.Errorf(nil, "CheckAuthCode fail")
}
return answer, nil
}
func (c *Captcha) generatorCodeImage(ctx context.Context, vals url.Values) (*imageResponse, error) {
urlStr := common.API_AUTH_CODE_BASE64_DOWNLOAD + "?" + vals.Encode()
code := &imageResponse{}
rs := rest.NewHttp()
_, err := rs.DoRest(http.MethodGet, urlStr, nil).ParseJsonBody(code)
if err != nil {
return nil, err
}
for key, ck := range rs.RespCookies() {
switch key {
case common.Cookie_PassportCt, common.Cookie_PassportSession:
c.CookieMap[ck.Name] = rs.RespCookies()[key]
}
}
if code.ResultCode != "0" || code.ResultMessage != "生成验证码成功" {
return nil, errors.Errorf(nil, "code: %s, message: %s", code.ResultCode, code.ResultMessage)
}
return code, nil
}
func getVerifyCode(img string) ([]int, error) {
vals := make(url.Values, 0)
vals.Set("img", img)
ret := struct {
Msg string `json:"msg"`
Result []int `json:"result"`
}{}
rs := rest.NewHttp().SetContentType(rest.ContentTypeForm)
_, err := rs.DoRest(http.MethodPost, common.API_FREE_CODE_QCR_API_URL, vals.Encode()).ParseJsonBody(&ret)
if err != nil {
return nil, err
}
if ret.Msg != "success" || len(ret.Result) == 0 {
return nil, errors.Errorf(nil, "result is not success %+v", ret)
}
return ret.Result, nil
}
func (c *Captcha) checkAuthCode(ctx context.Context, answer string) (bool, error) {
vals := url.Values{
"login_site": []string{"E"},
"module": []string{"login"},
"rand": []string{"sjrand"},
"_": []string{strconv.FormatFloat(rand.Float64(), 'f', -1, 64)},
"answer": []string{answer},
}
urlStr := common.API_AUTH_CODE_CHECK_URL + "?" + vals.Encode()
ret := struct {
ResultMessage string `json:"result_message"`
ResultCode string `json:"result_code"`
}{}
rs := rest.NewHttp().SetContentType(rest.ContentTypeForm)
rs.SetCookie(rest.RestMultiCookiesOption([]*http.Cookie{
c.CookieMap[common.Cookie_PassportSession],
c.CookieMap[common.Cookie_PassportCt],
}))
_, err := rs.DoRest(http.MethodGet, urlStr, nil).ParseJsonBody(&ret)
if err != nil {
return false, err
}
bSuccess := ret.ResultCode == "4"
if bSuccess {
logger.Info("check auth code success")
}
return bSuccess, nil
}
func getImagePositionByOffset(offsets []int) []string {
positions := make([]string, 0)
width := (75)
height := (75)
for _, offset := range offsets {
random_x := rand.Intn(20) + -10
random_y := rand.Intn(20) + -10
offset = int(offset)
x := width*((offset-1)%4+1) - width/2 + random_x
y := height*int(math.Ceil(float64(offset)/4)) - height/2 + random_y
positions = append(positions, strconv.Itoa(x))
positions = append(positions, strconv.Itoa(y))
}
return positions
}
func saveImage(imgStr string) error {
//save picture
reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(imgStr))
img, _, err := image.Decode(reader)
if err != nil {
return errors.Errorf(err, "image.Decode err")
}
dir := utils.GetCurDir()
//Encode from image format to writer
dstFileName := dir + fmt.Sprintf("/code_%d.jpeg", 0)
f, err := os.OpenFile(dstFileName, os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
return err
}
err = jpeg.Encode(f, img, &jpeg.Options{Quality: 100})
if err != nil {
return err
}
return nil
}