client.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import asyncio
  2. import httpx
  3. import sys
  4. from pathlib import Path
  5. from sqlmodel import Session, select
  6. sys.path.append(str(Path(__file__).parent.parent.absolute()))
  7. print(sys.path)
  8. from config.logu import get_logger
  9. from routers.mihomo import MihomoMetaWithURL
  10. from database.models.subscription import SubscriptionManager, MihomoMeta
  11. logger = get_logger('client',file=False)
  12. BASE_URL = "http://localhost:5010"
  13. async def get_proxies() -> dict:
  14. """获取所有运行中的mihomo代理"""
  15. url = f"{BASE_URL}/subscriptions/proxies"
  16. async with httpx.AsyncClient() as client:
  17. response = await client.get(url)
  18. response.raise_for_status()
  19. return response.json()
  20. async def get_mihomo_proxies() -> list:
  21. """获取所有运行中的mihomo代理"""
  22. url = f"{BASE_URL}/subscriptions/proxies"
  23. async with httpx.AsyncClient() as client:
  24. response = await client.get(url)
  25. response.raise_for_status()
  26. return response.json()
  27. def startup():
  28. url = f"{BASE_URL}/mihomo/startup"
  29. response = httpx.post(url,timeout=30)
  30. response.raise_for_status() # 确保请求成功
  31. return response.json()
  32. async def start_proxy(proxy_id: int, port: int=None):
  33. """启动单个代理"""
  34. url = f"{BASE_URL}/mihomo/start"
  35. payload = {
  36. "id": proxy_id,
  37. }
  38. if port:
  39. payload["port"] = port
  40. async with httpx.AsyncClient() as client:
  41. try:
  42. response = await client.post(url, json=payload, timeout=30)
  43. response.raise_for_status()
  44. return response.json()
  45. except Exception as e:
  46. logger.error(f"启动代理 {proxy_id} 失败: {str(e)}")
  47. raise
  48. async def proxies_reachability() -> list:
  49. """测试所有运行中代理的延迟并启动可用代理"""
  50. url = f"{BASE_URL}/mihomo/proxies_reachability"
  51. async with httpx.AsyncClient() as client:
  52. response = await client.post(url, timeout=30)
  53. response.raise_for_status()
  54. results = response.json()
  55. logger.info(f"results {len(results)}")
  56. return results
  57. async def start_proxies():
  58. # 启动所有代理
  59. res = startup()
  60. # 测试所有代理的延迟
  61. await proxies_reachability()
  62. res = await get_proxies()
  63. count = 10
  64. for key in res.keys():
  65. provider_proxies = res[key]
  66. for proxy in provider_proxies:
  67. proxy_id = proxy["id"]
  68. if proxy["delay"] is not None and proxy["delay"] < 2000:
  69. logger.info(f"{proxy_id} {proxy}")
  70. await start_proxy(proxy_id)
  71. count -= 1
  72. if count == 0:
  73. return
  74. async def get_random_proxy():
  75. """测试所有运行中代理的延迟并启动可用代理"""
  76. url = f"{BASE_URL}/get"
  77. async with httpx.AsyncClient() as client:
  78. response = await client.get(url, timeout=30)
  79. response.raise_for_status()
  80. results = response.json()
  81. logger.info(f"results {results}")
  82. port = results["port"]
  83. addr = f'http://127.0.0.1:{port}'
  84. logger.info(f"curl -i -x {addr} https://www.google.com")
  85. return results
  86. async def start_by_ids(proxy_ids: list):
  87. for proxy_id in proxy_ids:
  88. await start_proxy(proxy_id)
  89. async def main():
  90. # await start_proxies()
  91. # await get_random_proxy()
  92. await start_by_ids([26,27,28,38,39,40,41])
  93. if __name__ == "__main__":
  94. asyncio.run(main())