AgentizedSolutions commited on
Commit
0d7762f
·
verified ·
1 Parent(s): 826539e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +111 -12
main.py CHANGED
@@ -2,51 +2,150 @@ import os
2
  import uuid
3
  import json
4
  import logging
5
- from fastapi import FastAPI, Request, BackgroundTasks
 
6
 
7
  logging.basicConfig(level=logging.INFO)
8
  logger = logging.getLogger(__name__)
9
 
10
- app = FastAPI(title="Resend Webhook Bridge")
11
 
 
12
  MSG_FOLDER = "/msg"
13
-
14
  if not os.path.exists(MSG_FOLDER):
15
  os.makedirs(MSG_FOLDER, exist_ok=True)
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  def save_email_to_bucket(payload: dict):
18
  try:
19
  unique_id = str(uuid.uuid4())[:8]
20
  file_name = f"email_{unique_id}.json"
21
  full_path = os.path.join(MSG_FOLDER, file_name)
22
-
23
  with open(full_path, "w", encoding="utf-8") as f:
24
  json.dump(payload, f, ensure_ascii=False, indent=2)
25
-
26
  logger.info(f"[BRIDGE] Успішно збережено новий лист: {file_name}")
27
  except Exception as e:
28
  logger.error(f"[BRIDGE] Помилка запису файлу: {e}")
29
 
30
- # --- Роут для перевірки працездатності (тест 404 помилки) ---
 
31
  @app.get("/")
32
  async def root_check():
33
- return {"status": "online", "message": "High-Ticket AI Agent Webhook Bridge is running via Docker"}
 
 
 
 
34
 
35
- # Міняємо шлях на той, куди реально б'є відправник
 
 
36
  @app.post("/listener")
37
  async def handle_email_webhook(request: Request, background_tasks: BackgroundTasks):
38
  try:
39
  payload = await request.json()
40
-
41
- # Закидуємо в бекграунд, щоб миттєво віддати статус 200 OK
42
  background_tasks.add_task(save_email_to_bucket, payload)
43
-
44
  return {"status": "accepted", "message": "Email queued in shared bucket"}
45
  except Exception as e:
46
  logger.error(f"[BRIDGE ERROR]: {str(e)}")
47
  return {"status": "error", "message": str(e)}, 400
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  if __name__ == "__main__":
50
  import uvicorn
51
- # Запуск безпосередньо, якщо локально, але в Docker краще через CMD
52
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
2
  import uuid
3
  import json
4
  import logging
5
+ import sqlite3
6
+ from fastapi import FastAPI, Request, BackgroundTasks, HTTPException
7
 
8
  logging.basicConfig(level=logging.INFO)
9
  logger = logging.getLogger(__name__)
10
 
11
+ app = FastAPI(title="Resend & NOWPayments Webhook Bridge")
12
 
13
+ # Твоя папка-бакет для імейлів
14
  MSG_FOLDER = "/msg"
 
15
  if not os.path.exists(MSG_FOLDER):
16
  os.makedirs(MSG_FOLDER, exist_ok=True)
17
 
18
+ # Шлях до ПУБЛІЧНОЇ бази даних токенів
19
+ PUBLIC_DB_PATH = "public_agents.db"
20
+
21
+ def init_public_db():
22
+ """Створюємо таблицю в публічній SQLite для збереження оплачених токенів"""
23
+ try:
24
+ conn = sqlite3.connect(PUBLIC_DB_PATH)
25
+ cursor = conn.cursor()
26
+ cursor.execute("""
27
+ CREATE TABLE IF NOT EXISTS paid_tokens (
28
+ agent_id TEXT PRIMARY KEY,
29
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
30
+ )
31
+ """)
32
+ conn.commit()
33
+ conn.close()
34
+ logger.info("[DB] Публічна база токенів успішно ініціалізована.")
35
+ except Exception as e:
36
+ logger.error(f"[DB ERROR] Помилка ініціалізації бази: {e}")
37
+
38
+ # Ініціалізуємо базу при старті контейнера
39
+ init_public_db()
40
+
41
  def save_email_to_bucket(payload: dict):
42
  try:
43
  unique_id = str(uuid.uuid4())[:8]
44
  file_name = f"email_{unique_id}.json"
45
  full_path = os.path.join(MSG_FOLDER, file_name)
46
+
47
  with open(full_path, "w", encoding="utf-8") as f:
48
  json.dump(payload, f, ensure_ascii=False, indent=2)
49
+
50
  logger.info(f"[BRIDGE] Успішно збережено новий лист: {file_name}")
51
  except Exception as e:
52
  logger.error(f"[BRIDGE] Помилка запису файлу: {e}")
53
 
