Fix downloading vcard and webdoc with Path

Closes #4027.
This commit is contained in:
Lonami Exo 2023-01-23 08:48:00 +01:00
parent 1f8b59043b
commit 9f077e356b

View File

@ -918,22 +918,19 @@ class DownloadMethods:
'END:VCARD\n' 'END:VCARD\n'
).format(f=first_name, l=last_name, p=phone_number).encode('utf-8') ).format(f=first_name, l=last_name, p=phone_number).encode('utf-8')
if file is bytes:
return result
elif isinstance(file, str):
file = cls._get_proper_filename( file = cls._get_proper_filename(
file, 'contact', '.vcard', file, 'contact', '.vcard',
possible_names=[first_name, phone_number, last_name] possible_names=[first_name, phone_number, last_name]
) )
f = open(file, 'wb') if file is bytes:
else: return result
f = file f = file if hasattr(file, 'write') else open(file, 'wb')
try: try:
f.write(result) f.write(result)
finally: finally:
# Only close the stream if we opened it # Only close the stream if we opened it
if isinstance(file, str): if f != file:
f.close() f.close()
return file return file
@ -950,18 +947,17 @@ class DownloadMethods:
) )
# TODO Better way to get opened handles of files and auto-close # TODO Better way to get opened handles of files and auto-close
in_memory = file is bytes kind, possible_names = self._get_kind_and_names(web.attributes)
if in_memory: file = self._get_proper_filename(
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), file, kind, utils.get_extension(web),
possible_names=possible_names possible_names=possible_names
) )
f = open(file, 'wb') if file is bytes:
else: f = io.BytesIO()
elif hasattr(file, 'write'):
f = file f = file
else:
f = open(file, 'wb')
try: try:
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
@ -974,10 +970,10 @@ class DownloadMethods:
break break
f.write(chunk) f.write(chunk)
finally: finally:
if isinstance(file, str) or file is bytes: if f != file:
f.close() f.close()
return f.getvalue() if in_memory else file return f.getvalue() if file is bytes else file
@staticmethod @staticmethod
def _get_proper_filename(file, kind, extension, def _get_proper_filename(file, kind, extension,