Skip to content

Commit

Permalink
Use imghdr instead re to match image headers. Fixes #37
Browse files Browse the repository at this point in the history
  • Loading branch information
leandrotoledo committed Aug 15, 2015
1 parent 2cecca8 commit 5dc1e4c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 17 deletions.
19 changes: 4 additions & 15 deletions telegram/inputfile.py
Expand Up @@ -26,8 +26,8 @@
from urllib2 import urlopen
import mimetypes
import os
import re
import sys
import imghdr

from .error import TelegramError

Expand Down Expand Up @@ -128,20 +128,9 @@ def is_image(stream):
Returns:
The str mimetype of an image.
"""
try:
header = stream[:10]

if re.match(b'GIF8', header):
return 'image/gif'

if re.match(b'\x89PNG', header):
return 'image/png'

if re.match(b'\xff\xd8\xff\xe0\x00\x10JFIF', header) or \
re.match(b'\xff\xd8\xff\xe1(.*){2}Exif', header):
return 'image/jpeg'
except IndexError as e:
raise TelegramError(str(e))
image = imghdr.what(None, stream)
if image:
return 'image/%s' % image

raise TelegramError({'message': 'Could not parse file content'})

Expand Down
25 changes: 23 additions & 2 deletions tests/test_bot.py
Expand Up @@ -79,13 +79,27 @@ def testResendPhoto(self):
chat_id=12173560)
self.assertEqual('AgADAQADr6cxGzU8LQe6q0dMJD2rHYkP2ykABFymiQqJgjxRGGMAAgI', message.photo[0].file_id)

def testSendURLPhoto(self):
def testSendJPGURLPhoto(self):
'''Test the telegram.Bot sendPhoto method'''
print('Testing sendPhoto - URL')
print('Testing testSendJPGURLPhoto - URL')
message = self._bot.sendPhoto(photo=str('http://dummyimage.com/600x400/000/fff.jpg&text=telegram'),
chat_id=12173560)
self.assertEqual(822, message.photo[0].file_size)

def testSendPNGURLPhoto(self):
'''Test the telegram.Bot sendPhoto method'''
print('Testing testSendPNGURLPhoto - URL')
message = self._bot.sendPhoto(photo=str('http://dummyimage.com/600x400/000/fff.png&text=telegram'),
chat_id=12173560)
self.assertEqual(684, message.photo[0].file_size)

def testSendGIFURLPhoto(self):
'''Test the telegram.Bot sendPhoto method'''
print('Testing testSendGIFURLPhoto - URL')
message = self._bot.sendPhoto(photo=str('http://dummyimage.com/600x400/000/fff.gif&text=telegram'),
chat_id=12173560)
self.assertEqual(684, message.photo[0].file_size)

def testSendAudio(self):
'''Test the telegram.Bot sendAudio method'''
print('Testing sendAudio - File')
Expand All @@ -107,6 +121,13 @@ def testSendDocument(self):
chat_id=12173560)
self.assertEqual(12948, message.document.file_size)

def testSendGIFURLDocument(self):
'''Test the telegram.Bot sendDocument method'''
print('Testing sendDocument - File')
message = self._bot.sendPhoto(photo=str('http://dummyimage.com/600x400/000/fff.gif&text=telegram'),
chat_id=12173560)
self.assertEqual(684, message.photo[0].file_size)

def testResendDocument(self):
'''Test the telegram.Bot sendDocument method'''
print('Testing sendDocument - Resend')
Expand Down

0 comments on commit 5dc1e4c

Please sign in to comment.