diff options
Diffstat (limited to 'mastodon')
-rw-r--r-- | mastodon/Mastodon.py | 28 |
1 files changed, 23 insertions, 5 deletions
diff --git a/mastodon/Mastodon.py b/mastodon/Mastodon.py index a00f249..eb16bfa 100644 --- a/mastodon/Mastodon.py +++ b/mastodon/Mastodon.py | |||
@@ -3,6 +3,10 @@ | |||
3 | import requests | 3 | import requests |
4 | import os | 4 | import os |
5 | import os.path | 5 | import os.path |
6 | import mimetypes | ||
7 | import time | ||
8 | import random | ||
9 | import string | ||
6 | 10 | ||
7 | class Mastodon: | 11 | class Mastodon: |
8 | """ | 12 | """ |
@@ -302,17 +306,31 @@ class Mastodon: | |||
302 | ### | 306 | ### |
303 | # Writing data: Media | 307 | # Writing data: Media |
304 | ### | 308 | ### |
305 | def media_post(self, media_file): | 309 | def media_post(self, media_file, mime_type = None): |
306 | """ | 310 | """ |
307 | Posts an image. media_file can either be image data or | 311 | Posts an image. media_file can either be image data or |
308 | a file name. | 312 | a file name. If image data is passed directly, the mime |
309 | 313 | type has to be specified manually, otherwise, it is | |
314 | determined from the file name. | ||
315 | |||
310 | Returns the ID of the media that can then be used in status_post(). | 316 | Returns the ID of the media that can then be used in status_post(). |
317 | |||
318 | Throws a ValueError if the mime type of the passed data or file can | ||
319 | not be determined properly. | ||
311 | """ | 320 | """ |
321 | |||
312 | if os.path.isfile(media_file): | 322 | if os.path.isfile(media_file): |
323 | mime_type = mimetypes.guess_type(media_file)[0] | ||
313 | media_file = open(media_file, 'rb') | 324 | media_file = open(media_file, 'rb') |
314 | 325 | ||
315 | return self.__api_request('POST', '/api/v1/media', files = {'file': media_file}) | 326 | if mime_type == None: |
327 | raise ValueError('Could not determine mime type or data passed directly without mime type.') | ||
328 | |||
329 | random_suffix = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) | ||
330 | file_name = "mastodonpyupload_" + str(time.time()) + "_" + str(random_suffix) + mimetypes.guess_extension(mime_type) | ||
331 | |||
332 | media_file_description = (file_name, media_file, mime_type) | ||
333 | return self.__api_request('POST', '/api/v1/media', files = {'file': media_file_description}) | ||
316 | 334 | ||
317 | ### | 335 | ### |
318 | # Internal helpers, dragons probably | 336 | # Internal helpers, dragons probably |