user_download.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from __future__ import annotations
  2. import asyncio
  3. import time
  4. from pathlib import Path
  5. from typing import TYPE_CHECKING, Any, List, Optional, Union
  6. import httpx
  7. from .. import background_tasks
  8. if TYPE_CHECKING:
  9. from .user import User
  10. class UserDownload:
  11. def __init__(self, user: User) -> None:
  12. self.http_responses: List[httpx.Response] = []
  13. self.user = user
  14. def __call__(self, src: Union[str, Path, bytes], filename: Optional[str] = None, media_type: str = '') -> Any:
  15. background_tasks.create(self._get(src))
  16. async def _get(self, src: Union[str, Path, bytes]) -> None:
  17. if isinstance(src, bytes):
  18. await asyncio.sleep(0)
  19. response = httpx.Response(httpx.codes.OK, content=src)
  20. else:
  21. response = await self.user.http_client.get(str(src))
  22. self.http_responses.append(response)
  23. async def next(self, *, timeout: float = 1.0) -> httpx.Response:
  24. """Wait for a new download to happen.
  25. :param timeout: the maximum time to wait (default: 1.0)
  26. :returns: the HTTP response
  27. """
  28. assert self.user.client
  29. downloads = len(self.http_responses)
  30. deadline = time.time() + timeout
  31. while len(self.http_responses) < downloads + 1:
  32. await asyncio.sleep(0.1)
  33. if time.time() > deadline:
  34. raise TimeoutError('Download did not happen')
  35. return self.http_responses[-1]