2015-07-10 18:43:35 +02:00
|
|
|
#!/usr/bin/env python
|
|
|
|
|
|
|
|
|
|
|
|
import mimetools
|
|
|
|
import mimetypes
|
|
|
|
import os
|
2015-07-11 00:46:15 +02:00
|
|
|
import urllib2
|
2015-07-10 18:43:35 +02:00
|
|
|
|
|
|
|
|
|
|
|
class InputFile(object):
|
|
|
|
def __init__(self,
|
|
|
|
data):
|
|
|
|
self.data = data
|
|
|
|
self.boundary = mimetools.choose_boundary()
|
|
|
|
|
2015-07-11 00:46:15 +02:00
|
|
|
if 'audio' in data:
|
2015-07-10 18:43:35 +02:00
|
|
|
self.input_name = 'audio'
|
|
|
|
self.input_file = data.pop('audio')
|
2015-07-11 00:46:15 +02:00
|
|
|
if 'document' in data:
|
2015-07-10 18:43:35 +02:00
|
|
|
self.input_name = 'document'
|
|
|
|
self.input_file = data.pop('document')
|
2015-07-11 00:46:15 +02:00
|
|
|
if 'photo' in data:
|
2015-07-10 18:43:35 +02:00
|
|
|
self.input_name = 'photo'
|
|
|
|
self.input_file = data.pop('photo')
|
2015-07-11 00:46:15 +02:00
|
|
|
if 'video' in data:
|
2015-07-10 18:43:35 +02:00
|
|
|
self.input_name = 'video'
|
|
|
|
self.input_file = data.pop('video')
|
|
|
|
|
2015-07-11 00:46:15 +02:00
|
|
|
if isinstance(self.input_file, file):
|
|
|
|
self.filename = os.path.basename(self.input_file.name)
|
|
|
|
self.input_file_content = self.input_file.read()
|
|
|
|
if 'http' in self.input_file:
|
|
|
|
self.filename = os.path.basename(self.input_file)
|
|
|
|
self.input_file_content = urllib2.urlopen(self.input_file).read()
|
|
|
|
|
2015-07-10 18:43:35 +02:00
|
|
|
self.mimetype = mimetypes.guess_type(self.filename)[0] or \
|
|
|
|
'application/octet-stream'
|
|
|
|
|
|
|
|
@property
|
|
|
|
def headers(self):
|
|
|
|
return {'User-agent': 'Python Telegram Bot (https://github.com/leandrotoledo/python-telegram-bot)',
|
|
|
|
'Content-type': self.content_type}
|
|
|
|
|
|
|
|
@property
|
|
|
|
def content_type(self):
|
|
|
|
return 'multipart/form-data; boundary=%s' % self.boundary
|
|
|
|
|
|
|
|
def to_form(self):
|
|
|
|
form = []
|
|
|
|
form_boundary = '--' + self.boundary
|
|
|
|
|
|
|
|
# Add data fields
|
|
|
|
for name, value in self.data.iteritems():
|
|
|
|
form.extend([
|
|
|
|
form_boundary,
|
2015-07-10 21:50:33 +02:00
|
|
|
str('Content-Disposition: form-data; name="%s"' % name),
|
2015-07-10 18:43:35 +02:00
|
|
|
'',
|
|
|
|
str(value)
|
|
|
|
])
|
|
|
|
|
|
|
|
# Add input_file to upload
|
|
|
|
form.extend([
|
|
|
|
form_boundary,
|
2015-07-10 21:50:33 +02:00
|
|
|
str('Content-Disposition: form-data; name="%s"; filename="%s"' % (
|
2015-07-10 18:43:35 +02:00
|
|
|
self.input_name, self.filename
|
2015-07-10 21:50:33 +02:00
|
|
|
)),
|
2015-07-10 18:43:35 +02:00
|
|
|
'Content-Type: %s' % self.mimetype,
|
|
|
|
'',
|
|
|
|
self.input_file_content
|
|
|
|
])
|
|
|
|
|
|
|
|
form.append('--' + self.boundary + '--')
|
|
|
|
form.append('')
|
|
|
|
|
|
|
|
return '\r\n'.join(form)
|