sub.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import httpx
  2. import yaml
  3. from pathlib import Path
  4. from typing import Optional, Dict, Any
  5. from fastapi import HTTPException
  6. def save_yaml_dump(config: dict, save_as: Path) -> Path:
  7. """保存配置文件"""
  8. save_as.parent.mkdir(parents=True, exist_ok=True)
  9. with open(save_as, 'w', encoding='utf-8') as f:
  10. yaml.dump(
  11. config,
  12. f,
  13. Dumper=yaml.SafeDumper,
  14. allow_unicode=True,
  15. indent=2,
  16. sort_keys=False
  17. )
  18. return save_as
  19. async def async_get_sub(sub_url: str, save_path: Path, timeout: int = 10) -> Path:
  20. """获取订阅文件"""
  21. headers = {'User-Agent': 'clash-verge/v1.7.5'}
  22. try:
  23. async with httpx.AsyncClient() as client:
  24. resp = await client.get(sub_url, headers=headers, follow_redirects=True, timeout=timeout)
  25. resp.raise_for_status()
  26. except httpx.HTTPError as e:
  27. raise HTTPException(status_code=500, detail=f"订阅获取失败: {str(e)}")
  28. save_path = Path(save_path)
  29. save_path.parent.mkdir(parents=True, exist_ok=True)
  30. with open(save_path, 'w', encoding='utf-8') as f:
  31. f.write(resp.text)
  32. return save_path
  33. def get_sub(sub_url: str, save_path: Path) -> Path:
  34. """获取订阅文件"""
  35. headers = {'User-Agent': 'clash-verge/v1.7.5'}
  36. try:
  37. resp = httpx.get(sub_url, headers=headers, follow_redirects=True, timeout=10)
  38. resp.raise_for_status()
  39. except httpx.HTTPError as e:
  40. raise HTTPException(status_code=500, detail=f"订阅获取失败: {str(e)}")
  41. save_path = Path(save_path)
  42. save_path.parent.mkdir(parents=True, exist_ok=True)
  43. with open(save_path, 'w', encoding='utf-8') as f:
  44. f.write(resp.text)
  45. return save_path
  46. def update_config(
  47. read_path: Path,
  48. config_update: dict,
  49. save_as: Optional[Path] = None,
  50. ) -> Path:
  51. """更新配置文件"""
  52. config: Dict[str, Any] = {}
  53. if read_path.exists():
  54. with open(read_path, 'r', encoding='utf-8') as f:
  55. config = yaml.safe_load(f) or {}
  56. config.update(config_update)
  57. save_as = save_as or read_path
  58. save_yaml_dump(config, save_as)
  59. def main():
  60. sub_url = 'https://www.yfjc.xyz/api/v1/client/subscribe?token=b74f2207492053926f7511a8e474048f'
  61. OUTPUT = Path(__file__).parent.parent.absolute() / "output"
  62. save_path = get_sub(sub_url, OUTPUT / "config.yaml")
  63. update_config(
  64. read_path=save_path,
  65. config_update={
  66. "port": 7890,
  67. "socks-port": 7891,
  68. "redir-port": 7892,
  69. "allow-lan": True,
  70. "mode": "rule",
  71. "log-level": "silent",
  72. "external-controller": "127.0.0.1:9090",
  73. "secret": "",
  74. }
  75. )
  76. if __name__ == "__main__":
  77. main()