Procházet zdrojové kódy

新增 clash web UI 多代理访问示例

mrh před 10 měsíci
rodič
revize
840cb046d7

+ 78 - 0
tests/mytest/mihomo/proxy_api_test.py

@@ -0,0 +1,78 @@
+import json
+import httpx
+import asyncio
+import yaml
+from pprint import pprint, pformat
+from pathlib import Path
+OUTPUT = Path(__file__).parent.absolute() / "output"
+yaml_path = OUTPUT / "config_9389.yaml"
+with open(yaml_path, "r", encoding="utf-8") as f:
+    yaml_data = yaml.safe_load(f)
+BASE_URL = 'http://' + yaml_data.get("external-controller")
+print(f"BASE_URL: {BASE_URL}")
+async def test_get_proxies(client: httpx.AsyncClient):
+    """测试 /proxies 接口"""
+    print("\nTesting /proxies endpoint:")
+    response = await client.get(f"{BASE_URL}/proxies")
+    print(f"Status: {response.status_code}")
+    pprint(response.json(), compact=True)
+    with open(OUTPUT / "proxies.json", "w", encoding="utf-8") as f:
+        json.dump(response.json(), f, indent=4, ensure_ascii=False)
+    return response.json()
+
+async def test_get_proxies_name(client: httpx.AsyncClient, name: str):
+    print("\nTesting /proxies/{proxies_name} endpoint:")
+    response = await client.get(f"{BASE_URL}/proxies/{name}")
+    print(f"Status: {response.status_code}")
+    print("Response:", response.json())
+
+async def test_put_proxies_name(client: httpx.AsyncClient, name: str):
+    print(f"\nTesting PUT /proxies/{name} endpoint:")
+    response = await client.put(
+        f"{BASE_URL}/proxies/{name}",
+        json={"name": name}
+    )
+    print(f"Status: {response.status_code}")
+    print("Response:", response.json())
+
+async def test_get_proxies_delay(client: httpx.AsyncClient):
+    """测试 /proxies/proxies_name/delay 接口"""
+    print("\nTesting /proxies/proxies_name/delay endpoint:")
+    params = {"url": "http://example.com", "timeout": 5000}
+    response = await client.get(
+        f"{BASE_URL}/proxies/proxies_name/delay",
+        params=params
+    )
+    print(f"Status: {response.status_code}")
+    print("Response:", response.json())
+
+async def run_all_tests():
+    async with httpx.AsyncClient() as client:
+        try:
+            # res = await test_get_proxies(client)
+            # pprint(res, compact=True)
+            # return
+            # proxies_name = res
+            await test_get_proxies_name(client, name="新加坡aws - 001")
+            await test_put_proxies_name(client, name="新加坡aws - 001")
+            # await test_get_proxies_delay(client)
+        except httpx.HTTPError as e:
+            print(f"HTTP Error occurred: {str(e)}")
+        except Exception as e:
+            print(f"Error: {str(e)}")
+
+def load():
+    with open(OUTPUT / "config_9389.yaml", "r", encoding="utf-8") as f:
+        data = yaml.safe_load(f)
+    return data
+
+def all_name():
+    proxies = yaml_data.get("proxies", [])
+    all_names = [proxy.get("name") for proxy in proxies]
+    print("获取到的所有代理名称:")
+    for name in all_names:
+        print(f"{name}")
+
+if __name__ == "__main__":
+    asyncio.run(run_all_tests())
+    # all_name()

+ 31 - 4
tests/mytest/mihomo/readme.md

@@ -14,10 +14,37 @@ python api_t.py
 curl https://www.google.com
 curl https://www.google.com
 curl -x http://127.0.0.1:9388 https://www.google.com
 curl -x http://127.0.0.1:9388 https://www.google.com
 curl -i -x http://localhost:9388 https://www.google.com/
 curl -i -x http://localhost:9388 https://www.google.com/
-# socket5
-curl -i -x socks5://127.0.0.1:9388 https://www.google.com
-curl -i -x http://localhost:1881 https://www.google.com/
 ```
 ```
 
 
 # API 文档
 # API 文档
