__init__.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import aiofiles
  2. import aiohttp
  3. import hashlib
  4. import config
  5. import json
  6. import os
  7. from types import SimpleNamespace
  8. async def move(src, dst):
  9. async with aiofiles.open(src, "rb") as f:
  10. content = await f.read()
  11. async with aiofiles.open(dst, "wb") as f:
  12. await f.write(content)
  13. if hasattr(config, "delete"):
  14. try:
  15. os.remove(src)
  16. except:
  17. pass
  18. def hash(string: str):
  19. return hashlib.md5(string.encode("utf-8")).hexdigest()
  20. async def download_image(url: str):
  21. extension = "." + url.split(".")[-1]
  22. filename = hash(url) + extension
  23. dst = config.tmp_folder / filename
  24. if dst.exists():
  25. return dst
  26. session = aiohttp.ClientSession()
  27. async with session.get(url) as res:
  28. content = await res.read()
  29. await session.close()
  30. # Check everything went well
  31. if res.status != 200:
  32. print(f"Download failed: {res.status}")
  33. return
  34. async with aiofiles.open(dst, "+wb") as f:
  35. await f.write(content)
  36. return dst
  37. class Namespace(SimpleNamespace):
  38. def __contains__(self, key):
  39. return hasattr(self, key)
  40. def parse_json(text: str):
  41. return json.loads(text, object_hook=lambda d: Namespace(**d))
  42. def add_zeros(string: str, length: int):
  43. string = str(string)
  44. return "0" * (length - len(string)) + string