api.py 45.9 KB
Newer Older
1
# Tweepy
2
3
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
4

Mark Smith's avatar
Mark Smith committed
5
6
from __future__ import print_function

7
8
9
import os
import mimetypes

Mark Smith's avatar
Mark Smith committed
10
11
import six

Josh Roesslein's avatar
Josh Roesslein committed
12
13
from tweepy.binder import bind_api
from tweepy.error import TweepError
14
from tweepy.parsers import ModelParser, Parser
15
from tweepy.utils import list_to_csv
16

Josh Roesslein's avatar
Josh Roesslein committed
17

18
class API(object):
Josh Roesslein's avatar
Josh Roesslein committed
19
20
    """Twitter API"""

21
    def __init__(self, auth_handler=None,
22
                 host='api.twitter.com', search_host='search.twitter.com',
Florent Espanet's avatar
Florent Espanet committed
23
24
25
26
                 upload_host='upload.twitter.com', cache=None, api_root='/1.1',
                 search_root='', upload_root='/1.1', retry_count=0,
                 retry_delay=0, retry_errors=None, timeout=60, parser=None,
                 compression=False, wait_on_rate_limit=False,
27
28
29
30
31
32
                 wait_on_rate_limit_notify=False, proxy=''):
        """ Api instance Constructor

        :param auth_handler:
        :param host:  url of the server of the rest api, default:'api.twitter.com'
        :param search_host: url of the search server, default:'search.twitter.com'
Florent Espanet's avatar
Florent Espanet committed
33
        :param upload_host: url of the upload server, default:'upload.twitter.com'
34
35
36
        :param cache: Cache to query if a GET method is used, default:None
        :param api_root: suffix of the api version, default:'/1.1'
        :param search_root: suffix of the search version, default:''
Florent Espanet's avatar
Florent Espanet committed
37
        :param upload_root: suffix of the upload version, default:'/1.1'
38
39
40
41
42
43
44
45
46
47
48
49
        :param retry_count: number of allowed retries, default:0
        :param retry_delay: delay in second between retries, default:0
        :param retry_errors: default:None
        :param timeout: delay before to consider the request as timed out in seconds, default:60
        :param parser: ModelParser instance to parse the responses, default:None
        :param compression: If the response is compressed, default:False
        :param wait_on_rate_limit: If the api wait when it hits the rate limit, default:False
        :param wait_on_rate_limit_notify: If the api print a notification when the rate limit is hit, default:False
        :param proxy: Url to use as proxy during the HTTP request, default:''

        :raise TypeError: If the given parser is not a ModelParser instance.
        """
Josh Roesslein's avatar
Josh Roesslein committed
50
        self.auth = auth_handler
Josh Roesslein's avatar
Josh Roesslein committed
51
        self.host = host
52
        self.search_host = search_host
Florent Espanet's avatar
Florent Espanet committed
53
        self.upload_host = upload_host
Josh Roesslein's avatar
Josh Roesslein committed
54
        self.api_root = api_root
55
        self.search_root = search_root
Florent Espanet's avatar
Florent Espanet committed
56
        self.upload_root = upload_root
Josh Roesslein's avatar
Josh Roesslein committed
57
        self.cache = cache
Mike's avatar
Mike committed
58
        self.compression = compression
59
60
        self.retry_count = retry_count
        self.retry_delay = retry_delay
61
        self.retry_errors = retry_errors
62
        self.timeout = timeout
63
        self.wait_on_rate_limit = wait_on_rate_limit
64
        self.wait_on_rate_limit_notify = wait_on_rate_limit_notify
65
        self.parser = parser or ModelParser()
Aaron Hill's avatar
Aaron Hill committed
66
67
68
        self.proxy = {}
        if proxy:
            self.proxy['https'] = proxy
Josh Roesslein's avatar
Josh Roesslein committed
69

70
71
72
73
74
75
        # Attempt to explain more clearly the parser argument requirements
        # https://github.com/tweepy/tweepy/issues/421
        #
        parser_type = Parser
        if not isinstance(self.parser, parser_type):
            raise TypeError(
Mark Smith's avatar
Mark Smith committed
76
77
78
79
80
                '"parser" argument has to be an instance of "{required}".'
                ' It is currently a {actual}.'.format(
                    required=parser_type.__name__,
                    actual=type(self.parser)
                )
81
            )
Josh Roesslein's avatar
Josh Roesslein committed
82

83
84
    @property
    def home_timeline(self):
85
        """ :reference: https://dev.twitter.com/rest/reference/get/statuses/home_timeline
86
87
88
89
90
91
92
93
94
95
            :allowed_param:'since_id', 'max_id', 'count'
        """
        return bind_api(
            api=self,
            path='/statuses/home_timeline.json',
            payload_type='status', payload_list=True,
            allowed_param=['since_id', 'max_id', 'count'],
            require_auth=True
        )

Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
96
97
    def statuses_lookup(self, id_, include_entities=None,
                        trim_user=None, map_=None):
98
99
100
101
102
        return self._statuses_lookup(list_to_csv(id_), include_entities,
                                     trim_user, map_)

    @property
    def _statuses_lookup(self):
103
        """ :reference: https://dev.twitter.com/rest/reference/get/statuses/lookup
104
105
106
107
108
109
110
111
112
113
114
115
            :allowed_param:'id', 'include_entities', 'trim_user', 'map'
        """
        return bind_api(
            api=self,
            path='/statuses/lookup.json',
            payload_type='status', payload_list=True,
            allowed_param=['id', 'include_entities', 'trim_user', 'map'],
            require_auth=True
        )

    @property
    def user_timeline(self):
116
        """ :reference: https://dev.twitter.com/rest/reference/get/statuses/user_timeline
117
118
119
120
121
122
123
124
125
126
127
128
            :allowed_param:'id', 'user_id', 'screen_name', 'since_id'
        """
        return bind_api(
            api=self,
            path='/statuses/user_timeline.json',
            payload_type='status', payload_list=True,
            allowed_param=['id', 'user_id', 'screen_name', 'since_id',
                           'max_id', 'count', 'include_rts']
        )

    @property
    def mentions_timeline(self):
