Skip to content

Commit

Permalink
Fix downloading vcard and webdoc with Path
Browse files Browse the repository at this point in the history
Closes #4027.
  • Loading branch information
Lonami committed Jan 23, 2023
1 parent 1f8b590 commit 9f077e3
Showing 1 changed file with 17 additions and 21 deletions.
38 changes: 17 additions & 21 deletions telethon/client/downloads.py
Original file line number Diff line number Diff line change
Expand Up @@ -918,22 +918,19 @@ def _download_contact(cls, mm_contact, file):
'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
Expand All @@ -950,18 +947,17 @@ async def _download_web_document(cls, web, file, progress_callback):
)

# 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:
Expand All @@ -974,10 +970,10 @@ async def _download_web_document(cls, web, file, progress_callback):
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,
Expand Down

0 comments on commit 9f077e3

Please sign in to comment.