Spaces:
Paused
Paused
| import os | |
| import re | |
| import sys | |
| import yaml | |
| import requests | |
| from flask import Flask, Response, request | |
| from urllib.parse import urlencode | |
| from asgiref.wsgi import WsgiToAsgi | |
| app = Flask(__name__) | |
| # 从环境变量中获取密钥 | |
| API_KEY = os.environ.get('API_KEY') | |
| SUBSCRIBE_URLS = os.environ.get('SUBSCRIBE_URLS') # 存储真实URL的变量 | |
| def subscribe_mixin(content: str) -> str: | |
| """输入 YAML 字符串,输出转换后的 YAML 字符串 | |
| """ | |
| try: | |
| d = yaml.safe_load(content) | |
| my_auto_group_name = "AI Unrestrict" | |
| regex_list = [ | |
| re.compile(r"美国", re.IGNORECASE), # 美国 (不区分大小写) | |
| re.compile(r"america", re.IGNORECASE), # america (不区分大小写) | |
| re.compile(r"us", re.IGNORECASE), # us (不区分大小写) | |
| re.compile(r"新加坡", re.IGNORECASE), # 新加坡 (不区分大小写) | |
| re.compile(r"singapore", re.IGNORECASE), # singapore (不区分大小写) | |
| re.compile(r"sg", re.IGNORECASE), # sg (不区分大小写) | |
| re.compile(r"加拿大", re.IGNORECASE), # 加拿大 (不区分大小写) | |
| re.compile(r"canada", re.IGNORECASE), # canada (不区分大小写) | |
| re.compile(r"ca", re.IGNORECASE), # ca (不区分大小写) | |
| ] | |
| matching_proxies = [] # 用于存储匹配的代理名称 | |
| # 1. 查找并保存符合正则表达式的 proxy name | |
| if "proxies" in d and isinstance(d["proxies"], list): | |
| for proxy in d["proxies"]: | |
| if "name" in proxy: | |
| for regex in regex_list: | |
| if regex.search(proxy["name"]): # 使用 re.search | |
| matching_proxies.append(proxy["name"]) | |
| break # 匹配到一个 regex 就跳出循环,避免重复添加 | |
| # 2. 创建新的 proxy-group 对象 | |
| new_proxy_group = { | |
| "name": my_auto_group_name, | |
| "type": "url-test", | |
| "proxies": matching_proxies, | |
| "url": "http://www.gstatic.com/generate_204", | |
| "interval": 7200 | |
| } | |
| # 3. 将新的 proxy-group 添加到 proxy-groups 数组 | |
| if "proxy-groups" in d and isinstance(d["proxy-groups"], list): | |
| d["proxy-groups"].append(new_proxy_group) | |
| # 4. 将 myAutoGroupName 添加到第一个 proxy-group 的 "proxies" 列表的最前面 | |
| if d["proxy-groups"] and len(d["proxy-groups"]) > 0 and \ | |
| "proxies" in d["proxy-groups"][0] and isinstance(d["proxy-groups"][0]["proxies"], list): | |
| d["proxy-groups"][0]["proxies"].insert(0, my_auto_group_name) # 使用 insert(0, ...) | |
| else: | |
| d["proxy-groups"] = [new_proxy_group] # 如果 proxy-groups 不存在,则创建 | |
| # 将修改后的字典转换回 YAML 字符串 | |
| modified_yaml = yaml.dump(d, allow_unicode=True, indent=2) # 使用 yaml.dump | |
| return modified_yaml | |
| except yaml.YAMLError as e: | |
| print(f"YAML 解析错误:{e}") | |
| return "" # 或者抛出异常,根据你的需求 | |
| except Exception as e: | |
| print(f"其他错误:{e}") | |
| return "" | |
| def read_subscribe(): | |
| # 验证API Key | |
| key = request.args.get('key') | |
| if key != API_KEY: | |
| return {"error": "Unauthorized"}, 401 | |
| # 从环境变量获取URL列表 | |
| if not SUBSCRIBE_URLS: | |
| return {"error": "SUBSCRIBE_URLS not configured"}, 500 | |
| urls = SUBSCRIBE_URLS.split('\n') | |
| cleaned_urls = [url.strip() for url in urls] | |
| new_url = '|'.join(cleaned_urls) | |
| encoded_url = urlencode({ | |
| 'target': 'clash', | |
| 'url': new_url | |
| }) # Correct way to encode the URL | |
| target_url = f"http://127.0.0.1:25500/sub?{encoded_url}" | |
| try: | |
| resp = requests.get(target_url) | |
| resp.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx) | |
| data = resp.text | |
| data = subscribe_mixin(data) | |
| return Response(data, mimetype='text/yaml') | |
| except requests.exceptions.RequestException as e: | |
| return {"error": str(e)}, 500 # Handle request errors and return an error response | |
| def read_root(): | |
| return {"hello": 'world'} | |
| asgi_app = WsgiToAsgi(app) | |