Spaces:
Sleeping
Sleeping
Download main.py from AgentizedSolutions/webhook-bridge: direct link, hf CLI and curl.
- Browser
- Download file 6.03 kB
-
https://huggingface.co/spaces/AgentizedSolutions/webhook-bridge/resolve/main/main.py
- Command line
-
hf download hf://spaces/AgentizedSolutions/webhook-bridge/main.py
-
curl -L -o main.py https://huggingface.co/spaces/AgentizedSolutions/webhook-bridge/resolve/main/main.py
6.03 kB
| import os | |
| import uuid | |
| import json | |
| import logging | |
| import sqlite3 | |
| from fastapi import FastAPI, Request, BackgroundTasks, HTTPException | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| app = FastAPI(title="Resend & NOWPayments Webhook Bridge") | |
| # Твоя папка-бакет для імейлів | |
| MSG_FOLDER = "/msg" | |
| if not os.path.exists(MSG_FOLDER): | |
| os.makedirs(MSG_FOLDER, exist_ok=True) | |
| # Шлях до ПУБЛІЧНОЇ бази даних токенів | |
| PUBLIC_DB_PATH = "public_agents.db" | |
| def init_public_db(): | |
| """Створюємо таблицю в публічній SQLite для збереження оплачених токенів""" | |
| try: | |
| conn = sqlite3.connect(PUBLIC_DB_PATH) | |
| cursor = conn.cursor() | |
| cursor.execute(""" | |
| CREATE TABLE IF NOT EXISTS paid_tokens ( | |
| agent_id TEXT PRIMARY KEY, | |
| created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP | |
| ) | |
| """) | |
| conn.commit() | |
| conn.close() | |
| logger.info("[DB] Публічна база токенів успішно ініціалізована.") | |
| except Exception as e: | |
| logger.error(f"[DB ERROR] Помилка ініціалізації бази: {e}") | |
| # Ініціалізуємо базу при старті контейнера | |
| init_public_db() | |
| def save_email_to_bucket(payload: dict): | |
| try: | |
| unique_id = str(uuid.uuid4())[:8] | |
| file_name = f"email_{unique_id}.json" | |
| full_path = os.path.join(MSG_FOLDER, file_name) | |
| with open(full_path, "w", encoding="utf-8") as f: | |
| json.dump(payload, f, ensure_ascii=False, indent=2) | |
| logger.info(f"[BRIDGE] Успішно збережено новий лист: {file_name}") | |
| except Exception as e: | |
| logger.error(f"[BRIDGE] Помилка запису файлу: {e}") | |
| # --- Головний статус-чек --- | |
| async def root_check(): | |
| return { | |
| "status": "online", | |
| "message": "Webhook Bridge (Emails + NOWPayments) is running flawlessly via Docker" | |
| } | |
| # ===================================================================== | |
| # 1. СТАРИЙ РОУТ ДЛЯ ПОШТИ (Resend / Listener) | |
| # ===================================================================== | |
| async def handle_email_webhook(request: Request, background_tasks: BackgroundTasks): | |
| try: | |
| payload = await request.json() | |
| background_tasks.add_task(save_email_to_bucket, payload) | |
| return {"status": "accepted", "message": "Email queued in shared bucket"} | |
| except Exception as e: | |
| logger.error(f"[BRIDGE ERROR]: {str(e)}") | |
| return {"status": "error", "message": str(e)}, 400 | |
| # ===================================================================== | |
| # 2. НОВИЙ ВЕБХУК ДЛЯ NOWPAYMENTS (Ловить кеш -> пише ID в SQLite) | |
| # ===================================================================== | |
| async def handle_nowpayments_ipn(request: Request): | |
| try: | |
| data = await request.json() | |
| except Exception: | |
| raise HTTPException(status_code=400, detail="Invalid JSON payload") | |
| # Якщо транзакція ще не завершена — пропускаємо мимо вух | |
| if data.get("payment_status") != "finished": | |
| return {"status": "ignored", "reason": "payment_not_finished"} | |
| payment_id = data.get("payment_id") | |
| if not payment_id: | |
| raise HTTPException(status_code=400, detail="Missing payment_id") | |
| # Твій формат: agent_id_(payment_id) | |
| unique_suffix = uuid.uuid4().hex[:8] | |
| agent_id = f"agent_{unique_suffix}_{payment_id}" | |
| # Записуємо ТОКЕН у публічну таблицю | |
| conn = sqlite3.connect(PUBLIC_DB_PATH) | |
| cursor = conn.cursor() | |
| try: | |
| cursor.execute("INSERT INTO paid_tokens (agent_id) VALUES (?)", (agent_id,)) | |
| conn.commit() | |
| conn.close() | |
| # 🔥 ТВОЯ ОПЦІЯ 3: Вивід чистого ID в консоль Docker / Спейсу | |
| print("\n" + "═"*60, flush=True) | |
| print(f"💰 [NOWPAYMENTS SUCCESS] Payment ID: {payment_id}", flush=True) | |
| print(f"🔑 [PUBLIC DB UPDATED] Generated ID: {agent_id}", flush=True) | |
| print("═"*60 + "\n", flush=True) | |
| return {"status": "success", "agent_id": agent_id} | |
| except sqlite3.IntegrityError: | |
| conn.close() | |
| return {"status": "already_processed", "message": "This payment ID was already added."} | |
| except Exception as e: | |
| if conn: conn.close() | |
| logger.error(f"[IPN DATABASE ERROR]: {e}") | |
| raise HTTPException(status_code=500, detail="Database write error") | |
| # ===================================================================== | |
| # 3. API ЕНДПОІНТ ДЛЯ GRADIO (Перевірка токена з Main Space) | |
| # ===================================================================== | |
| async def verify_agent(agent_id: str): | |
| """Цей ендпоінт смикне твоє Gradio (Main space), коли юзер натисне 'Load Config'""" | |
| if not agent_id: | |
| return {"valid": False, "error": "Empty agent_id"} | |
| try: | |
| conn = sqlite3.connect(PUBLIC_DB_PATH) | |
| cursor = conn.cursor() | |
| cursor.execute("SELECT agent_id FROM paid_tokens WHERE agent_id = ?", (agent_id,)) | |
| result = cursor.fetchone() | |
| conn.close() | |
| if result: | |
| return {"valid": True} | |
| return {"valid": False} | |
| except Exception as e: | |
| logger.error(f"[VERIFY API ERROR]: {e}") | |
| return {"valid": False, "error": "Internal database check failed"} | |
| if __name__ == "__main__": | |
| import uvicorn | |
| # 7860 порт — стандарт для Hugging Face / Docker дефолту | |
| uvicorn.run(app, host="0.0.0.0", port=7860) |