-
Notifications
You must be signed in to change notification settings - Fork 5
/
bing.go
103 lines (86 loc) · 2.59 KB
/
bing.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
package fy
import (
"context"
"fmt"
"net/http"
"net/url"
"regexp"
"strings"
"github.com/tidwall/gjson"
)
type bingTranslator struct{}
var bing translator = new(bingTranslator)
func (b *bingTranslator) Desc() (string, string) {
return "bing", "https://cn.bing.com/translator"
}
func BingTranslate(ctx context.Context, req Request) *Response {
return bing.translate(ctx, req)
}
func (b *bingTranslator) translate(ctx context.Context, req Request) (resp *Response) {
resp = newResp(b)
r, data, err := sendRequest(ctx, http.MethodGet, "https://www.bing.com/translator", nil, nil)
if err != nil {
resp.Err = fmt.Errorf("readResp error: %v", err)
return
}
timestamp, token, err := b.getTimestampAndToken(string(data))
if err != nil {
resp.Err = err
return
}
igValue, err := b.getIGValue(string(data))
if err != nil {
resp.Err = err
return
}
req.ToLang = b.convertLanguage(req.ToLang)
param := url.Values{
"fromLang": {"auto-detect"},
"to": {req.ToLang},
"text": {req.Text},
"key": {timestamp},
"token": {token},
}
urlStr := fmt.Sprintf("https://www.bing.com/ttranslatev3?isVertical=1&IG=%s&IID=translator.5023.1", igValue)
body := strings.NewReader(param.Encode())
_, data, err = sendRequest(ctx, "POST", urlStr, body, func(req *http.Request) error {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", UserAgent)
addCookies(req, r.Cookies())
return nil
})
if err != nil {
resp.Err = fmt.Errorf("sendRequest error: %v", err)
return
}
jr := gjson.Parse(string(data))
resp.Result = jr.Get("0.translations.0.text").String()
if resp.Result == "" {
resp.Err = fmt.Errorf(string(data))
}
return
}
func (b *bingTranslator) convertLanguage(language string) string {
l := language
switch language {
case Chinese:
l = "zh-Hans"
}
return l
}
func (*bingTranslator) getTimestampAndToken(dataStr string) (string, string, error) {
// dataStr := `var params_RichTranslateHelper = [1623165977131,"Q5b9PD_0XEdOagXBcPVtlnB6ZML4958D",3600000,true];`
result := regexp.MustCompile(`var params_RichTranslateHelper = \[(?P<result>[\s\S]+),"(?P<result1>[\s\S]+)",3600000,`).FindStringSubmatch(dataStr)
if len(result) != 3 {
return "", "", fmt.Errorf("cannot get timestamp and token")
}
return result[1], result[2], nil
}
func (*bingTranslator) getIGValue(dataStr string) (string, error) {
// IG:"678CAA0BB18740F3A5D3EF29A6D434B0"
igResult := regexp.MustCompile(`IG:"(?P<token>\S+)",`).FindStringSubmatch(dataStr)
if len(igResult) != 2 {
return "", fmt.Errorf("cannot get ig value")
}
return igResult[1], nil
}