functions.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. """
  2. MIT License
  3. Copyright (c) 2021 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. import codecs
  21. import pickle
  22. from asyncio import gather, get_running_loop
  23. from math import atan2, cos, radians, sin, sqrt
  24. from random import randint
  25. import aiofiles
  26. import aiohttp
  27. import speedtest
  28. from carbonnow import Carbon
  29. from PIL import Image, ImageDraw, ImageFilter, ImageFont
  30. from wget import download
  31. from wbb.utils import aiodownloader
  32. from wbb.utils.fetch import fetch
  33. """
  34. Just import 'downloader' anywhere and do downloader.download() to
  35. download file from a given url
  36. """
  37. downloader = aiodownloader.Handler()
  38. # Another downloader, but with wget
  39. async def download_url(url: str):
  40. loop = get_running_loop()
  41. file = await loop.run_in_executor(None, download, url)
  42. return file
  43. def generate_captcha():
  44. # Generate one letter
  45. def gen_letter():
  46. return chr(randint(65, 90))
  47. def rndColor():
  48. return (randint(64, 255), randint(64, 255), randint(64, 255))
  49. def rndColor2():
  50. return (randint(32, 127), randint(32, 127), randint(32, 127))
  51. # Generate a 4 letter word
  52. def gen_wrong_answer():
  53. word = ""
  54. for _ in range(4):
  55. word += gen_letter()
  56. return word
  57. # Generate 8 wrong captcha answers
  58. wrong_answers = []
  59. for _ in range(8):
  60. wrong_answers.append(gen_wrong_answer())
  61. width = 80 * 4
  62. height = 100
  63. correct_answer = ""
  64. font = ImageFont.truetype("assets/arial.ttf", 55)
  65. file = f"assets/{randint(1000, 9999)}.jpg"
  66. image = Image.new("RGB", (width, height), (255, 255, 255))
  67. draw = ImageDraw.Draw(image)
  68. # Draw random points on image
  69. for x in range(width):
  70. for y in range(height):
  71. draw.point((x, y), fill=rndColor())
  72. for t in range(4):
  73. letter = gen_letter()
  74. correct_answer += letter
  75. draw.text((60 * t + 50, 15), letter, font=font, fill=rndColor2())
  76. image = image.filter(ImageFilter.BLUR)
  77. image.save(file, "jpeg")
  78. return [file, correct_answer, wrong_answers]
  79. async def test_speedtest():
  80. def speed_convert(size):
  81. power = 2 ** 10
  82. zero = 0
  83. units = {0: "", 1: "Kb/s", 2: "Mb/s", 3: "Gb/s", 4: "Tb/s"}
  84. while size > power:
  85. size /= power
  86. zero += 1
  87. return f"{round(size, 2)} {units[zero]}"
  88. speed = speedtest.Speedtest()
  89. info = speed.get_best_server()
  90. download = speed.download()
  91. upload = speed.upload()
  92. return [speed_convert(download), speed_convert(upload), info]
  93. async def file_size_from_url(url: str) -> int:
  94. async with aiohttp.ClientSession() as session:
  95. async with session.head(url) as resp:
  96. size = int(resp.headers["content-length"])
  97. return size
  98. async def get_http_status_code(url: str) -> int:
  99. async with aiohttp.ClientSession() as session:
  100. async with session.head(url) as resp:
  101. return resp.status
  102. async def make_carbon(code):
  103. carbon = Carbon(code=code)
  104. image = await carbon.save(str(randint(1000, 10000)))
  105. return image
  106. async def transfer_sh(file):
  107. async with aiofiles.open(file, "rb") as f:
  108. params = {file: await f.read()}
  109. async with aiohttp.ClientSession() as session:
  110. async with session.post("https://transfer.sh/", data=params) as resp:
  111. download_link = str(await resp.text()).strip()
  112. return download_link
  113. def obj_to_str(object):
  114. if not object:
  115. return False
  116. string = codecs.encode(pickle.dumps(object), "base64").decode()
  117. return string
  118. def str_to_obj(string: str):
  119. object = pickle.loads(codecs.decode(string.encode(), "base64"))
  120. return object
  121. async def calc_distance_from_ip(ip1: str, ip2: str) -> float:
  122. Radius_Earth = 6371.0088
  123. data1, data2 = await gather(
  124. fetch(f"http://ipinfo.io/{ip1}"), fetch(f"http://ipinfo.io/{ip2}")
  125. )
  126. lat1, lon1 = data1["loc"].split(",")
  127. lat2, lon2 = data2["loc"].split(",")
  128. lat1, lon1 = radians(float(lat1)), radians(float(lon1))
  129. lat2, lon2 = radians(float(lat2)), radians(float(lon2))
  130. dlon = lon2 - lon1
  131. dlat = lat2 - lat1
  132. a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
  133. c = 2 * atan2(sqrt(a), sqrt(1 - a))
  134. distance = Radius_Earth * c
  135. return distance