54
+
55
+ # --- Головний статус-чек ---
56
  @app.get("/")
57
  async def root_check():
58
+ return {
59
+ "status": "online",
60
+ "message": "Webhook Bridge (Emails + NOWPayments) is running flawlessly via Docker"
61
+ }
62
+
63
 
64
+ # =====================================================================
65
+ # 1. СТАРИЙ РОУТ ДЛЯ ПОШТИ (Resend / Listener)
66
+ # =====================================================================
67
  @app.post("/listener")
68
  async def handle_email_webhook(request: Request, background_tasks: BackgroundTasks):
69
  try:
70
  payload = await request.json()
 
 
71
  background_tasks.add_task(save_email_to_bucket, payload)
 
72
  return {"status": "accepted", "message": "Email queued in shared bucket"}
73
  except Exception as e:
74
  logger.error(f"[BRIDGE ERROR]: {str(e)}")
75
  return {"status": "error", "message": str(e)}, 400
76
 
77
+
78
+ # =====================================================================
79
+ # 2. НОВИЙ ВЕБХУК ДЛЯ NOWPAYMENTS (Ловить кеш -> пише ID в SQLite)
80
+ # =====================================================================
81
+ @app.post("/webhook/nowpayments")
82
+ async def handle_nowpayments_ipn(request: Request):
83
+ try:
84
+ data = await request.json()
85
+ except Exception:
86
+ raise HTTPException(status_code=400, detail="Invalid JSON payload")
87
+
88
+ # Якщо транзакція ще не завершена — пропускаємо мимо вух
89
+ if data.get("payment_status") != "finished":
90
+ return {"status": "ignored", "reason": "payment_not_finished"}
91
+
92
+ payment_id = data.get("payment_id")
93
+ if not payment_id:
94
+ raise HTTPException(status_code=400, detail="Missing payment_id")
95
+
96
+ # Твій формат: agent_id_(payment_id)
97
+ unique_suffix = uuid.uuid4().hex[:8]
98
+ agent_id = f"agent_{unique_suffix}_{payment_id}"
99
+
100
+ # Записуємо ТОКЕН у публічну таблицю
101
+ conn = sqlite3.connect(PUBLIC_DB_PATH)
102
+ cursor = conn.cursor()
103
+ try:
104
+ cursor.execute("INSERT INTO paid_tokens (agent_id) VALUES (?)", (agent_id,))
105
+ conn.commit()
106
+ conn.close()
107
+
108
+ # 🔥 ТВОЯ ОПЦІЯ 3: Вивід чистого ID в консоль Docker / Спейсу
109
+ print("\n" + "═"*60, flush=True)
110
+ print(f"💰 [NOWPAYMENTS SUCCESS] Payment ID: {payment_id}", flush=True)
111
+ print(f"🔑 [PUBLIC DB UPDATED] Generated ID: {agent_id}", flush=True)
112
+ print("═"*60 + "\n", flush=True)
113
+
114
+ return {"status": "success", "agent_id": agent_id}
115
+ except sqlite3.IntegrityError:
116
+ conn.close()
117
+ return {"status": "already_processed", "message": "This payment ID was already added."}
118
+ except Exception as e:
119
+ if conn: conn.close()
120
+ logger.error(f"[IPN DATABASE ERROR]: {e}")
121
+ raise HTTPException(status_code=500, detail="Database write error")
122
+
123
+
124
+ # =====================================================================
125
+ # 3. API ЕНДПОІНТ ДЛЯ GRADIO (Перевірка токена з Main Space)
126
+ # =====================================================================
127
+ @app.get("/api/verify-agent")
128
+ async def verify_agent(agent_id: str):
129
+ """Цей ендпоінт смикне твоє Gradio (Main space), коли юзер натисне 'Load Config'"""
130
+ if not agent_id:
131
+ return {"valid": False, "error": "Empty agent_id"}
132
+
133
+ try:
134
+ conn = sqlite3.connect(PUBLIC_DB_PATH)
135
+ cursor = conn.cursor()
136
+ cursor.execute("SELECT agent_id FROM paid_tokens WHERE agent_id = ?", (agent_id,))
137
+ result = cursor.fetchone()
138
+ conn.close()
139
+
140
+ if result:
141
+ return {"valid": True}
142
+ return {"valid": False}
143
+ except Exception as e:
144
+ logger.error(f"[VERIFY API ERROR]: {e}")
145
+ return {"valid": False, "error": "Internal database check failed"}
146
+
147
+
148
  if __name__ == "__main__":
149
  import uvicorn
150
+ # 7860 порт — стандарт для Hugging Face / Docker дефолту
151
  uvicorn.run(app, host="0.0.0.0", port=7860)