From b83a659bc2da08e80b215889a9645f1bd1307208 Mon Sep 17 00:00:00 2001 From: leandrotoledo Date: Mon, 13 Jul 2015 18:53:30 -0300 Subject: [PATCH] hack to detect image from stream --- telegram/inputfile.py | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/telegram/inputfile.py b/telegram/inputfile.py index f33045dd8..fdfc5f6fd 100644 --- a/telegram/inputfile.py +++ b/telegram/inputfile.py @@ -4,6 +4,7 @@ import mimetools import mimetypes import os +import re import urllib2 @@ -27,14 +28,16 @@ class InputFile(object): self.input_file = data.pop('video') if isinstance(self.input_file, file): - self.filename = os.path.basename(self.input_file.name) self.input_file_content = self.input_file.read() + self.filename = os.path.basename(self.input_file.name) + self.mimetype = mimetypes.guess_type(self.filename)[0] or \ + 'application/octet-stream' if 'http' in self.input_file: - self.filename = os.path.basename(self.input_file) self.input_file_content = urllib2.urlopen(self.input_file).read() + self.mimetype = InputFile.image_type(self.input_file_content) + self.filename = self.mimetype.replace('/', '.') + - self.mimetype = mimetypes.guess_type(self.filename)[0] or \ - 'application/octet-stream' @property def headers(self): @@ -73,3 +76,17 @@ class InputFile(object): form.append('') return '\r\n'.join(form) + + @staticmethod + def image_type(stream): + header = stream[:10] + + if re.match(r'GIF8', header): + return 'image/gif' + + if re.match(r'\x89PNG', header): + return 'image/png' + + if re.match(r'\xff\xd8\xff\xe0\x00\x10JFIF', header) or \ + re.match(r'\xff\xd8\xff\xe1(.*){2}Exif', header): + return 'image/jpeg'