downloader.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """
  2. MIT License
  3. Copyright (c) present TheHamkerCat
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. """
  20. from os.path import abspath as absolute_path
  21. from time import time
  22. import aiofiles
  23. from wbb import aiohttpsession as session
  24. from wbb.core.tasks import add_task
  25. def ensure_status(status_code: int):
  26. if status_code < 200 or status_code >= 300:
  27. raise Exception(f"HttpProcessingError: {status_code}")
  28. async def download_url(
  29. url,
  30. file_path,
  31. chunk_size,
  32. ):
  33. file_path = file_path or url.split("/")[-1][:20]
  34. async with session.get(url) as response:
  35. ensure_status(response.status)
  36. async with aiofiles.open(file_path, "wb") as f:
  37. # Save content in file using aiohttp streamReader.
  38. async for chunk in response.content.iter_chunked(chunk_size):
  39. await f.write(chunk)
  40. return absolute_path(file_path)
  41. async def download(
  42. url: str,
  43. file_path: str = None,
  44. chunk_size: int = 1000000, # 1MB chunk
  45. task_id: int = int(time()),
  46. ):
  47. """
  48. :url: url where the file is located
  49. :file_path: path/to/file
  50. :chunk_size: size of a single chunk
  51. Returns:
  52. (asyncio.Task, task_id), With which you can await
  53. the task, track task progress or cancel it.
  54. """
  55. # Create a task and add it to main tasks dict
  56. # So we can cancel it using .cancelTask
  57. task, task_id = await add_task(
  58. download_url,
  59. "Downloader",
  60. url=url,
  61. file_path=file_path,
  62. chunk_size=chunk_size,
  63. )
  64. return task, task_id