functions.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 PIL import Image, ImageDraw, ImageFilter, ImageFont
  29. from wget import download
  30. from wbb import aiohttpsession as aiosession
  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. 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 aiosession.head(url) as resp:
  95. size = int(resp.headers["content-length"])
  96. return size
  97. async def get_http_status_code(url: str) -> int:
  98. async with aiosession.head(url) as resp:
  99. return resp.status
  100. async def make_carbon(code):
  101. url = "https://carbonara.vercel.app/api/cook"
  102. async with aiosession.post(url, json={"code": code}) as resp:
  103. data = await resp.read()
  104. image = f"{randint(100, 10000)}.png"
  105. async with aiofiles.open(image, mode="wb") as f:
  106. await f.write(data)
  107. return image
  108. async def transfer_sh(file):
  109. async with aiofiles.open(file, "rb") as f:
  110. params = {file: await f.read()}
  111. async with aiohttp.ClientSession() as session:
  112. async with session.post("https://transfer.sh/", data=params) as resp:
  113. download_link = str(await resp.text()).strip()
  114. return download_link
  115. def obj_to_str(object):
  116. if not object:
  117. return False
  118. string = codecs.encode(pickle.dumps(object), "base64").decode()
  119. return string
  120. def str_to_obj(string: str):
  121. object = pickle.loads(codecs.decode(string.encode(), "base64"))
  122. return object
  123. async def calc_distance_from_ip(ip1: str, ip2: str) -> float:
  124. Radius_Earth = 6371.0088
  125. data1, data2 = await gather(
  126. fetch(f"http://ipinfo.io/{ip1}"), fetch(f"http://ipinfo.io/{ip2}")
  127. )
  128. lat1, lon1 = data1["loc"].split(",")
  129. lat2, lon2 = data2["loc"].split(",")
  130. lat1, lon1 = radians(float(lat1)), radians(float(lon1))
  131. lat2, lon2 = radians(float(lat2)), radians(float(lon2))
  132. dlon = lon2 - lon1
  133. dlat = lat2 - lat1
  134. a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
  135. c = 2 * atan2(sqrt(a), sqrt(1 - a))
  136. distance = Radius_Earth * c
  137. return distance