-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrestapi.go
More file actions
296 lines (240 loc) · 6.39 KB
/
Copy pathrestapi.go
File metadata and controls
296 lines (240 loc) · 6.39 KB
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
//Heavily inspired/derived from discordgo https://github.com/bwmarrin/discordgo
package gobeam
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// ErrJSONUnmarshal is returned for JSON Unmarshall errors.
var ErrJSONUnmarshal = errors.New("json unmarshal")
// Request makes a (GET/POST/...) Requests to Beam REST API with JSON data.
// All the other Beam REST Calls in this file use this function.
func (s *Session) Request(method, urlStr string, data interface{}) (response []byte, err error) {
if s.Debug {
fmt.Println("API REQUEST PAYLOAD :: [" + fmt.Sprintf("%+v", data) + "]")
}
var body []byte
if data != nil {
body, err = json.Marshal(data)
if err != nil {
return
}
}
return s.request(method, urlStr, "application/json", body)
}
// request makes a (GET/POST/...) Requests to Beam REST API.
func (s *Session) request(method, urlStr, contentType string, b []byte) (response []byte, err error) {
if s.Debug {
fmt.Printf("API REQUEST %8s :: %s\n", method, urlStr)
}
req, err := http.NewRequest(method, urlStr, bytes.NewBuffer(b))
if err != nil {
return
}
if s.UseCookies {
for _, c := range s.Cookies {
if c.Name != "sid" {
continue
}
req.Header.Add("Cookie", fmt.Sprintf("%s=%s", c.Name, c.Value))
}
} else {
req.Header.Set("X-CSRF-Token", s.CsrfToken)
}
// Not used on initial login..
if s.Token != "" {
req.Header.Set("authorization", s.Token)
}
req.Header.Set("Content-Type", contentType)
// TODO: Make a configurable static variable.
req.Header.Set("User-Agent", fmt.Sprintf("GoBeamBot (https://github.com/xackery/gobeam, v%s)", VERSION))
if s.Debug {
for k, v := range req.Header {
fmt.Printf("API REQUEST HEADER :: [%s] = %+v\n", k, v)
}
}
client := &http.Client{Timeout: (20 * time.Second)}
resp, err := client.Do(req)
if err != nil {
return
}
defer func() {
err := resp.Body.Close()
if err != nil {
fmt.Println("error closing resp body")
}
}()
response, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if s.UseCookies {
s.Cookies = resp.Cookies()
} else {
s.CsrfToken = resp.Header.Get("X-CSRF-Token")
}
if s.Debug {
fmt.Printf("API RESPONSE STATUS :: %s\n", resp.Status)
for k, v := range resp.Header {
fmt.Printf("API RESPONSE HEADER :: [%s] = %+v\n", k, v)
}
fmt.Printf("API RESPONSE BODY :: [%s]\n", response)
}
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
switch resp.StatusCode {
case 200: // OK
case 204: // No Content
// TODO check for 401 response, invalidate token if we get one.
case 429: // TOO MANY REQUESTS - Rate limiting
//err = fmt.Errorf("Request unmarshal rate limit error : %+v", err)
default: // Error condition
err = fmt.Errorf("HTTP %s, %s", resp.Status, response)
}
return
}
func unmarshal(data []byte, v interface{}) error {
err := json.Unmarshal(data, v)
if err != nil {
return ErrJSONUnmarshal
}
return nil
}
// ------------------------------------------------------------------------------------------------
// Functions specific to Beam Sessions
// ------------------------------------------------------------------------------------------------
// Login asks the Beam server for an authentication token.
func (s *Session) Login() (err error) {
if s.config == nil {
s.config = &GoBeamConfig{}
err = s.config.Load("gobeam.json")
if err != nil {
err = fmt.Errorf("Failed to load gobeam.json config: %s", err.Error())
return
}
}
data := struct {
Username string `json:"username"`
Password string `json:"password"`
}{s.config.Username, s.config.Password}
response, err := s.Request("POST", LOGIN, data)
if err != nil {
return
}
temp := &LoginPayload{}
err = unmarshal(response, &temp)
if err != nil {
return
}
s.LoginPayload = temp
return
}
// ------------------------------------------------------------------------------------------------
// Functions specific to Beam Websockets
// ------------------------------------------------------------------------------------------------
// Gateway returns the a websocket Gateway address
func (s *Session) Gateway() (gateway string, err error) {
response, err := s.Request("GET", fmt.Sprintf("%s%d", GATEWAY, s.LoginPayload.Channel.ID), nil)
if err != nil {
return
}
temp := struct {
Endpoints []string `json:"endpoints,omitempty"`
Authkey string `json:"authkey"`
}{}
err = unmarshal(response, &temp)
if err != nil {
return
}
if len(temp.Endpoints) > 0 {
gateway = temp.Endpoints[0]
}
//if len(temp.Authkey) < 1 {
// err = fmt.Errorf("No authkey provided")
// return
//}
s.authKey = temp.Authkey
return
}
// Gateway returns the a websocket Gateway address
func (s *Session) TetrisGateway() (gateway string, err error) {
if s.LoginPayload == nil {
err = fmt.Errorf("No login payload set")
return
}
response, err := s.Request("GET", fmt.Sprintf("%s%d/robot", TETRIS, s.LoginPayload.Channel.ID), nil)
if err != nil {
return
}
temp := struct {
Address string `json:"address,omitempty"`
Key string `json:"key,omitempty"`
}{}
err = unmarshal(response, &temp)
if err != nil {
return
}
if len(temp.Key) < 1 {
err = fmt.Errorf("No authkey provided")
return
}
gateway = temp.Address
s.authKey = temp.Key
return
}
//Return channel details
func (s *Session) Channels(id uint32) (channel *Channel, err error) {
if s.LoginPayload == nil {
err = fmt.Errorf("Not logged in")
return
}
if id == 0 {
id = s.LoginPayload.Channel.ID
}
response, err := s.Request("GET", fmt.Sprintf("%s%d", CHANNELS, id), nil)
if err != nil {
return
}
err = unmarshal(response, &channel)
if err != nil {
return
}
return
}
//Return tetris details
func (s *Session) TetrisGamesPublic(id uint32) (versions *VersionsResponse, err error) {
if id == 0 && s.LoginPayload != nil {
id = s.LoginPayload.Channel.ID
}
if id < 1 {
err = fmt.Errorf("Version ID not found")
return
}
response, err := s.Request("GET", fmt.Sprintf("%s%s%d", TETRIS_GAMES, "versions/", id), nil)
if err != nil {
return
}
err = unmarshal(response, &versions)
if err != nil {
return
}
return
}
func (s *Session) TetrisGamesOwned() (versions *VersionsResponse, err error) {
if s.LoginPayload == nil {
err = fmt.Errorf("Not logged in")
return
}
response, err := s.Request("GET", fmt.Sprintf("%s%s", TETRIS_GAMES, "owned"), nil)
if err != nil {
return
}
err = unmarshal(response, &versions)
if err != nil {
return
}
return
}