87 lines
2.4 KiB
Go
87 lines
2.4 KiB
Go
package xuexitong
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"likedream-goframe/internal/utils"
|
|
"log"
|
|
"math/rand"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"resty.dev/v3"
|
|
)
|
|
|
|
var randChar []string = []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"}
|
|
|
|
func ApiVerifyCode(client *resty.Client, retry int) (string, error) {
|
|
if retry < 0 {
|
|
return "", fmt.Errorf("retry limit exceeded")
|
|
}
|
|
urlStr := "https://mooc1-api.chaoxing.com/processVerifyPng.ac?t=" + fmt.Sprintf("%d", time.Now().UnixMilli())
|
|
|
|
req := client.R()
|
|
req.Header.Add("User-Agent", GetUA("mobile"))
|
|
req.Header.Add("Accept", "*/*")
|
|
req.Header.Add("Host", "mooc1-api.chaoxing.com")
|
|
req.Header.Add("Connection", "keep-alive")
|
|
res, err := req.Get(urlStr)
|
|
if err != nil {
|
|
if retry > 0 {
|
|
return ApiVerifyCode(client, retry-1)
|
|
} else {
|
|
return res.String(), err
|
|
}
|
|
}
|
|
codeFileName := "code" + randChar[rand.Intn(len(randChar))] //生成验证码文件名称
|
|
for i := 0; i < 10; i++ {
|
|
codeFileName += randChar[rand.Intn(len(randChar))]
|
|
}
|
|
codeFileName += ".png"
|
|
utils.PathExistForCreate("./assets/code/") //检测是否存在路径,如果不存在则创建
|
|
filepath := fmt.Sprintf("./assets/code/%s", codeFileName)
|
|
file, err := os.Create(filepath)
|
|
if err != nil {
|
|
res.Body.Close() //立即释放
|
|
log.Println(err)
|
|
return "", err
|
|
}
|
|
|
|
_, err = io.Copy(file, res.Body)
|
|
if err != nil {
|
|
res.Body.Close() //立即释放
|
|
log.Println(err)
|
|
return "", err
|
|
}
|
|
|
|
file.Close()
|
|
if utils.IsBadImg(filepath) {
|
|
res.Body.Close() //立即释放
|
|
utils.DeleteFile(filepath) //删除坏的文件
|
|
return ApiVerifyCode(client, retry-1)
|
|
}
|
|
return filepath, nil
|
|
}
|
|
|
|
func ApiPassVerifyCode(client *resty.Client, code string, retry int) bool {
|
|
if retry < 0 {
|
|
return false
|
|
}
|
|
urlStr := "https://mooc1-api.chaoxing.com/html/processVerify.ac"
|
|
client.SetRedirectPolicy(resty.NoRedirectPolicy())
|
|
req := client.R()
|
|
req.SetMultipartField("ucode", "", "", strings.NewReader(code))
|
|
req.SetMultipartField("app", "", "", strings.NewReader("0"))
|
|
req.Header.Add("User-Agent", GetUA("mobile"))
|
|
req.Header.Add("Accept", "*/*")
|
|
req.Header.Add("Host", "mooc1-api.chaoxing.com")
|
|
req.Header.Add("Connection", "keep-alive")
|
|
res, err := req.Post(urlStr)
|
|
if err != nil {
|
|
return ApiPassVerifyCode(client, code, retry-1)
|
|
}
|
|
client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20))
|
|
return res.StatusCode() == 302
|
|
}
|