Skip to content

Commit b83a659

Browse files
committed
hack to detect image from stream
1 parent 3df9d2b commit b83a659

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

telegram/inputfile.py

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import mimetools
55
import mimetypes
66
import os
7+
import re
78
import urllib2
89

910

@@ -27,14 +28,16 @@ def __init__(self,
2728
self.input_file = data.pop('video')
2829

2930
if isinstance(self.input_file, file):
30-
self.filename = os.path.basename(self.input_file.name)
3131
self.input_file_content = self.input_file.read()
32+
self.filename = os.path.basename(self.input_file.name)
33+
self.mimetype = mimetypes.guess_type(self.filename)[0] or \
34+
'application/octet-stream'
3235
if 'http' in self.input_file:
33-
self.filename = os.path.basename(self.input_file)
3436
self.input_file_content = urllib2.urlopen(self.input_file).read()
37+
self.mimetype = InputFile.image_type(self.input_file_content)
38+
self.filename = self.mimetype.replace('/', '.')
39+
3540

36-
self.mimetype = mimetypes.guess_type(self.filename)[0] or \
37-
'application/octet-stream'
3841

3942
@property
4043
def headers(self):
@@ -73,3 +76,17 @@ def to_form(self):
7376
form.append('')
7477

7578
return '\r\n'.join(form)
79+
80+
@staticmethod
81+
def image_type(stream):
82+
header = stream[:10]
83+
84+
if re.match(r'GIF8', header):
85+
return 'image/gif'
86+
87+
if re.match(r'\x89PNG', header):
88+
return 'image/png'
89+
90+
if re.match(r'\xff\xd8\xff\xe0\x00\x10JFIF', header) or \
91+
re.match(r'\xff\xd8\xff\xe1(.*){2}Exif', header):
92+
return 'image/jpeg'

0 commit comments

Comments
 (0)