2020-03-21 14:43:32 +00:00
|
|
|
# Pyrogram - Telegram MTProto API Client Library for Python
|
|
|
|
# Copyright (C) 2017-2020 Dan <https://github.com/delivrance>
|
2018-05-09 11:36:33 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# This file is part of Pyrogram.
|
2018-05-09 11:36:33 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# 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.
|
2018-05-09 11:36:33 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# 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.
|
2018-05-09 11:36:33 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# 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-05-09 11:36:33 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
import asyncio
|
2019-05-29 08:40:37 +00:00
|
|
|
import binascii
|
2019-06-15 21:02:31 +00:00
|
|
|
import os
|
2019-05-29 08:40:37 +00:00
|
|
|
import struct
|
2019-06-15 21:02:31 +00:00
|
|
|
import time
|
|
|
|
from datetime import datetime
|
2018-12-19 13:50:23 +00:00
|
|
|
from typing import Union
|
2018-05-09 11:36:33 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
from pyrogram import types
|
|
|
|
from pyrogram import utils
|
2019-05-29 08:40:37 +00:00
|
|
|
from pyrogram.errors import FileIdInvalid
|
2020-08-22 06:05:05 +00:00
|
|
|
from pyrogram.scaffold import Scaffold
|
2018-05-09 11:36:33 +00:00
|
|
|
|
2019-06-15 21:02:31 +00:00
|
|
|
DEFAULT_DOWNLOAD_DIR = "downloads/"
|
|
|
|
|
2018-05-09 11:36:33 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
class FileData:
|
|
|
|
def __init__(
|
|
|
|
self, *, media_type: int = None, dc_id: int = None, document_id: int = None, access_hash: int = None,
|
|
|
|
thumb_size: str = None, peer_id: int = None, peer_type: str = None, peer_access_hash: int = None,
|
|
|
|
volume_id: int = None, local_id: int = None, is_big: bool = None, file_size: int = None, mime_type: str = None,
|
|
|
|
file_name: str = None, date: int = None, file_ref: str = None
|
|
|
|
):
|
|
|
|
self.media_type = media_type
|
|
|
|
self.dc_id = dc_id
|
|
|
|
self.document_id = document_id
|
|
|
|
self.access_hash = access_hash
|
|
|
|
self.thumb_size = thumb_size
|
|
|
|
self.peer_id = peer_id
|
|
|
|
self.peer_type = peer_type
|
|
|
|
self.peer_access_hash = peer_access_hash
|
|
|
|
self.volume_id = volume_id
|
|
|
|
self.local_id = local_id
|
|
|
|
self.is_big = is_big
|
|
|
|
self.file_size = file_size
|
|
|
|
self.mime_type = mime_type
|
|
|
|
self.file_name = file_name
|
|
|
|
self.date = date
|
|
|
|
self.file_ref = file_ref
|
|
|
|
|
|
|
|
|
|
|
|
class DownloadMedia(Scaffold):
|
2020-08-21 05:28:27 +00:00
|
|
|
async def download_media(
|
2019-03-16 18:23:23 +00:00
|
|
|
self,
|
2020-08-22 06:05:05 +00:00
|
|
|
message: Union["types.Message", str],
|
2019-09-21 20:13:02 +00:00
|
|
|
file_ref: str = None,
|
2019-06-15 21:02:31 +00:00
|
|
|
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]:
|
2019-05-12 17:49:06 +00:00
|
|
|
"""Download the media from a message.
|
2018-05-09 11:36:33 +00:00
|
|
|
|
2019-05-09 02:28:46 +00:00
|
|
|
Parameters:
|
2020-08-22 06:05:05 +00:00
|
|
|
message (:obj:`~pyrogram.types.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.
|
|
|
|
|
2019-09-21 20:13:02 +00:00
|
|
|
file_ref (``str``, *optional*):
|
2019-09-21 19:12:11 +00:00
|
|
|
A valid file reference obtained by a recently fetched media message.
|
2019-09-21 20:13:02 +00:00
|
|
|
To be used in combination with a file id in case a file reference is needed.
|
2019-09-21 19:12:11 +00:00
|
|
|
|
2018-05-09 11:36:33 +00:00
|
|
|
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
|
|
|
|
2018-05-12 09:21:02 +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:
|
2019-05-17 11:44:44 +00:00
|
|
|
``str`` | ``None``: On success, the absolute path of the downloaded file is returned, otherwise, in case
|
2020-08-22 06:05:05 +00:00
|
|
|
the download failed or was deliberately stopped with :meth:`~pyrogram.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
|
2020-07-27 13:12:24 +00:00
|
|
|
app.download_media("CAADBAADzg4AAvLQYAEz_x2EOgdRwBYE")
|
2020-03-30 12:39:16 +00:00
|
|
|
|
|
|
|
# Keep track of the progress while downloading
|
|
|
|
def progress(current, total):
|
2020-08-22 06:05:05 +00:00
|
|
|
print(f"{current * 100 / total:.1f}%")
|
2020-03-30 12:39:16 +00:00
|
|
|
|
|
|
|
app.download_media(message, progress=progress)
|
2018-05-09 11:36:33 +00:00
|
|
|
"""
|
2018-07-11 22:24:57 +00:00
|
|
|
error_message = "This message doesn't contain any downloadable media"
|
2019-05-29 08:40:37 +00:00
|
|
|
available_media = ("audio", "document", "photo", "sticker", "animation", "video", "voice", "video_note")
|
|
|
|
|
2019-06-11 18:36:09 +00:00
|
|
|
media_file_name = None
|
2019-05-29 08:40:37 +00:00
|
|
|
file_size = None
|
|
|
|
mime_type = None
|
|
|
|
date = None
|
2018-07-11 22:24:57 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
if isinstance(message, types.Message):
|
2019-05-29 08:40:37 +00:00
|
|
|
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:
|
2018-07-11 22:24:57 +00:00
|
|
|
raise ValueError(error_message)
|
2019-05-29 08:40:37 +00:00
|
|
|
else:
|
|
|
|
media = message
|
|
|
|
|
|
|
|
if isinstance(media, str):
|
|
|
|
file_id_str = media
|
|
|
|
else:
|
|
|
|
file_id_str = media.file_id
|
2019-06-11 18:36:09 +00:00
|
|
|
media_file_name = getattr(media, "file_name", "")
|
2019-05-29 08:40:37 +00:00
|
|
|
file_size = getattr(media, "file_size", None)
|
|
|
|
mime_type = getattr(media, "mime_type", None)
|
|
|
|
date = getattr(media, "date", None)
|
2019-09-21 19:12:11 +00:00
|
|
|
file_ref = getattr(media, "file_ref", None)
|
2019-05-29 08:40:37 +00:00
|
|
|
|
2019-06-07 16:48:34 +00:00
|
|
|
data = FileData(
|
2019-06-11 18:36:09 +00:00
|
|
|
file_name=media_file_name,
|
2019-05-29 08:40:37 +00:00
|
|
|
file_size=file_size,
|
|
|
|
mime_type=mime_type,
|
2019-09-21 19:12:11 +00:00
|
|
|
date=date,
|
2019-09-21 20:13:02 +00:00
|
|
|
file_ref=file_ref
|
2019-05-29 08:40:37 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
def get_existing_attributes() -> dict:
|
2019-06-07 16:48:34 +00:00
|
|
|
return dict(filter(lambda x: x[1] is not None, data.__dict__.items()))
|
2019-05-29 08:40:37 +00:00
|
|
|
|
|
|
|
try:
|
2019-09-21 20:17:42 +00:00
|
|
|
decoded = utils.decode_file_id(file_id_str)
|
2019-05-29 08:40:37 +00:00
|
|
|
media_type = decoded[0]
|
|
|
|
|
|
|
|
if media_type == 1:
|
2019-08-02 00:33:52 +00:00
|
|
|
unpacked = struct.unpack("<iiqqqiiiqi", decoded)
|
2019-10-19 14:24:23 +00:00
|
|
|
dc_id, photo_id, _, volume_id, size_type, peer_id, x, peer_access_hash, local_id = unpacked[1:]
|
|
|
|
|
|
|
|
if x == 0:
|
|
|
|
peer_type = "user"
|
|
|
|
elif x == -1:
|
|
|
|
peer_id = -peer_id
|
|
|
|
peer_type = "chat"
|
|
|
|
else:
|
|
|
|
peer_id = utils.get_channel_id(peer_id - 1000727379968)
|
|
|
|
peer_type = "channel"
|
2019-05-29 08:40:37 +00:00
|
|
|
|
2019-06-07 16:48:34 +00:00
|
|
|
data = FileData(
|
2019-05-29 08:40:37 +00:00
|
|
|
**get_existing_attributes(),
|
|
|
|
media_type=media_type,
|
|
|
|
dc_id=dc_id,
|
|
|
|
peer_id=peer_id,
|
2019-10-19 14:24:23 +00:00
|
|
|
peer_type=peer_type,
|
2019-08-02 00:33:52 +00:00
|
|
|
peer_access_hash=peer_access_hash,
|
2019-05-29 08:40:37 +00:00
|
|
|
volume_id=volume_id,
|
|
|
|
local_id=local_id,
|
2019-08-02 00:33:52 +00:00
|
|
|
is_big=size_type == 3
|
2019-05-29 08:40:37 +00:00
|
|
|
)
|
|
|
|
elif media_type in (0, 2, 14):
|
2019-08-02 00:33:52 +00:00
|
|
|
unpacked = struct.unpack("<iiqqqiiii", decoded)
|
|
|
|
dc_id, document_id, access_hash, volume_id, _, _, thumb_size, local_id = unpacked[1:]
|
2019-05-29 08:40:37 +00:00
|
|
|
|
2019-06-07 16:48:34 +00:00
|
|
|
data = FileData(
|
2019-05-29 08:40:37 +00:00
|
|
|
**get_existing_attributes(),
|
|
|
|
media_type=media_type,
|
|
|
|
dc_id=dc_id,
|
2019-06-07 16:48:34 +00:00
|
|
|
document_id=document_id,
|
2019-05-29 08:40:37 +00:00
|
|
|
access_hash=access_hash,
|
2019-08-02 00:33:52 +00:00
|
|
|
thumb_size=chr(thumb_size)
|
2019-05-29 08:40:37 +00:00
|
|
|
)
|
|
|
|
elif media_type in (3, 4, 5, 8, 9, 10, 13):
|
|
|
|
unpacked = struct.unpack("<iiqq", decoded)
|
2019-06-07 16:48:34 +00:00
|
|
|
dc_id, document_id, access_hash = unpacked[1:]
|
2019-05-29 08:40:37 +00:00
|
|
|
|
2019-06-07 16:48:34 +00:00
|
|
|
data = FileData(
|
2019-05-29 08:40:37 +00:00
|
|
|
**get_existing_attributes(),
|
|
|
|
media_type=media_type,
|
|
|
|
dc_id=dc_id,
|
2019-06-07 16:48:34 +00:00
|
|
|
document_id=document_id,
|
2019-05-29 08:40:37 +00:00
|
|
|
access_hash=access_hash
|
2018-07-01 17:43:43 +00:00
|
|
|
)
|
|
|
|
else:
|
2020-08-22 06:05:05 +00:00
|
|
|
raise ValueError(f"Unknown media type: {file_id_str}")
|
2019-05-29 08:40:37 +00:00
|
|
|
except (AssertionError, binascii.Error, struct.error):
|
|
|
|
raise FileIdInvalid from None
|
2018-05-09 11:36:33 +00:00
|
|
|
|
2019-06-15 21:02:31 +00:00
|
|
|
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
|
|
|
|
)
|
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
downloader = self.handle_download((data, directory, file_name, progress, progress_args))
|
2018-05-09 11:36:33 +00:00
|
|
|
|
|
|
|
if block:
|
2020-08-22 06:05:05 +00:00
|
|
|
return await downloader
|
|
|
|
else:
|
|
|
|
asyncio.get_event_loop().create_task(downloader)
|