From 9f077e356bfec8becf47ab4637813a548f3a63d4 Mon Sep 17 00:00:00 2001 From: Lonami Exo Date: Mon, 23 Jan 2023 08:48:00 +0100 Subject: [PATCH] Fix downloading vcard and webdoc with Path Closes #4027. --- telethon/client/downloads.py | 38 ++++++++++++++++-------------------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/telethon/client/downloads.py b/telethon/client/downloads.py index 685c61d0..06368428 100644 --- a/telethon/client/downloads.py +++ b/telethon/client/downloads.py @@ -918,22 +918,19 @@ class DownloadMethods: 'END:VCARD\n' ).format(f=first_name, l=last_name, p=phone_number).encode('utf-8') + file = cls._get_proper_filename( + file, 'contact', '.vcard', + possible_names=[first_name, phone_number, last_name] + ) if file is bytes: return result - elif isinstance(file, str): - file = cls._get_proper_filename( - file, 'contact', '.vcard', - possible_names=[first_name, phone_number, last_name] - ) - f = open(file, 'wb') - else: - f = file + f = file if hasattr(file, 'write') else open(file, 'wb') try: f.write(result) finally: # Only close the stream if we opened it - if isinstance(file, str): + if f != file: f.close() return file @@ -950,18 +947,17 @@ class DownloadMethods: ) # TODO Better way to get opened handles of files and auto-close - in_memory = file is bytes - if in_memory: + kind, possible_names = self._get_kind_and_names(web.attributes) + file = self._get_proper_filename( + file, kind, utils.get_extension(web), + possible_names=possible_names + ) + if file is bytes: f = io.BytesIO() - elif isinstance(file, str): - kind, possible_names = cls._get_kind_and_names(web.attributes) - file = cls._get_proper_filename( - file, kind, utils.get_extension(web), - possible_names=possible_names - ) - f = open(file, 'wb') - else: + elif hasattr(file, 'write'): f = file + else: + f = open(file, 'wb') try: async with aiohttp.ClientSession() as session: @@ -974,10 +970,10 @@ class DownloadMethods: break f.write(chunk) finally: - if isinstance(file, str) or file is bytes: + if f != file: f.close() - return f.getvalue() if in_memory else file + return f.getvalue() if file is bytes else file @staticmethod def _get_proper_filename(file, kind, extension,