utils.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import asyncio
  2. import os
  3. import re
  4. import subprocess
  5. import sys
  6. import webbrowser
  7. from functools import lru_cache
  8. from typing import Awaitable, Callable
  9. import pkg_resources
  10. import httpx
  11. from loguru import logger
  12. @logger.catch
  13. def open_url(url: str):
  14. logger.info(f"Opening {url}...")
  15. if "com.termux" in os.environ.get("PREFIX", ""): # If device is running Termux
  16. try:
  17. subprocess.run(
  18. [
  19. "am",
  20. "start",
  21. "--user",
  22. "0",
  23. "-a",
  24. "android.intent.action.VIEW",
  25. "-d",
  26. url,
  27. ]
  28. )
  29. return
  30. except FileNotFoundError:
  31. pass
  32. webbrowser.open(url, new=2, autoraise=True)
  33. @logger.catch
  34. @lru_cache(maxsize=None)
  35. def retrieve_installed_version() -> str:
  36. package_info = subprocess.run(
  37. [sys.executable, "-m", "pip", "show", "db0mb3r"],
  38. stdout=subprocess.PIPE,
  39. check=True,
  40. )
  41. bytes_version = re.search(br"Version: ([0-9]\.[0-9.]*)", package_info.stdout).group(
  42. 1
  43. )
  44. return bytes_version.decode()
  45. @logger.catch
  46. def check_and_upgrade():
  47. logger.info("Checking for updates")
  48. version = pkg_resources.get_distribution("db0mb3r").version
  49. updates = httpx.get("https://raw.githubusercontent.com/dmitrijkotov634/b0mb3r/master/version")
  50. if updates.status_code == 200:
  51. values = updates.text[1:].split("\r\n", maxsplit=1)
  52. if version == values[0]:
  53. logger.success("No update required")
  54. else:
  55. logger.info("Downloading an update using pip")
  56. subprocess.check_call([sys.executable, "-m", "pip", "install", "db0mb3r==" + values[0]])
  57. logger.success("db0mb3r updated, changes will take effect after restart")
  58. print("\nChanges {}:\n{}\n".format(*values))
  59. os.chdir(os.path.join(pkg_resources.get_distribution("db0mb3r").location, "db0mb3r"))
  60. @logger.catch
  61. async def await_with_callback(
  62. coroutine: Awaitable, callback: Callable, *args, **kwargs
  63. ):
  64. try:
  65. await coroutine
  66. except asyncio.CancelledError:
  67. raise
  68. except Exception:
  69. pass
  70. finally:
  71. callback(*args, **kwargs)