MTPyroger/pyrogram/client/methods/messages/download_media.py

226 lines
8.6 KiB
Python
Raw Normal View History

2018-05-09 11:36:33 +00:00
# Pyrogram - Telegram MTProto API Client Library for Python
2019-01-01 11:36:16 +00:00
# Copyright (C) 2017-2019 Dan Tès <https://github.com/delivrance>
2018-05-09 11:36:33 +00:00
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
2018-06-18 19:30:13 +00:00
import asyncio
import binascii
import os
import struct
import time
from datetime import datetime
2018-05-09 11:36:33 +00:00
from threading import Event
from typing import Union
2018-05-09 11:36:33 +00:00
import pyrogram
from pyrogram.client.ext import BaseClient, FileData, utils
from pyrogram.errors import FileIdInvalid
2018-05-09 11:36:33 +00:00
DEFAULT_DOWNLOAD_DIR = "downloads/"
2018-05-09 11:36:33 +00:00
class DownloadMedia(BaseClient):
Merge branch 'develop' into asyncio # Conflicts: # pyrogram/__init__.py # pyrogram/client/client.py # pyrogram/client/methods/bots/answer_callback_query.py # pyrogram/client/methods/bots/get_game_high_scores.py # pyrogram/client/methods/bots/get_inline_bot_results.py # pyrogram/client/methods/bots/request_callback_answer.py # pyrogram/client/methods/bots/send_game.py # pyrogram/client/methods/bots/send_inline_bot_result.py # pyrogram/client/methods/bots/set_game_score.py # pyrogram/client/methods/chats/delete_chat_photo.py # pyrogram/client/methods/chats/export_chat_invite_link.py # pyrogram/client/methods/chats/get_chat.py # pyrogram/client/methods/chats/get_chat_member.py # pyrogram/client/methods/chats/get_chat_members.py # pyrogram/client/methods/chats/get_chat_members_count.py # pyrogram/client/methods/chats/get_dialogs.py # pyrogram/client/methods/chats/iter_chat_members.py # pyrogram/client/methods/chats/iter_dialogs.py # pyrogram/client/methods/chats/join_chat.py # pyrogram/client/methods/chats/kick_chat_member.py # pyrogram/client/methods/chats/leave_chat.py # pyrogram/client/methods/chats/pin_chat_message.py # pyrogram/client/methods/chats/promote_chat_member.py # pyrogram/client/methods/chats/restrict_chat_member.py # pyrogram/client/methods/chats/set_chat_description.py # pyrogram/client/methods/chats/set_chat_photo.py # pyrogram/client/methods/chats/set_chat_title.py # pyrogram/client/methods/chats/unban_chat_member.py # pyrogram/client/methods/chats/unpin_chat_message.py # pyrogram/client/methods/contacts/add_contacts.py # pyrogram/client/methods/contacts/delete_contacts.py # pyrogram/client/methods/contacts/get_contacts.py # pyrogram/client/methods/messages/delete_messages.py # pyrogram/client/methods/messages/download_media.py # pyrogram/client/methods/messages/edit_message_caption.py # pyrogram/client/methods/messages/edit_message_media.py # pyrogram/client/methods/messages/edit_message_reply_markup.py # pyrogram/client/methods/messages/edit_message_text.py # pyrogram/client/methods/messages/forward_messages.py # pyrogram/client/methods/messages/get_history.py # pyrogram/client/methods/messages/get_messages.py # pyrogram/client/methods/messages/iter_history.py # pyrogram/client/methods/messages/send_animation.py # pyrogram/client/methods/messages/send_audio.py # pyrogram/client/methods/messages/send_cached_media.py # pyrogram/client/methods/messages/send_chat_action.py # pyrogram/client/methods/messages/send_contact.py # pyrogram/client/methods/messages/send_document.py # pyrogram/client/methods/messages/send_location.py # pyrogram/client/methods/messages/send_media_group.py # pyrogram/client/methods/messages/send_message.py # pyrogram/client/methods/messages/send_photo.py # pyrogram/client/methods/messages/send_sticker.py # pyrogram/client/methods/messages/send_venue.py # pyrogram/client/methods/messages/send_video.py # pyrogram/client/methods/messages/send_video_note.py # pyrogram/client/methods/messages/send_voice.py # pyrogram/client/methods/password/change_cloud_password.py # pyrogram/client/methods/password/enable_cloud_password.py # pyrogram/client/methods/password/remove_cloud_password.py # pyrogram/client/methods/users/delete_user_profile_photos.py # pyrogram/client/methods/users/get_user_profile_photos.py # pyrogram/client/methods/users/get_users.py # pyrogram/session/auth.py # pyrogram/session/session.py
2019-03-16 18:49:01 +00:00
async def download_media(
2019-03-16 18:23:23 +00:00
self,
message: Union["pyrogram.Message", str],
file_name: str = DEFAULT_DOWNLOAD_DIR,
2019-03-16 18:23:23 +00:00
block: bool = True,
progress: callable = None,
progress_args: tuple = ()
) -> Union[str, None]:
"""Download the media from a message.
2018-05-09 11:36:33 +00:00
Parameters:
message (:obj:`Message` | ``str``):
2018-05-09 11:36:33 +00:00
Pass a Message containing the media, the media itself (message.audio, message.video, ...) or
the file id as string.
file_name (``str``, *optional*):
A custom *file_name* to be used instead of the one provided by Telegram.
By default, all files are downloaded in the *downloads* folder in your working directory.
You can also specify a path for downloading files in a custom location: paths that end with "/"
are considered directories. All non-existent folders will be created automatically.
block (``bool``, *optional*):
Blocks the code execution until the file has been downloaded.
Defaults to True.
2019-07-25 09:22:14 +00:00
progress (``callable``, *optional*):
Pass a callback function to view the file transmission progress.
The function must take *(current, total)* as positional arguments (look at Other Parameters below for a
detailed description) and will be called back each time a new file chunk has been successfully
transmitted.
2018-05-09 11:36:33 +00:00
2019-07-25 09:22:14 +00:00
progress_args (``tuple``, *optional*):
Extra custom arguments for the progress callback function.
You can pass anything you need to be available in the progress callback scope; for example, a Message
object or a Client instance in order to edit the message with the updated progress status.
2018-05-09 11:36:33 +00:00
Other Parameters:
current (``int``):
2019-07-25 09:22:14 +00:00
The amount of bytes transmitted so far.
2018-05-09 11:36:33 +00:00
total (``int``):
2019-07-25 09:22:14 +00:00
The total size of the file.
2018-05-09 11:36:33 +00:00
*args (``tuple``, *optional*):
2018-05-09 11:36:33 +00:00
Extra custom arguments as defined in the *progress_args* parameter.
You can either keep *\*args* or add every single extra argument in your function signature.
Returns:
``str`` | ``None``: On success, the absolute path of the downloaded file is returned, otherwise, in case
2019-05-30 13:23:43 +00:00
the download failed or was deliberately stopped with :meth:`~Client.stop_transmission`, None is returned.
2018-05-09 11:36:33 +00:00
Raises:
2019-07-09 17:03:15 +00:00
ValueError: if the message doesn't contain any downloadable media
2019-07-25 09:22:14 +00:00
Example:
.. code-block:: python
# Download from Message
app.download_media(message)
# Download from file id
app.download_media("CAADBAADyg4AAvLQYAEYD4F7vcZ43AI")
2018-05-09 11:36:33 +00:00
"""
error_message = "This message doesn't contain any downloadable media"
available_media = ("audio", "document", "photo", "sticker", "animation", "video", "voice", "video_note")
media_file_name = None
file_size = None
mime_type = None
date = None
if isinstance(message, pyrogram.Message):
for kind in available_media:
media = getattr(message, kind, None)
if media is not None:
break
2018-05-09 11:36:33 +00:00
else:
raise ValueError(error_message)
else:
media = message
if isinstance(media, str):
file_id_str = media
else:
file_id_str = media.file_id
media_file_name = getattr(media, "file_name", "")
file_size = getattr(media, "file_size", None)
mime_type = getattr(media, "mime_type", None)
date = getattr(media, "date", None)
data = FileData(
file_name=media_file_name,
file_size=file_size,
mime_type=mime_type,
date=date
)
def get_existing_attributes() -> dict:
return dict(filter(lambda x: x[1] is not None, data.__dict__.items()))
try:
decoded = utils.decode(file_id_str)
media_type = decoded[0]
if media_type == 1:
unpacked = struct.unpack("<iiqqqiiiqi", decoded)
dc_id, photo_id, _, volume_id, size_type, peer_id, _, peer_access_hash, local_id = unpacked[1:]
data = FileData(
**get_existing_attributes(),
media_type=media_type,
dc_id=dc_id,
peer_id=peer_id,
peer_access_hash=peer_access_hash,
volume_id=volume_id,
local_id=local_id,
is_big=size_type == 3
)
elif media_type in (0, 2, 14):
unpacked = struct.unpack("<iiqqqiiii", decoded)
dc_id, document_id, access_hash, volume_id, _, _, thumb_size, local_id = unpacked[1:]
data = FileData(
**get_existing_attributes(),
media_type=media_type,
dc_id=dc_id,
document_id=document_id,
access_hash=access_hash,
thumb_size=chr(thumb_size)
)
elif media_type in (3, 4, 5, 8, 9, 10, 13):
unpacked = struct.unpack("<iiqq", decoded)
dc_id, document_id, access_hash = unpacked[1:]
data = FileData(
**get_existing_attributes(),
media_type=media_type,
dc_id=dc_id,
document_id=document_id,
access_hash=access_hash
2018-07-01 17:43:43 +00:00
)
else:
raise ValueError("Unknown media type: {}".format(file_id_str))
except (AssertionError, binascii.Error, struct.error):
raise FileIdInvalid from None
2018-05-09 11:36:33 +00:00
2018-06-18 19:30:13 +00:00
done = asyncio.Event()
2018-05-09 11:36:33 +00:00
path = [None]
directory, file_name = os.path.split(file_name)
file_name = file_name or data.file_name or ""
if not os.path.isabs(file_name):
directory = self.PARENT_DIR / (directory or DEFAULT_DOWNLOAD_DIR)
media_type_str = self.MEDIA_TYPE_ID[data.media_type]
if not file_name:
guessed_extension = self.guess_extension(data.mime_type)
if data.media_type in (0, 1, 2, 14):
extension = ".jpg"
elif data.media_type == 3:
extension = guessed_extension or ".ogg"
elif data.media_type in (4, 10, 13):
extension = guessed_extension or ".mp4"
elif data.media_type == 5:
extension = guessed_extension or ".zip"
elif data.media_type == 8:
extension = guessed_extension or ".webp"
elif data.media_type == 9:
extension = guessed_extension or ".mp3"
else:
extension = ".unknown"
file_name = "{}_{}_{}{}".format(
media_type_str,
datetime.fromtimestamp(data.date or time.time()).strftime("%Y-%m-%d_%H-%M-%S"),
self.rnd_id(),
extension
)
# Cast to string because Path objects aren't supported by Python 3.5
2019-07-29 22:06:06 +00:00
self.download_queue.put_nowait((data, str(directory), str(file_name), done, progress, progress_args, path))
2018-05-09 11:36:33 +00:00
if block:
2018-06-18 19:30:13 +00:00
await done.wait()
2018-05-09 11:36:33 +00:00
return path[0]