|
1 |
| -import logging |
2 | 1 | import os
|
3 | 2 | import re
|
4 | 3 | import time
|
5 | 4 | import json
|
| 5 | +import shutil |
| 6 | +import logging |
| 7 | +import tempfile |
6 | 8 | import threading
|
7 | 9 | import concurrent.futures
|
8 | 10 | import requests
|
@@ -609,17 +611,25 @@ def download_from_libgen(self, req_item, link):
|
609 | 611 |
|
610 | 612 | self.general_logger.info(f"Downloading: {os.path.basename(file_path)} - Size: {total_size/1048576:.2f} MB")
|
611 | 613 |
|
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}") |
623 | 633 |
|
624 | 634 | if os.path.exists(file_path):
|
625 | 635 | self.general_logger.info(f"Downloaded: {link_url} to {file_path}")
|
|
0 commit comments