2018-06-09 23:05:06 +03:00
|
|
|
import hashlib
|
|
|
|
import io
|
|
|
|
import os
|
2018-06-16 18:01:20 +03:00
|
|
|
import pathlib
|
2018-06-26 17:39:22 +03:00
|
|
|
import re
|
2019-05-03 22:37:27 +03:00
|
|
|
import typing
|
2018-06-09 23:05:06 +03:00
|
|
|
from io import BytesIO
|
|
|
|
|
2018-10-05 15:20:50 +03:00
|
|
|
from .buttons import ButtonMethods
|
2018-06-10 12:30:51 +03:00
|
|
|
from .messageparse import MessageParseMethods
|
2018-06-09 23:05:06 +03:00
|
|
|
from .users import UserMethods
|
2019-05-03 22:37:27 +03:00
|
|
|
from .. import utils, helpers, hints
|
2018-06-09 23:05:06 +03:00
|
|
|
from ..tl import types, functions, custom
|
|
|
|
|
2019-02-13 11:50:00 +03:00
|
|
|
try:
|
|
|
|
import PIL
|
|
|
|
import PIL.Image
|
|
|
|
except ImportError:
|
|
|
|
PIL = None
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
if typing.TYPE_CHECKING:
|
|
|
|
from .telegramclient import TelegramClient
|
|
|
|
|
|
|
|
|
2018-12-25 19:02:33 +03:00
|
|
|
class _CacheType:
|
|
|
|
"""Like functools.partial but pretends to be the wrapped class."""
|
|
|
|
def __init__(self, cls):
|
|
|
|
self._cls = cls
|
|
|
|
|
|
|
|
def __call__(self, *args, **kwargs):
|
|
|
|
return self._cls(*args, file_reference=b'', **kwargs)
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
return self._cls == other
|
|
|
|
|
|
|
|
|
2019-02-14 14:10:34 +03:00
|
|
|
def _resize_photo_if_needed(
|
2019-02-19 19:48:27 +03:00
|
|
|
file, is_image, width=1280, height=1280, background=(255, 255, 255)):
|
2019-02-14 14:10:34 +03:00
|
|
|
|
2019-02-13 11:58:02 +03:00
|
|
|
# https://github.com/telegramdesktop/tdesktop/blob/12905f0dcb9d513378e7db11989455a1b764ef75/Telegram/SourceFiles/boxes/photo_crop_box.cpp#L254
|
2019-02-13 11:50:00 +03:00
|
|
|
if (not is_image
|
|
|
|
or PIL is None
|
|
|
|
or (isinstance(file, io.IOBase) and not file.seekable())):
|
|
|
|
return file
|
|
|
|
|
|
|
|
if isinstance(file, bytes):
|
|
|
|
file = io.BytesIO(file)
|
|
|
|
|
2019-04-09 08:29:06 +03:00
|
|
|
before = file.tell() if isinstance(file, io.IOBase) else None
|
|
|
|
|
2019-02-13 11:50:00 +03:00
|
|
|
try:
|
2019-03-06 11:14:06 +03:00
|
|
|
# Don't use a `with` block for `image`, or `file` would be closed.
|
|
|
|
# See https://github.com/LonamiWebs/Telethon/issues/1121 for more.
|
|
|
|
image = PIL.Image.open(file)
|
|
|
|
if image.width <= width and image.height <= height:
|
|
|
|
return file
|
|
|
|
|
|
|
|
image.thumbnail((width, height), PIL.Image.ANTIALIAS)
|
|
|
|
|
|
|
|
alpha_index = image.mode.find('A')
|
|
|
|
if alpha_index == -1:
|
|
|
|
# If the image mode doesn't have alpha
|
|
|
|
# channel then don't bother masking it away.
|
|
|
|
result = image
|
|
|
|
else:
|
|
|
|
# We could save the resized image with the original format, but
|
|
|
|
# JPEG often compresses better -> smaller size -> faster upload
|
|
|
|
# We need to mask away the alpha channel ([3]), since otherwise
|
|
|
|
# IOError is raised when trying to save alpha channels in JPEG.
|
|
|
|
result = PIL.Image.new('RGB', image.size, background)
|
|
|
|
result.paste(image, mask=image.split()[alpha_index])
|
|
|
|
|
|
|
|
buffer = io.BytesIO()
|
|
|
|
result.save(buffer, 'JPEG')
|
|
|
|
buffer.seek(0)
|
|
|
|
return buffer
|
2019-02-13 11:50:00 +03:00
|
|
|
|
|
|
|
except IOError:
|
|
|
|
return file
|
|
|
|
finally:
|
|
|
|
if before is not None:
|
|
|
|
file.seek(before, io.SEEK_SET)
|
|
|
|
|
|
|
|
|
2018-07-10 14:11:56 +03:00
|
|
|
class UploadMethods(ButtonMethods, MessageParseMethods, UserMethods):
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
# region Public methods
|
|
|
|
|
|
|
|
async def send_file(
|
2019-05-03 22:37:27 +03:00
|
|
|
self: 'TelegramClient',
|
|
|
|
entity: hints.EntityLike,
|
|
|
|
file: hints.FileLike,
|
|
|
|
*,
|
|
|
|
caption: str = None,
|
|
|
|
force_document: bool = False,
|
|
|
|
progress_callback: hints.ProgressCallback = None,
|
|
|
|
reply_to: hints.MessageIDLike = None,
|
|
|
|
attributes: typing.Sequence[types.TypeDocumentAttribute] = None,
|
|
|
|
thumb: hints.FileLike = None,
|
|
|
|
allow_cache: bool = True,
|
|
|
|
parse_mode: str = (),
|
|
|
|
voice_note: bool = False,
|
|
|
|
video_note: bool = False,
|
|
|
|
buttons: hints.MarkupLike = None,
|
|
|
|
silent: bool = None,
|
|
|
|
supports_streaming: bool = False,
|
|
|
|
**kwargs) -> types.Message:
|
2018-06-09 23:05:06 +03:00
|
|
|
"""
|
|
|
|
Sends a file to the specified entity.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
entity (`entity`):
|
|
|
|
Who will receive the file.
|
|
|
|
|
|
|
|
file (`str` | `bytes` | `file` | `media`):
|
2019-03-10 15:29:34 +03:00
|
|
|
The file to send, which can be one of:
|
|
|
|
|
|
|
|
* A local file path to an in-disk file. The file name
|
|
|
|
will be the path's base name.
|
|
|
|
|
|
|
|
* A `bytes` byte array with the file's data to send
|
|
|
|
(for example, by using ``text.encode('utf-8')``).
|
|
|
|
A default file name will be used.
|
|
|
|
|
|
|
|
* A bytes `io.IOBase` stream over the file to send
|
|
|
|
(for example, by using ``open(file, 'rb')``).
|
|
|
|
Its ``.name`` property will be used for the file name,
|
|
|
|
or a default if it doesn't have one.
|
|
|
|
|
|
|
|
* An external URL to a file over the internet. This will
|
|
|
|
send the file as "external" media, and Telegram is the
|
|
|
|
one that will fetch the media and send it.
|
|
|
|
|
|
|
|
* A Bot API-like ``file_id``. You can convert previously
|
|
|
|
sent media to file IDs for later reusing with
|
|
|
|
`telethon.utils.pack_bot_file_id`.
|
|
|
|
|
|
|
|
* A handle to an existing file (for example, if you sent a
|
|
|
|
message with media before, you can use its ``message.media``
|
|
|
|
as a file here).
|
|
|
|
|
|
|
|
* A handle to an uploaded file (from `upload_file`).
|
|
|
|
|
|
|
|
To send an album, you should provide a list in this parameter.
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
If a list or similar is provided, the files in it will be
|
|
|
|
sent as an album in the order in which they appear, sliced
|
|
|
|
in chunks of 10 if more than 10 are given.
|
|
|
|
|
|
|
|
caption (`str`, optional):
|
2019-03-18 19:30:45 +03:00
|
|
|
Optional caption for the sent media message. When sending an
|
|
|
|
album, the caption may be a list of strings, which will be
|
|
|
|
assigned to the files pairwise.
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
force_document (`bool`, optional):
|
|
|
|
If left to ``False`` and the file is a path that ends with
|
|
|
|
the extension of an image file or a video file, it will be
|
|
|
|
sent as such. Otherwise always as a document.
|
|
|
|
|
|
|
|
progress_callback (`callable`, optional):
|
|
|
|
A callback function accepting two parameters:
|
|
|
|
``(sent bytes, total)``.
|
|
|
|
|
2019-01-12 15:06:14 +03:00
|
|
|
reply_to (`int` | `Message <telethon.tl.custom.message.Message>`):
|
2018-06-09 23:05:06 +03:00
|
|
|
Same as `reply_to` from `send_message`.
|
|
|
|
|
|
|
|
attributes (`list`, optional):
|
|
|
|
Optional attributes that override the inferred ones, like
|
|
|
|
:tl:`DocumentAttributeFilename` and so on.
|
|
|
|
|
|
|
|
thumb (`str` | `bytes` | `file`, optional):
|
2018-07-07 13:01:42 +03:00
|
|
|
Optional JPEG thumbnail (for documents). **Telegram will
|
|
|
|
ignore this parameter** unless you pass a ``.jpg`` file!
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2018-10-06 21:20:11 +03:00
|
|
|
The file must also be small in dimensions and in-disk size.
|
|
|
|
Successful thumbnails were files below 20kb and 200x200px.
|
|
|
|
Width/height and dimensions/size ratios may be important.
|
|
|
|
|
2018-12-25 18:50:11 +03:00
|
|
|
allow_cache (`bool`, optional):
|
|
|
|
Whether to allow using the cached version stored in the
|
|
|
|
database or not. Defaults to ``True`` to avoid re-uploads.
|
|
|
|
Must be ``False`` if you wish to use different attributes
|
|
|
|
or thumb than those that were used when the file was cached.
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
parse_mode (`object`, optional):
|
2019-01-12 15:06:14 +03:00
|
|
|
See the `TelegramClient.parse_mode
|
|
|
|
<telethon.client.messageparse.MessageParseMethods.parse_mode>`
|
|
|
|
property for allowed values. Markdown parsing will be used by
|
|
|
|
default.
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
voice_note (`bool`, optional):
|
|
|
|
If ``True`` the audio will be sent as a voice note.
|
|
|
|
|
2018-12-25 18:50:11 +03:00
|
|
|
Set `allow_cache` to ``False`` if you sent the same file
|
|
|
|
without this setting before for it to work.
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
video_note (`bool`, optional):
|
|
|
|
If ``True`` the video will be sent as a video note,
|
|
|
|
also known as a round video message.
|
|
|
|
|
2018-12-25 18:50:11 +03:00
|
|
|
Set `allow_cache` to ``False`` if you sent the same file
|
|
|
|
without this setting before for it to work.
|
|
|
|
|
2018-10-06 21:20:11 +03:00
|
|
|
buttons (`list`, `custom.Button <telethon.tl.custom.button.Button>`, :tl:`KeyboardButton`):
|
2018-07-10 14:11:56 +03:00
|
|
|
The matrix (list of lists), row list or button to be shown
|
|
|
|
after sending the message. This parameter will only work if
|
|
|
|
you have signed in as a bot. You can also pass your own
|
|
|
|
:tl:`ReplyMarkup` here.
|
|
|
|
|
2018-07-11 11:16:21 +03:00
|
|
|
silent (`bool`, optional):
|
|
|
|
Whether the message should notify people in a broadcast
|
|
|
|
channel or not. Defaults to ``False``, which means it will
|
|
|
|
notify them. Set it to ``True`` to alter this behaviour.
|
|
|
|
|
2019-01-21 21:46:33 +03:00
|
|
|
supports_streaming (`bool`, optional):
|
|
|
|
Whether the sent video supports streaming or not. Note that
|
|
|
|
Telegram only recognizes as streamable some formats like MP4,
|
|
|
|
and others like AVI or MKV will not work. You should convert
|
|
|
|
these to MP4 before sending if you want them to be streamable.
|
|
|
|
Unsupported formats will result in ``VideoContentTypeError``.
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
Notes:
|
|
|
|
If the ``hachoir3`` package (``hachoir`` module) is installed,
|
|
|
|
it will be used to determine metadata from audio and video files.
|
|
|
|
|
2019-02-13 11:58:02 +03:00
|
|
|
If the `pillow` package is installed and you are sending a photo,
|
|
|
|
it will be resized to fit within the maximum dimensions allowed
|
|
|
|
by Telegram to avoid ``errors.PhotoInvalidDimensionsError``. This
|
|
|
|
cannot be done if you are sending :tl:`InputFile`, however.
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
Returns:
|
|
|
|
The `telethon.tl.custom.message.Message` (or messages) containing
|
|
|
|
the sent file, or messages if a list of them was passed.
|
|
|
|
"""
|
2019-02-19 18:41:51 +03:00
|
|
|
# i.e. ``None`` was used
|
|
|
|
if not file:
|
|
|
|
raise TypeError('Cannot use {!r} as file'.format(file))
|
|
|
|
|
2018-12-20 12:50:16 +03:00
|
|
|
if not caption:
|
|
|
|
caption = ''
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
# First check if the user passed an iterable, in which case
|
|
|
|
# we may want to send as an album if all are photo files.
|
|
|
|
if utils.is_list_like(file):
|
|
|
|
# TODO Fix progress_callback
|
|
|
|
images = []
|
|
|
|
if force_document:
|
|
|
|
documents = file
|
|
|
|
else:
|
|
|
|
documents = []
|
|
|
|
for x in file:
|
|
|
|
if utils.is_image(x):
|
|
|
|
images.append(x)
|
|
|
|
else:
|
|
|
|
documents.append(x)
|
|
|
|
|
|
|
|
result = []
|
|
|
|
while images:
|
|
|
|
result += await self._send_album(
|
|
|
|
entity, images[:10], caption=caption,
|
|
|
|
progress_callback=progress_callback, reply_to=reply_to,
|
2018-07-11 11:16:21 +03:00
|
|
|
parse_mode=parse_mode, silent=silent
|
2018-06-09 23:05:06 +03:00
|
|
|
)
|
|
|
|
images = images[10:]
|
|
|
|
|
2018-06-20 21:18:16 +03:00
|
|
|
for x in documents:
|
|
|
|
result.append(await self.send_file(
|
2018-12-25 18:50:11 +03:00
|
|
|
entity, x, allow_cache=allow_cache,
|
2018-06-09 23:05:06 +03:00
|
|
|
caption=caption, force_document=force_document,
|
|
|
|
progress_callback=progress_callback, reply_to=reply_to,
|
|
|
|
attributes=attributes, thumb=thumb, voice_note=voice_note,
|
2018-07-11 11:16:21 +03:00
|
|
|
video_note=video_note, buttons=buttons, silent=silent,
|
2019-01-21 21:46:33 +03:00
|
|
|
supports_streaming=supports_streaming,
|
2018-07-11 11:16:21 +03:00
|
|
|
**kwargs
|
2018-06-20 21:18:16 +03:00
|
|
|
))
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
return result
|
|
|
|
|
|
|
|
entity = await self.get_input_entity(entity)
|
|
|
|
reply_to = utils.get_message_id(reply_to)
|
|
|
|
|
|
|
|
# Not document since it's subject to change.
|
|
|
|
# Needed when a Message is passed to send_message and it has media.
|
|
|
|
if 'entities' in kwargs:
|
|
|
|
msg_entities = kwargs['entities']
|
|
|
|
else:
|
|
|
|
caption, msg_entities =\
|
|
|
|
await self._parse_message_text(caption, parse_mode)
|
|
|
|
|
2019-03-06 11:38:17 +03:00
|
|
|
file_handle, media, image = await self._file_to_media(
|
2018-06-26 17:39:43 +03:00
|
|
|
file, force_document=force_document,
|
|
|
|
progress_callback=progress_callback,
|
2018-12-25 18:50:11 +03:00
|
|
|
attributes=attributes, allow_cache=allow_cache, thumb=thumb,
|
2019-01-21 21:46:33 +03:00
|
|
|
voice_note=voice_note, video_note=video_note,
|
|
|
|
supports_streaming=supports_streaming
|
2018-06-26 17:39:43 +03:00
|
|
|
)
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2019-02-19 18:41:51 +03:00
|
|
|
# e.g. invalid cast from :tl:`MessageMediaWebPage`
|
|
|
|
if not media:
|
|
|
|
raise TypeError('Cannot use {!r} as file'.format(file))
|
|
|
|
|
2018-07-21 14:54:36 +03:00
|
|
|
markup = self.build_reply_markup(buttons)
|
2018-06-09 23:05:06 +03:00
|
|
|
request = functions.messages.SendMediaRequest(
|
|
|
|
entity, media, reply_to_msg_id=reply_to, message=caption,
|
2018-07-11 11:16:21 +03:00
|
|
|
entities=msg_entities, reply_markup=markup, silent=silent
|
2018-06-09 23:05:06 +03:00
|
|
|
)
|
|
|
|
msg = self._get_response_message(request, await self(request), entity)
|
2019-03-06 11:38:17 +03:00
|
|
|
await self._cache_media(msg, file, file_handle, image=image)
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
return msg
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def _send_album(self: 'TelegramClient', entity, files, caption='',
|
2019-01-11 17:52:30 +03:00
|
|
|
progress_callback=None, reply_to=None,
|
|
|
|
parse_mode=(), silent=None):
|
2018-06-09 23:05:06 +03:00
|
|
|
"""Specialized version of .send_file for albums"""
|
2018-12-25 18:50:11 +03:00
|
|
|
# We don't care if the user wants to avoid cache, we will use it
|
|
|
|
# anyway. Why? The cached version will be exactly the same thing
|
|
|
|
# we need to produce right now to send albums (uploadMedia), and
|
|
|
|
# cache only makes a difference for documents where the user may
|
|
|
|
# want the attributes used on them to change.
|
|
|
|
#
|
|
|
|
# In theory documents can be sent inside the albums but they appear
|
|
|
|
# as different messages (not inside the album), and the logic to set
|
|
|
|
# the attributes/avoid cache is already written in .send_file().
|
2018-06-09 23:05:06 +03:00
|
|
|
entity = await self.get_input_entity(entity)
|
|
|
|
if not utils.is_list_like(caption):
|
|
|
|
caption = (caption,)
|
2018-06-20 21:18:16 +03:00
|
|
|
|
|
|
|
captions = []
|
|
|
|
for c in reversed(caption): # Pop from the end (so reverse)
|
|
|
|
captions.append(await self._parse_message_text(c or '', parse_mode))
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
reply_to = utils.get_message_id(reply_to)
|
|
|
|
|
2018-12-25 18:50:11 +03:00
|
|
|
# Need to upload the media first, but only if they're not cached yet
|
2018-06-09 23:05:06 +03:00
|
|
|
media = []
|
|
|
|
for file in files:
|
2019-02-25 20:23:39 +03:00
|
|
|
# Albums want :tl:`InputMedia` which, in theory, includes
|
|
|
|
# :tl:`InputMediaUploadedPhoto`. However using that will
|
|
|
|
# make it `raise MediaInvalidError`, so we need to upload
|
|
|
|
# it as media and then convert that to :tl:`InputMediaPhoto`.
|
2019-03-06 11:38:17 +03:00
|
|
|
fh, fm, _ = await self._file_to_media(file)
|
2019-02-25 20:23:39 +03:00
|
|
|
if isinstance(fm, types.InputMediaUploadedPhoto):
|
2018-06-09 23:05:06 +03:00
|
|
|
r = await self(functions.messages.UploadMediaRequest(
|
2019-02-25 20:23:39 +03:00
|
|
|
entity, media=fm
|
2018-06-09 23:05:06 +03:00
|
|
|
))
|
2019-02-25 20:25:49 +03:00
|
|
|
self.session.cache_file(
|
|
|
|
fh.md5, fh.size, utils.get_input_photo(r.photo))
|
|
|
|
|
|
|
|
fm = utils.get_input_media(r.photo)
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
if captions:
|
|
|
|
caption, msg_entities = captions.pop()
|
|
|
|
else:
|
|
|
|
caption, msg_entities = '', None
|
2018-07-15 12:31:14 +03:00
|
|
|
media.append(types.InputSingleMedia(
|
2019-02-25 20:23:39 +03:00
|
|
|
fm,
|
2018-07-15 12:31:14 +03:00
|
|
|
message=caption,
|
|
|
|
entities=msg_entities
|
|
|
|
))
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
# Now we can construct the multi-media request
|
|
|
|
result = await self(functions.messages.SendMultiMediaRequest(
|
2018-07-11 11:16:21 +03:00
|
|
|
entity, reply_to_msg_id=reply_to, multi_media=media, silent=silent
|
2018-06-09 23:05:06 +03:00
|
|
|
))
|
2019-04-09 15:48:36 +03:00
|
|
|
|
|
|
|
# We never sent a `random_id` for the messages that resulted from
|
|
|
|
# the request so we can't pair them up with the `Updates` that we
|
|
|
|
# get from Telegram. However, the sent messages have a photo and
|
|
|
|
# the photo IDs match with those we did send.
|
|
|
|
#
|
|
|
|
# Updates -> {_: message}
|
|
|
|
messages = self._get_response_message(None, result, entity)
|
|
|
|
# {_: message} -> {photo ID: message}
|
|
|
|
messages = {m.photo.id: m for m in messages.values()}
|
|
|
|
# Sent photo IDs -> messages
|
|
|
|
return [messages[m.media.id.id] for m in media]
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
async def upload_file(
|
2019-05-03 22:37:27 +03:00
|
|
|
self: 'TelegramClient',
|
|
|
|
file: hints.FileLike,
|
|
|
|
*,
|
|
|
|
part_size_kb: float = None,
|
|
|
|
file_name: str = None,
|
|
|
|
use_cache: type = None,
|
|
|
|
progress_callback: hints.ProgressCallback = None) -> types.TypeInputFile:
|
2018-06-09 23:05:06 +03:00
|
|
|
"""
|
|
|
|
Uploads the specified file and returns a handle (an instance of
|
|
|
|
:tl:`InputFile` or :tl:`InputFileBig`, as required) which can be
|
|
|
|
later used before it expires (they are usable during less than a day).
|
|
|
|
|
|
|
|
Uploading a file will simply return a "handle" to the file stored
|
|
|
|
remotely in the Telegram servers, which can be later used on. This
|
|
|
|
will **not** upload the file to your own chat or any chat at all.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
file (`str` | `bytes` | `file`):
|
|
|
|
The path of the file, byte array, or stream that will be sent.
|
|
|
|
Note that if a byte array or a stream is given, a filename
|
|
|
|
or its type won't be inferred, and it will be sent as an
|
|
|
|
"unnamed application/octet-stream".
|
|
|
|
|
|
|
|
part_size_kb (`int`, optional):
|
|
|
|
Chunk size when uploading files. The larger, the less
|
|
|
|
requests will be made (up to 512KB maximum).
|
|
|
|
|
|
|
|
file_name (`str`, optional):
|
|
|
|
The file name which will be used on the resulting InputFile.
|
|
|
|
If not specified, the name will be taken from the ``file``
|
|
|
|
and if this is not a ``str``, it will be ``"unnamed"``.
|
|
|
|
|
2018-12-25 18:50:11 +03:00
|
|
|
use_cache (`type`, optional):
|
|
|
|
The type of cache to use (currently either :tl:`InputDocument`
|
|
|
|
or :tl:`InputPhoto`). If present and the file is small enough
|
|
|
|
to need the MD5, it will be checked against the database,
|
|
|
|
and if a match is found, the upload won't be made. Instead,
|
|
|
|
an instance of type ``use_cache`` will be returned.
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
progress_callback (`callable`, optional):
|
|
|
|
A callback function accepting two parameters:
|
|
|
|
``(sent bytes, total)``.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
:tl:`InputFileBig` if the file size is larger than 10MB,
|
2018-07-28 12:28:02 +03:00
|
|
|
`telethon.tl.custom.inputsizedfile.InputSizedFile`
|
2018-06-09 23:05:06 +03:00
|
|
|
(subclass of :tl:`InputFile`) otherwise.
|
|
|
|
"""
|
|
|
|
if isinstance(file, (types.InputFile, types.InputFileBig)):
|
|
|
|
return file # Already uploaded
|
|
|
|
|
2018-06-21 17:31:03 +03:00
|
|
|
if not file_name and getattr(file, 'name', None):
|
|
|
|
file_name = file.name
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
if isinstance(file, str):
|
|
|
|
file_size = os.path.getsize(file)
|
|
|
|
elif isinstance(file, bytes):
|
|
|
|
file_size = len(file)
|
|
|
|
else:
|
2019-03-06 11:24:50 +03:00
|
|
|
if isinstance(file, io.IOBase) and file.seekable():
|
|
|
|
pos = file.tell()
|
|
|
|
else:
|
|
|
|
pos = None
|
|
|
|
|
|
|
|
# TODO Don't load the entire file in memory always
|
|
|
|
data = file.read()
|
|
|
|
if pos is not None:
|
|
|
|
file.seek(pos)
|
|
|
|
|
|
|
|
file = data
|
2018-06-09 23:05:06 +03:00
|
|
|
file_size = len(file)
|
|
|
|
|
|
|
|
# File will now either be a string or bytes
|
|
|
|
if not part_size_kb:
|
|
|
|
part_size_kb = utils.get_appropriated_part_size(file_size)
|
|
|
|
|
|
|
|
if part_size_kb > 512:
|
|
|
|
raise ValueError('The part size must be less or equal to 512KB')
|
|
|
|
|
|
|
|
part_size = int(part_size_kb * 1024)
|
|
|
|
if part_size % 1024 != 0:
|
|
|
|
raise ValueError(
|
|
|
|
'The part size must be evenly divisible by 1024')
|
|
|
|
|
|
|
|
# Set a default file name if None was specified
|
|
|
|
file_id = helpers.generate_random_long()
|
|
|
|
if not file_name:
|
|
|
|
if isinstance(file, str):
|
|
|
|
file_name = os.path.basename(file)
|
|
|
|
else:
|
|
|
|
file_name = str(file_id)
|
|
|
|
|
2019-02-12 13:33:06 +03:00
|
|
|
# If the file name lacks extension, add it if possible.
|
|
|
|
# Else Telegram complains with `PHOTO_EXT_INVALID_ERROR`
|
|
|
|
# even if the uploaded image is indeed a photo.
|
|
|
|
if not os.path.splitext(file_name)[-1]:
|
|
|
|
file_name += utils._get_extension(file)
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
# Determine whether the file is too big (over 10MB) or not
|
|
|
|
# Telegram does make a distinction between smaller or larger files
|
|
|
|
is_large = file_size > 10 * 1024 * 1024
|
|
|
|
hash_md5 = hashlib.md5()
|
|
|
|
if not is_large:
|
2018-12-25 18:50:11 +03:00
|
|
|
# Calculate the MD5 hash before anything else.
|
|
|
|
# As this needs to be done always for small files,
|
|
|
|
# might as well do it before anything else and
|
|
|
|
# check the cache.
|
2018-06-09 23:05:06 +03:00
|
|
|
if isinstance(file, str):
|
|
|
|
with open(file, 'rb') as stream:
|
|
|
|
file = stream.read()
|
|
|
|
hash_md5.update(file)
|
2018-12-25 18:50:11 +03:00
|
|
|
if use_cache:
|
|
|
|
cached = self.session.get_file(
|
2018-12-25 19:02:33 +03:00
|
|
|
hash_md5.digest(), file_size, cls=_CacheType(use_cache)
|
2018-12-25 18:50:11 +03:00
|
|
|
)
|
|
|
|
if cached:
|
|
|
|
return cached
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
part_count = (file_size + part_size - 1) // part_size
|
2019-01-11 17:52:30 +03:00
|
|
|
self._log[__name__].info('Uploading file of %d bytes in %d chunks of %d',
|
|
|
|
file_size, part_count, part_size)
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
with open(file, 'rb') if isinstance(file, str) else BytesIO(file)\
|
|
|
|
as stream:
|
|
|
|
for part_index in range(part_count):
|
|
|
|
# Read the file by in chunks of size part_size
|
|
|
|
part = stream.read(part_size)
|
|
|
|
|
|
|
|
# The SavePartRequest is different depending on whether
|
|
|
|
# the file is too large or not (over or less than 10MB)
|
|
|
|
if is_large:
|
|
|
|
request = functions.upload.SaveBigFilePartRequest(
|
|
|
|
file_id, part_index, part_count, part)
|
|
|
|
else:
|
|
|
|
request = functions.upload.SaveFilePartRequest(
|
|
|
|
file_id, part_index, part)
|
|
|
|
|
|
|
|
result = await self(request)
|
|
|
|
if result:
|
2019-01-11 17:52:30 +03:00
|
|
|
self._log[__name__].debug('Uploaded %d/%d',
|
|
|
|
part_index + 1, part_count)
|
2018-06-09 23:05:06 +03:00
|
|
|
if progress_callback:
|
|
|
|
progress_callback(stream.tell(), file_size)
|
|
|
|
else:
|
|
|
|
raise RuntimeError(
|
|
|
|
'Failed to upload file part {}.'.format(part_index))
|
|
|
|
|
|
|
|
if is_large:
|
|
|
|
return types.InputFileBig(file_id, part_count, file_name)
|
|
|
|
else:
|
|
|
|
return custom.InputSizedFile(
|
|
|
|
file_id, part_count, file_name, md5=hash_md5, size=file_size
|
|
|
|
)
|
|
|
|
|
|
|
|
# endregion
|
|
|
|
|
|
|
|
async def _file_to_media(
|
|
|
|
self, file, force_document=False,
|
|
|
|
progress_callback=None, attributes=None, thumb=None,
|
2019-01-21 21:46:33 +03:00
|
|
|
allow_cache=True, voice_note=False, video_note=False,
|
2019-05-01 17:02:21 +03:00
|
|
|
supports_streaming=False, mime_type=None, as_image=None):
|
2018-06-09 23:05:06 +03:00
|
|
|
if not file:
|
2019-03-06 11:38:17 +03:00
|
|
|
return None, None, None
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2018-06-16 18:01:20 +03:00
|
|
|
if isinstance(file, pathlib.Path):
|
|
|
|
file = str(file.absolute())
|
|
|
|
|
2019-05-01 17:02:21 +03:00
|
|
|
if as_image is None:
|
|
|
|
as_image = utils.is_image(file) and not force_document
|
2019-02-13 14:33:11 +03:00
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
if not isinstance(file, (str, bytes, io.IOBase)):
|
|
|
|
# The user may pass a Message containing media (or the media,
|
|
|
|
# or anything similar) that should be treated as a file. Try
|
|
|
|
# getting the input media for whatever they passed and send it.
|
2019-02-13 14:33:11 +03:00
|
|
|
#
|
|
|
|
# We pass all attributes since these will be used if the user
|
|
|
|
# passed :tl:`InputFile`, and all information may be relevant.
|
2018-06-09 23:05:06 +03:00
|
|
|
try:
|
2019-02-13 14:33:11 +03:00
|
|
|
return (None, utils.get_input_media(
|
|
|
|
file,
|
|
|
|
is_photo=as_image,
|
|
|
|
attributes=attributes,
|
|
|
|
force_document=force_document,
|
|
|
|
voice_note=voice_note,
|
|
|
|
video_note=video_note,
|
|
|
|
supports_streaming=supports_streaming
|
2019-03-06 11:38:17 +03:00
|
|
|
), as_image)
|
2018-06-09 23:05:06 +03:00
|
|
|
except TypeError:
|
2019-03-06 11:38:17 +03:00
|
|
|
# Can't turn whatever was given into media
|
|
|
|
return None, None, as_image
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2018-06-26 17:39:22 +03:00
|
|
|
media = None
|
2018-08-01 00:35:22 +03:00
|
|
|
file_handle = None
|
2018-12-25 18:50:11 +03:00
|
|
|
use_cache = types.InputPhoto if as_image else types.InputDocument
|
2018-08-06 19:03:42 +03:00
|
|
|
if not isinstance(file, str) or os.path.isfile(file):
|
2018-08-01 00:35:22 +03:00
|
|
|
file_handle = await self.upload_file(
|
2019-02-13 11:50:00 +03:00
|
|
|
_resize_photo_if_needed(file, as_image),
|
|
|
|
progress_callback=progress_callback,
|
2018-12-25 18:50:11 +03:00
|
|
|
use_cache=use_cache if allow_cache else None
|
2018-08-01 00:35:22 +03:00
|
|
|
)
|
|
|
|
elif re.match('https?://', file):
|
2018-06-26 17:39:22 +03:00
|
|
|
if as_image:
|
|
|
|
media = types.InputMediaPhotoExternal(file)
|
|
|
|
elif not force_document and utils.is_gif(file):
|
|
|
|
media = types.InputMediaGifExternal(file, '')
|
|
|
|
else:
|
|
|
|
media = types.InputMediaDocumentExternal(file)
|
|
|
|
else:
|
2018-08-01 00:35:22 +03:00
|
|
|
bot_file = utils.resolve_bot_file_id(file)
|
|
|
|
if bot_file:
|
|
|
|
media = utils.get_input_media(bot_file)
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2018-06-26 17:39:22 +03:00
|
|
|
if media:
|
|
|
|
pass # Already have media, don't check the rest
|
2018-08-06 19:03:42 +03:00
|
|
|
elif not file_handle:
|
|
|
|
raise ValueError(
|
|
|
|
'Failed to convert {} to media. Not an existing file, '
|
|
|
|
'an HTTP URL or a valid bot-API-like file ID'.format(file)
|
|
|
|
)
|
2018-12-25 18:50:11 +03:00
|
|
|
elif isinstance(file_handle, use_cache):
|
|
|
|
# File was cached, so an instance of use_cache was returned
|
|
|
|
if as_image:
|
|
|
|
media = types.InputMediaPhoto(file_handle)
|
|
|
|
else:
|
|
|
|
media = types.InputMediaDocument(file_handle)
|
2018-06-09 23:05:06 +03:00
|
|
|
elif as_image:
|
|
|
|
media = types.InputMediaUploadedPhoto(file_handle)
|
|
|
|
else:
|
2018-07-15 12:31:14 +03:00
|
|
|
attributes, mime_type = utils.get_attributes(
|
|
|
|
file,
|
2019-05-01 17:02:21 +03:00
|
|
|
mime_type=mime_type,
|
2018-07-15 12:31:14 +03:00
|
|
|
attributes=attributes,
|
|
|
|
force_document=force_document,
|
|
|
|
voice_note=voice_note,
|
2019-01-21 21:46:33 +03:00
|
|
|
video_note=video_note,
|
|
|
|
supports_streaming=supports_streaming
|
2018-07-15 12:31:14 +03:00
|
|
|
)
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
input_kw = {}
|
|
|
|
if thumb:
|
2019-01-22 20:52:53 +03:00
|
|
|
if isinstance(thumb, pathlib.Path):
|
|
|
|
thumb = str(thumb.absolute())
|
2018-06-09 23:05:06 +03:00
|
|
|
input_kw['thumb'] = await self.upload_file(thumb)
|
|
|
|
|
|
|
|
media = types.InputMediaUploadedDocument(
|
|
|
|
file=file_handle,
|
|
|
|
mime_type=mime_type,
|
2018-07-15 12:31:14 +03:00
|
|
|
attributes=attributes,
|
2018-06-09 23:05:06 +03:00
|
|
|
**input_kw
|
|
|
|
)
|
2019-03-06 11:38:17 +03:00
|
|
|
return file_handle, media, as_image
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def _cache_media(self: 'TelegramClient', msg, file, file_handle, image):
|
2018-12-25 18:50:11 +03:00
|
|
|
if file and msg and isinstance(file_handle,
|
|
|
|
custom.InputSizedFile):
|
|
|
|
# There was a response message and we didn't use cached
|
|
|
|
# version, so cache whatever we just sent to the database.
|
|
|
|
md5, size = file_handle.md5, file_handle.size
|
2019-03-06 11:38:17 +03:00
|
|
|
if image:
|
2018-12-25 18:50:11 +03:00
|
|
|
to_cache = utils.get_input_photo(msg.media.photo)
|
|
|
|
else:
|
|
|
|
to_cache = utils.get_input_document(msg.media.document)
|
|
|
|
self.session.cache_file(md5, size, to_cache)
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
# endregion
|