Skip to content

Commit 3940ca9

Browse files
committed
Revamp handling of partial downloads
1 parent 468ebf5 commit 3940ca9

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

pyrogram/client.py

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
import re
2626
import shutil
2727
import sys
28-
import tempfile
2928
from concurrent.futures.thread import ThreadPoolExecutor
3029
from hashlib import sha256
3130
from importlib import import_module
@@ -726,32 +725,29 @@ def load_plugins(self):
726725

727726
async def handle_download(self, packet):
728727
file_id, directory, file_name, in_memory, file_size, progress, progress_args = packet
729-
file = BytesIO() if in_memory else tempfile.NamedTemporaryFile("wb", delete=False)
730728

729+
os.makedirs(directory, exist_ok=True)
730+
temp_file_path = os.path.abspath(re.sub("\\\\", "/", os.path.join(directory, file_name))) + ".temp"
731+
file = BytesIO() if in_memory else open(temp_file_path, "wb")
732+
733+
# noinspection PyBroadException
731734
try:
732735
async for chunk in self.get_file(file_id, file_size, 0, 0, progress, progress_args):
733736
file.write(chunk)
734-
except pyrogram.StopTransmission:
737+
except BaseException:
735738
if not in_memory:
736739
file.close()
737-
os.remove(file.name)
740+
os.remove(temp_file_path)
738741

739742
return None
740-
except asyncio.CancelledError:
741-
if not in_memory:
742-
file.close()
743-
os.remove(file.name)
744-
745-
raise asyncio.CancelledError()
746743
else:
747744
if in_memory:
748745
file.name = file_name
749746
return file
750747
else:
751-
file_path = os.path.abspath(re.sub("\\\\", "/", os.path.join(directory, file_name)))
752-
os.makedirs(directory, exist_ok=True)
753748
file.close()
754-
shutil.move(file.name, file_path)
749+
file_path = os.path.splitext(temp_file_path)[0]
750+
shutil.move(temp_file_path, file_path)
755751
return file_path
756752

757753
async def get_file(

0 commit comments

Comments
 (0)