Drop InputFile.is_image (#3053)

This commit is contained in:
Bibo-Joshi 2022-05-29 14:35:26 +02:00 committed by GitHub
parent 5e0bcfbcc6
commit 6ded9cc25c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 40 deletions

View file

@ -18,7 +18,6 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram InputFile."""
import imghdr
import logging
import mimetypes
from pathlib import Path
@ -35,7 +34,11 @@ class InputFile:
"""This object represents a Telegram InputFile.
.. versionchanged:: 20.0
The former attribute ``attach`` was renamed to :attr:`attach_name`.
* The former attribute ``attach`` was renamed to :attr:`attach_name`.
* Method ``is_image`` was removed. If you pass :obj:`bytes` to :paramref:`obj` and would
like to have the mime type automatically guessed, please pass :paramref:`filename`
in addition.
Args:
obj (:term:`file object` | :obj:`bytes` | :obj:`str`): An open file descriptor or the files
@ -82,39 +85,13 @@ class InputFile:
):
filename = Path(obj.name).name # type: ignore[union-attr]
image_mime_type = self.is_image(self.input_file_content)
if image_mime_type:
self.mimetype = image_mime_type
elif filename:
self.mimetype = mimetypes.guess_type(filename)[0] or _DEFAULT_MIME_TYPE
if filename:
self.mimetype = mimetypes.guess_type(filename, strict=False)[0] or _DEFAULT_MIME_TYPE
else:
self.mimetype = _DEFAULT_MIME_TYPE
self.filename = filename or self.mimetype.replace("/", ".")
@staticmethod
def is_image(stream: bytes) -> Optional[str]:
"""Check if the content file is an image by analyzing its headers.
Args:
stream (:obj:`bytes`): A byte stream representing the content of a file.
Returns:
:obj:`str` | :obj:`None`: The mime-type of an image, if the input is an image, or
:obj:`None` else.
"""
try:
image = imghdr.what(None, stream)
if image:
return f"image/{image}"
return None
except Exception:
logger.debug(
"Could not parse file content. Assuming that file is not an image.", exc_info=True
)
return None
@property
def field_tuple(self) -> FieldTuple:
"""Field tuple representing the contents of the file for upload to the Telegram servers.

BIN
tests/data/telegram.midi Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View file

@ -16,7 +16,6 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import logging
import subprocess
import sys
from io import BytesIO
@ -46,8 +45,8 @@ class TestInputFile:
in_file = InputFile(proc.stdout)
assert in_file.input_file_content == png_file.read_bytes()
assert in_file.mimetype == "image/png"
assert in_file.filename == "image.png"
assert in_file.mimetype == "application/octet-stream"
assert in_file.filename == "application.octet-stream"
try:
proc.kill()
@ -69,8 +68,17 @@ class TestInputFile:
def test_mimetypes(self, caplog):
# Only test a few to make sure logic works okay
assert InputFile(data_file("telegram.jpg").open("rb")).mimetype == "image/jpeg"
assert InputFile(data_file("telegram.webp").open("rb")).mimetype == "image/webp"
# For some reason python can guess the type on macOS
assert InputFile(data_file("telegram.webp").open("rb")).mimetype in [
"application/octet-stream",
"image/webp",
]
assert InputFile(data_file("telegram.mp3").open("rb")).mimetype == "audio/mpeg"
# For some reason windows drops the trailing i
assert InputFile(data_file("telegram.midi").open("rb")).mimetype in [
"audio/mid",
"audio/midi",
]
# Test guess from file
assert InputFile(BytesIO(b"blah"), filename="tg.jpg").mimetype == "image/jpeg"
@ -84,12 +92,8 @@ class TestInputFile:
assert InputFile(BytesIO(b"blah")).mimetype == "application/octet-stream"
# Test string file
with caplog.at_level(logging.DEBUG):
assert InputFile(data_file("text_file.txt").open()).mimetype == "text/plain"
assert len(caplog.records) == 1
assert caplog.records[0].getMessage().startswith("Could not parse file content")
def test_filenames(self):
assert InputFile(data_file("telegram.jpg").open("rb")).filename == "telegram.jpg"
assert InputFile(data_file("telegram.jpg").open("rb"), filename="blah").filename == "blah"
@ -111,7 +115,10 @@ class TestInputFile:
def read(self):
return self.f.read()
assert InputFile(MockedFileobject(data_file("telegram.jpg"))).filename == "image.jpeg"
assert (
InputFile(MockedFileobject(data_file("telegram.jpg"))).filename
== "application.octet-stream"
)
assert (
InputFile(MockedFileobject(data_file("telegram.jpg")), filename="blah").filename
== "blah"