nopoh22 commited on
Commit
0472279
·
verified ·
1 Parent(s): 8343fc0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -90
app.py CHANGED
@@ -1,15 +1,14 @@
1
- import json
2
  import os
3
  import threading
4
  import time
5
  import logging
6
- from datetime import datetime, timedelta
7
- from fastapi import FastAPI, Request
8
  from fastapi.responses import HTMLResponse, JSONResponse
9
  import uvicorn
10
 
11
  from keep_alive import start_ping_server
12
- from renewer import load_accounts, save_accounts, get_host, renew_account, run_renewals
13
 
14
  logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
15
  logger = logging.getLogger(__name__)
@@ -34,85 +33,18 @@ async def index():
34
 
35
  @app.get("/api/accounts")
36
  async def get_accounts():
37
- # Never return token or password to the frontend
38
- safe_keys = {"username", "host", "last_renewed", "next_renewal", "last_results", "auth_method"}
39
- return [{k: v for k, v in a.items() if k in safe_keys} for a in load_accounts()]
40
-
41
- @app.post("/api/accounts")
42
- async def add_account(request: Request):
43
- body = await request.json()
44
- username = body.get("username", "").strip()
45
- token = body.get("token", "").strip()
46
- password = body.get("password", "").strip()
47
-
48
- if not username:
49
- return JSONResponse({"ok": False, "message": "❌ أدخل اسم المستخدم"})
50
- if not token and not password:
51
- return JSONResponse({"ok": False, "message": "❌ أدخل API Token أو كلمة المرور"})
52
-
53
- accounts = load_accounts()
54
- if any(a["username"] == username for a in accounts):
55
- return JSONResponse({"ok": False, "message": f"⚠️ الحساب {username} موجود مسبقاً"})
56
-
57
- add_log(f"🔍 جاري التحقق من {username}...")
58
-
59
- # Detect host
60
- host = None
61
- auth_method = ""
62
-
63
- if token:
64
- host = get_host(username, token)
65
- auth_method = "token"
66
- if not host:
67
- add_log(f"❌ فشل الاتصال بـ {username} عبر Token")
68
- if not password:
69
- return JSONResponse({"ok": False, "message": "❌ فشل الاتصال. تحقق من Token."})
70
- add_log(f"🔄 سأحاول عبر كلمة المرور...")
71
-
72
- if not host and password:
73
- # Try to detect host via simple HTTP check
74
- import requests as req
75
- for h in ["www.pythonanywhere.com", "eu.pythonanywhere.com"]:
76
- try:
77
- r = req.get(f"https://{h}/login/", timeout=8)
78
- if r.status_code == 200:
79
- host = h
80
- break
81
- except Exception:
82
- continue
83
- auth_method = "password"
84
-
85
- if not host:
86
- add_log(f"❌ تعذّر تحديد الخادم لـ {username}")
87
- return JSONResponse({"ok": False, "message": "❌ فشل الاتصال. تحقق من البيانات."})
88
-
89
- new_account = {
90
- "username": username,
91
- "host": host,
92
- "auth_method": auth_method,
93
- "last_renewed": None,
94
- "next_renewal": None,
95
- "last_results": []
96
- }
97
- if token:
98
- new_account["token"] = token
99
- if password:
100
- new_account["password"] = password
101
-
102
- accounts.append(new_account)
103
- save_accounts(accounts)
104
- add_log(f"✅ تمت إضافة {username} على {host} [{auth_method}]")
105
- return JSONResponse({"ok": True, "message": f"✅ تمت إضافة {username} على {host} [{auth_method}]"})
106
-
107
- @app.delete("/api/accounts/{username}")
108
- async def delete_account(username: str):
109
  accounts = load_accounts()
110
- new_list = [a for a in accounts if a["username"] != username]
111
- if len(new_list) == len(accounts):
112
- return JSONResponse({"ok": False, "message": f"⚠️ لم يُعثر على {username}"})
113
- save_accounts(new_list)
114
- add_log(f"🗑️ تم حذف {username}")
115
- return JSONResponse({"ok": True, "message": f"🗑️ تم حذف {username}"})
 
 
 
 
 
116
 
117
  @app.post("/api/renew")
118
  async def renew_all():
@@ -132,18 +64,13 @@ async def renew_one(username: str):
132
  accounts = load_accounts()
133
  account = next((a for a in accounts if a["username"] == username), None)
134
  if not account:
135
- return {"ok": False}
136
  account["next_renewal"] = None
137
- save_accounts(accounts)
138
  def do():
139
  add_log(f"🔄 تجديد {username}...")
140
  success, results = renew_account(account)
141
- accs2 = load_accounts()
142
- for i, a in enumerate(accs2):
143
- if a["username"] == username:
144
- accs2[i] = account
145
- save_accounts(accs2)
146
- for r in (results if success else []):
147
  add_log(f" [{username}] {r['domain']} → {r['status']}")
148
  add_log(f"{'✅' if success else '❌'} {'تم' if success else 'فشل'} تجديد {username}")
149
  threading.Thread(target=do, daemon=True).start()
@@ -177,4 +104,10 @@ async def health():
177
  if __name__ == "__main__":
178
  start_ping_server(port=8080)
179
  add_log("🚀 PythonAnywhere Manager started")
 
 
 
 
 
 
180
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
1
  import os
2
  import threading
3
  import time
4
  import logging
5
+ from datetime import datetime
6
+ from fastapi import FastAPI
7
  from fastapi.responses import HTMLResponse, JSONResponse
8
  import uvicorn
9
 
10
  from keep_alive import start_ping_server
11
+ from renewer import load_accounts, save_accounts, renew_account, run_renewals
12
 
13
  logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
14
  logger = logging.getLogger(__name__)
 
33
 
34
  @app.get("/api/accounts")
35
  async def get_accounts():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  accounts = load_accounts()
37
+ # لا نُرجع كلمة المرور أبداً
38
+ safe = []
39
+ for a in accounts:
40
+ safe.append({
41
+ "username": a["username"],
42
+ "host": a.get("host", "—"),
43
+ "last_renewed": a.get("last_renewed"),
44
+ "next_renewal": a.get("next_renewal"),
45
+ "last_results": a.get("last_results", []),
46
+ })
47
+ return safe
48
 
49
  @app.post("/api/renew")
50
  async def renew_all():
 
64
  accounts = load_accounts()
65
  account = next((a for a in accounts if a["username"] == username), None)
66
  if not account:
67
+ return JSONResponse({"ok": False, "message": f"⚠️ لم يُعثر على {username} في الـ Secrets"})
68
  account["next_renewal"] = None
 
69
  def do():
70
  add_log(f"🔄 تجديد {username}...")
71
  success, results = renew_account(account)
72
+ save_accounts(accounts)
73
+ for r in results:
 
 
 
 
74
  add_log(f" [{username}] {r['domain']} → {r['status']}")
75
  add_log(f"{'✅' if success else '❌'} {'تم' if success else 'فشل'} تجديد {username}")
76
  threading.Thread(target=do, daemon=True).start()
 
104
  if __name__ == "__main__":
105
  start_ping_server(port=8080)
106
  add_log("🚀 PythonAnywhere Manager started")
107
+ # عرض الحسابات المحملة عند البدء
108
+ accounts = load_accounts()
109
+ if accounts:
110
+ add_log(f"📋 تم تحميل {len(accounts)} حساب من Secrets: {[a['username'] for a in accounts]}")
111
+ else:
112
+ add_log("⚠️ لم يتم العثور على حسابات — أضف ACCOUNTS في Secrets")
113
  uvicorn.run(app, host="0.0.0.0", port=7860)