downloader.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from inspect import iscoroutinefunction
  2. from os.path import abspath as absolute_path
  3. from time import time
  4. import aiofiles
  5. from wbb import aiohttpsession as session
  6. from wbb.modules.userbot import add_task, rm_task
  7. def ensure_status(status_code: int):
  8. if status_code < 200 or status_code >= 300:
  9. raise Exception(f"HttpProcessingError: {status_code}")
  10. async def download_url(
  11. url,
  12. file_path,
  13. chunk_size,
  14. ):
  15. file_path = file_path or url.split("/")[-1][:20]
  16. async with session.get(url) as response:
  17. ensure_status(response.status)
  18. async with aiofiles.open(file_path, "wb") as f:
  19. # Save content in file using aiohttp streamReader.
  20. async for chunk in response.content.iter_chunked(
  21. chunk_size
  22. ):
  23. await f.write(chunk)
  24. return absolute_path(file_path)
  25. async def download(
  26. url: str,
  27. file_path: str = None,
  28. chunk_size: int = 1000000, # 1MB chunk
  29. task_id: int = int(time()),
  30. ):
  31. """
  32. :url: url where the file is located
  33. :file_path: path/to/file
  34. :chunk_size: size of a single chunk
  35. """
  36. # Create a task and add it to main tasks dict
  37. # So we can cancel it using .cancelTask
  38. task = await add_task(
  39. download_url,
  40. task_id,
  41. "Downloader",
  42. url=url,
  43. file_path=file_path,
  44. chunk_size=chunk_size,
  45. )
  46. await task
  47. await rm_task(task_id)
  48. return task.result()