sfun commited on
Commit
2ab6cd2
1 Parent(s): 0ef2fde

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -32
app.py CHANGED
@@ -8,7 +8,6 @@ import traceback
8
  from aiohttp import web
9
  from urllib.parse import parse_qs
10
  from cachetools import TTLCache
11
- from functools import partial
12
 
13
  # 创建一个TTL缓存,最多存储1000个项目,每个项目的有效期为30分钟
14
  cache = TTLCache(maxsize=1000, ttl=1800)
@@ -18,42 +17,94 @@ async def fetch_url(url, session):
18
  return await response.text()
19
 
20
  async def extract_and_transform_proxies(input_text):
21
- # 使用正则表达式提取代理信息
22
- pattern = r'([a-zA-Z0-9+/=]+)(?:@|:\/\/)([^:]+):(\d+)'
23
- matches = re.findall(pattern, input_text)
24
-
25
- proxies = []
26
- for match in matches:
27
- encoded_info, server, port = match
28
- try:
29
- decoded_info = base64.b64decode(encoded_info).decode('utf-8')
30
- method, password = decoded_info.split(':')
31
- proxy = {
32
- 'name': f'{server}:{port}',
33
- 'type': 'ss',
34
- 'server': server,
35
- 'port': int(port),
36
- 'cipher': method,
37
- 'password': password
38
- }
39
- proxies.append(proxy)
40
- except:
41
- continue
42
-
43
- # 转换为YAML格式
44
- yaml_data = yaml.dump({'proxies': proxies}, allow_unicode=True)
45
- return yaml_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  async def log_request(request, response):
48
- print(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - "
49
- f"Request: {request.method} {request.path} - "
50
- f"Response: {response.status}", flush=True)
 
 
 
 
 
 
 
51
 
52
  @web.middleware
53
  async def logging_middleware(request, handler):
54
- response = await handler(request)
55
- await log_request(request, response)
56
- return response
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  async def handle_request(request):
59
  if request.path == '/':
 
8
  from aiohttp import web
9
  from urllib.parse import parse_qs
10
  from cachetools import TTLCache
 
11
 
12
  # 创建一个TTL缓存,最多存储1000个项目,每个项目的有效期为30分钟
13
  cache = TTLCache(maxsize=1000, ttl=1800)
 
17
  return await response.text()
18
 
19
  async def extract_and_transform_proxies(input_text):
20
+ try:
21
+ data = yaml.safe_load(input_text)
22
+ if isinstance(data, dict) and 'proxies' in data:
23
+ proxies_list = data['proxies']
24
+ elif isinstance(data, list):
25
+ proxies_list = data
26
+ else:
27
+ proxies_match = re.search(r'proxies:\s*\n((?:[-\s]*{.*\n?)*)', input_text, re.MULTILINE)
28
+ if proxies_match:
29
+ proxies_text = proxies_match.group(1)
30
+ proxies_list = yaml.safe_load(proxies_text)
31
+ else:
32
+ return "未找到有效的代理配置"
33
+ except yaml.YAMLError:
34
+ return "YAML解析错误"
35
+
36
+ if not proxies_list:
37
+ return "未找到有效的代理配置"
38
+
39
+ transformed_proxies = []
40
+
41
+ for proxy in proxies_list:
42
+ if proxy.get('type') == 'ss':
43
+ name = proxy.get('name', '').strip()
44
+ server = proxy.get('server', '').strip()
45
+ port = str(proxy.get('port', '')).strip()
46
+
47
+ ss_parts = [f"{name} = ss, {server}, {port}"]
48
+
49
+ if 'cipher' in proxy:
50
+ ss_parts.append(f"encrypt-method={proxy['cipher'].strip()}")
51
+ if 'password' in proxy:
52
+ ss_parts.append(f"password={proxy['password'].strip()}")
53
+ if 'udp' in proxy:
54
+ ss_parts.append(f"udp-relay={'true' if proxy['udp'] in [True, 'true', 'True'] else 'false'}")
55
+
56
+ transformed = ", ".join(ss_parts)
57
+ transformed_proxies.append(transformed)
58
+
59
+ elif proxy.get('type') == 'trojan':
60
+ name = proxy.get('name', '').strip()
61
+ server = proxy.get('server', '').strip()
62
+ port = str(proxy.get('port', '')).strip()
63
+
64
+ trojan_parts = [f"{name} = trojan, {server}, {port}"]
65
+
66
+ if 'password' in proxy:
67
+ trojan_parts.append(f"password={proxy['password'].strip()}")
68
+ if 'sni' in proxy:
69
+ trojan_parts.append(f"sni={proxy['sni'].strip()}")
70
+ if 'skip-cert-verify' in proxy:
71
+ trojan_parts.append(f"skip-cert-verify={str(proxy['skip-cert-verify']).lower()}")
72
+ if 'udp' in proxy:
73
+ trojan_parts.append(f"udp={'true' if proxy['udp'] in [True, 'true', 'True'] else 'false'}")
74
+
75
+ transformed = ", ".join(trojan_parts)
76
+ transformed_proxies.append(transformed)
77
+
78
+ return "\n".join(transformed_proxies) if transformed_proxies else "未找到有效的SS或Trojan代理配置"
79
 
80
  async def log_request(request, response):
81
+ timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
82
+ client_ip = request.remote
83
+ request_line = f"{request.method} {request.path}"
84
+ if request.query_string:
85
+ request_line += f"?{request.query_string}"
86
+ status_code = response.status
87
+ content_length = response.content_length
88
+
89
+ log_message = f"{timestamp} - {client_ip} - \"{request_line}\" {status_code} {content_length}"
90
+ print(log_message, flush=True)
91
 
92
  @web.middleware
93
  async def logging_middleware(request, handler):
94
+ start_time = datetime.datetime.now()
95
+ try:
96
+ response = await handler(request)
97
+ await log_request(request, response)
98
+ end_time = datetime.datetime.now()
99
+ print(f"Request processing time: {end_time - start_time}", flush=True)
100
+ return response
101
+ except Exception as e:
102
+ end_time = datetime.datetime.now()
103
+ print(f"Error occurred: {str(e)}", flush=True)
104
+ print(f"Request processing time: {end_time - start_time}", flush=True)
105
+ print("Traceback:", flush=True)
106
+ traceback.print_exc()
107
+ return web.Response(text=f"Internal Server Error: {str(e)}", status=500)
108
 
109
  async def handle_request(request):
110
  if request.path == '/':