-https://wiki.metacubex.one/api/
+https://wiki.metacubex.one/api/
+
+API 页面接口测试,填写 external-controller http://127.0.0.1:9791
+https://wiki.metacubex.one/startup/web/?h=we
+
+在页面中,可以管理代理,在 配置 - 切换到后端, 可以切换不同的配置文件API接口
+
+在浏览器 debug tool 中点击代理,可以看到请求的http信息:
+```shell
+请求 URL:
+http://127.0.0.1:9791/proxies/FSCloud
+Request Method:
+PUT
+{"name":"美国001 - hysteria2"}
+```
+## WEB UI 面板
+https://www.clashverge.dev/friendship.html#_1
+
+面板访问方式,以及构造 URL 后端
+```shell
+# https://github.com/MetaCubeX/metacubexd
+http://yacd.metacubex.one?hostname=127.0.0.1&port=9791&secret=
+# https://github.com/MetaCubeX/Yacd-meta/tree/master
+https://metacubex.github.io/metacubexd/#/setup?http=true&hostname=127.0.0.1&port=9792&secret=
+
+# 在上述面板设置好代理地址后,可以用下列命令测试
+curl -i -x http://localhost:9389 http://ip-api.com/json/
+curl -i -x http://localhost:9389 https://www.google.com
+curl -i -x http://localhost:9390 http://ip-api.com/json/
+curl -i -x http://localhost:9390 https://www.google.com
+```

+ 15 - 9
tests/mytest/mihomo/api_t.py → tests/mytest/mihomo/sub.py

@@ -5,6 +5,7 @@ from typing import Optional, Dict, Any
 
 
 sub_url = 'https://www.yfjc.xyz/api/v1/client/subscribe?token=b74f2207492053926f7511a8e474048f'
 sub_url = 'https://www.yfjc.xyz/api/v1/client/subscribe?token=b74f2207492053926f7511a8e474048f'
 sub_url2 = 'http://sub.sub.sub.subsub123456789.com/answer/land?token=a7cbdde987a58068b82e52d57ee5eecd'
 sub_url2 = 'http://sub.sub.sub.subsub123456789.com/answer/land?token=a7cbdde987a58068b82e52d57ee5eecd'
+OUTPUT = Path(__file__).parent.absolute() / "output"
 
 
 CONFIG_SCHEMA = {
 CONFIG_SCHEMA = {
     "mode": ("rule", "运行模式 (rule/global/direct)"),
     "mode": ("rule", "运行模式 (rule/global/direct)"),
@@ -45,8 +46,8 @@ def update_config(
             config = yaml.safe_load(f) or {}
             config = yaml.safe_load(f) or {}
     
     
     # 过滤掉值为None的项
     # 过滤掉值为None的项
-    filtered_update = {k: v for k, v in config_update.items() if v is not None}
-    config.update(filtered_update)
+    # filtered_update = {k: v for k, v in config_update.items() if v is not None}
+    config.update(config_update)
     
     
     save_as = save_as or read_path
     save_as = save_as or read_path
     with open(save_as, 'w', encoding='utf-8') as f:
     with open(save_as, 'w', encoding='utf-8') as f:
@@ -60,26 +61,31 @@ def update_config(
             default_flow_style=None
             default_flow_style=None
         )
         )
 
 
-if __name__ == '__main__':
-    sub1_save_path = Path(__file__).parent /'sub1.yaml'
-    sub2_save_path = Path(__file__).parent / 'sub2.yaml'
+
+def sub_update():
+    sub1_save_path = OUTPUT /'sub1.yaml'
+    sub2_save_path = OUTPUT / 'sub2.yaml'
     save_path = sub2_save_path
     save_path = sub2_save_path
     url = sub_url
     url = sub_url
     # get_sub(url, save_path)
     # get_sub(url, save_path)
     config_update = {
     config_update = {
         "mode": "rule",
         "mode": "rule",
-        "mixed-port": 9389,
+        "mixed-port": 9390,
         "allow-lan": False,
         "allow-lan": False,
         "log-level": "info",
         "log-level": "info",
         "ipv6": False,
         "ipv6": False,
-        "external-controller": "127.0.0.1:9791",
+        "external-controller": "127.0.0.1:9792",
         "secret": ""
         "secret": ""
     }
     }
     print("将要写入的配置参数:", config_update)
     print("将要写入的配置参数:", config_update)
     
     
-    save_as = save_path.parent / f'config_{config_update["mixed-port"]}.yaml'
+    save_as = OUTPUT / f'config_{config_update["mixed-port"]}.yaml'
     update_config(
     update_config(
         read_path=save_path,
         read_path=save_path,
         config_update=config_update,
         config_update=config_update,
         save_as=save_as
         save_as=save_as
-    )
+    )
+    print(f"配置已更新并保存到 {save_as}")
+
+if __name__ == '__main__':
+    sub_update()