Spaces:
Running

File size: 17,784 Bytes
cd61bf7
526e04d
cd61bf7
ac6b5b5
cd61bf7
 
ac6b5b5
 
 
cd61bf7
 
 
 
28a640e
cd61bf7
 
e07475a
ca13047
cd61bf7
28a640e
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28a640e
 
 
6915fff
cd61bf7
6915fff
cd61bf7
 
 
 
 
 
 
 
 
2b2e573
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2e573
 
eaae5c4
 
2b2e573
cd61bf7
2b2e573
cd61bf7
 
 
 
2b2e573
cd61bf7
2b2e573
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
ca13047
 
cd61bf7
 
 
 
 
 
 
ca13047
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca13047
 
cd61bf7
 
 
 
 
 
 
ca13047
cd61bf7
 
 
 
 
 
 
ca13047
cd61bf7
 
 
 
 
 
 
ca13047
cd61bf7
 
 
 
 
 
ca13047
cd61bf7
 
ca13047
 
28a640e
 
 
 
 
 
 
 
 
 
 
ca13047
28a640e
 
 
 
 
 
 
 
6915fff
28a640e
 
6915fff
28a640e
ca13047
 
 
 
6915fff
 
ca13047
 
 
 
 
6915fff
ca13047
28a640e
 
 
 
ca13047
6915fff
 
28a640e
 
 
 
 
 
 
 
 
6915fff
28a640e
 
 
 
 
ca13047
 
28a640e
 
 
 
 
 
 
ca13047
28a640e
 
 
 
 
 
 
 
 
 
 
 
 
 
ca13047
 
28a640e
 
 
 
ca13047
 
28a640e
 
 
 
 
 
 
ca13047
28a640e
 
 
 
 
 
 
 
 
 
 
ca13047
28a640e
 
ca13047
 
f0311eb
 
e07475a
 
678b361
 
 
 
 
 
 
 
 
2eb43c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e07475a
 
 
 
 
 
 
 
 
 
ca3fae4
 
 
 
e07475a
ca3fae4
 
e07475a
 
 
 
 
 
 
 
 
 
 
 
 
0ce5872
e07475a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ce5872
e07475a
 
 
 
ca3fae4
0ce5872
e07475a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ce5872
e07475a
 
ca3fae4
 
 
 
ca13047
ca3fae4
 
 
e07475a
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
"""
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))