-
Notifications
You must be signed in to change notification settings - Fork 14
/
poeditor.go
124 lines (99 loc) · 2.2 KB
/
poeditor.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
package localize
import (
"encoding/json"
"log"
"net/http"
"net/url"
"strings"
)
type PoeditorSource struct {
apiKey string
projectID string
language string
}
type termListResponse struct {
Response struct {
Status string
Code string
Message string
}
Result struct {
Terms []struct {
Term string
Translation struct {
Content string
}
}
}
}
func (l *PoeditorSource) Pull() (pairs map[string]string, err error) {
termList := termListResponse{}
params := url.Values{}
params.Add("api_token", l.apiKey)
params.Add("id", l.projectID)
params.Add("language", l.language)
body := strings.NewReader(params.Encode())
req, err := http.NewRequest("POST", "https://api.poeditor.com/v2/terms/list", body)
if err != nil {
log.Fatal(err)
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
return
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&termList)
if err != nil {
log.Fatal(err)
return
}
if pairs == nil {
pairs = make(map[string]string)
}
for _, term := range termList.Result.Terms {
pairs[term.Term] = term.Translation.Content
}
return
}
func (l *PoeditorSource) Push(terms []string) (err error) {
termsModel := []map[string]string{}
for _, k := range terms {
termsModel = append(termsModel, map[string]string{
"term": k,
})
}
b, err := json.Marshal(termsModel)
if err != nil {
log.Fatal(err)
return
}
params := url.Values{}
params.Add("api_token", l.apiKey)
params.Add("id", l.projectID)
params.Add("language", l.language)
params.Add("data", string(b))
body := strings.NewReader(params.Encode())
req, err := http.NewRequest("POST", "https://api.poeditor.com/v2/projects/sync", body)
if err != nil {
log.Fatal(err)
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
return
}
defer resp.Body.Close()
return
}
func NewPoeditorSource(apiKey string, projectID string, language string) *PoeditorSource {
return &PoeditorSource{
apiKey: apiKey,
projectID: projectID,
language: language,
}
}