129
        """ :reference: https://dev.twitter.com/rest/reference/get/statuses/mentions_timeline
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
            :allowed_param:'since_id', 'max_id', 'count'
        """
        return bind_api(
            api=self,
            path='/statuses/mentions_timeline.json',
            payload_type='status', payload_list=True,
            allowed_param=['since_id', 'max_id', 'count'],
            require_auth=True
        )

    @property
    def related_results(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/get/related_results/show/%3id.format
            :allowed_param:'id'
        """
        return bind_api(
            api=self,
            path='/related_results/show/{id}.json',
            payload_type='relation', payload_list=True,
            allowed_param=['id'],
            require_auth=False
        )

    @property
    def retweets_of_me(self):
155
        """ :reference: https://dev.twitter.com/rest/reference/get/statuses/retweets_of_me
156
157
158
159
160
161
162
163
164
165
166
167
            :allowed_param:'since_id', 'max_id', 'count'
        """
        return bind_api(
            api=self,
            path='/statuses/retweets_of_me.json',
            payload_type='status', payload_list=True,
            allowed_param=['since_id', 'max_id', 'count'],
            require_auth=True
        )

    @property
    def get_status(self):
168
169
        """ :reference: https://dev.twitter.com/rest/reference/get/statuses/show/%3Aid
            :allowed_param:'id'
170
171
172
173
174
175
176
177
178
179
        """
        return bind_api(
            api=self,
            path='/statuses/show.json',
            payload_type='status',
            allowed_param=['id']
        )

    @property
    def update_status(self):
180
        """ :reference: https://dev.twitter.com/rest/reference/post/statuses/update
181
182
183
184
185
186
187
188
189
190
191
            :allowed_param:'status', 'in_reply_to_status_id', 'lat', 'long', 'source', 'place_id', 'display_coordinates'
        """
        return bind_api(
            api=self,
            path='/statuses/update.json',
            method='POST',
            payload_type='status',
            allowed_param=['status', 'in_reply_to_status_id', 'lat', 'long', 'source', 'place_id', 'display_coordinates'],
            require_auth=True
        )

Florent Espanet's avatar
Florent Espanet committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    def media_upload(self, filename, *args, **kwargs):
        """ :reference: https://dev.twitter.com/rest/reference/post/media/upload
            :allowed_param:
        """
        f = kwargs.pop('file', None)
        headers, post_data = API._pack_image(filename, 3072, form_field='media', f=f)
        kwargs.update({'headers': headers, 'post_data': post_data})

        return bind_api(
            api=self,
            path='/media/upload.json',
            method='POST',
            payload_type='media',
            allowed_param=[],
            require_auth=True,
            upload_api=True
        )(*args, **kwargs)

210
    def update_with_media(self, filename, *args, **kwargs):
211
212
213
        """ :reference: https://dev.twitter.com/rest/reference/post/statuses/update_with_media
            :allowed_param:'status', 'possibly_sensitive', 'in_reply_to_status_id', 'lat', 'long', 'place_id', 'display_coordinates'
        """
214
215
        f = kwargs.pop('file', None)
        headers, post_data = API._pack_image(filename, 3072, form_field='media[]', f=f)
216
217
218
        kwargs.update({'headers': headers, 'post_data': post_data})

        return bind_api(
219
            api=self,
220
            path='/statuses/update_with_media.json',
221
            method='POST',
222
            payload_type='status',
223
            allowed_param=[
224
225
226
227
                'status', 'possibly_sensitive', 'in_reply_to_status_id', 'lat', 'long',
                'place_id', 'display_coordinates'
            ],
            require_auth=True
Aaron Hill's avatar
Aaron Hill committed
228
        )(*args, **kwargs)
229

230
231
    @property
    def destroy_status(self):
232
        """ :reference: https://dev.twitter.com/rest/reference/post/statuses/destroy/%3Aid
233
234
235
236
237
238
239
240
241
242
243
244
245
            :allowed_param:'id'
        """
        return bind_api(
            api=self,
            path='/statuses/destroy/{id}.json',
            method='POST',
            payload_type='status',
            allowed_param=['id'],
            require_auth=True
        )

    @property
    def retweet(self):
246
        """ :reference: https://dev.twitter.com/rest/reference/post/statuses/retweet/%3Aid
247
248
249
250
251
252
253
254
255
256
257
258
259
            :allowed_param:'id'
        """
        return bind_api(
            api=self,
            path='/statuses/retweet/{id}.json',
            method='POST',
            payload_type='status',
            allowed_param=['id'],
            require_auth=True
        )

    @property
    def retweets(self):
260
        """ :reference: https://dev.twitter.com/rest/reference/get/statuses/retweets/%3Aid
261
262
263
264
265
266
267
268
269
270
271
272
            :allowed_param:'id', 'count'
        """
        return bind_api(
            api=self,
            path='/statuses/retweets/{id}.json',
            payload_type='status', payload_list=True,
            allowed_param=['id', 'count'],
            require_auth=True
        )

    @property
    def retweeters(self):
273
        """ :reference: https://dev.twitter.com/rest/reference/get/statuses/retweeters/ids
274
275
276
277
278
279
280
281
282
283
284
            :allowed_param:'id', 'cursor', 'stringify_ids
        """
        return bind_api(
            api=self,
            path='/statuses/retweeters/ids.json',
            payload_type='ids',
            allowed_param=['id', 'cursor', 'stringify_ids']
        )

    @property
    def get_user(self):
285
286
        """ :reference: https://dev.twitter.com/rest/reference/get/users/show
            :allowed_param:'id', 'user_id', 'screen_name'
287
288
289
290
291
292
293
294
295
296
        """
        return bind_api(
            api=self,
            path='/users/show.json',
            payload_type='user',
            allowed_param=['id', 'user_id', 'screen_name']
        )

    @property
    def get_oembed(self):
297
298
        """ :reference: https://dev.twitter.com/rest/reference/get/statuses/oembed
            :allowed_param:'id', 'url', 'maxwidth', 'hide_media', 'omit_script', 'align', 'related', 'lang'
299
300
301
302
303
304
305
306
        """
        return bind_api(
            api=self,
            path='/statuses/oembed.json',
            payload_type='json',
            allowed_param=['id', 'url', 'maxwidth', 'hide_media', 'omit_script', 'align', 'related', 'lang']
        )

chebee7i's avatar
chebee7i committed
307
    def lookup_users(self, user_ids=None, screen_names=None, include_entities=None):
308
        """ Perform bulk look up of users from user ID or screenname """
chebee7i's avatar
chebee7i committed
309
310
311
312
313
314
315
316
317
318
        post_data = {}
        if include_entities is not None:
            include_entities = 'true' if include_entities else 'false'
            post_data['include_entities'] = include_entities
        if user_ids:
            post_data['user_id'] = list_to_csv(user_ids)
        if screen_names:
            post_data['screen_name'] = list_to_csv(screen_names)

        return self._lookup_users(post_data=post_data)
319

320
321
    @property
    def _lookup_users(self):
322
        """ :reference: https://dev.twitter.com/rest/reference/get/users/lookup
chebee7i's avatar
chebee7i committed
323
            allowed_param='user_id', 'screen_name', 'include_entities'
324
325
326
327
328
        """
        return bind_api(
            api=self,
            path='/users/lookup.json',
            payload_type='user', payload_list=True,
chebee7i's avatar
chebee7i committed
329
            method='POST',
330
        )
331

Josh Roesslein's avatar
Josh Roesslein committed
332
    def me(self):
333
        """ Get the authenticated user """
Josh Roesslein's avatar
Josh Roesslein committed
334
        return self.get_user(screen_name=self.auth.get_username())
Josh Roesslein's avatar
Josh Roesslein committed
335

336
337
    @property
    def search_users(self):
338
        """ :reference: https://dev.twitter.com/rest/reference/get/users/search
339
340
341
342
343
344
345
346
347
348
349
350
            :allowed_param:'q', 'count', 'page'
        """
        return bind_api(
            api=self,
            path='/users/search.json',
            payload_type='user', payload_list=True,
            require_auth=True,
            allowed_param=['q', 'count', 'page']
        )

    @property
    def suggested_users(self):
351
352
        """ :reference: https://dev.twitter.com/rest/reference/get/users/suggestions/%3Aslug
            :allowed_param:'slug', 'lang'
353
354
355
356
357
358
359
360
361
362
363
        """
        return bind_api(
            api=self,
            path='/users/suggestions/{slug}.json',
            payload_type='user', payload_list=True,
            require_auth=True,
            allowed_param=['slug', 'lang']
        )

    @property
    def suggested_categories(self):
364
        """ :reference: https://dev.twitter.com/rest/reference/get/users/suggestions
365
366
367
368
369
370
371
372
373
374
375
376
            :allowed_param:'lang'
        """
        return bind_api(
            api=self,
            path='/users/suggestions.json',
            payload_type='category', payload_list=True,
            allowed_param=['lang'],
            require_auth=True
        )

    @property
    def suggested_users_tweets(self):
377
        """ :reference: https://dev.twitter.com/rest/reference/get/users/suggestions/%3Aslug/members
378
379
380
381
382
383
384
385
386
387
388
389
            :allowed_param:'slug'
        """
        return bind_api(
            api=self,
            path='/users/suggestions/{slug}/members.json',
            payload_type='status', payload_list=True,
            allowed_param=['slug'],
            require_auth=True
        )

    @property
    def direct_messages(self):
390
        """ :reference: https://dev.twitter.com/rest/reference/get/direct_messages
391
392
393
394
395
396
397
398
399
400
401
402
            :allowed_param:'since_id', 'max_id', 'count'
        """
        return bind_api(
            api=self,
            path='/direct_messages.json',
            payload_type='direct_message', payload_list=True,
            allowed_param=['since_id', 'max_id', 'count'],
            require_auth=True
        )

    @property
    def get_direct_message(self):
403
        """ :reference: https://dev.twitter.com/rest/reference/get/direct_messages/show
404
405
406
407
408
409
410
411
412
413
414
415
            :allowed_param:'id'
        """
        return bind_api(
            api=self,
            path='/direct_messages/show/{id}.json',
            payload_type='direct_message',
            allowed_param=['id'],
            require_auth=True
        )

    @property
    def sent_direct_messages(self):
416
        """ :reference: https://dev.twitter.com/rest/reference/get/direct_messages/sent
417
418
419
420
421
422
423
424
425
426
427
428
            :allowed_param:'since_id', 'max_id', 'count', 'page'
        """
        return bind_api(
            api=self,
            path='/direct_messages/sent.json',
            payload_type='direct_message', payload_list=True,
            allowed_param=['since_id', 'max_id', 'count', 'page'],
            require_auth=True
        )

    @property
    def send_direct_message(self):
429
        """ :reference: https://dev.twitter.com/rest/reference/post/direct_messages/new
430
431
432
433
434
435
436
437
438
439
440
441
442
            :allowed_param:'user', 'screen_name', 'user_id', 'text'
        """
        return bind_api(
            api=self,
            path='/direct_messages/new.json',
            method='POST',
            payload_type='direct_message',
            allowed_param=['user', 'screen_name', 'user_id', 'text'],
            require_auth=True
        )

    @property
    def destroy_direct_message(self):
443
        """ :reference: https://dev.twitter.com/rest/reference/post/direct_messages/destroy
444
445
446
447
448
            :allowed_param:'id'
        """
        return bind_api(
            api=self,
            path='/direct_messages/destroy.json',
449
            method='POST',
450
451
452
453
454
455
456
            payload_type='direct_message',
            allowed_param=['id'],
            require_auth=True
        )

    @property
    def create_friendship(self):
457
        """ :reference: https://dev.twitter.com/rest/reference/post/friendships/create
458
459
460
461
462
463
464
465
466
467
468
469
470
            :allowed_param:'id', 'user_id', 'screen_name', 'follow'
        """
        return bind_api(
            api=self,
            path='/friendships/create.json',
            method='POST',
            payload_type='user',
            allowed_param=['id', 'user_id', 'screen_name', 'follow'],
            require_auth=True
        )

    @property
    def destroy_friendship(self):
471
        """ :reference: https://dev.twitter.com/rest/reference/post/friendships/destroy
472
473
474
475
476
            :allowed_param:'id', 'user_id', 'screen_name'
        """
        return bind_api(
            api=self,
            path='/friendships/destroy.json',
477
            method='POST',
478
479
480
481
482
483
484
            payload_type='user',
            allowed_param=['id', 'user_id', 'screen_name'],
            require_auth=True
        )

    @property
    def show_friendship(self):
485
486
        """ :reference: https://dev.twitter.com/rest/reference/get/friendships/show
            :allowed_param:'source_id', 'source_screen_name'
487
488
489
490
491
492
493
494
495
        """
        return bind_api(
            api=self,
            path='/friendships/show.json',
            payload_type='friendship',
            allowed_param=['source_id', 'source_screen_name',
                           'target_id', 'target_screen_name']
        )

496
    def lookup_friendships(self, user_ids=None, screen_names=None):
497
        """ Perform bulk look up of friendships from user ID or screenname """
Santosh Kumar's avatar
Santosh Kumar committed
498
        return self._lookup_friendships(list_to_csv(user_ids), list_to_csv(screen_names))
499

500
501
    @property
    def _lookup_friendships(self):
502
        """ :reference: https://dev.twitter.com/rest/reference/get/friendships/lookup
503
504
505
506
507
508
509
510
511
512
513
514
            :allowed_param:'user_id', 'screen_name'
        """
        return bind_api(
            api=self,
            path='/friendships/lookup.json',
            payload_type='relationship', payload_list=True,
            allowed_param=['user_id', 'screen_name'],
            require_auth=True
        )

    @property
    def friends_ids(self):
515
516
        """ :reference: https://dev.twitter.com/rest/reference/get/friends/ids
            :allowed_param:'id', 'user_id', 'screen_name', 'cursor'
517
518
519
520
521
522
523
524
525
526
        """
        return bind_api(
            api=self,
            path='/friends/ids.json',
            payload_type='ids',
            allowed_param=['id', 'user_id', 'screen_name', 'cursor']
        )

    @property
    def friends(self):
527
528
        """ :reference: https://dev.twitter.com/rest/reference/get/friends/list
            :allowed_param:'id', 'user_id', 'screen_name', 'cursor'
529
530
531
532
533
534
535
536
537
538
        """
        return bind_api(
            api=self,
            path='/friends/list.json',
            payload_type='user', payload_list=True,
            allowed_param=['id', 'user_id', 'screen_name', 'cursor']
        )

    @property
    def friendships_incoming(self):
539
540
        """ :reference: https://dev.twitter.com/rest/reference/get/friendships/incoming
            :allowed_param:'cursor'
541
542
543
544
545
546
547
548
549
550
        """
        return bind_api(
            api=self,
            path='/friendships/incoming.json',
            payload_type='ids',
            allowed_param=['cursor']
        )

    @property
    def friendships_outgoing(self):
551
552
        """ :reference: https://dev.twitter.com/rest/reference/get/friendships/outgoing
            :allowed_param:'cursor'
553
554
555
556
557
558
559
560
561
562
        """
        return bind_api(
            api=self,
            path='/friendships/outgoing.json',
            payload_type='ids',
            allowed_param=['cursor']
        )

    @property
    def followers_ids(self):
563
564
        """ :reference: https://dev.twitter.com/rest/reference/get/followers/ids
            :allowed_param:'id', 'user_id', 'screen_name', 'cursor', 'count'
565
566
567
568
569
570
571
572
573
574
        """
        return bind_api(
            api=self,
            path='/followers/ids.json',
            payload_type='ids',
            allowed_param=['id', 'user_id', 'screen_name', 'cursor', 'count']
        )

    @property
    def followers(self):
575
        """ :reference: https://dev.twitter.com/rest/reference/get/followers/list
576
577
578
579
580
581
582
583
584
585
            :allowed_param:'id', 'user_id', 'screen_name', 'cursor', 'count', 'skip_status', 'include_user_entities'
        """
        return bind_api(
            api=self,
            path='/followers/list.json',
            payload_type='user', payload_list=True,
            allowed_param=['id', 'user_id', 'screen_name', 'cursor', 'count',
                           'skip_status', 'include_user_entities']
        )

586
    def verify_credentials(self, **kargs):
587
588
589
        """ :reference: https://dev.twitter.com/rest/reference/get/account/verify_credentials
            :allowed_param:'include_entities', 'skip_status'
        """
Josh Roesslein's avatar
Josh Roesslein committed
590
591
        try:
            return bind_api(
592
593
594
595
596
                api=self,
                path='/account/verify_credentials.json',
                payload_type='user',
                require_auth=True,
                allowed_param=['include_entities', 'skip_status'],
Aaron Hill's avatar
Aaron Hill committed
597
            )(**kargs)
598
        except TweepError as e:
599
600
601
            if e.response and e.response.status == 401:
                return False
            raise
Josh Roesslein's avatar
Josh Roesslein committed
602

603
604
    @property
    def rate_limit_status(self):
605
        """ :reference: https://dev.twitter.com/rest/reference/get/application/rate_limit_status
606
607
608
609
610
611
612
613
614
615
616
617
            :allowed_param:'resources'
        """
        return bind_api(
            api=self,
            path='/application/rate_limit_status.json',
            payload_type='json',
            allowed_param=['resources'],
            use_cache=False
        )

    @property
    def set_delivery_device(self):
618
        """ :reference: https://dev.twitter.com/rest/reference/post/account/update_delivery_device
619
620
621
622
623
624
625
626
627
628
629
630
631
632
            :allowed_param:'device'
        """
        return bind_api(
            api=self,
            path='/account/update_delivery_device.json',
            method='POST',
            allowed_param=['device'],
            payload_type='user',
            require_auth=True
        )

    @property
    def update_profile_colors(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/post/account/update_profile_colors
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
633
634
635
            :allowed_param:'profile_background_color', 'profile_text_color',
             'profile_link_color', 'profile_sidebar_fill_color',
             'profile_sidebar_border_color'],
636
637
638
639
640
641
642
643
644
645
646
647
648
        """
        return bind_api(
            api=self,
            path='/account/update_profile_colors.json',
            method='POST',
            payload_type='user',
            allowed_param=['profile_background_color', 'profile_text_color',
                           'profile_link_color', 'profile_sidebar_fill_color',
                           'profile_sidebar_border_color'],
            require_auth=True
        )

    def update_profile_image(self, filename, file_=None):
649
650
651
        """ :reference: https://dev.twitter.com/rest/reference/post/account/update_profile_image
            :allowed_param:'include_entities', 'skip_status'
        """
652
653
654
655
656
657
        headers, post_data = API._pack_image(filename, 700, f=file_)
        return bind_api(
            api=self,
            path='/account/update_profile_image.json',
            method='POST',
            payload_type='user',
658
            allowed_param=['include_entities', 'skip_status'],
659
            require_auth=True
Josh Roesslein's avatar
Josh Roesslein committed
660
661
        )(self, post_data=post_data, headers=headers)

662
    def update_profile_background_image(self, filename, **kargs):
663
664
665
        """ :reference: https://dev.twitter.com/rest/reference/post/account/update_profile_background_image
            :allowed_param:'tile', 'include_entities', 'skip_status', 'use'
        """
666
667
        f = kargs.pop('file', None)
        headers, post_data = API._pack_image(filename, 800, f=f)
Josh Roesslein's avatar
Josh Roesslein committed
668
        bind_api(
Jordi Riera's avatar
Jordi Riera committed
669
            api=self,
670
671
672
            path='/account/update_profile_background_image.json',
            method='POST',
            payload_type='user',
Arudmin's avatar
Arudmin committed
673
            allowed_param=['tile', 'include_entities', 'skip_status', 'use'],
674
            require_auth=True
Mark Smith's avatar
Mark Smith committed
675
        )(post_data=post_data, headers=headers)
Josh Roesslein's avatar
Josh Roesslein committed
676

677
    def update_profile_banner(self, filename, **kargs):
678
679
680
        """ :reference: https://dev.twitter.com/rest/reference/post/account/update_profile_banner
            :allowed_param:'width', 'height', 'offset_left', 'offset_right'
        """
681
682
        f = kargs.pop('file', None)
        headers, post_data = API._pack_image(filename, 700, form_field="banner", f=f)
683
        bind_api(
Jordi Riera's avatar
Jordi Riera committed
684
            api=self,
685
686
687
688
            path='/account/update_profile_banner.json',
            method='POST',
            allowed_param=['width', 'height', 'offset_left', 'offset_right'],
            require_auth=True
Mark Smith's avatar
Mark Smith committed
689
        )(post_data=post_data, headers=headers)
690

691
692
    @property
    def update_profile(self):
693
        """ :reference: https://dev.twitter.com/rest/reference/post/account/update_profile
694
695
696
697
698
699
700
701
702
703
704
705
706
            :allowed_param:'name', 'url', 'location', 'description'
        """
        return bind_api(
            api=self,
            path='/account/update_profile.json',
            method='POST',
            payload_type='user',
            allowed_param=['name', 'url', 'location', 'description'],
            require_auth=True
        )

    @property
    def favorites(self):
707
708
        """ :reference: https://dev.twitter.com/rest/reference/get/favorites/list
            :allowed_param:'screen_name', 'user_id', 'max_id', 'count', 'since_id', 'max_id'
709
710
711
712
713
714
715
716
717
718
        """
        return bind_api(
            api=self,
            path='/favorites/list.json',
            payload_type='status', payload_list=True,
            allowed_param=['screen_name', 'user_id', 'max_id', 'count', 'since_id', 'max_id']
        )

    @property
    def create_favorite(self):
719
        """ :reference:https://dev.twitter.com/rest/reference/post/favorites/create
720
721
722
723
724
725
726
727
728
729
730
731
732
            :allowed_param:'id'
        """
        return bind_api(
            api=self,
            path='/favorites/create.json',
            method='POST',
            payload_type='status',
            allowed_param=['id'],
            require_auth=True
        )

    @property
    def destroy_favorite(self):
733
        """ :reference: https://dev.twitter.com/rest/reference/post/favorites/destroy
734
735
736
737
738
739
740
741
742
743
744
745
746
            :allowed_param:'id'
        """
        return bind_api(
            api=self,
            path='/favorites/destroy.json',
            method='POST',
            payload_type='status',
            allowed_param=['id'],
            require_auth=True
        )

    @property
    def create_block(self):
747
        """ :reference: https://dev.twitter.com/rest/reference/post/blocks/create
748
749
750
751
752
753
754
755
756
757
758
759
760
            :allowed_param:'id', 'user_id', 'screen_name'
        """
        return bind_api(
            api=self,
            path='/blocks/create.json',
            method='POST',
            payload_type='user',
            allowed_param=['id', 'user_id', 'screen_name'],
            require_auth=True
        )

    @property
    def destroy_block(self):
761
        """ :reference: https://dev.twitter.com/rest/reference/post/blocks/destroy
762
763
764
765
766
            :allowed_param:'id', 'user_id', 'screen_name'
        """
        return bind_api(
            api=self,
            path='/blocks/destroy.json',
767
            method='POST',
768
769
770
771
772
773
774
            payload_type='user',
            allowed_param=['id', 'user_id', 'screen_name'],
            require_auth=True
        )

    @property
    def blocks(self):
775
        """ :reference: https://dev.twitter.com/rest/reference/get/blocks/list
776
777
778
779
780
781
782
783
784
785
786
787
            :allowed_param:'cursor'
        """
        return bind_api(
            api=self,
            path='/blocks/list.json',
            payload_type='user', payload_list=True,
            allowed_param=['cursor'],
            require_auth=True
        )

    @property
    def blocks_ids(self):
788
        """ :reference: https://dev.twitter.com/rest/reference/get/blocks/ids """
789
790
791
792
793
794
795
796
797
        return bind_api(
            api=self,
            path='/blocks/ids.json',
            payload_type='json',
            require_auth=True
        )

    @property
    def report_spam(self):
798
        """ :reference: https://dev.twitter.com/rest/reference/post/users/report_spam
799
800
801
802
803
804
805
806
807
808
809
810
811
            :allowed_param:'user_id', 'screen_name'
        """
        return bind_api(
            api=self,
            path='/users/report_spam.json',
            method='POST',
            payload_type='user',
            allowed_param=['user_id', 'screen_name'],
            require_auth=True
        )

    @property
    def saved_searches(self):
812
        """ :reference: https://dev.twitter.com/rest/reference/get/saved_searches/show/%3Aid """
813
814
815
816
817
818
819
820
821
        return bind_api(
            api=self,
            path='/saved_searches/list.json',
            payload_type='saved_search', payload_list=True,
            require_auth=True
        )

    @property
    def get_saved_search(self):
822
        """ :reference: https://dev.twitter.com/rest/reference/get/saved_searches/show/%3Aid
823
824
825
826
827
828
829
830
831
832
833
834
            :allowed_param:'id'
        """
        return bind_api(
            api=self,
            path='/saved_searches/show/{id}.json',
            payload_type='saved_search',
            allowed_param=['id'],
            require_auth=True
        )

    @property
    def create_saved_search(self):
835
        """ :reference: https://dev.twitter.com/rest/reference/post/saved_searches/create
836
837
838
839
840
841
842
843
844
845
846
847
848
            :allowed_param:'query'
        """
        return bind_api(
            api=self,
            path='/saved_searches/create.json',
            method='POST',
            payload_type='saved_search',
            allowed_param=['query'],
            require_auth=True
        )

    @property
    def destroy_saved_search(self):
849
        """ :reference: https://dev.twitter.com/rest/reference/post/saved_searches/destroy/%3Aid
850
851
852
853
854
855
856
857
858
859
860
861
862
            :allowed_param:'id'
        """
        return bind_api(
            api=self,
            path='/saved_searches/destroy/{id}.json',
            method='POST',
            payload_type='saved_search',
            allowed_param=['id'],
            require_auth=True
        )

    @property
    def create_list(self):
863
        """ :reference: https://dev.twitter.com/rest/reference/post/lists/create
864
865
866
867
868
869
870
871
872
873
874
875
876
            :allowed_param:'name', 'mode', 'description'
        """
        return bind_api(
            api=self,
            path='/lists/create.json',
            method='POST',
            payload_type='list',
            allowed_param=['name', 'mode', 'description'],
            require_auth=True
        )

    @property
    def destroy_list(self):
877
        """ :reference: https://dev.twitter.com/rest/reference/post/lists/destroy
878
879
880
881
882
883
884
885
886
887
888
889
890
            :allowed_param:'owner_screen_name', 'owner_id', 'list_id', 'slug'
        """
        return bind_api(
            api=self,
            path='/lists/destroy.json',
            method='POST',
            payload_type='list',
            allowed_param=['owner_screen_name', 'owner_id', 'list_id', 'slug'],
            require_auth=True
        )

    @property
    def update_list(self):
891
        """ :reference: https://dev.twitter.com/rest/reference/post/lists/update
892
893
894
895
896
897
898
899
900
901
902
903
904
            :allowed_param: list_id', 'slug', 'name', 'mode', 'description', 'owner_screen_name', 'owner_id'
        """
        return bind_api(
            api=self,
            path='/lists/update.json',
            method='POST',
            payload_type='list',
            allowed_param=['list_id', 'slug', 'name', 'mode', 'description', 'owner_screen_name', 'owner_id'],
            require_auth=True
        )

    @property
    def lists_all(self):
905
        """ :reference: https://dev.twitter.com/rest/reference/get/lists/list
906
907
908
909
910
911
912
913
914
915
916
917
            :allowed_param:'screen_name', 'user_id'
        """
        return bind_api(
            api=self,
            path='/lists/list.json',
            payload_type='list', payload_list=True,
            allowed_param=['screen_name', 'user_id'],
            require_auth=True
        )

    @property
    def lists_memberships(self):
918
        """ :reference: https://dev.twitter.com/rest/reference/get/lists/memberships
919
920
921
922
923
924
925
926
927
928
929
930
            :allowed_param:'screen_name', 'user_id', 'filter_to_owned_lists', 'cursor'
        """
        return bind_api(
            api=self,
            path='/lists/memberships.json',
            payload_type='list', payload_list=True,
            allowed_param=['screen_name', 'user_id', 'filter_to_owned_lists', 'cursor'],
            require_auth=True
        )

    @property
    def lists_subscriptions(self):
931
        """ :reference: https://dev.twitter.com/rest/reference/get/lists/subscriptions
932
933
934
935
936
937
938
939
940
941
942
943
944
            :allowed_param:'screen_name', 'user_id', 'cursor'
        """
        return bind_api(
            api=self,
            path='/lists/subscriptions.json',
            payload_type='list', payload_list=True,
            allowed_param=['screen_name', 'user_id', 'cursor'],
            require_auth=True
        )

    @property
    def list_timeline(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/get/lists/statuses
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
945
946
            :allowed_param:'owner_screen_name', 'slug', 'owner_id', 'list_id',
             'since_id', 'max_id', 'count', 'include_rts
947
948
949
950
951
        """
        return bind_api(
            api=self,
            path='/lists/statuses.json',
            payload_type='status', payload_list=True,
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
952
953
954
            allowed_param=['owner_screen_name', 'slug', 'owner_id',
                           'list_id', 'since_id', 'max_id', 'count',
                           'include_rts']
955
956
957
958
        )

    @property
    def get_list(self):
959
960
        """ :reference: https://dev.twitter.com/rest/reference/get/lists/show
            :allowed_param:'owner_screen_name', 'owner_id', 'slug', 'list_id'
961
962
963
964
965
966
967
968
969
970
971
        """
        return bind_api(
            api=self,
            path='/lists/show.json',
            payload_type='list',
            allowed_param=['owner_screen_name', 'owner_id', 'slug', 'list_id']
        )

    @property
    def add_list_member(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/post/lists/members/create
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
972
973
            :allowed_param:'screen_name', 'user_id', 'owner_screen_name',
             'owner_id', 'slug', 'list_id'
974
975
976
977
978
979
        """
        return bind_api(
            api=self,
            path='/lists/members/create.json',
            method='POST',
            payload_type='list',
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
980
981
            allowed_param=['screen_name', 'user_id', 'owner_screen_name',
                           'owner_id', 'slug', 'list_id'],
982
983
984
985
986
987
            require_auth=True
        )

    @property
    def remove_list_member(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/post/lists/members/destroy
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
988
989
            :allowed_param:'screen_name', 'user_id', 'owner_screen_name',
             'owner_id', 'slug', 'list_id'
990
991
992
993
994
995
        """
        return bind_api(
            api=self,
            path='/lists/members/destroy.json',
            method='POST',
            payload_type='list',
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
996
997
            allowed_param=['screen_name', 'user_id', 'owner_screen_name',
                           'owner_id', 'slug', 'list_id'],
998
999
            require_auth=True
        )
1000

kk6's avatar
kk6 committed
1001
    def add_list_members(self, screen_name=None, user_id=None, slug=None,
1002
                         list_id=None, owner_id=None, owner_screen_name=None):
1003
        """ Perform bulk add of list members from user ID or screenname """
kk6's avatar
kk6 committed
1004
1005
        return self._add_list_members(list_to_csv(screen_name),
                                      list_to_csv(user_id),
1006
1007
1008
                                      slug, list_id, owner_id,
                                      owner_screen_name)

1009
1010
1011
    @property
    def _add_list_members(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/post/lists/members/create_all
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1012
1013
            :allowed_param:'screen_name', 'user_id', 'slug', 'lit_id',
            'owner_id', 'owner_screen_name'
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1014

1015
1016
1017
1018
1019
1020
        """
        return bind_api(
            api=self,
            path='/lists/members/create_all.json',
            method='POST',
            payload_type='list',
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1021
1022
            allowed_param=['screen_name', 'user_id', 'slug', 'lit_id',
                           'owner_id', 'owner_screen_name'],
1023
1024
1025
            require_auth=True
        )

kk6's avatar
kk6 committed
1026
    def remove_list_members(self, screen_name=None, user_id=None, slug=None,
1027
1028
                            list_id=None, owner_id=None, owner_screen_name=None):
        """ Perform bulk remove of list members from user ID or screenname """
kk6's avatar
kk6 committed
1029
        return self._remove_list_members(list_to_csv(screen_name),
1030
1031
1032
1033
1034
1035
1036
                                         list_to_csv(user_id),
                                         slug, list_id, owner_id,
                                         owner_screen_name)

    @property
    def _remove_list_members(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/post/lists/members/destroy_all
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1037
1038
            :allowed_param:'screen_name', 'user_id', 'slug', 'lit_id',
            'owner_id', 'owner_screen_name'
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1039

1040
1041
1042
1043
1044
1045
        """
        return bind_api(
            api=self,
            path='/lists/members/destroy_all.json',
            method='POST',
            payload_type='list',
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1046
1047
            allowed_param=['screen_name', 'user_id', 'slug', 'lit_id',
                           'owner_id', 'owner_screen_name'],
1048
1049
            require_auth=True
        )
1050

1051
1052
1053
    @property
    def list_members(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/get/lists/members
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1054
1055
            :allowed_param:'owner_screen_name', 'slug', 'list_id',
             'owner_id', 'cursor
1056
1057
1058
1059
1060
        """
        return bind_api(
            api=self,
            path='/lists/members.json',
            payload_type='user', payload_list=True,
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1061
1062
            allowed_param=['owner_screen_name', 'slug', 'list_id',
                           'owner_id', 'cursor']
1063
1064
1065
1066
1067
        )

    @property
    def show_list_member(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/get/lists/members/show
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1068
1069
            :allowed_param:'list_id', 'slug', 'user_id', 'screen_name',
             'owner_screen_name', 'owner_id
1070
1071
1072
1073
1074
        """
        return bind_api(
            api=self,
            path='/lists/members/show.json',
            payload_type='user',
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1075
1076
            allowed_param=['list_id', 'slug', 'user_id', 'screen_name',
                           'owner_screen_name', 'owner_id']
1077
1078
1079
1080
1081
        )

    @property
    def subscribe_list(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/post/lists/subscribers/create
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1082
1083
            :allowed_param:'owner_screen_name', 'slug', 'owner_id',
            'list_id'
1084
1085
1086
1087
1088
1089
        """
        return bind_api(
            api=self,
            path='/lists/subscribers/create.json',
            method='POST',
            payload_type='list',
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1090
1091
            allowed_param=['owner_screen_name', 'slug', 'owner_id',
                           'list_id'],
1092
1093
1094
1095
1096
1097
            require_auth=True
        )

    @property
    def unsubscribe_list(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/post/lists/subscribers/destroy
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1098
1099
            :allowed_param:'owner_screen_name', 'slug', 'owner_id',
            'list_id'
1100
1101
1102
1103
1104
1105
        """
        return bind_api(
            api=self,
            path='/lists/subscribers/destroy.json',
            method='POST',
            payload_type='list',
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1106
1107
            allowed_param=['owner_screen_name', 'slug', 'owner_id',
                           'list_id'],
1108
1109
1110
1111
1112
1113
            require_auth=True
        )

    @property
    def list_subscribers(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/get/lists/subscribers
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1114
1115
            :allowed_param:'owner_screen_name', 'slug', 'owner_id',
             'list_id', 'cursor
1116
1117
1118
1119
1120
        """
        return bind_api(
            api=self,
            path='/lists/subscribers.json',
            payload_type='user', payload_list=True,
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1121
1122
            allowed_param=['owner_screen_name', 'slug', 'owner_id',
                           'list_id', 'cursor']
1123
1124
1125
1126
1127
        )

    @property
    def show_list_subscriber(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/get/lists/subscribers/show
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1128
1129
            :allowed_param:'owner_screen_name', 'slug', 'screen_name',
             'owner_id', 'list_id', 'user_id
1130
1131
1132
1133
1134
        """
        return bind_api(
            api=self,
            path='/lists/subscribers/show.json',
            payload_type='user',
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1135
1136
            allowed_param=['owner_screen_name', 'slug', 'screen_name',
                           'owner_id', 'list_id', 'user_id']
1137
1138
1139
1140
        )

    @property
    def trends_available(self):
1141
        """ :reference: https://dev.twitter.com/rest/reference/get/trends/available """
1142
1143
1144
1145
1146
1147
1148
1149
        return bind_api(
            api=self,
            path='/trends/available.json',
            payload_type='json'
        )

    @property
    def trends_place(self):
1150
1151
        """ :reference: https://dev.twitter.com/rest/reference/get/trends/place
            :allowed_param:'id', 'exclude'
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
        """
        return bind_api(
            api=self,
            path='/trends/place.json',
            payload_type='json',
            allowed_param=['id', 'exclude']
        )

    @property
    def trends_closest(self):
1162
1163
        """ :reference: https://dev.twitter.com/rest/reference/get/trends/closest
            :allowed_param:'lat', 'long'
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
        """
        return bind_api(
            api=self,
            path='/trends/closest.json',
            payload_type='json',
            allowed_param=['lat', 'long']
        )

    @property
    def search(self):
1174
        """ :reference: https://dev.twitter.com/rest/reference/get/search/tweets
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1175
1176
1177
            :allowed_param:'q', 'lang', 'locale', 'since_id', 'geocode',
             'max_id', 'since', 'until', 'result_type', 'count',
              'include_entities', 'from', 'to', 'source']
1178
1179
1180
1181
1182
        """
        return bind_api(
            api=self,
            path='/search/tweets.json',
            payload_type='search_results',
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1183
1184
1185
1186
            allowed_param=['q', 'lang', 'locale', 'since_id', 'geocode',
                           'max_id', 'since', 'until', 'result_type',
                           'count', 'include_entities', 'from',
                           'to', 'source']
1187
1188
1189
1190
        )

    @property
    def reverse_geocode(self):
1191
1192
        """ :reference: https://dev.twitter.com/rest/reference/get/geo/reverse_geocode
            :allowed_param:'lat', 'long', 'accuracy', 'granularity', 'max_results'
1193
1194
1195
1196
1197
        """
        return bind_api(
            api=self,
            path='/geo/reverse_geocode.json',
            payload_type='place', payload_list=True,
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1198
1199
            allowed_param=['lat', 'long', 'accuracy', 'granularity',
                           'max_results']
1200
1201
1202
1203
        )

    @property
    def geo_id(self):
1204
1205
        """ :reference: https://dev.twitter.com/rest/reference/get/geo/id/%3Aplace_id
            :allowed_param:'id'
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
        """
        return bind_api(
            api=self,
            path='/geo/id/{id}.json',
            payload_type='place',
            allowed_param=['id']
        )

    @property
    def geo_search(self):
        """ :reference: https://dev.twitter.com/docs/api/1.1/get/geo/search
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1217
1218
            :allowed_param:'lat', 'long', 'query', 'ip', 'granularity',
             'accuracy', 'max_results', 'contained_within
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1219

1220
1221
1222
1223
1224
        """
        return bind_api(
            api=self,
            path='/geo/search.json',
            payload_type='place', payload_list=True,
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1225
1226
            allowed_param=['lat', 'long', 'query', 'ip', 'granularity',
                           'accuracy', 'max_results', 'contained_within']
1227
1228
1229
1230
        )

    @property
    def geo_similar_places(self):
1231
1232
        """ :reference: https://dev.twitter.com/rest/reference/get/geo/similar_places
            :allowed_param:'lat', 'long', 'name', 'contained_within'
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
        """
        return bind_api(
            api=self,
            path='/geo/similar_places.json',
            payload_type='place', payload_list=True,
            allowed_param=['lat', 'long', 'name', 'contained_within']
        )

    @property
    def supported_languages(self):
1243
        """ :reference: https://dev.twitter.com/rest/reference/get/help/languages """
1244
1245
1246
1247
1248
1249
        return bind_api(
            api=self,
            path='/help/languages.json',
            payload_type='json',
            require_auth=True
        )
1250

1251
1252
    @property
    def configuration(self):
1253
        """ :reference: https://dev.twitter.com/rest/reference/get/help/configuration """
1254
1255
1256
1257
1258
1259
        return bind_api(
            api=self,
            path='/help/configuration.json',
            payload_type='json',
            require_auth=True
        )
1260

1261
    """ Internal use only """
1262

Josh Roesslein's avatar
Josh Roesslein committed
1263
    @staticmethod
1264
    def _pack_image(filename, max_size, form_field="image", f=None):
Josh Roesslein's avatar
Josh Roesslein committed
1265
1266
        """Pack image from file into multipart-formdata post body"""
        # image must be less than 700kb in size
1267
        if f is None:
1268
1269
1270
1271
1272
1273
1274
1275
1276
            try:
                if os.path.getsize(filename) > (max_size * 1024):
                    raise TweepError('File is too big, must be less than 700kb.')
            except os.error:
                raise TweepError('Unable to access file')

            # build the mulitpart-formdata body
            fp = open(filename, 'rb')
        else:
1277
            f.seek(0, 2)  # Seek to end of file
1278
            if f.tell() > (max_size * 1024):
Josh Roesslein's avatar
Josh Roesslein committed
1279
                raise TweepError('File is too big, must be less than 700kb.')
1280
            f.seek(0)  # Reset to beginning of file
1281
            fp = f
Josh Roesslein's avatar
Josh Roesslein committed
1282
1283
1284
1285
1286
1287
1288
1289
1290

        # image must be gif, jpeg, or png
        file_type = mimetypes.guess_type(filename)
        if file_type is None:
            raise TweepError('Could not determine file type')
        file_type = file_type[0]
        if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
            raise TweepError('Invalid file type for image: %s' % file_type)

Mark Smith's avatar
Mark Smith committed
1291
        if isinstance(filename, six.text_type):
1292
            filename = filename.encode("utf-8")
1293

Mark Smith's avatar
Mark Smith committed
1294
        BOUNDARY = b'Tw3ePy'
Omer Murat Yildirim's avatar
Omer Murat Yildirim committed
1295
        body = list()
Mark Smith's avatar
Mark Smith committed
1296
1297
1298
1299
1300
1301
        body.append(b'--' + BOUNDARY)
        body.append('Content-Disposition: form-data; name="{0}";'
                    ' filename="{1}"'.format(form_field, filename)
                    .encode('utf-8'))
        body.append('Content-Type: {0}'.format(file_type).encode('utf-8'))
        body.append(b'')
Josh Roesslein's avatar
Josh Roesslein committed
1302
        body.append(fp.read())
Mark Smith's avatar
Mark Smith committed
1303
1304
        body.append(b'--' + BOUNDARY + b'--')
        body.append(b'')
Josh Roesslein's avatar
Josh Roesslein committed
1305
        fp.close()
Mark Smith's avatar
Mark Smith committed
1306
        body = b'\r\n'.join(body)
Josh Roesslein's avatar
Josh Roesslein committed
1307
1308
1309
1310

        # build headers
        headers = {
            'Content-Type': 'multipart/form-data; boundary=Tw3ePy',
1311
            'Content-Length': str(len(body))
Josh Roesslein's avatar
Josh Roesslein committed
1312
1313
1314
        }

        return headers, body