zulip/zerver/webhooks/circleci/view.py

49 lines
1.7 KiB
Python
Raw Normal View History

2016-05-09 19:59:33 +02:00
# Webhooks for external integrations.
2016-07-30 00:41:28 +02:00
from typing import Any, Dict, Text
2016-07-30 00:41:28 +02:00
2017-11-16 00:43:10 +01:00
import ujson
from django.http import HttpRequest, HttpResponse
from zerver.decorator import api_key_only_webhook_view
from zerver.lib.request import REQ, has_request_variables
2017-11-16 00:43:10 +01:00
from zerver.lib.response import json_error, json_success
from zerver.lib.webhooks.common import check_send_webhook_message
from zerver.models import UserProfile
2016-05-09 19:59:33 +02:00
CIRCLECI_SUBJECT_TEMPLATE = u'{repository_name}'
CIRCLECI_MESSAGE_TEMPLATE = u'[Build]({build_url}) triggered by {username} on {branch} branch {status}.'
2016-05-09 19:59:33 +02:00
FAILED_STATUS = 'failed'
@api_key_only_webhook_view('CircleCI')
2016-05-09 19:59:33 +02:00
@has_request_variables
def api_circleci_webhook(request: HttpRequest, user_profile: UserProfile,
payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
2016-05-09 19:59:33 +02:00
payload = payload['payload']
subject = get_subject(payload)
body = get_body(payload)
check_send_webhook_message(request, user_profile, subject, body)
2016-05-09 19:59:33 +02:00
return json_success()
def get_subject(payload: Dict[str, Any]) -> Text:
2016-05-09 19:59:33 +02:00
return CIRCLECI_SUBJECT_TEMPLATE.format(repository_name=payload['reponame'])
def get_body(payload: Dict[str, Any]) -> Text:
2016-05-09 19:59:33 +02:00
data = {
'build_url': payload['build_url'],
'username': payload['username'],
'branch': payload['branch'],
'status': get_status(payload)
}
return CIRCLECI_MESSAGE_TEMPLATE.format(**data)
def get_status(payload: Dict[str, Any]) -> Text:
2016-05-09 19:59:33 +02:00
status = payload['status']
if payload['previous'] and payload['previous']['status'] == FAILED_STATUS and status == FAILED_STATUS:
return u'is still failing'
2016-05-09 19:59:33 +02:00
if status == 'success':
return u'succeeded'
2016-05-09 19:59:33 +02:00
return status