speed.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from aiohttp import ClientSession, TCPConnector
  2. from time import time
  3. from asyncio import gather
  4. import re
  5. from utils.config import get_config
  6. config = get_config()
  7. timeout = 15
  8. async def get_speed(url, timeout=timeout, proxy=None):
  9. """
  10. Get the speed of the url
  11. """
  12. async with ClientSession(
  13. connector=TCPConnector(verify_ssl=False), trust_env=True
  14. ) as session:
  15. start = time()
  16. end = None
  17. try:
  18. async with session.get(url, timeout=timeout, proxy=proxy) as response:
  19. resStatus = response.status
  20. if resStatus == 200:
  21. end = time()
  22. else:
  23. return float("inf")
  24. except Exception as e:
  25. return float("inf")
  26. return int(round((end - start) * 1000)) if end else float("inf")
  27. async def sort_urls_by_speed_and_resolution(infoList):
  28. """
  29. Sort by speed and resolution
  30. """
  31. response_times = await gather(*(get_speed(url) for url, _, _ in infoList))
  32. valid_responses = [(info, rt) for info, rt in zip(infoList, response_times)]
  33. def extract_resolution(resolution_str):
  34. numbers = re.findall(r"\d+x\d+", resolution_str)
  35. if numbers:
  36. width, height = map(int, numbers[0].split("x"))
  37. return width * height
  38. else:
  39. return 0
  40. default_response_time_weight = 0.5
  41. default_resolution_weight = 0.5
  42. response_time_weight = getattr(
  43. config, "response_time_weight", default_response_time_weight
  44. )
  45. resolution_weight = getattr(config, "resolution_weight", default_resolution_weight)
  46. # Check if weights are valid
  47. if not (
  48. 0 <= response_time_weight <= 1
  49. and 0 <= resolution_weight <= 1
  50. and response_time_weight + resolution_weight == 1
  51. ):
  52. response_time_weight = default_response_time_weight
  53. resolution_weight = default_resolution_weight
  54. def combined_key(item):
  55. (_, _, resolution), response_time = item
  56. resolution_value = extract_resolution(resolution) if resolution else 0
  57. return (
  58. -(response_time_weight * response_time)
  59. + resolution_weight * resolution_value
  60. )
  61. sorted_res = sorted(valid_responses, key=combined_key, reverse=True)
  62. return sorted_res