From 376909f3565cfc3ea2f556873eb38c806747d207 Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Thu, 30 May 2019 14:56:59 +0200 Subject: [PATCH] Add get_input_media_from_file_id utility method For internal usage --- pyrogram/client/ext/utils.py | 53 ++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/pyrogram/client/ext/utils.py b/pyrogram/client/ext/utils.py index 981752fa..e1959309 100644 --- a/pyrogram/client/ext/utils.py +++ b/pyrogram/client/ext/utils.py @@ -16,8 +16,11 @@ # You should have received a copy of the GNU Lesser General Public License # along with Pyrogram. If not, see . +import struct from base64 import b64decode, b64encode +from typing import Union +from . import BaseClient from ...api import types @@ -82,3 +85,53 @@ def get_offset_date(dialogs): return m.date else: return 0 + + +def get_input_media_from_file_id( + file_id_str: str, + expected_media_type: int = None +) -> Union[types.InputMediaPhoto, types.InputMediaDocument]: + try: + decoded = decode(file_id_str) + except Exception: + raise ValueError("Failed to decode file_id: {}".format(file_id_str)) + else: + media_type = decoded[0] + + if expected_media_type is not None: + if media_type != expected_media_type: + media_type_str = BaseClient.MEDIA_TYPE_ID.get(media_type, None) + expected_media_type_str = BaseClient.MEDIA_TYPE_ID.get(expected_media_type, None) + + raise ValueError( + 'Expected: "{}", got "{}" file_id instead'.format(expected_media_type_str, media_type_str) + ) + + if media_type in (0, 1, 14): + raise ValueError("This file_id can only be used for download: {}".format(file_id_str)) + + if media_type == 2: + unpacked = struct.unpack("