Skip to content

Bulk asynchronous downloader for multiple file hosts

Go back to mem storage, clean up.

Jules-WinnfieldX20ad735f412f
diff --git a/main.py b/main.py
index 30d2f6263..78acf32ab 100644
--- a/main.py
+++ b/main.py
@@ -1,5 +1,12 @@
import logging
import asyncio
+import requests
+import os
+import re
+import warnings
+import readchar
+import settings
+import nest_asyncio
# Fixes reactor already installed error
try:
@@ -7,17 +14,10 @@ try:
except:
pass
-import nest_asyncio
from pathlib import Path
from utils.scraper import scrape
from utils.downloaders import get_downloaders
-import settings
from colorama import Fore, Style
-import requests
-import os
-import re
-import warnings
-import readchar
from requests.structures import CaseInsensitiveDict
logging.basicConfig(level=logging.DEBUG, filename='logs.log',
diff --git a/utils/downloaders.py b/utils/downloaders.py
index 3499e18b1..1b7dd8175 100644
--- a/utils/downloaders.py
+++ b/utils/downloaders.py
@@ -136,14 +136,10 @@ class Downloader:
show_progress: bool = True
) -> None:
"""Download the content of given URL"""
- complete_file = (self.folder / self.title / filename)
- temp_file = complete_file.with_suffix(".download")
+ temp_file = (self.folder / self.title / filename).with_suffix(".download")
resume_point = 0
- user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' \
- '(KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36'
-
- headers['Referer'] = referal
- headers['user-agent'] = user_agent
+ downloaded = bytearray()
+ user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36'
if temp_file.exists():
resume_point = temp_file.stat().st_size
@@ -153,24 +149,38 @@ class Downloader:
async with self._semaphore:
await throttle(self, yarl.URL(url))
resp = await session.get(url, headers=headers, raise_for_status=True)
- total = int(resp.headers.get('Content-Length', str(0))) + resume_point
+ total = int(resp.headers.get('Content-Length', 0)) + resume_point
with tqdm(
- total=total, unit_scale=True,
- unit='B', leave=False, initial=resume_point,
- desc=filename, disable=(not show_progress)
+ total=total, unit_scale=True,
+ unit='B', leave=False, initial=resume_point,
+ desc=filename, disable=(not show_progress)
) as progress:
- # FIX THIS SHIT
- async with aiofiles.open(temp_file, mode='ab') as f:
- async for chunk, _ in resp.content.iter_chunks():
- await f.write(chunk)
- progress.update(len(chunk))
- temp_file.rename(complete_file)
- logger.debug("Finished " + filename)
+ async for chunk, _ in resp.content.iter_chunks():
+ downloaded.extend(chunk)
+ progress.update(len(chunk))
+ await self.write_partial(temp_file, downloaded)
except (aiohttp.client_exceptions.ClientPayloadError, aiohttp.client_exceptions.ClientOSError,
aiohttp.client_exceptions.ServerDisconnectedError, asyncio.TimeoutError) as e:
+ await self.write_partial(temp_file, downloaded)
raise FailureException(e)
+ async def write_partial(self, filename: Path, downloaded: bytearray) -> None:
+ """Store partial or full data into file"""
+ async with aiofiles.open(filename, mode='ab') as f:
+ await f.write(downloaded)
+
+ async def rename_file(self, filename: str) -> None:
+ """Rename complete file."""
+ complete_file = (self.folder / self.title / filename)
+ temp_file = complete_file.with_suffix(".download")
+ if complete_file.exists():
+ logger.debug(str(self.folder / self.title / filename) + " Already Exists")
+ await aiofiles.os.remove(temp_file)
+ else:
+ temp_file.rename(complete_file)
+ logger.debug("Finished " + filename)
+
async def download_and_store(
self,
url_object: str,
@@ -196,6 +206,7 @@ class Downloader:
try:
await self.download_file(url, referal=referal, filename=filename, session=session, headers=headers,
show_progress=show_progress)
+ await self.rename_file(filename)
except Exception:
logger.debug(traceback.format_exc())
log(f"\nSkipping {filename}: likely exceeded download attempts\nRe-run program after "