Spaces:
Running

File size: 21,406 Bytes
90be4ab
 
 
 
 
 
9db1202
 
 
 
 
90be4ab
9db1202
90be4ab
9db1202
90be4ab
9db1202
90be4ab
1c2c4a2
9db1202
 
b6a8f90
9db1202
90be4ab
6770e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9db1202
895402e
9db1202
 
 
 
 
 
90be4ab
5a3f04c
 
 
 
9db1202
5a3f04c
 
9db1202
5a3f04c
9db1202
90be4ab
1d33ce6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9db1202
 
5f721d1
 
9db1202
90be4ab
9db1202
fa63236
 
9db1202
bbc6d21
fa63236
90be4ab
fa63236
 
bbc6d21
 
 
 
 
 
 
 
fa63236
9db1202
 
 
 
bbc6d21
 
 
90be4ab
9db1202
 
 
 
 
 
fa63236
bbc6d21
 
9db1202
 
 
 
 
 
90be4ab
7efb057
 
 
 
 
 
 
 
 
 
 
 
 
 
4fe7869
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9c53fb
 
 
4fe7869
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9db1202
 
 
 
a0c82c7
bbc6d21
 
9db1202
 
 
90be4ab
9db1202
bbc6d21
 
 
 
db0923c
 
9db1202
 
90be4ab
9db1202
 
90be4ab
9db1202
 
90be4ab
9db1202
90be4ab
9db1202
 
db0923c
1d33ce6
4b3688e
 
 
 
bbc6d21
90be4ab
bbc6d21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90be4ab
db0923c
bbc6d21
 
 
db0923c
bbc6d21
db0923c
9db1202
bbc6d21
 
 
db0923c
bbc6d21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90be4ab
 
9db1202
90be4ab
 
 
 
 
bbc6d21
 
 
9db1202
 
90be4ab
 
 
9db1202
90be4ab
9db1202
 
 
90be4ab
9db1202
 
90be4ab
 
9db1202
 
90be4ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a76cbc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Telegram Webhook Handler.

