-
Notifications
You must be signed in to change notification settings - Fork 56
/
apiv2.go
127 lines (101 loc) · 2.22 KB
/
apiv2.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
package gtranslate
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"time"
"golang.org/x/text/language"
"github.com/robertkrimen/otto"
)
var ttk otto.Value
func init() {
ttk, _ = otto.ToValue("0")
}
const (
defaultNumberOfRetries = 2
)
func translate(text, from, to string, withVerification bool, tries int, delay time.Duration) (string, error) {
if tries == 0 {
tries = defaultNumberOfRetries
}
if withVerification {
if _, err := language.Parse(from); err != nil && from != "auto" {
log.Println("[WARNING], '" + from + "' is a invalid language, switching to 'auto'")
from = "auto"
}
if _, err := language.Parse(to); err != nil {
log.Println("[WARNING], '" + to + "' is a invalid language, switching to 'en'")
to = "en"
}
}
t, _ := otto.ToValue(text)
urll := fmt.Sprintf("https://translate.%s/translate_a/single", GoogleHost)
token := get(t, ttk)
data := map[string]string{
"client": "gtx",
"sl": from,
"tl": to,
"hl": to,
// "dt": []string{"at", "bd", "ex", "ld", "md", "qca", "rw", "rm", "ss", "t"},
"ie": "UTF-8",
"oe": "UTF-8",
"otf": "1",
"ssel": "0",
"tsel": "0",
"kc": "7",
"q": text,
}
u, err := url.Parse(urll)
if err != nil {
return "", nil
}
parameters := url.Values{}
for k, v := range data {
parameters.Add(k, v)
}
for _, v := range []string{"at", "bd", "ex", "ld", "md", "qca", "rw", "rm", "ss", "t"} {
parameters.Add("dt", v)
}
parameters.Add("tk", token)
u.RawQuery = parameters.Encode()
var r *http.Response
for tries > 0 {
r, err = http.Get(u.String())
if err != nil {
if err == http.ErrHandlerTimeout {
return "", errBadNetwork
}
return "", err
}
if r.StatusCode == http.StatusOK {
break
}
if r.StatusCode == http.StatusForbidden {
tries--
time.Sleep(delay)
}
}
raw, err := ioutil.ReadAll(r.Body)
if err != nil {
return "", err
}
var resp []interface{}
err = json.Unmarshal([]byte(raw), &resp)
if err != nil {
return "", err
}
responseText := ""
for _, obj := range resp[0].([]interface{}) {
if len(obj.([]interface{})) == 0 {
break
}
t, ok := obj.([]interface{})[0].(string)
if ok {
responseText += t
}
}
return responseText, nil
}