File size: 7,175 Bytes
a10e62e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Communication Webhooks - Receive and process incoming events from messaging platforms.
"""

import json
import logging
import os
from typing import Any, Dict

from fastapi import APIRouter, Header, Request, BackgroundTasks, Query
from core.communication_service import communication_service

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/webhooks", tags=["webhooks"])

@router.post("/slack")
async def slack_webhook(
    request: Request,
    background_tasks: BackgroundTasks,
    x_slack_signature: str = Header(None),
    x_slack_request_timestamp: str = Header(None)
):
    """
    Handle Slack Events and Interactivity (Button Clicks).
    """
    body = await request.body()
    form_data = await request.form()
    adapter = communication_service.get_adapter("slack")

    # 1. Handle Interactivity (Button Clicks)
    if "payload" in form_data:
        payload = json.loads(form_data["payload"])
        logger.info(f"Received Slack interactivity payload: {payload.get('type')}")
        
        normalized = adapter.normalize_payload(payload)
        if not normalized:
            return {"status": "ignored"}
            
        # Dispatch to CommunicationService
        return await communication_service.handle_incoming_message(
            source="slack",
            payload=normalized,
            background_tasks=background_tasks
        )

    # 2. Handle Events (Message mentions, etc.)
    try:
        data = json.loads(body)
    except json.JSONDecodeError:
        return {"status": "error", "message": "Invalid JSON"}

    # Slack URL Verification (Challenge)
    if data.get("type") == "url_verification":
        return {"challenge": data.get("challenge")}

    # Verify Signature
    if not await adapter.verify_request(request, body):
        logger.warning("Slack signature verification failed")
        return {"status": "error", "message": "Signature mismatch"}

    logger.info(f"Received Slack event: {data.get('type')}")
    
    normalized = adapter.normalize_payload(data)
    if not normalized:
        return {"status": "ignored"}

    return await communication_service.handle_incoming_message(
        source="slack",
        payload=normalized,
        background_tasks=background_tasks
    )

@router.post("/discord")
async def discord_webhook(
    request: Request,
    background_tasks: BackgroundTasks,
    x_signature_ed25519: str = Header(None),
    x_signature_timestamp: str = Header(None)
):
    """
    Handle Discord Interactions (Buttons, Commands).
    """
    body = await request.body()
    adapter = communication_service.get_adapter("discord")
    
    # 1. Verify Signature
    if not await adapter.verify_request(request, body):
        logger.warning("Discord signature verification failed")
        return {"status": "error", "message": "Signature mismatch"}

    try:
        data = json.loads(body)
    except json.JSONDecodeError:
        return {"status": "error", "message": "Invalid JSON"}

    logger.info(f"Received Discord interaction: {data.get('type')}")
    
    normalized = adapter.normalize_payload(data)
    if not normalized:
        return {"status": "ignored"}
        
    # Support Discord PING/PONG challenge in normalization
    if normalized.get("type") == "challenge":
        return normalized.get("response")

    return await communication_service.handle_incoming_message(
        source="discord",
        payload=normalized,
        background_tasks=background_tasks
    )

@router.get("/whatsapp")
async def whatsapp_verify(
    request: Request,
    hub_mode: str = Query(None, alias="hub.mode"),
    hub_challenge: str = Query(None, alias="hub.challenge"),
    hub_verify_token: str = Query(None, alias="hub.verify_token")
):
    """Handle Meta/WhatsApp Webhook Verification (Handshake)"""
    verify_token = os.getenv("WHATSAPP_VERIFY_TOKEN")
    
    if hub_mode == "subscribe" and hub_verify_token == verify_token:
        logger.info("WhatsApp webhook verified successfully")
        return int(hub_challenge)
    
    logger.warning("WhatsApp webhook verification failed")
    return {"status": "error", "message": "Verification failed"}

@router.post("/whatsapp")
async def whatsapp_webhook(
    request: Request,
    background_tasks: BackgroundTasks,
    x_hub_signature_256: str = Header(None)
):
    """Handle WhatsApp Message Events and Interactivity"""
    body = await request.body()
    
    # 1. Verify Signature
    adapter = communication_service.get_adapter("whatsapp")
    if not await adapter.verify_request(request, body):
        logger.warning("WhatsApp signature verification failed")
        return {"status": "error", "message": "Signature mismatch"}

    try:
        data = json.loads(body)
    except json.JSONDecodeError:
        return {"status": "error", "message": "Invalid JSON"}

    logger.info("Received WhatsApp webhook event")
    
    normalized = adapter.normalize_payload(data)
    if not normalized:
        return {"status": "ignored"}
        
    return await communication_service.handle_incoming_message(
        source="whatsapp",
        payload=normalized,
        background_tasks=background_tasks
    )

@router.post("/telegram")
async def telegram_webhook(
    request: Request,
    background_tasks: BackgroundTasks,
    x_telegram_bot_api_secret_token: str = Header(None)
):
    """Handle Telegram Message Events"""
    body = await request.body()
    adapter = communication_service.get_adapter("telegram")
    
    # 1. Verify Signature
    if not await adapter.verify_request(request, body):
        logger.warning("Telegram verification failed")
        return {"status": "error", "message": "Verification failed"}

    try:
        data = json.loads(body)
    except json.JSONDecodeError:
        return {"status": "error", "message": "Invalid JSON"}

    logger.info("Received Telegram webhook event")
    
    normalized = await adapter.normalize_payload(request, body)
    if not normalized:
        return {"status": "ignored"}
    
    return await communication_service.handle_incoming_message(
        source="telegram",
        payload=normalized,
        background_tasks=background_tasks
    )

@router.post("/teams")
async def teams_webhook(
    request: Request,
    background_tasks: BackgroundTasks,
    authorization: str = Header(None)
):
    """Handle Microsoft Teams Interactions"""
    body = await request.body()
    adapter = communication_service.get_adapter("teams")
    
    # 1. Verify Signature
    if not await adapter.verify_request(request, body):
        logger.warning("Teams verification failed")
        return {"status": "error", "message": "Verification failed"}

    try:
        data = json.loads(body)
    except json.JSONDecodeError:
        return {"status": "error", "message": "Invalid JSON"}

    logger.info("Received Teams webhook event")
    
    normalized = await adapter.normalize_payload(request, body)
    if not normalized:
        return {"status": "ignored"}
        
    return await communication_service.handle_incoming_message(
        source="teams",
        payload=normalized,
        background_tasks=background_tasks
    )