zulip/zerver/webhooks/circleci/view.py

54 lines
1.8 KiB
Python
Raw Normal View History

2016-05-09 19:59:33 +02:00
# Webhooks for external integrations.
from __future__ import absolute_import
2016-07-30 00:41:28 +02:00
from django.http import HttpRequest, HttpResponse
from typing import Any, Text
2016-07-30 00:41:28 +02:00
2016-05-09 19:59:33 +02:00
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
2016-07-30 00:41:28 +02:00
from zerver.models import UserProfile, Client
2016-05-09 19:59:33 +02:00
import ujson
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, user_profile, client, payload=REQ(argument_type='body'),
stream=REQ(default='circleci')):
# type: (HttpRequest, UserProfile, Client, Dict[str, Any], Text) -> HttpResponse
2016-05-09 19:59:33 +02:00
payload = payload['payload']
subject = get_subject(payload)
body = get_body(payload)
check_send_message(user_profile, client, 'stream', [stream], subject, body)
2016-05-09 19:59:33 +02:00
return json_success()
def get_subject(payload):
# type: (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):
# type: (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):
# type: (Dict[str, Any]) -> Text
2016-05-09 19:59:33 +02:00
status = payload['status']
if 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