/
deathbycaptcha.go
114 lines (95 loc) · 2.34 KB
/
deathbycaptcha.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
package deathbycaptcha
import (
"net/http"
"time"
"log"
"bytes"
"strings"
"os"
"mime/multipart"
"path/filepath"
"io"
"errors"
)
type DeathByCaptcha struct {}
func New() (*DeathByCaptcha) {
return &DeathByCaptcha{}
}
func (DeathByCaptcha) Solve(username, password, imagePath string) (captchaText string, err error) {
extraParams := map[string]string {
"username": username,
"password": password,
}
request, err := newfileUploadRequest("http://api.dbcapi.me/api/captcha", extraParams, "captchafile", imagePath)
if err != nil {
return
}
client := &http.Client{}
startTime := time.Now()
log.Printf("Start time: %v\n", startTime)
resp, err := client.Do(request)
if err != nil {
return captchaText, err
} else {
body := &bytes.Buffer{}
_, err := body.ReadFrom(resp.Body)
if err != nil {
return captchaText, err
}
resp.Body.Close()
resultURL := resp.Request.URL.String()
result := strings.Split(body.String(), "&")
if len(result) <= 1 {
log.Println("Result not solved")
log.Panicln(body.String())
return captchaText, errors.New("Result not solved")
}
for {
if strings.HasPrefix(result[2], "text=") {
captchaText = strings.TrimPrefix(result[2], "text=")
if len(captchaText) > 0 {
finishTime := time.Now()
log.Printf("Complete time: %v\n", finishTime)
log.Printf("Elapsed time: %v\n", finishTime.Sub(startTime))
break
}
}
resp, err = client.Get(resultURL)
if err != nil {
return captchaText, err
}
body := &bytes.Buffer{}
_, err := body.ReadFrom(resp.Body)
if err != nil {
return captchaText, err
}
resp.Body.Close()
result = strings.Split(body.String(), "&")
}
return captchaText, err
}
}
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
for key, val := range params {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", uri, body)
req.Header.Set("Content-Type", writer.FormDataContentType())
return req, err
}