Uses unified MessageProcessor for message handling.
"""

from fastapi import APIRouter, Request, HTTPException, BackgroundTasks, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from uuid import UUID
from datetime import datetime
import logging
import httpx

from app.core.database import get_async_session, async_session_maker
from app.models.tenant import Tenant
from app.services.message_processor import IncomingMessage, get_message_processor
from app.core.logging import get_logger
from app.core.config import settings
from app.core.limiter import limiter

logger = get_logger(__name__)
router = APIRouter(prefix="/webhook/telegram-notify", tags=["Telegram Notification Bot"])


@router.post("/global")
@limiter.limit("20/minute")
async def handle_global_telegram_webhook(
    request: Request,
    background_tasks: BackgroundTasks,
    session: AsyncSession = Depends(get_async_session)
):
    """Handle incoming updates for the Global Notification Bot."""
    try:
        raw_body = await request.body()
        import json
        data = json.loads(raw_body)
    except Exception:
        return {"status": "ignored"}
        
    logger.info(f"🚨 GLOBAL BOT WEBHOOK: body_preview={raw_body[:200]}")
    
    # 1. Handle Group Addition
    if "my_chat_member" in data:
        my_chat_member = data["my_chat_member"]
        chat = my_chat_member.get("chat", {})
        new_status = my_chat_member.get("new_chat_member", {}).get("status")
        chat_id = str(chat.get("id"))
        
        if new_status in ["member", "administrator"]:
            token = settings.TELEGRAM_NOTIFICATION_TOKEN
            if token:
                from app.services.telegram_service import telegram_service
                msg = f"✅ <b>Бота добавили в группу!</b>\n\n🆔 Group ID: <code>{chat_id}</code>\n\nВставьте этот ID в поле 'Групповой чат' в настройках уведомлений."
                background_tasks.add_task(telegram_service.send_message, token=token, chat_id=chat_id, text=msg)
        return {"status": "ok"}
        
    # 2. Handle /start for Personal ID
    if "message" in data:
        msg_data = data["message"]
        text = msg_data.get("text", "")
        chat_id = str(msg_data.get("chat", {}).get("id"))
        
        if text and text.strip().lower().startswith("/start"):
            token = settings.TELEGRAM_NOTIFICATION_TOKEN
            if token:
                from app.services.telegram_service import telegram_service
                reply = f"✅ <b>Бот готов к работе!</b>\n\n🆔 Ваш Personal ID: <code>{chat_id}</code>\n\nВставьте этот ID в поле 'Личный чат' в настройках уведомлений."
                background_tasks.add_task(telegram_service.send_message, token=token, chat_id=chat_id, text=reply)
        
    return {"status": "ok"}


@router.post("/{tenant_id}")
@limiter.limit("5/minute")
async def handle_telegram_webhook(
    tenant_id: UUID,
    request: Request,
    background_tasks: BackgroundTasks,
    session: AsyncSession = Depends(get_async_session)
):
    """Handle incoming Telegram updates."""
    # ABSOLUTE FIRST LOG - Before anything else
    raw_body = await request.body()
    logger.info(f"🚨 RAW TELEGRAM REQUEST: tenant={tenant_id}, bytes={len(raw_body)}, body_preview={raw_body[:200]}")
    
    try:
        import json
        data = json.loads(raw_body)
    except Exception as e:
        logger.error(f"❌ JSON parse failed: {e}")
        raise HTTPException(status_code=400, detail="Invalid JSON")
    
    # Check for My Chat Member (Bot added/removed from group)
    if "my_chat_member" in data:
        my_chat_member = data["my_chat_member"]
        chat = my_chat_member.get("chat", {})
        new_status = my_chat_member.get("new_chat_member", {}).get("status")
        chat_id = str(chat.get("id"))
        chat_title = chat.get("title", "Group")
        
        logger.info(f"📢 Bot status changed in chat {chat_id} ({chat_title}): {new_status}")
        
        if new_status in ["member", "administrator"]:
            try:
                # Send Welcome & ID so user can copy it
                tenant = await session.get(Tenant, tenant_id)
                if tenant:
                    token = tenant.telegram_bot_token or settings.TELEGRAM_NOTIFICATION_TOKEN
                    if token:
                        from app.services.telegram_service import telegram_service
                        msg = f"✅ <b>Бот подключен к группе!</b>\n\n🆔 ID группы: <code>{chat_id}</code>\n\nСкопируйте этот ID в настройки уведомлений MicroFunnel."
                        background_tasks.add_task(
                            telegram_service.send_message,
                            token=token,
                            chat_id=chat_id,
                            text=msg
                        )
                        logger.info(f"✅ Sent Group ID {chat_id} to chat")
            except Exception as e:
                logger.error(f"Failed to handle group add: {e}")
        
        return {"status": "processed_group_update"}

    # Check if it's a message
    if "message" not in data:
        # Debug log for ignored updates
        logger.info(f"📩 Telegram Update (Ignored): {list(data.keys())}")
        return {"status": "ignored"}
    
    message_data = data["message"]
    logger.info(f"📩 Telegram Webhook: {list(data.keys())} | Msg Keys: {list(message_data.keys())}")
    
    chat_id = str(message_data.get("chat", {}).get("id"))
    text = message_data.get("text", "") or message_data.get("caption", "")
    
    # Check for Voice OR Audio
    voice = message_data.get("voice") or message_data.get("audio") or {}
    voice_file_id = voice.get("file_id")

    # Check for Photo (array)
    photo_list = message_data.get("photo", [])
    photo_file_id = photo_list[-1]["file_id"] if photo_list else None

    # Check for Document
    doc = message_data.get("document", {})
    doc_file_id = doc.get("file_id")
    
    user_data = message_data.get("from", {})
    username = user_data.get("username", "")
    first_name = user_data.get("first_name", "")
    
    if not text and not voice_file_id and not photo_file_id and not doc_file_id:
        logger.warning(f"⚠️ Ignored message with no content. Keys: {list(message_data.keys())}")
        return {"status": "ignored_no_content"}
    
    # Process in background
    background_tasks.add_task(
        process_telegram_message,
        tenant_id=tenant_id,
        chat_id=chat_id,
        text=text,
        voice_file_id=voice_file_id,
        photo_file_id=photo_file_id,
        doc_file_id=doc_file_id,
        username=username,
        first_name=first_name
    )
    
    return {"status": "ok"}


@router.get("/{tenant_id}")
async def verify_webhook_status(tenant_id: UUID):
    """
    Simple GET endpoint to verify that the webhook URL is reachable.
    Useful for debugging "no logs" issues.
    """
    logger.info(f"✅ Webhook endpoint reachable for Tenant {tenant_id}")
    return {
        "status": "active", 
        "message": "Telegram Webhook Endpoint is online.",
        "tenant_id": str(tenant_id)
    }


@router.post("/{tenant_id}/register")
async def register_telegram_webhook(
    tenant_id: UUID,
    session: AsyncSession = Depends(get_async_session)
):
    """
    Re-register Telegram webhook with correct allowed_updates.
    This MUST be called after initial setup to enable voice/photo/document messages!
    """
    tenant = await session.get(Tenant, tenant_id)
    if not tenant:
        raise HTTPException(status_code=404, detail="Tenant not found")
    
    bot_token = tenant.telegram_bot_token or settings.TELEGRAM_NOTIFICATION_TOKEN
    if not bot_token:
        raise HTTPException(status_code=400, detail="No Telegram bot token configured")
    
    # Construct webhook URL from settings
    webhook_base = (settings.TELEGRAM_WEBHOOK_URL or "https://axeronis-microfunnel-api.hf.space").rstrip("/")
    webhook_url = f"{webhook_base}/api/v1/webhook/telegram-notify/{tenant_id}"
    
    # Register webhook with ALL message types
    async with httpx.AsyncClient() as client:
        # First, delete existing webhook
        await client.get(f"https://api.telegram.org/bot{bot_token}/deleteWebhook")
        
        # Then set new webhook with allowed_updates
        response = await client.post(
            f"https://api.telegram.org/bot{bot_token}/setWebhook",
            json={
                "url": webhook_url,
                "allowed_updates": ["message", "edited_message", "channel_post"]
            }
        )
        result = response.json()
        
        # Also get current webhook info
        info_res = await client.get(f"https://api.telegram.org/bot{bot_token}/getWebhookInfo")
        info = info_res.json()
        
    logger.info(f"📡 Webhook registered: {result}")
    return {
        "status": "registered",
        "webhook_url": webhook_url,
        "telegram_response": result,
        "webhook_info": info.get("result", {})
    }


async def process_telegram_message(
    tenant_id: UUID,
    chat_id: str,
    text: str,
    voice_file_id: str | None,
    photo_file_id: str | None,
    doc_file_id: str | None,
    username: str,
    first_name: str
):
    """Background task: Process Telegram message using unified MessageProcessor."""
    from app.services.telegram_service import telegram_service
    from app.core.supabase import supabase_client
    import time
    import re

    logger.info(f"🔧 Processing TG message: text={text[:30] if text else 'N/A'}..., voice={voice_file_id}, photo={photo_file_id}, doc={doc_file_id}")
    
    async with async_session_maker() as session:
        try:
            # 1. Get Tenant & Bot Token
            tenant = await session.get(Tenant, tenant_id)
            if not tenant:
                logger.error(f"Tenant {tenant_id} not found")
                return
            
            bot_token = tenant.telegram_bot_token or settings.TELEGRAM_NOTIFICATION_TOKEN
            if not bot_token:
                logger.error(f"No Telegram token for tenant {tenant_id}")
                return
            
            logger.info(f"✅ Tenant found, bot_token={'present' if bot_token else 'MISSING'}")

            # NOTE: /start is handled in the AI processing flow (webhook.py) 
            # which sends the welcome message. We don't intercept it here.
            # The ID message is only sent by the global notification bot (/tg-global).

            # 2. Process Media (Voice, Photo, Doc)
            is_voice = False
            media_url = None
            media_type = None
            
            # Helper to download file
            async def download_file(file_id: str) -> tuple[bytes, str, str]:
                 async with httpx.AsyncClient() as client:
                    file_res = await client.get(f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}")
                    if not file_res.json().get("ok"): return None, None, None
                    path = file_res.json()["result"]["file_path"]
                    url = f"https://api.telegram.org/file/bot{bot_token}/{path}"
                    
                    data_res = await client.get(url)
                    data_res.raise_for_status()
                    
                    # Guess MIME/Name
                    ext = path.split('.')[-1].lower() if '.' in path else "bin"
                    mime_map = {
                        "jpg": "image/jpeg",
                        "jpeg": "image/jpeg",
                        "png": "image/png",
                        "webp": "image/webp",
                        "oga": "audio/ogg",
                        "ogg": "audio/ogg",
                        "mp3": "audio/mpeg",
                        "pdf": "application/pdf",
                        "txt": "text/plain"
                    }
                    mime = mime_map.get(ext, "application/octet-stream")
                    return data_res.content, path.split('/')[-1], mime

            # Handle Voice
            if voice_file_id:
                logger.info(f"🎤 Voice file detected: {voice_file_id}")
                try:
                    text = await transcribe_telegram_voice(bot_token, voice_file_id)
                    is_voice = True
                    logger.info(f"✅ Voice transcribed: {text[:50]}...")
                except Exception as e:
                    logger.error(f"❌ Voice processing failed: {e}", exc_info=True)
            
            # Handle Photo / Document
            target_file_id = photo_file_id or doc_file_id
            if target_file_id:
                logger.info(f"📎 Media file detected: {target_file_id}")
                try:
                    content, name, mime = await download_file(target_file_id)
                    if content and supabase_client:
                        bucket = "chat-attachments"
                        ts = int(time.time())
                        safe_name = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', name)
                        # Store in incoming path
                        path = f"{tenant.id}/incoming/{ts}_{safe_name}"
                        
                        supabase_client.storage.from_(bucket).upload(
                            path=path, file=content, file_options={"content-type": mime}
                        )
                        media_url = supabase_client.storage.from_(bucket).get_public_url(path)
                        media_type = mime
                        logger.info(f"📎 Media uploaded: {media_url}")
                except Exception as e:
                    logger.error(f"Media upload failed: {e}")

            # 3. Build incoming message
            sender_name = f"{first_name} {username}".strip() or f"TG User {chat_id}"
            
            incoming = IncomingMessage(
                channel="telegram",
                sender_id=chat_id,
                sender_name=sender_name,
                text=text,
                is_voice=is_voice,
                media_url=media_url,
                media_type=media_type
            )
            
            # 4. Process with unified MessageProcessor
            processor = get_message_processor()
            result = await processor.process(session, tenant, incoming)
            
            # 5. Send response via Telegram
            await telegram_service.send_message(
                token=bot_token,
                chat_id=chat_id,
                text=result["response_text"]
            )
            
            logger.info(f"✅ Telegram reply sent to {chat_id}")
            
        except Exception as e:
            logger.error(f"Error processing Telegram message: {e}", exc_info=True)


async def transcribe_telegram_voice(bot_token: str, file_id: str) -> str:
    """Download and transcribe Telegram voice message."""
    try:
        logger.info("🎤 Processing Telegram voice message...")
        
        async with httpx.AsyncClient() as client:
            # Get file path
            file_res = await client.get(
                f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}"
            )
            file_data = file_res.json()
            
            if not file_data.get("ok"):
                logger.error(f"Failed to get file path: {file_data}")
                return "[Voice Message] (Ошибка загрузки)"
            
            file_path = file_data["result"]["file_path"]
            download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
            
            # Download file
            audio_res = await client.get(download_url)
            audio_res.raise_for_status()
            audio_bytes = audio_res.content
            
            # Transcribe with Gemini
            from app.services.llm_client import get_llm_client
            llm = get_llm_client()
            transcription = await llm.transcribe_audio(audio_bytes, mime_type="audio/ogg")
            
            logger.info(f"✅ Transcription: {transcription[:50]}...")
            return f"[Voice] {transcription}"
            
    except Exception as e:
        logger.error(f"❌ Voice transcription failed: {e}")
        return "[Voice Message] (Не удалось распознать)"


async def analyze_telegram_image(bot_token: str, file_id: str) -> str:
    """Download and analyze Telegram image using Gemini Vision."""
    try:
        logger.info("📷 Processing Telegram image...")
        
        async with httpx.AsyncClient() as client:
            # Get file path
            file_res = await client.get(
                f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}"
            )
            file_data = file_res.json()
            
            if not file_data.get("ok"):
                logger.error(f"Failed to get file path: {file_data}")
                return "[Фото] (Ошибка загрузки)"
            
            file_path = file_data["result"]["file_path"]
            download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
            
            # Download file
            img_res = await client.get(download_url)
            img_res.raise_for_status()
            img_bytes = img_res.content
            
            # Determine mime type from file extension
            ext = file_path.split(".")[-1].lower()
            mime_map = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "webp": "image/webp", "gif": "image/gif"}
            mime_type = mime_map.get(ext, "image/jpeg")
            
            # Analyze with Gemini Vision
            from app.services.llm_client import get_llm_client
            llm = get_llm_client()
            analysis = await llm.analyze_image(img_bytes, mime_type=mime_type)
            
            logger.info(f"✅ Image analysis: {analysis[:50]}...")
            return f"[Фото: {analysis}]"
            
    except Exception as e:
        logger.error(f"❌ Image analysis failed: {e}")
        return "[Фото] (Не удалось проанализировать)"


async def analyze_telegram_document(bot_token: str, file_id: str, mime_type: str, file_name: str) -> str:
    """Download and analyze Telegram document."""
    try:
        logger.info(f"📄 Processing Telegram document: {file_name} ({mime_type})")
        
        async with httpx.AsyncClient() as client:
            # Get file path
            file_res = await client.get(
                f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}"
            )
            file_data = file_res.json()
            
            if not file_data.get("ok"):
                logger.error(f"Failed to get file path: {file_data}")
                return f"[Документ: {file_name}] (Ошибка загрузки)"
            
            file_path = file_data["result"]["file_path"]
            download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
            
            # Download file
            doc_res = await client.get(download_url)
            doc_res.raise_for_status()
            doc_bytes = doc_res.content
            
            # Handle based on file type
            if mime_type and mime_type.startswith("image/"):
                # It's an image sent as document
                from app.services.llm_client import get_llm_client
                llm = get_llm_client()
                analysis = await llm.analyze_image(doc_bytes, mime_type=mime_type)
                logger.info(f"✅ Document (image) analysis: {analysis[:50]}...")
                return f"[Документ-изображение: {analysis}]"
            
            elif mime_type == "application/pdf":
                # PDF - try to extract text or analyze as image
                from app.services.llm_client import get_llm_client
                llm = get_llm_client()
                # Gemini can analyze PDFs directly
                analysis = await llm.analyze_document(doc_bytes, mime_type="application/pdf", file_name=file_name)
                logger.info(f"✅ PDF analysis: {analysis[:50]}...")
                return f"[PDF-документ '{file_name}': {analysis}]"
            
            elif mime_type and mime_type.startswith("text/"):
                # Text file - read directly
                try:
                    text_content = doc_bytes.decode("utf-8")[:2000]  # Limit to 2000 chars
                    logger.info(f"✅ Text file read: {len(text_content)} chars")
                    return f"[Текстовый файл '{file_name}':\n{text_content}]"
                except:
                    return f"[Документ: {file_name}] (Не удалось прочитать текст)"
            
            else:
                # Unknown format
                return f"[Документ: {file_name}] (Формат {mime_type or 'неизвестен'} не поддерживается для анализа)"
            
    except Exception as e:
        logger.error(f"❌ Document analysis failed: {e}")
        return f"[Документ: {file_name}] (Ошибка анализа)"