2021-04-09 03:50:04 +02:00
|
|
|
import json
|
2024-07-12 02:30:17 +02:00
|
|
|
from typing import Any
|
2021-04-09 03:50:04 +02:00
|
|
|
|
|
|
|
from django.http import HttpRequest, HttpResponse
|
|
|
|
|
2021-07-16 22:11:10 +02:00
|
|
|
from zerver.decorator import webhook_view
|
2021-04-09 03:50:04 +02:00
|
|
|
from zerver.lib.response import json_success
|
2023-09-27 19:01:31 +02:00
|
|
|
from zerver.lib.typed_endpoint import JsonBodyPayload, typed_endpoint
|
2021-04-09 03:50:04 +02:00
|
|
|
from zerver.lib.webhooks.common import check_send_webhook_message
|
|
|
|
from zerver.models import UserProfile
|
|
|
|
|
|
|
|
JSON_MESSAGE_TEMPLATE = """
|
|
|
|
```json
|
|
|
|
{webhook_payload}
|
|
|
|
```
|
|
|
|
""".strip()
|
|
|
|
|
|
|
|
|
|
|
|
@webhook_view("JSON")
|
2023-08-14 23:40:43 +02:00
|
|
|
@typed_endpoint
|
2021-04-09 03:50:04 +02:00
|
|
|
def api_json_webhook(
|
|
|
|
request: HttpRequest,
|
|
|
|
user_profile: UserProfile,
|
2023-08-14 23:40:43 +02:00
|
|
|
*,
|
2024-07-12 02:30:17 +02:00
|
|
|
payload: JsonBodyPayload[dict[str, Any]],
|
2021-04-09 03:50:04 +02:00
|
|
|
) -> HttpResponse:
|
|
|
|
body = get_body_for_http_request(payload)
|
2024-01-17 15:53:30 +01:00
|
|
|
topic_name = get_topic_for_http_request(payload)
|
2021-04-09 03:50:04 +02:00
|
|
|
|
2024-01-17 15:53:30 +01:00
|
|
|
check_send_webhook_message(request, user_profile, topic_name, body)
|
2022-01-31 13:44:02 +01:00
|
|
|
return json_success(request)
|
2021-04-09 03:50:04 +02:00
|
|
|
|
|
|
|
|
2024-07-12 02:30:17 +02:00
|
|
|
def get_topic_for_http_request(payload: dict[str, Any]) -> str:
|
2021-04-09 03:50:04 +02:00
|
|
|
return "JSON"
|
|
|
|
|
|
|
|
|
2024-07-12 02:30:17 +02:00
|
|
|
def get_body_for_http_request(payload: dict[str, Any]) -> str:
|
2021-04-09 03:50:04 +02:00
|
|
|
prettypayload = json.dumps(payload, indent=2)
|
|
|
|
return JSON_MESSAGE_TEMPLATE.format(webhook_payload=prettypayload, sort_keys=True)
|