Spaces:
Running

microfunnel-api / backend /app /api /channels.py
axeronis's picture
Fix: Save bot token first, graceful degradation if webhook setup fails
2b2e573
Raw History Blame Contribute Delete
17.8 kB
"""
Channels API - Telegram, WhatsApp (Cloud API), LinkedIn Connection
"""
from typing import List, Dict, Any, Optional
from uuid import UUID
import httpx
from fastapi import APIRouter, Depends, HTTPException, Header, Body, Request
from sqlmodel import Session, select
from pydantic import BaseModel, Field
from app.core.database import get_session
from app.models.tenant import Tenant
from app.core.config import settings
from app.core.logging import get_logger
from app.models import User
from app.api.deps import get_current_user
from app.services.whatsapp_cloud import whatsapp_cloud_service
from app.services.linkedin_service import linkedin_service
logger = get_logger(__name__)
router = APIRouter(prefix="/channels", tags=["Channels"])
class TelegramConnectRequest(BaseModel):
"""Telegram bot connection request."""
bot_token: str
class TelegramConnectResponse(BaseModel):
"""Telegram bot connection response."""
ok: bool
status: str
webhook_url: str
message: str
class LinkedInConnectRequest(BaseModel):
"""LinkedIn channel connection request."""
access_token: str
organization_id: str = "personal" # Default to personal
verify_token: str
jsession_id: Optional[str] = None # Added for Cookie Auth
@router.post("/telegram/connect", response_model=TelegramConnectResponse)
async def connect_telegram_bot(
request: TelegramConnectRequest,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""
Connect Telegram bot to authenticated user's tenant account.
Saves token first, then attempts webhook setup (graceful degradation if network issues).
"""
try:
tenant_id = current_user.tenant_id
tenant = await session.get(Tenant, tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
bot_token = request.bot_token.strip()
if not bot_token or ":" not in bot_token:
raise HTTPException(
status_code=400,
detail="Неверный формат токена. Токен должен быть вида: 123456:ABC-DEF..."
)
# Build webhook URL
webhook_base = (settings.TELEGRAM_WEBHOOK_URL or "https://axeronis-microfunnel-api.hf.space").rstrip("/")
if webhook_base.endswith("/api/v1"):
webhook_base = webhook_base[:-7]
webhook_url = f"{webhook_base}/api/v1/webhook/telegram-notify/{tenant_id}"
# ALWAYS save token first (before any network calls)
tenant.telegram_bot_token = bot_token
tenant.webhook_url = webhook_url
session.add(tenant)
await session.commit()
logger.info(f"✅ Bot token saved for tenant {tenant_id}")
# Now attempt to verify token and set webhook (best-effort)
bot_username = "Unknown"
webhook_set = False
network_error = False
try:
async with httpx.AsyncClient(timeout=15.0) as client:
# Verify bot token
bot_info_response = await client.get(
f"https://api.telegram.org/bot{bot_token}/getMe"
)
if bot_info_response.status_code == 200:
bot_data = bot_info_response.json()
if bot_data.get("ok"):
bot_username = bot_data.get("result", {}).get("username", "Unknown")
# Set webhook
webhook_response = await client.post(
f"https://api.telegram.org/bot{bot_token}/setWebhook",
json={
"url": webhook_url,
"allowed_updates": ["message", "edited_message", "my_chat_member"],
"drop_pending_updates": True
}
)
webhook_data = webhook_response.json()
webhook_set = webhook_data.get("ok", False)
else:
# Invalid token - rollback
tenant.telegram_bot_token = None
tenant.webhook_url = None
session.add(tenant)
await session.commit()
raise HTTPException(
status_code=400,
detail="Неверный токен бота. Проверьте токен и попробуйте снова."
)
except (httpx.ConnectError, httpx.TimeoutException, OSError) as e:
# Network error (DNS, timeout, etc.) - token is saved, webhook not set
network_error = True
logger.warning(f"⚠️ Network error during webhook setup: {e}. Token saved, manual webhook needed.")
# Return appropriate response
if webhook_set:
return TelegramConnectResponse(
ok=True,
status="connected",
webhook_url=webhook_url,
message=f"✅ Бот @{bot_username} успешно подключен! Webhook установлен."
)
elif network_error:
# Token saved but webhook not set due to network issues
return TelegramConnectResponse(
ok=True,
status="partial",
webhook_url=webhook_url,
message=f"⚠️ Токен сохранен! Webhook не установлен автоматически (сетевая ошибка). Установите вручную: https://api.telegram.org/bot{bot_token}/setWebhook?url={webhook_url}"
)
else:
return TelegramConnectResponse(
ok=True,
status="connected",
webhook_url=webhook_url,
message=f"✅ Бот @{bot_username} подключен! Если не работает, установите webhook вручную."
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Telegram connection error: {e}")
raise HTTPException(status_code=500, detail=f"Ошибка подключения: {str(e)}")
@router.get("/telegram/status")
async def get_telegram_status(
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Get current Telegram bot connection status."""
try:
tenant_id = current_user.tenant_id
tenant = await session.get(Tenant, tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
has_token = bool(tenant.telegram_bot_token and tenant.telegram_bot_token.strip())
bot_info = None
if has_token:
try:
async with httpx.AsyncClient(timeout=10.0) as client:
response = await client.get(
f"https://api.telegram.org/bot{tenant.telegram_bot_token}/getMe"
)
if response.status_code == 200:
data = response.json()
if data.get("ok"):
result = data.get("result", {})
bot_info = {
"username": result.get("username"),
"first_name": result.get("first_name"),
"id": result.get("id")
}
except:
pass
return {
"ok": True,
"connected": has_token,
"webhook_url": tenant.webhook_url if has_token else None,
"bot_info": bot_info
}
except Exception as e:
logger.error(f"Failed to get Telegram status: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.delete("/telegram/disconnect")
async def disconnect_telegram_bot(
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Disconnect Telegram bot."""
try:
tenant_id = current_user.tenant_id
tenant = await session.get(Tenant, tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
if tenant.telegram_bot_token:
try:
async with httpx.AsyncClient(timeout=10.0) as client:
await client.post(
f"https://api.telegram.org/bot{tenant.telegram_bot_token}/deleteWebhook",
json={"drop_pending_updates": True}
)
except:
pass
tenant.telegram_bot_token = None
tenant.webhook_url = None
session.add(tenant)
await session.commit()
return {"ok": True, "status": "disconnected"}
except Exception as e:
logger.error(f"Failed to disconnect Telegram: {e}")
raise HTTPException(status_code=500, detail=str(e))
# ==================== LINKEDIN ENDPOINTS ====================
@router.post("/linkedin/connect")
async def connect_linkedin(
request: LinkedInConnectRequest,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""
Connect LinkedIn channel.
"""
try:
tenant_id = current_user.tenant_id
tenant = await session.get(Tenant, tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
if not request.access_token:
raise HTTPException(
status_code=400,
detail="Cookie (li_at) обязателен"
)
# Verify credentials with LinkedIn Service
org_info = await linkedin_service.get_organization_info(
request.access_token,
request.organization_id,
request.jsession_id
)
if not org_info:
raise HTTPException(
status_code=400,
detail="Не удалось верифицировать Cookie. Проверьте li_at и JSESSIONID."
)
config = {
"access_token": request.access_token.strip(),
"organization_id": request.organization_id.strip(),
"verify_token": request.verify_token.strip(),
"jsession_id": request.jsession_id.strip() if request.jsession_id else None,
"org_name": org_info.get("vanityName", "LinkedIn Profile")
}
tenant.linkedin_config = config
session.add(tenant)
await session.commit()
return {
"ok": True,
"status": "connected",
"message": f"LinkedIn: {org_info.get('vanityName')} успешно подключен!"
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to connect LinkedIn: {e}")
raise HTTPException(status_code=500, detail=f"Ошибка подключения LinkedIn: {str(e)}")
@router.get("/linkedin/status")
async def get_linkedin_status(
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Get LinkedIn connection status."""
try:
tenant_id = current_user.tenant_id
tenant = await session.get(Tenant, tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
config = tenant.linkedin_config
is_connected = bool(config and isinstance(config, dict) and config.get("access_token"))
return {
"ok": True,
"connected": is_connected,
"config": {
"organization_id": config.get("organization_id"),
"org_name": config.get("org_name")
} if config else None
}
except Exception as e:
logger.error(f"Failed to get LinkedIn status: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.delete("/linkedin/disconnect")
async def disconnect_linkedin(
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Disconnect LinkedIn."""
try:
tenant_id = current_user.tenant_id
tenant = await session.get(Tenant, tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
tenant.linkedin_config = None
session.add(tenant)
await session.commit()
return {"ok": True, "status": "disconnected", "message": "LinkedIn успешно отключен"}
except Exception as e:
logger.error(f"Failed to disconnect LinkedIn: {e}")
raise HTTPException(status_code=500, detail=str(e))
# ==================== WHATSAPP CLOUD API ENDPOINTS ====================
@router.get("/meta/whatsapp/status")
async def get_meta_whatsapp_status(
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Get Meta WhatsApp connection status (alias)."""
return await get_whatsapp_status(current_user, session)
@router.delete("/meta/whatsapp/disconnect")
async def disconnect_meta_whatsapp(
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Disconnect Meta WhatsApp Cloud API."""
try:
tenant_id = current_user.tenant_id
tenant = await session.get(Tenant, tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
# Clear WhatsApp config
tenant.meta_wa_config = None
tenant.whatsapp_connected = False
session.add(tenant)
await session.commit()
logger.info(f"WhatsApp disconnected for tenant {tenant_id}")
return {"ok": True, "status": "disconnected", "message": "WhatsApp успешно отключен"}
except Exception as e:
logger.error(f"Failed to disconnect WhatsApp: {e}")
raise HTTPException(status_code=500, detail=str(e))
class WhatsAppConnectRequest(BaseModel):
"""WhatsApp Cloud API connection request."""
access_token: str
phone_number_id: str
business_account_id: str
@router.post("/whatsapp/connect")
async def connect_whatsapp(
request: WhatsAppConnectRequest,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""
Connect WhatsApp Cloud API - no QR codes needed!
"""
try:
tenant_id = current_user.tenant_id
tenant = await session.get(Tenant, tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
# Store credentials (in production, encrypt these!)
config = {
"access_token": request.access_token.strip(),
"phone_number_id": request.phone_number_id.strip(),
"business_account_id": request.business_account_id.strip()
}
tenant.meta_wa_config = config # Updated to meta_wa_config
tenant.whatsapp_connected = True
await session.commit()
return {
"ok": True,
"status": "connected",
"message": "WhatsApp Cloud API connected successfully!",
"phone_number_id": request.phone_number_id
}
except Exception as e:
logger.error(f"Failed to connect WhatsApp: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/whatsapp/status")
async def get_whatsapp_status(
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""
Get WhatsApp connection status.
"""
try:
tenant_id = current_user.tenant_id
tenant = await session.get(Tenant, tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
if not tenant.whatsapp_connected or not tenant.meta_wa_config:
return {
"connected": False,
"status": "disconnected"
}
config = tenant.meta_wa_config
return {
"connected": True,
"status": "active",
"phone_number_id": config.get("phone_number_id", "Unknown")
}
except Exception as e:
logger.error(f"Failed to check WhatsApp status: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/whatsapp/disconnect")
async def disconnect_whatsapp(
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""
Disconnect WhatsApp Cloud API.
"""
try:
tenant_id = current_user.tenant_id
tenant = await session.get(Tenant, tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
tenant.whatsapp_connected = False
tenant.meta_wa_config = None
await session.commit()
return {
"ok": True,
"status": "disconnected",
"message": "WhatsApp disconnected successfully"
}
except Exception as e:
logger.error(f"Failed to disconnect WhatsApp: {e}")
raise HTTPException(status_code=500, detail=str(e))