Skip to content

Commit d96d914

Browse files
Download to a temp file and move file on success.
kinda closes #22
1 parent aeca11b commit d96d914

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

src/BookBounty.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
import logging
21
import os
32
import re
43
import time
54
import json
5+
import shutil
6+
import logging
7+
import tempfile
68
import threading
79
import concurrent.futures
810
import requests
@@ -609,17 +611,25 @@ def download_from_libgen(self, req_item, link):
609611

610612
self.general_logger.info(f"Downloading: {os.path.basename(file_path)} - Size: {total_size/1048576:.2f} MB")
611613

612-
with open(file_path, "wb") as f:
613-
for chunk in download_response.iter_content(chunk_size=1024):
614-
if self.libgen_stop_event.is_set():
615-
raise Exception("Cancelled")
616-
f.write(chunk)
617-
downloaded_size += len(chunk)
618-
chunk_counter += 1
619-
620-
if chunk_counter % 100 == 0:
621-
percent_completion = (downloaded_size / total_size) * 100 if total_size > 0 else 0
622-
self.general_logger.info(f"Downloading: {os.path.basename(file_path)} - Progress: {percent_completion:.2f}%")
614+
try:
615+
with tempfile.NamedTemporaryFile(delete=False) as f:
616+
for chunk in download_response.iter_content(chunk_size=1024):
617+
if self.libgen_stop_event.is_set():
618+
raise Exception("Cancelled")
619+
f.write(chunk)
620+
downloaded_size += len(chunk)
621+
chunk_counter += 1
622+
if chunk_counter % 100 == 0:
623+
percent_completion = (downloaded_size / total_size) * 100 if total_size > 0 else 0
624+
self.general_logger.info(f"Downloading: {os.path.basename(file_path)} - Progress: {percent_completion:.2f}%")
625+
626+
shutil.move(f.name, file_path)
627+
628+
except Exception as e:
629+
self.general_logger.error(f"Error downloading to temp file: {str(e)}")
630+
if os.path.exists(f.name):
631+
os.remove(f.name)
632+
self.general_logger.info(f"Removed temp file: {f.name}")
623633

624634
if os.path.exists(file_path):
625635
self.general_logger.info(f"Downloaded: {link_url} to {file_path}")

0 commit comments

Comments
 (0)