forked from SebastianCzoch/onesky-go
/
onesky.go
284 lines (232 loc) · 6.63 KB
/
onesky.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Package onesky is go utils for working with OneSky translation service
// Copyright (c) 2015 Sebastian Czoch <sebastian@czoch.eu>. All rights reserved.
// Use of this source code is governed by a GNU v2 license found in the LICENSE file.
package onesky
import (
"bytes"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"os"
"strconv"
"time"
)
// APIAddress is https address to OneSky API
const APIAddress = "https://platform.api.onesky.io"
// API Version is OneSky API version which will be used
const APIVersion = "1"
// Client is basics struct for this package contains Secret, APIKey and ProjectID which is needed to authorize in OneSky service
type Client struct {
Secret string
APIKey string
ProjectID int
}
type apiEndpoint struct {
path string
method string
}
var apiEndpoints = map[string]apiEndpoint{
"getFile": apiEndpoint{"projects/%d/translations", "GET"},
"getMultilanguageFile": apiEndpoint{"projects/%d/translations/multilingual", "GET"},
"postFile": apiEndpoint{"projects/%d/files", "POST"},
"deleteFile": apiEndpoint{"projects/%d/files", "DELETE"},
"listFiles": apiEndpoint{"projects/%d/files", "GET"},
"getImportTasks": apiEndpoint{"projects/%d/import-tasks", "GET"},
}
// FileData is a struct which contains informations about file uploaded to OneSky service
type FileData struct {
Name string `json:"name"`
StringCount int `json:"string_count"`
LastImport LastImport `json:"last_import"`
UpoladedAt string `json:"uploaded_at"`
UpoladedAtTimestamp int `json:"uploaded_at_timestamp"`
}
// LastImport is a struct which contains informations about last upload
type LastImport struct {
ID int `json:"id"`
Status string `json:"status"`
}
type listFilesResponse struct {
Data []FileData `json:"data"`
}
// ListFiles is method on Client struct which download form OneSky service informations about uploaded files
func (c *Client) ListFiles(page, perPage int) ([]FileData, error) {
endpoint, err := getEndpoint("listFiles")
if err != nil {
return nil, err
}
v := url.Values{}
v.Set("page", strconv.Itoa(page))
v.Set("per_page", strconv.Itoa(perPage))
urlStr, err := endpoint.full(c, v)
if err != nil {
return nil, err
}
res, err := makeRequest(endpoint.method, urlStr, nil, "")
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("bad status: %s", res.Status)
}
body, err := getResponseBodyAsString(res)
if err != nil {
return nil, err
}
aux := listFilesResponse{}
err = json.Unmarshal([]byte(body), &aux)
if err != nil {
return nil, err
}
return aux.Data, nil
}
// DownloadFile is method on Client struct which download form OneSky service choosen file as string
func (c *Client) DownloadFile(fileName, locale string) (string, error) {
var endpointId string
v := url.Values{}
if locale != "" {
endpointId = "getFile"
v.Set("locale", locale)
} else {
// Download ALL translations in a single json file
endpointId = "getMultilanguageFile"
v.Set("file_format", "I18NEXT_MULTILINGUAL_JSON")
}
endpoint, err := getEndpoint(endpointId)
if err != nil {
return "", err
}
v.Set("source_file_name", fileName)
urlStr, err := endpoint.full(c, v)
if err != nil {
return "", err
}
res, err := makeRequest(endpoint.method, urlStr, nil, "")
if err != nil {
return "", err
}
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("bad status: %s", res.Status)
}
body, err := getResponseBodyAsString(res)
if err != nil {
return "", err
}
return body, nil
}
// UploadFile is method on Client struct which upload file to OneSky service
func (c *Client) UploadFile(file, fileFormat, locale string) (string, error) {
endpoint, err := getEndpoint("postFile")
if err != nil {
return "", err
}
v := url.Values{}
v.Set("locale", locale)
v.Set("file_format", fileFormat)
// Deprecate strings that are not included in uploaded file
v.Set("is_keeping_all_strings", "false")
urlStr, err := endpoint.full(c, v)
if err != nil {
return "", err
}
var b bytes.Buffer
w := multipart.NewWriter(&b)
f, err := os.Open(file)
if err != nil {
return "", err
}
defer w.Close()
fw, err := w.CreateFormFile("file", file)
if err != nil {
return "", err
}
if _, err = io.Copy(fw, f); err != nil {
return "", err
}
w.Close()
res, err := makeRequest(endpoint.method, urlStr, &b, w.FormDataContentType())
if err != nil {
return "", err
}
if res.StatusCode != http.StatusCreated {
return "", fmt.Errorf("bad status: %s", res.Status)
}
body, err := getResponseBodyAsString(res)
if err != nil {
return "", err
}
return body, nil
}
// DeleteFile is method on Client struct which remove file from OneSky service
func (c *Client) DeleteFile(fileName string) error {
endpoint, err := getEndpoint("deleteFile")
if err != nil {
return err
}
v := url.Values{}
v.Set("file_name", fileName)
urlStr, err := endpoint.full(c, v)
if err != nil {
return err
}
res, err := makeRequest(endpoint.method, urlStr, nil, "")
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", res.Status)
}
return nil
}
func makeRequest(method, urlStr string, body io.Reader, contentType string) (*http.Response, error) {
req, err := http.NewRequest(method, urlStr, body)
if err != nil {
return nil, err
}
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
func getResponseBodyAsString(response *http.Response) (string, error) {
res, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", err
}
return string(res), nil
}
func (c *Client) getAuthHashAndTime() (string, string) {
hasher := md5.New()
time := strconv.Itoa(int(time.Now().Unix()))
hasher.Write([]byte(time + c.Secret))
return hex.EncodeToString(hasher.Sum(nil)), time
}
func (e *apiEndpoint) full(c *Client, additionalArgs url.Values) (string, error) {
urlWithProjectID := fmt.Sprintf(e.path, c.ProjectID)
address, err := url.Parse(APIAddress + "/" + APIVersion + "/" + urlWithProjectID)
if err != nil {
return "", err
}
hash, timestamp := c.getAuthHashAndTime()
additionalArgs.Set("api_key", c.APIKey)
additionalArgs.Set("timestamp", timestamp)
additionalArgs.Set("dev_hash", hash)
return address.String() + "?" + additionalArgs.Encode(), nil
}
func getEndpoint(name string) (apiEndpoint, error) {
endpoint, ok := apiEndpoints[name]
if !ok {
return apiEndpoint{}, fmt.Errorf("endpoint %s not found", name)
}
return endpoint, nil
}