ssassxxaaus commited on
Commit
284810a
·
verified ·
1 Parent(s): c487835

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +577 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import json
4
+ import time
5
+ import base64
6
+ import shutil
7
+ import asyncio
8
+ import requests
9
+ import platform
10
+ import subprocess
11
+ import threading
12
+ from threading import Thread
13
+ from http.server import BaseHTTPRequestHandler, HTTPServer
14
+
15
+ # Environment variables
16
+ UPLOAD_URL = os.environ.get('UPLOAD_URL', '') # 节点或订阅上传地址,只填写这个地址将上传节点,同时填写PROJECT_URL将上传订阅,例如:https://merge.serv00.net
17
+ PROJECT_URL = os.environ.get('PROJECT_URL', '') # 项目url,需要自动保活或自动上传订阅需要填写,例如:https://www.google.com,
18
+ AUTO_ACCESS = os.environ.get('AUTO_ACCESS', 'false').lower() == 'true' # false关闭自动保活, true开启自动保活,默认关闭
19
+ FILE_PATH = os.environ.get('FILE_PATH', './.cache') # 运行路径,sub.txt保存路径
20
+ SUB_PATH = os.environ.get('SUB_PATH', 'sub') # 订阅token,默认sub,例如:https://www.google.com/sub
21
+ UUID = os.environ.get('UUID', '6240b21f-3cb6-18ea-df47-56a948c28b71') # UUID,如使用哪吒v1,在不同的平台部署需要修改,否则会覆盖
22
+ NEZHA_SERVER = os.environ.get('NEZHA_SERVER', 'gwwjllhldpjy.us-west-1.clawcloudrun.com:443') # 哪吒面板域名或ip, v1格式: nezha.xxx.com:8008, v0格式: nezha.xxx.com
23
+ NEZHA_PORT = os.environ.get('NEZHA_PORT', '') # v1哪吒请留空, v0哪吒的agent通信端口,自动匹配tls
24
+ NEZHA_KEY = os.environ.get('NEZHA_KEY', 'rRA5ZrgOmsosl7EiyIuJBhnGwcAqWDUr') # v1哪吒的NZ_CLIENT_SECRET或v0哪吒agent密钥
25
+ ARGO_DOMAIN = os.environ.get('ARGO_DOMAIN', 'py.testlls.filegear-sg.me') # Argo固定隧道域名,留空即使用临时隧道
26
+ ARGO_AUTH = os.environ.get('ARGO_AUTH', 'eyJhIjoiNWRmNTFlZjhhMTNiMWQ1ZDFhODhhZTAxNWFmYTU5OGIiLCJ0IjoiOGIwZGRmM2QtOWUxYi00NGY0LThhMjItMjI0OGQ0NGZiNDRiIiwicyI6Ik9EUmxNV1F5WWprdE9URTFaaTAwTjJNMkxUZzJaR0V0WVdOaU9UQmlNakV4TXpObCJ9') # Argo固定隧道密钥,留空即使用临时隧道
27
+ ARGO_PORT = int(os.environ.get('ARGO_PORT', '8001')) # Argo端口,使用固定隧道token需在cloudflare后台设置端口和这里一致
28
+ CFIP = os.environ.get('CFIP', 'www.visa.com.tw') # 优选ip或优选域名
29
+ CFPORT = int(os.environ.get('CFPORT', '443')) # 优选ip或优选域名对应端口
30
+ NAME = os.environ.get('NAME', 'Vls') # 节点名称
31
+ CHAT_ID = os.environ.get('CHAT_ID', '') # Telegram chat_id,推送节点到tg,两个变量同时填写才会推送
32
+ BOT_TOKEN = os.environ.get('BOT_TOKEN', '') # Telegram bot_token
33
+ PORT = int(os.environ.get('SERVER_PORT') or os.environ.get('PORT') or 3000) # 订阅端口,如无法订阅,请手动修改为分配的端口
34
+
35
+ # Create running folder
36
+ def create_directory():
37
+ print('\033c', end='')
38
+ if not os.path.exists(FILE_PATH):
39
+ os.makedirs(FILE_PATH)
40
+ print(f"{FILE_PATH} is created")
41
+ else:
42
+ print(f"{FILE_PATH} already exists")
43
+
44
+ # Global variables
45
+ npm_path = os.path.join(FILE_PATH, 'npm')
46
+ php_path = os.path.join(FILE_PATH, 'php')
47
+ web_path = os.path.join(FILE_PATH, 'web')
48
+ bot_path = os.path.join(FILE_PATH, 'bot')
49
+ sub_path = os.path.join(FILE_PATH, 'sub.txt')
50
+ list_path = os.path.join(FILE_PATH, 'list.txt')
51
+ boot_log_path = os.path.join(FILE_PATH, 'boot.log')
52
+ config_path = os.path.join(FILE_PATH, 'config.json')
53
+
54
+ # Delete nodes
55
+ def delete_nodes():
56
+ try:
57
+ if not UPLOAD_URL:
58
+ return
59
+
60
+ if not os.path.exists(sub_path):
61
+ return
62
+
63
+ try:
64
+ with open(sub_path, 'r') as file:
65
+ file_content = file.read()
66
+ except:
67
+ return None
68
+
69
+ decoded = base64.b64decode(file_content).decode('utf-8')
70
+ nodes = [line for line in decoded.split('\n') if any(protocol in line for protocol in ['vless://', 'vmess://', 'trojan://', 'hysteria2://', 'tuic://'])]
71
+
72
+ if not nodes:
73
+ return
74
+
75
+ try:
76
+ requests.post(f"{UPLOAD_URL}/api/delete-nodes",
77
+ data=json.dumps({"nodes": nodes}),
78
+ headers={"Content-Type": "application/json"})
79
+ except:
80
+ return None
81
+ except Exception as e:
82
+ print(f"Error in delete_nodes: {e}")
83
+ return None
84
+
85
+ # Clean up old files
86
+ def cleanup_old_files():
87
+ paths_to_delete = ['web', 'bot', 'npm', 'php', 'boot.log', 'list.txt']
88
+ for file in paths_to_delete:
89
+ file_path = os.path.join(FILE_PATH, file)
90
+ try:
91
+ if os.path.exists(file_path):
92
+ if os.path.isdir(file_path):
93
+ shutil.rmtree(file_path)
94
+ else:
95
+ os.remove(file_path)
96
+ except Exception as e:
97
+ print(f"Error removing {file_path}: {e}")
98
+
99
+ class RequestHandler(BaseHTTPRequestHandler):
100
+ def do_GET(self):
101
+ if self.path == '/':
102
+ self.send_response(200)
103
+ self.send_header('Content-type', 'text/html')
104
+ self.end_headers()
105
+ self.wfile.write(b'Hello World')
106
+
107
+ elif self.path == f'/{SUB_PATH}':
108
+ try:
109
+ with open(sub_path, 'rb') as f:
110
+ content = f.read()
111
+ self.send_response(200)
112
+ self.send_header('Content-type', 'text/plain')
113
+ self.end_headers()
114
+ self.wfile.write(content)
115
+ except:
116
+ self.send_response(404)
117
+ self.end_headers()
118
+ else:
119
+ self.send_response(404)
120
+ self.end_headers()
121
+
122
+ def log_message(self, format, *args):
123
+ pass
124
+
125
+ # Determine system architecture
126
+ def get_system_architecture():
127
+ architecture = platform.machine().lower()
128
+ if 'arm' in architecture or 'aarch64' in architecture:
129
+ return 'arm'
130
+ else:
131
+ return 'amd'
132
+
133
+ # Download file based on architecture
134
+ def download_file(file_name, file_url):
135
+ file_path = os.path.join(FILE_PATH, file_name)
136
+ try:
137
+ response = requests.get(file_url, stream=True)
138
+ response.raise_for_status()
139
+
140
+ with open(file_path, 'wb') as f:
141
+ for chunk in response.iter_content(chunk_size=8192):
142
+ f.write(chunk)
143
+
144
+ print(f"Download {file_name} successfully")
145
+ return True
146
+ except Exception as e:
147
+ if os.path.exists(file_path):
148
+ os.remove(file_path)
149
+ print(f"Download {file_name} failed: {e}")
150
+ return False
151
+
152
+ # Get files for architecture
153
+ def get_files_for_architecture(architecture):
154
+ if architecture == 'arm':
155
+ base_files = [
156
+ {"fileName": "web", "fileUrl": "https://arm64.ssss.nyc.mn/web"},
157
+ {"fileName": "bot", "fileUrl": "https://arm64.ssss.nyc.mn/2go"}
158
+ ]
159
+ else:
160
+ base_files = [
161
+ {"fileName": "web", "fileUrl": "https://amd64.ssss.nyc.mn/web"},
162
+ {"fileName": "bot", "fileUrl": "https://amd64.ssss.nyc.mn/2go"}
163
+ ]
164
+
165
+ if NEZHA_SERVER and NEZHA_KEY:
166
+ if NEZHA_PORT:
167
+ npm_url = "https://arm64.ssss.nyc.mn/agent" if architecture == 'arm' else "https://amd64.ssss.nyc.mn/agent"
168
+ base_files.insert(0, {"fileName": "npm", "fileUrl": npm_url})
169
+ else:
170
+ php_url = "https://arm64.ssss.nyc.mn/v1" if architecture == 'arm' else "https://amd64.ssss.nyc.mn/v1"
171
+ base_files.insert(0, {"fileName": "php", "fileUrl": php_url})
172
+
173
+ return base_files
174
+
175
+ # Authorize files with execute permission
176
+ def authorize_files(file_paths):
177
+ for relative_file_path in file_paths:
178
+ absolute_file_path = os.path.join(FILE_PATH, relative_file_path)
179
+ if os.path.exists(absolute_file_path):
180
+ try:
181
+ os.chmod(absolute_file_path, 0o775)
182
+ print(f"Empowerment success for {absolute_file_path}: 775")
183
+ except Exception as e:
184
+ print(f"Empowerment failed for {absolute_file_path}: {e}")
185
+
186
+ # Configure Argo tunnel
187
+ def argo_type():
188
+ if not ARGO_AUTH or not ARGO_DOMAIN:
189
+ print("ARGO_DOMAIN or ARGO_AUTH variable is empty, use quick tunnels")
190
+ return
191
+
192
+ if "TunnelSecret" in ARGO_AUTH:
193
+ with open(os.path.join(FILE_PATH, 'tunnel.json'), 'w') as f:
194
+ f.write(ARGO_AUTH)
195
+
196
+ tunnel_id = ARGO_AUTH.split('"')[11]
197
+ tunnel_yml = f"""
198
+ tunnel: {tunnel_id}
199
+ credentials-file: {os.path.join(FILE_PATH, 'tunnel.json')}
200
+ protocol: http2
201
+
202
+ ingress:
203
+ - hostname: {ARGO_DOMAIN}
204
+ service: http://localhost:{ARGO_PORT}
205
+ originRequest:
206
+ noTLSVerify: true
207
+ - service: http_status:404
208
+ """
209
+ with open(os.path.join(FILE_PATH, 'tunnel.yml'), 'w') as f:
210
+ f.write(tunnel_yml)
211
+ else:
212
+ print("Use token connect to tunnel,please set the {ARGO_PORT} in cloudflare")
213
+
214
+ # Execute shell command and return output
215
+ def exec_cmd(command):
216
+ try:
217
+ process = subprocess.Popen(
218
+ command,
219
+ shell=True,
220
+ stdout=subprocess.PIPE,
221
+ stderr=subprocess.PIPE,
222
+ text=True
223
+ )
224
+ stdout, stderr = process.communicate()
225
+ return stdout + stderr
226
+ except Exception as e:
227
+ print(f"Error executing command: {e}")
228
+ return str(e)
229
+
230
+ # Download and run necessary files
231
+ async def download_files_and_run():
232
+ global private_key, public_key
233
+
234
+ architecture = get_system_architecture()
235
+ files_to_download = get_files_for_architecture(architecture)
236
+
237
+ if not files_to_download:
238
+ print("Can't find a file for the current architecture")
239
+ return
240
+
241
+ # Download all files
242
+ download_success = True
243
+ for file_info in files_to_download:
244
+ if not download_file(file_info["fileName"], file_info["fileUrl"]):
245
+ download_success = False
246
+
247
+ if not download_success:
248
+ print("Error downloading files")
249
+ return
250
+
251
+ # Authorize files
252
+ files_to_authorize = ['npm', 'web', 'bot'] if NEZHA_PORT else ['php', 'web', 'bot']
253
+ authorize_files(files_to_authorize)
254
+
255
+ # Check TLS
256
+ port = NEZHA_SERVER.split(":")[-1] if ":" in NEZHA_SERVER else ""
257
+ if port in ["443", "8443", "2096", "2087", "2083", "2053"]:
258
+ nezha_tls = "true"
259
+ else:
260
+ nezha_tls = "false"
261
+
262
+ # Configure nezha
263
+ if NEZHA_SERVER and NEZHA_KEY:
264
+ if not NEZHA_PORT:
265
+ # Generate config.yaml for v1
266
+ config_yaml = f"""
267
+ client_secret: {NEZHA_KEY}
268
+ debug: false
269
+ disable_auto_update: true
270
+ disable_command_execute: false
271
+ disable_force_update: true
272
+ disable_nat: false
273
+ disable_send_query: false
274
+ gpu: false
275
+ insecure_tls: false
276
+ ip_report_period: 1800
277
+ report_delay: 4
278
+ server: {NEZHA_SERVER}
279
+ skip_connection_count: false
280
+ skip_procs_count: false
281
+ temperature: false
282
+ tls: {nezha_tls}
283
+ use_gitee_to_upgrade: false
284
+ use_ipv6_country_code: false
285
+ uuid: {UUID}"""
286
+
287
+ with open(os.path.join(FILE_PATH, 'config.yaml'), 'w') as f:
288
+ f.write(config_yaml)
289
+
290
+ # Generate configuration file
291
+ config ={"log":{"access":"/dev/null","error":"/dev/null","loglevel":"none",},"inbounds":[{"port":ARGO_PORT ,"protocol":"vless","settings":{"clients":[{"id":UUID ,"flow":"xtls-rprx-vision",},],"decryption":"none","fallbacks":[{"dest":3001 },{"path":"/vless-argo","dest":3002 },{"path":"/vmess-argo","dest":3003 },{"path":"/trojan-argo","dest":3004 },],},"streamSettings":{"network":"tcp",},},{"port":3001 ,"listen":"127.0.0.1","protocol":"vless","settings":{"clients":[{"id":UUID },],"decryption":"none"},"streamSettings":{"network":"ws","security":"none"}},{"port":3002 ,"listen":"127.0.0.1","protocol":"vless","settings":{"clients":[{"id":UUID ,"level":0 }],"decryption":"none"},"streamSettings":{"network":"ws","security":"none","wsSettings":{"path":"/vless-argo"}},"sniffing":{"enabled":True ,"destOverride":["http","tls","quic"],"metadataOnly":False }},{"port":3003 ,"listen":"127.0.0.1","protocol":"vmess","settings":{"clients":[{"id":UUID ,"alterId":0 }]},"streamSettings":{"network":"ws","wsSettings":{"path":"/vmess-argo"}},"sniffing":{"enabled":True ,"destOverride":["http","tls","quic"],"metadataOnly":False }},{"port":3004 ,"listen":"127.0.0.1","protocol":"trojan","settings":{"clients":[{"password":UUID },]},"streamSettings":{"network":"ws","security":"none","wsSettings":{"path":"/trojan-argo"}},"sniffing":{"enabled":True ,"destOverride":["http","tls","quic"],"metadataOnly":False }},],"outbounds":[{"protocol":"freedom","tag": "direct" },{"protocol":"blackhole","tag":"block"}]}
292
+ with open(os.path.join(FILE_PATH, 'config.json'), 'w', encoding='utf-8') as config_file:
293
+ json.dump(config, config_file, ensure_ascii=False, indent=2)
294
+
295
+ # Run nezha
296
+ if NEZHA_SERVER and NEZHA_PORT and NEZHA_KEY:
297
+ tls_ports = ['443', '8443', '2096', '2087', '2083', '2053']
298
+ nezha_tls = '--tls' if NEZHA_PORT in tls_ports else ''
299
+ command = f"nohup {os.path.join(FILE_PATH, 'npm')} -s {NEZHA_SERVER}:{NEZHA_PORT} -p {NEZHA_KEY} {nezha_tls} >/dev/null 2>&1 &"
300
+
301
+ try:
302
+ exec_cmd(command)
303
+ print('npm is running')
304
+ time.sleep(1)
305
+ except Exception as e:
306
+ print(f"npm running error: {e}")
307
+
308
+ elif NEZHA_SERVER and NEZHA_KEY:
309
+ # Run V1
310
+ command = f"nohup {FILE_PATH}/php -c \"{FILE_PATH}/config.yaml\" >/dev/null 2>&1 &"
311
+ try:
312
+ exec_cmd(command)
313
+ print('php is running')
314
+ time.sleep(1)
315
+ except Exception as e:
316
+ print(f"php running error: {e}")
317
+ else:
318
+ print('NEZHA variable is empty, skipping running')
319
+
320
+ # Run sbX
321
+ command = f"nohup {os.path.join(FILE_PATH, 'web')} -c {os.path.join(FILE_PATH, 'config.json')} >/dev/null 2>&1 &"
322
+ try:
323
+ exec_cmd(command)
324
+ print('web is running')
325
+ time.sleep(1)
326
+ except Exception as e:
327
+ print(f"web running error: {e}")
328
+
329
+ # Run cloudflared
330
+ if os.path.exists(os.path.join(FILE_PATH, 'bot')):
331
+ if re.match(r'^[A-Z0-9a-z=]{120,250}$', ARGO_AUTH):
332
+ args = f"tunnel --edge-ip-version auto --no-autoupdate --protocol http2 run --token {ARGO_AUTH}"
333
+ elif "TunnelSecret" in ARGO_AUTH:
334
+ args = f"tunnel --edge-ip-version auto --config {os.path.join(FILE_PATH, 'tunnel.yml')} run"
335
+ else:
336
+ args = f"tunnel --edge-ip-version auto --no-autoupdate --protocol http2 --logfile {os.path.join(FILE_PATH, 'boot.log')} --loglevel info --url http://localhost:{ARGO_PORT}"
337
+
338
+ try:
339
+ exec_cmd(f"nohup {os.path.join(FILE_PATH, 'bot')} {args} >/dev/null 2>&1 &")
340
+ print('bot is running')
341
+ time.sleep(2)
342
+ except Exception as e:
343
+ print(f"Error executing command: {e}")
344
+
345
+ time.sleep(5)
346
+
347
+ # Extract domains and generate sub.txt
348
+ await extract_domains()
349
+
350
+ # Extract domains from cloudflared logs
351
+ async def extract_domains():
352
+ argo_domain = None
353
+
354
+ if ARGO_AUTH and ARGO_DOMAIN:
355
+ argo_domain = ARGO_DOMAIN
356
+ print(f'ARGO_DOMAIN: {argo_domain}')
357
+ await generate_links(argo_domain)
358
+ else:
359
+ try:
360
+ with open(boot_log_path, 'r') as f:
361
+ file_content = f.read()
362
+
363
+ lines = file_content.split('\n')
364
+ argo_domains = []
365
+
366
+ for line in lines:
367
+ domain_match = re.search(r'https?://([^ ]*trycloudflare\.com)/?', line)
368
+ if domain_match:
369
+ domain = domain_match.group(1)
370
+ argo_domains.append(domain)
371
+
372
+ if argo_domains:
373
+ argo_domain = argo_domains[0]
374
+ print(f'ArgoDomain: {argo_domain}')
375
+ await generate_links(argo_domain)
376
+ else:
377
+ print('ArgoDomain not found, re-running bot to obtain ArgoDomain')
378
+ # Remove boot.log and restart bot
379
+ if os.path.exists(boot_log_path):
380
+ os.remove(boot_log_path)
381
+
382
+ try:
383
+ exec_cmd('pkill -f "[b]ot" > /dev/null 2>&1')
384
+ except:
385
+ pass
386
+
387
+ time.sleep(1)
388
+ args = f'tunnel --edge-ip-version auto --no-autoupdate --protocol http2 --logfile {FILE_PATH}/boot.log --loglevel info --url http://localhost:{ARGO_PORT}'
389
+ exec_cmd(f'nohup {os.path.join(FILE_PATH, "bot")} {args} >/dev/null 2>&1 &')
390
+ print('bot is running.')
391
+ time.sleep(6) # Wait 6 seconds
392
+ await extract_domains() # Try again
393
+ except Exception as e:
394
+ print(f'Error reading boot.log: {e}')
395
+
396
+ # Upload nodes to subscription service
397
+ def upload_nodes():
398
+ if UPLOAD_URL and PROJECT_URL:
399
+ subscription_url = f"{PROJECT_URL}/{SUB_PATH}"
400
+ json_data = {
401
+ "subscription": [subscription_url]
402
+ }
403
+
404
+ try:
405
+ response = requests.post(
406
+ f"{UPLOAD_URL}/api/add-subscriptions",
407
+ json=json_data,
408
+ headers={"Content-Type": "application/json"}
409
+ )
410
+
411
+ if response.status_code == 200:
412
+ print('Subscription uploaded successfully')
413
+ except Exception as e:
414
+ pass
415
+
416
+ elif UPLOAD_URL:
417
+ if not os.path.exists(list_path):
418
+ return
419
+
420
+ with open(list_path, 'r') as f:
421
+ content = f.read()
422
+
423
+ nodes = [line for line in content.split('\n') if any(protocol in line for protocol in ['vless://', 'vmess://', 'trojan://', 'hysteria2://', 'tuic://'])]
424
+
425
+ if not nodes:
426
+ return
427
+
428
+ json_data = json.dumps({"nodes": nodes})
429
+
430
+ try:
431
+ response = requests.post(
432
+ f"{UPLOAD_URL}/api/add-nodes",
433
+ data=json_data,
434
+ headers={"Content-Type": "application/json"}
435
+ )
436
+
437
+ if response.status_code == 200:
438
+ print('Nodes uploaded successfully')
439
+ except:
440
+ return None
441
+ else:
442
+ return
443
+
444
+ # Send notification to Telegram
445
+ def send_telegram():
446
+ if not BOT_TOKEN or not CHAT_ID:
447
+ # print('TG variables is empty, Skipping push nodes to TG')
448
+ return
449
+
450
+ try:
451
+ with open(sub_path, 'r') as f:
452
+ message = f.read()
453
+
454
+ url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
455
+
456
+ escaped_name = re.sub(r'([_*\[\]()~>#+=|{}.!\-])', r'\\\1', NAME)
457
+
458
+ params = {
459
+ "chat_id": CHAT_ID,
460
+ "text": f"**{escaped_name}节点推送通知**\n{message}",
461
+ "parse_mode": "MarkdownV2"
462
+ }
463
+
464
+ requests.post(url, params=params)
465
+ print('Telegram message sent successfully')
466
+ except Exception as e:
467
+ print(f'Failed to send Telegram message: {e}')
468
+
469
+ # Generate links and subscription content
470
+ async def generate_links(argo_domain):
471
+ meta_info = subprocess.run(['curl', '-s', 'https://speed.cloudflare.com/meta'], capture_output=True, text=True)
472
+ meta_info = meta_info.stdout.split('"')
473
+ ISP = f"{meta_info[25]}-{meta_info[17]}".replace(' ', '_').strip()
474
+
475
+ time.sleep(2)
476
+ VMESS = {"v": "2", "ps": f"{NAME}-{ISP}", "add": CFIP, "port": CFPORT, "id": UUID, "aid": "0", "scy": "none", "net": "ws", "type": "none", "host": argo_domain, "path": "/vmess-argo?ed=2560", "tls": "tls", "sni": argo_domain, "alpn": "", "fp": "chrome"}
477
+
478
+ list_txt = f"""
479
+ vless://{UUID}@{CFIP}:{CFPORT}?encryption=none&security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Fvless-argo%3Fed%3D2560#{NAME}-{ISP}
480
+
481
+ vmess://{ base64.b64encode(json.dumps(VMESS).encode('utf-8')).decode('utf-8')}
482
+
483
+ trojan://{UUID}@{CFIP}:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}-{ISP}
484
+ """
485
+
486
+ with open(os.path.join(FILE_PATH, 'list.txt'), 'w', encoding='utf-8') as list_file:
487
+ list_file.write(list_txt)
488
+
489
+ sub_txt = base64.b64encode(list_txt.encode('utf-8')).decode('utf-8')
490
+ with open(os.path.join(FILE_PATH, 'sub.txt'), 'w', encoding='utf-8') as sub_file:
491
+ sub_file.write(sub_txt)
492
+
493
+ print(sub_txt)
494
+
495
+ print(f"{FILE_PATH}/sub.txt saved successfully")
496
+
497
+ # Additional actions
498
+ send_telegram()
499
+ upload_nodes()
500
+
501
+ return sub_txt
502
+
503
+ # Add automatic access task
504
+ def add_visit_task():
505
+ if not AUTO_ACCESS or not PROJECT_URL:
506
+ print("Skipping adding automatic access task")
507
+ return
508
+
509
+ try:
510
+ response = requests.post(
511
+ 'https://keep.gvrander.eu.org/add-url',
512
+ json={"url": PROJECT_URL},
513
+ headers={"Content-Type": "application/json"}
514
+ )
515
+ print('automatic access task added successfully')
516
+ except Exception as e:
517
+ print(f'Failed to add URL: {e}')
518
+
519
+ # Clean up files after 90 seconds
520
+ def clean_files():
521
+ def _cleanup():
522
+ time.sleep(90) # Wait 90 seconds
523
+ files_to_delete = [boot_log_path, config_path, list_path, web_path, bot_path, php_path, npm_path]
524
+
525
+ if NEZHA_PORT:
526
+ files_to_delete.append(npm_path)
527
+ elif NEZHA_SERVER and NEZHA_KEY:
528
+ files_to_delete.append(php_path)
529
+
530
+ for file in files_to_delete:
531
+ try:
532
+ if os.path.exists(file):
533
+ if os.path.isdir(file):
534
+ shutil.rmtree(file)
535
+ else:
536
+ os.remove(file)
537
+ except:
538
+ pass
539
+
540
+ print('\033c', end='')
541
+ print('App is running')
542
+ print('Thank you for using this script, enjoy!')
543
+
544
+ threading.Thread(target=_cleanup, daemon=True).start()
545
+
546
+ # Main function to start the server
547
+ async def start_server():
548
+ delete_nodes()
549
+ cleanup_old_files()
550
+ create_directory()
551
+ argo_type()
552
+ await download_files_and_run()
553
+ add_visit_task()
554
+
555
+ server_thread = Thread(target=run_server)
556
+ server_thread.daemon = True
557
+ server_thread.start()
558
+
559
+ clean_files()
560
+
561
+ def run_server():
562
+ server = HTTPServer(('0.0.0.0', PORT), RequestHandler)
563
+ print(f"Server is running on port {PORT}")
564
+ print(f"Running done!")
565
+ print(f"\nLogs will be delete in 90 seconds")
566
+ server.serve_forever()
567
+
568
+ def run_async():
569
+ loop = asyncio.new_event_loop()
570
+ asyncio.set_event_loop(loop)
571
+ loop.run_until_complete(start_server())
572
+
573
+ while True:
574
+ time.sleep(3600)
575
+
576
+ if __name__ == "__main__":
577
+ run_async()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Flask
2
+ requests