forked from kurrik/twittergo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.go
497 lines (423 loc) · 10.7 KB
/
models.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// Copyright 2011 Arne Roomann-Kurrik
//
// 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 twittergo
import (
"compress/gzip"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const (
H_LIMIT = "X-Rate-Limit-Limit"
H_LIMIT_REMAIN = "X-Rate-Limit-Remaining"
H_LIMIT_RESET = "X-Rate-Limit-Reset"
H_MEDIA_LIMIT = "X-MediaRateLimit-Limit"
H_MEDIA_LIMIT_REMAIN = "X-MediaRateLimit-Remaining"
H_MEDIA_LIMIT_RESET = "X-MediaRateLimit-Reset"
)
const (
STATUS_OK = 200
STATUS_CREATED = 201
STATUS_ACCEPTED = 202
STATUS_NO_CONTENT = 204
STATUS_INVALID = 400
STATUS_UNAUTHORIZED = 401
STATUS_FORBIDDEN = 403
STATUS_NOTFOUND = 404
STATUS_LIMIT = 429
STATUS_GATEWAY = 502
)
// Error returned if there was an issue parsing the response body.
type ResponseError struct {
Body string
Code int
}
func NewResponseError(code int, body string) ResponseError {
return ResponseError{Code: code, Body: body}
}
func (e ResponseError) Error() string {
return fmt.Sprintf(
"Unable to handle response (status code %d): `%v`",
e.Code,
e.Body)
}
type Error map[string]interface{}
func (e Error) Code() int64 {
return int64(e["code"].(float64))
}
func (e Error) Message() string {
return e["message"].(string)
}
func (e Error) Error() string {
msg := "Error %v: %v"
return fmt.Sprintf(msg, e.Code(), e.Message())
}
type Errors map[string]interface{}
func (e Errors) Error() string {
var (
msg string = ""
err Error
ok bool
)
if e["errors"] == nil {
return msg
}
for _, val := range e["errors"].([]interface{}) {
if err, ok = val.(map[string]interface{}); ok {
msg += err.Error() + ". "
}
}
return msg
}
func (e Errors) String() string {
return e.Error()
}
func (e Errors) Errors() []Error {
var errs = e["errors"].([]interface{})
var out = make([]Error, len(errs))
for i, val := range errs {
out[i] = Error(val.(map[string]interface{}))
}
return out
}
// RateLimitResponse is implemented by both RateLimitError and APIResponse.
type RateLimitResponse interface {
// HasRateLimit returns false if the ratelimiting information is
// optional and missing.
HasRateLimit() bool
// RateLimit returns the requests per time period capacity of the
// limit.
RateLimit() uint32
// RateLimitRemaining returns how many requests are still available
// in the current time period.
RateLimitRemaining() uint32
// RateLimitReset returns when the rate limit will reset.
RateLimitReset() time.Time
}
// RateLimitError is returned from SendRequest when a rate limit is encountered.
type RateLimitError struct {
Limit uint32
Remaining uint32
Reset time.Time
}
func (e RateLimitError) Error() string {
msg := "Rate limit: %v, Remaining: %v, Reset: %v"
return fmt.Sprintf(msg, e.Limit, e.Remaining, e.Reset)
}
func (e RateLimitError) HasRateLimit() bool {
return true
}
func (e RateLimitError) RateLimit() uint32 {
return e.Limit
}
func (e RateLimitError) RateLimitRemaining() uint32 {
return e.Remaining
}
func (e RateLimitError) RateLimitReset() time.Time {
return e.Reset
}
// APIResponse provides methods for retrieving information from the HTTP
// headers in a Twitter API response.
type APIResponse http.Response
func (r APIResponse) HasRateLimit() bool {
return r.Header.Get(H_LIMIT) != ""
}
func (r APIResponse) RateLimit() uint32 {
h := r.Header.Get(H_LIMIT)
i, _ := strconv.ParseUint(h, 10, 32)
return uint32(i)
}
func (r APIResponse) RateLimitRemaining() uint32 {
h := r.Header.Get(H_LIMIT_REMAIN)
i, _ := strconv.ParseUint(h, 10, 32)
return uint32(i)
}
func (r APIResponse) RateLimitReset() time.Time {
h := r.Header.Get(H_LIMIT_RESET)
i, _ := strconv.ParseUint(h, 10, 32)
t := time.Unix(int64(i), 0)
return t
}
func (r APIResponse) HasMediaRateLimit() bool {
return r.Header.Get(H_MEDIA_LIMIT) != ""
}
func (r APIResponse) MediaRateLimit() uint32 {
h := r.Header.Get(H_MEDIA_LIMIT)
i, _ := strconv.ParseUint(h, 10, 32)
return uint32(i)
}
func (r APIResponse) MediaRateLimitRemaining() uint32 {
h := r.Header.Get(H_MEDIA_LIMIT_REMAIN)
i, _ := strconv.ParseUint(h, 10, 32)
return uint32(i)
}
func (r APIResponse) MediaRateLimitReset() time.Time {
h := r.Header.Get(H_MEDIA_LIMIT_RESET)
i, _ := strconv.ParseUint(h, 10, 32)
t := time.Unix(int64(i), 0)
return t
}
func (r APIResponse) readBody() (b []byte, err error) {
var (
header string
reader io.Reader
)
defer r.Body.Close()
header = strings.ToLower(r.Header.Get("Content-Encoding"))
if header == "" || strings.Index(header, "gzip") == -1 {
reader = r.Body
} else {
if reader, err = gzip.NewReader(r.Body); err != nil {
return
}
}
b, err = ioutil.ReadAll(reader)
return
}
// ReadBody returns the body of the response as a string.
// Only one of ReadBody and Parse may be called on a given APIResponse.
func (r APIResponse) ReadBody() string {
var (
b []byte
err error
)
if b, err = r.readBody(); err != nil {
return ""
}
return string(b)
}
// Parse unmarshals a JSON encoded HTTP response into the supplied interface,
// with handling for the various kinds of errors the Twitter API can return.
//
// The returned error may be of the type Errors, RateLimitError,
// ResponseError, or an error returned from io.Reader.Read().
func (r APIResponse) Parse(out interface{}) (err error) {
var b []byte
switch r.StatusCode {
case STATUS_UNAUTHORIZED:
fallthrough
case STATUS_NOTFOUND:
fallthrough
case STATUS_GATEWAY:
fallthrough
case STATUS_FORBIDDEN:
fallthrough
case STATUS_INVALID:
e := &Errors{}
if b, err = r.readBody(); err != nil {
return
}
if err = json.Unmarshal(b, e); err != nil {
err = NewResponseError(r.StatusCode, string(b))
} else {
err = *e
}
return
case STATUS_LIMIT:
err = RateLimitError{
Limit: r.RateLimit(),
Remaining: r.RateLimitRemaining(),
Reset: r.RateLimitReset(),
}
// consume the request body even if we don't need it
r.readBody()
return
case STATUS_NO_CONTENT:
return
case STATUS_CREATED:
fallthrough
case STATUS_ACCEPTED:
fallthrough
case STATUS_OK:
if b, err = r.readBody(); err != nil {
return
}
err = json.Unmarshal(b, out)
if err == io.EOF {
err = nil
}
default:
if b, err = r.readBody(); err != nil {
return
}
err = NewResponseError(r.StatusCode, string(b))
}
return
}
// It's a user!
type User map[string]interface{}
func (u User) Id() uint64 {
id, _ := strconv.ParseUint(u["id_str"].(string), 10, 64)
return id
}
func (u User) IdStr() string {
return u["id_str"].(string)
}
func (u User) Name() string {
return u["name"].(string)
}
func (u User) ScreenName() string {
return u["screen_name"].(string)
}
// It's a Tweet! (Adorably referred to by the API as a "status").
type Tweet map[string]interface{}
func (t Tweet) Id() (id uint64) {
var (
err error
src = t["id_str"].(string)
)
if id, err = strconv.ParseUint(src, 10, 64); err != nil {
panic(fmt.Sprintf("Could not parse ID: %v", err))
}
return
}
func (t Tweet) IdStr() string {
return t["id_str"].(string)
}
func (t Tweet) Text() string {
return t["text"].(string)
}
func (t Tweet) FullText() string {
return t["full_text"].(string)
}
func (t Tweet) User() User {
return User(t["user"].(map[string]interface{}))
}
func (t Tweet) Language() string {
return t["lang"].(string)
}
func (t Tweet) CreatedAt() (out time.Time) {
var (
err error
src = t["created_at"].(string)
)
if out, err = time.Parse(time.RubyDate, src); err != nil {
panic(fmt.Sprintf("Could not parse time: %v", err))
}
return
}
// It's a less structured list of Tweets!
type Timeline []Tweet
// It's a structured list of Tweets!
type SearchResults map[string]interface{}
func (sr SearchResults) Statuses() []Tweet {
var a []interface{} = sr["statuses"].([]interface{})
b := make([]Tweet, len(a))
for i, v := range a {
b[i] = v.(map[string]interface{})
}
return b
}
func (sr SearchResults) SearchMetadata() map[string]interface{} {
a := sr["search_metadata"].(map[string]interface{})
return a
}
func (sr SearchResults) NextQuery() (val url.Values, err error) {
var (
sm map[string]interface{}
n interface{}
next string
ok bool
)
sm = sr.SearchMetadata()
if n, ok = sm["next_results"]; !ok {
err = fmt.Errorf("Could not get next_results from search")
return
}
if next, ok = n.(string); !ok {
err = fmt.Errorf("Could not convert next_results to str: %v", n)
return
}
if next[0] == '?' {
next = next[1:]
}
val, err = url.ParseQuery(next)
return
}
// A List!
type List map[string]interface{}
func (l List) User() User {
return User(l["user"].(map[string]interface{}))
}
func (l List) Id() (id uint64) {
var (
err error
src = l["id_str"].(string)
)
if id, err = strconv.ParseUint(src, 10, 64); err != nil {
panic(fmt.Sprintf("Could not parse ID: %v", err))
}
return
}
func (l List) IdStr() string {
return l["id_str"].(string)
}
func (l List) Mode() string {
return l["mode"].(string)
}
func (l List) Name() string {
return l["name"].(string)
}
func (l List) Slug() string {
return l["slug"].(string)
}
func (l List) SubscriberCount() int64 {
return l["subscriber_count"].(int64)
}
func (l List) MemberCount() int64 {
return l["member_count"].(int64)
}
// It's a less structured list of Lists!
type Lists []List
// It's a cursored list of Lists!
type CursoredLists map[string]interface{}
func (cl CursoredLists) NextCursorStr() string {
return cl["next_cursor_str"].(string)
}
func (cl CursoredLists) PreviousCursorStr() string {
return cl["previous_cursor_str"].(string)
}
func (cl CursoredLists) Lists() Lists {
var a []interface{} = cl["lists"].([]interface{})
b := make([]List, len(a))
for i, v := range a {
b[i] = v.(map[string]interface{})
}
return b
}
// Nested response structure for video uploads.
type VideoUpload map[string]interface{}
func (v VideoUpload) Type() string {
return v["video_type"].(string)
}
// Response for media upload requests.
type MediaResponse map[string]interface{}
func (r MediaResponse) MediaId() int64 {
return r["media_id"].(int64)
}
func (r MediaResponse) Size() int64 {
return r["size"].(int64)
}
func (r MediaResponse) ExpiresAfterSecs() int32 {
return r["expires_after_secs"].(int32)
}
func (r MediaResponse) Video() VideoUpload {
return VideoUpload(r["video"].(map[string]interface{}))
}