-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathclient.go
346 lines (316 loc) · 13.7 KB
/
client.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Copyright 2013 Matthew Baird
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tableau4go
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
const content_type_header = "Content-Type"
const content_length_header = "Content-Length"
const auth_header = "X-Tableau-Auth"
const application_xml_content_type = "application/xml"
const POST = "POST"
const GET = "GET"
const DELETE = "DELETE"
var ErrDoesNotExist = errors.New("Does Not Exist")
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Sign_In%3FTocPath%3DAPI%2520Reference%7C_____51
func (api *API) Signin(username, password string, contentUrl string, userIdToImpersonate string) error {
url := fmt.Sprintf("%s/api/%s/auth/signin", api.Server, api.Version)
credentials := Credentials{Name: username, Password: password}
if len(userIdToImpersonate) > 0 {
credentials.Impersonate = &User{ID: userIdToImpersonate}
}
siteName := contentUrl
// this seems to have changed. If you are looking for the default site, you must pass
// blank
if api.OmitDefaultSiteName {
if contentUrl == api.DefaultSiteName {
siteName = ""
}
}
credentials.Site = &Site{ContentUrl: siteName}
request := SigninRequest{Request: credentials}
signInXML, err := request.XML()
if err != nil {
return err
}
payload := string(signInXML)
headers := make(map[string]string)
headers[content_type_header] = application_xml_content_type
retval := AuthResponse{}
err = api.makeRequest(url, POST, []byte(payload), &retval, headers, connectTimeOut, readWriteTimeout)
if err == nil {
api.AuthToken = retval.Credentials.Token
}
return err
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Sign_Out%3FTocPath%3DAPI%2520Reference%7C_____52
func (api *API) Signout() error {
url := fmt.Sprintf("%s/api/%s/auth/signout", api.Server, api.Version)
headers := make(map[string]string)
headers[content_type_header] = application_xml_content_type
err := api.makeRequest(url, POST, nil, nil, headers, connectTimeOut, readWriteTimeout)
return err
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Server_Info%3FTocPath%3DAPI%2520Reference%7C__
func (api *API) ServerInfo() (ServerInfo, error) {
// this call only works on apiVersion 2.4 and up
url := fmt.Sprintf("%s/api/%s/serverinfo", api.Server, "2.4")
headers := make(map[string]string)
retval := ServerInfoResponse{}
err := api.makeRequest(url, GET, nil, &retval, headers, connectTimeOut, readWriteTimeout)
return retval.ServerInfo, err
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Query_Sites%3FTocPath%3DAPI%2520Reference%7C_____40
func (api *API) QuerySites() ([]Site, error) {
url := fmt.Sprintf("%s/api/%s/sites/", api.Server, api.Version)
headers := make(map[string]string)
retval := QuerySitesResponse{}
err := api.makeRequest(url, GET, nil, &retval, headers, connectTimeOut, readWriteTimeout)
return retval.Sites.Sites, err
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Query_Sites%3FTocPath%3DAPI%2520Reference%7C_____40
func (api *API) QuerySite(siteID string, includeStorage bool) (Site, error) {
url := fmt.Sprintf("%s/api/%s/sites/%s", api.Server, api.Version, siteID)
if includeStorage {
url += fmt.Sprintf("?includeStorage=%v", includeStorage)
}
return api.querySite(url)
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Query_Sites%3FTocPath%3DAPI%2520Reference%7C_____40
func (api *API) QuerySiteByName(name string, includeStorage bool) (Site, error) {
return api.querySiteByKey("name", name, includeStorage)
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Query_Sites%3FTocPath%3DAPI%2520Reference%7C_____40
func (api *API) QuerySiteByContentUrl(contentUrl string, includeStorage bool) (Site, error) {
return api.querySiteByKey("contentUrl", contentUrl, includeStorage)
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Query_Sites%3FTocPath%3DAPI%2520Reference%7C_____40
func (api *API) querySiteByKey(key, value string, includeStorage bool) (Site, error) {
url := fmt.Sprintf("%s/api/%s/sites/%s?key=%s", api.Server, api.Version, value, key)
if includeStorage {
url += fmt.Sprintf("&includeStorage=%v", includeStorage)
}
return api.querySite(url)
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Query_Sites%3FTocPath%3DAPI%2520Reference%7C_____40
func (api *API) querySite(url string) (Site, error) {
headers := make(map[string]string)
retval := QuerySiteResponse{}
err := api.makeRequest(url, GET, nil, &retval, headers, connectTimeOut, readWriteTimeout)
return retval.Site, err
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Query_User_On_Site%3FTocPath%3DAPI%2520Reference%7C_____47
func (api *API) QueryUserOnSite(siteId, userId string) (User, error) {
url := fmt.Sprintf("%s/api/%s/sites/%s/users/%s", api.Server, api.Version, siteId, userId)
headers := make(map[string]string)
retval := QueryUserOnSiteResponse{}
err := api.makeRequest(url, GET, nil, &retval, headers, connectTimeOut, readWriteTimeout)
return retval.User, err
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Query_Projects%3FTocPath%3DAPI%2520Reference%7C_____38
func (api *API) QueryProjects(siteId string) ([]Project, error) {
url := fmt.Sprintf("%s/api/%s/sites/%s/projects", api.Server, api.Version, siteId)
headers := make(map[string]string)
retval := QueryProjectsResponse{}
err := api.makeRequest(url, GET, nil, &retval, headers, connectTimeOut, readWriteTimeout)
return retval.Projects.Projects, err
}
func (api *API) GetProjectByName(siteId, name string) (Project, error) {
projects, err := api.QueryProjects(siteId)
if err != nil {
return Project{}, err
}
for _, project := range projects {
if project.Name == name {
return project, nil
}
}
return Project{}, fmt.Errorf("Project Named '%s' Not Found", name)
}
func (api *API) GetProjectByID(siteId, ID string) (Project, error) {
projects, err := api.QueryProjects(siteId)
if err != nil {
return Project{}, err
}
for _, project := range projects {
if project.ID == ID {
return project, nil
}
}
return Project{}, fmt.Errorf("Project with ID '%s' Not Found", ID)
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Query_Datasources%3FTocPath%3DAPI%2520Reference%7C_____33
func (api *API) QueryDatasources(siteId string) ([]Datasource, error) {
url := fmt.Sprintf("%s/api/%s/sites/%s/datasources", api.Server, api.Version, siteId)
headers := make(map[string]string)
retval := QueryDatasourcesResponse{}
err := api.makeRequest(url, GET, nil, &retval, headers, connectTimeOut, readWriteTimeout)
return retval.Datasources.Datasources, err
}
func (api *API) GetSiteID(siteName string) (string, error) {
site, err := api.QuerySiteByName(siteName, false)
if err != nil {
return "", err
}
return site.ID, err
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Create_Project%3FTocPath%3DAPI%2520Reference%7C_____14
//POST /api/api-version/sites/site-id/projects
func (api *API) CreateProject(siteId string, project Project) (*Project, error) {
url := fmt.Sprintf("%s/api/%s/sites/%s/projects", api.Server, api.Version, siteId)
createProjectRequest := CreateProjectRequest{Request: project}
xmlRep, err := createProjectRequest.XML()
if err != nil {
return nil, err
}
headers := make(map[string]string)
headers[content_type_header] = application_xml_content_type
createProjectResponse := CreateProjectResponse{}
err = api.makeRequest(url, POST, xmlRep, &createProjectResponse, headers, connectTimeOut, readWriteTimeout)
return &createProjectResponse.Project, err
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Publish_Datasource%3FTocPath%3DAPI%2520Reference%7C_____31
func (api *API) PublishTDS(siteId string, tdsMetadata Datasource, fullTds string, overwrite bool) (retval *Datasource, err error) {
return api.publishDatasource(siteId, tdsMetadata, fullTds, "tds", overwrite)
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Publish_Datasource%3FTocPath%3DAPI%2520Reference%7C_____31
func (api *API) publishDatasource(siteId string, tdsMetadata Datasource, datasource string, datasourceType string, overwrite bool) (retval *Datasource, err error) {
url := fmt.Sprintf("%s/api/%s/sites/%s/datasources?datasourceType=%s&overwrite=%v", api.Server, api.Version, siteId, datasourceType, overwrite)
payload := fmt.Sprintf("--%s\r\n", api.Boundary)
payload += "Content-Disposition: name=\"request_payload\"\r\n"
payload += "Content-Type: text/xml\r\n"
payload += "\r\n"
tdsRequest := DatasourceCreateRequest{Request: tdsMetadata}
xmlRepresentation, err := tdsRequest.XML()
if err != nil {
return retval, err
}
payload += string(xmlRepresentation)
payload += fmt.Sprintf("\r\n--%s\r\n", api.Boundary)
payload += fmt.Sprintf("Content-Disposition: name=\"tableau_datasource\"; filename=\"%s.tds\"\r\n", tdsMetadata.Name)
payload += "Content-Type: application/octet-stream\r\n"
payload += "\r\n"
payload += datasource
payload += fmt.Sprintf("\r\n--%s--\r\n", api.Boundary)
headers := make(map[string]string)
headers[content_type_header] = fmt.Sprintf("multipart/mixed; boundary=%s", api.Boundary)
err = api.makeRequest(url, POST, []byte(payload), retval, headers, connectTimeOut, readWriteTimeout)
return retval, err
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Delete_Datasource%3FTocPath%3DAPI%2520Reference%7C_____15
func (api *API) DeleteDatasource(siteId string, datasourceId string) error {
url := fmt.Sprintf("%s/api/%s/sites/%s/datasources/%s", api.Server, api.Version, siteId, datasourceId)
return api.delete(url)
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Delete_Project%3FTocPath%3DAPI%2520Reference%7C_____17
func (api *API) DeleteProject(siteId string, projectId string) error {
url := fmt.Sprintf("%s/api/%s/sites/%s/projects/%s", api.Server, api.Version, siteId, projectId)
return api.delete(url)
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Delete_Project%3FTocPath%3DAPI%2520Reference%7C_____17
func (api *API) DeleteSite(siteId string) error {
url := fmt.Sprintf("%s/api/%s/sites/%s", api.Server, api.Version, siteId)
return api.delete(url)
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Delete_Site%3FTocPath%3DAPI%2520Reference%7C_____19
func (api *API) DeleteSiteByName(name string) error {
return api.deleteSiteByKey("name", name)
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Delete_Site%3FTocPath%3DAPI%2520Reference%7C_____19
func (api *API) DeleteSiteByContentUrl(contentUrl string) error {
return api.deleteSiteByKey("contentUrl", contentUrl)
}
//http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Delete_Site%3FTocPath%3DAPI%2520Reference%7C_____19
func (api *API) deleteSiteByKey(key string, value string) error {
url := fmt.Sprintf("%s/api/%s/sites/%s?key=%s", api.Server, api.Version, value, key)
return api.delete(url)
}
func (api *API) delete(url string) error {
headers := make(map[string]string)
return api.makeRequest(url, DELETE, nil, nil, headers, connectTimeOut, readWriteTimeout)
}
func (api *API) makeRequest(requestUrl string, method string, payload []byte, result interface{}, headers map[string]string,
cTimeout time.Duration, rwTimeout time.Duration) error {
var debug = false
if debug {
fmt.Printf("%s:%v\n", method, requestUrl)
if payload != nil {
fmt.Printf("%v\n", string(payload))
}
}
client := DefaultTimeoutClient()
var req *http.Request
if len(payload) > 0 {
var httpErr error
req, httpErr = http.NewRequest(strings.TrimSpace(method), strings.TrimSpace(requestUrl), bytes.NewBuffer(payload))
if httpErr != nil {
return httpErr
}
req.Header.Add(content_length_header, strconv.Itoa(len(payload)))
} else {
var httpErr error
req, httpErr = http.NewRequest(strings.TrimSpace(method), strings.TrimSpace(requestUrl), nil)
if httpErr != nil {
return httpErr
}
}
if headers != nil {
for header, headerValue := range headers {
req.Header.Add(header, headerValue)
}
}
if len(api.AuthToken) > 0 {
if debug {
fmt.Printf("%s:%s\n", auth_header, api.AuthToken)
}
req.Header.Add(auth_header, api.AuthToken)
}
var httpErr error
resp, httpErr := client.Do(req)
if httpErr != nil {
return httpErr
}
defer resp.Body.Close()
body, readBodyError := ioutil.ReadAll(resp.Body)
if debug {
fmt.Printf("t4g Response:%v\n", string(body))
}
if readBodyError != nil {
return readBodyError
}
if resp.StatusCode == 404 {
return ErrDoesNotExist
}
if resp.StatusCode >= 300 {
tErrorResponse := ErrorResponse{}
err := xml.Unmarshal(body, &tErrorResponse)
if err != nil {
return err
}
return tErrorResponse.Error
}
if result != nil {
// else unmarshall to the result type specified by caller
err := xml.Unmarshal(body, &result)
if err != nil {
return err
}
}
return nil
}