2021-04-15 23:39:16 +02:00
|
|
|
from typing import Any, Dict
|
|
|
|
|
|
|
|
from django.http import HttpRequest, HttpResponse
|
|
|
|
|
2021-07-16 22:11:10 +02:00
|
|
|
from zerver.decorator import webhook_view
|
|
|
|
from zerver.lib.request import REQ, has_request_variables
|
2021-04-15 23:39:16 +02:00
|
|
|
from zerver.lib.response import json_success
|
|
|
|
from zerver.lib.webhooks.common import check_send_webhook_message, get_setup_webhook_message
|
|
|
|
from zerver.models import UserProfile
|
|
|
|
|
|
|
|
FRESHPING_TOPIC_TEMPLATE_TEST = "Freshping"
|
|
|
|
FRESHPING_TOPIC_TEMPLATE = "{check_name}"
|
|
|
|
|
|
|
|
FRESHPING_MESSAGE_TEMPLATE_UNREACHABLE = """
|
|
|
|
{request_url} has just become unreachable.
|
2021-05-10 07:02:14 +02:00
|
|
|
Error code: {http_status_code}.
|
2021-04-15 23:39:16 +02:00
|
|
|
""".strip()
|
|
|
|
FRESHPING_MESSAGE_TEMPLATE_UP = "{request_url} is back up and no longer unreachable."
|
2021-07-16 11:40:46 +02:00
|
|
|
ALL_EVENT_TYPES = ["Reporting Error", "Available"]
|
2021-04-15 23:39:16 +02:00
|
|
|
|
|
|
|
|
2021-07-16 11:40:46 +02:00
|
|
|
@webhook_view("Freshping", all_event_types=ALL_EVENT_TYPES)
|
2021-04-15 23:39:16 +02:00
|
|
|
@has_request_variables
|
|
|
|
def api_freshping_webhook(
|
|
|
|
request: HttpRequest,
|
|
|
|
user_profile: UserProfile,
|
|
|
|
payload: Dict[str, Any] = REQ(argument_type="body"),
|
|
|
|
) -> HttpResponse:
|
|
|
|
|
|
|
|
body = get_body_for_http_request(payload)
|
|
|
|
subject = get_subject_for_http_request(payload)
|
|
|
|
|
2021-07-16 11:40:46 +02:00
|
|
|
check_send_webhook_message(
|
|
|
|
request, user_profile, subject, body, payload["webhook_event_data"]["check_state_name"]
|
|
|
|
)
|
2022-01-31 13:44:02 +01:00
|
|
|
return json_success(request)
|
2021-04-15 23:39:16 +02:00
|
|
|
|
|
|
|
|
|
|
|
def get_subject_for_http_request(payload: Dict[str, Any]) -> str:
|
|
|
|
webhook_event_data = payload["webhook_event_data"]
|
|
|
|
if webhook_event_data["application_name"] == "Webhook test":
|
|
|
|
subject = FRESHPING_TOPIC_TEMPLATE_TEST
|
|
|
|
else:
|
|
|
|
subject = FRESHPING_TOPIC_TEMPLATE.format(check_name=webhook_event_data["check_name"])
|
|
|
|
|
|
|
|
return subject
|
|
|
|
|
|
|
|
|
|
|
|
def get_body_for_http_request(payload: Dict[str, Any]) -> str:
|
|
|
|
webhook_event_data = payload["webhook_event_data"]
|
|
|
|
if webhook_event_data["check_state_name"] == "Reporting Error":
|
|
|
|
body = FRESHPING_MESSAGE_TEMPLATE_UNREACHABLE.format(**webhook_event_data)
|
|
|
|
elif webhook_event_data["check_state_name"] == "Available":
|
|
|
|
if webhook_event_data["application_name"] == "Webhook test":
|
|
|
|
body = get_setup_webhook_message("Freshping")
|
|
|
|
else:
|
|
|
|
body = FRESHPING_MESSAGE_TEMPLATE_UP.format(**webhook_event_data)
|
|
|
|
|
|
|
|
return body
|