Exemplo n.º 1
0
def api_freshdesk_webhook(request: HttpRequest, user_profile: UserProfile,
                          payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
    ticket_data = payload["freshdesk_webhook"]

    required_keys = [
        "triggered_event", "ticket_id", "ticket_url", "ticket_type",
        "ticket_subject", "ticket_description", "ticket_status",
        "ticket_priority", "requester_name", "requester_email",
    ]

    for key in required_keys:
        if ticket_data.get(key) is None:
            logging.warning("Freshdesk webhook error. Payload was:")
            logging.warning(request.body)
            return json_error(_("Missing key %s in JSON") % (key,))

    ticket = TicketDict(ticket_data)

    subject = "#%s: %s" % (ticket.id, ticket.subject)
    event_info = parse_freshdesk_event(ticket.triggered_event)

    if event_info[1] == "created":
        content = format_freshdesk_ticket_creation_message(ticket)
    elif event_info[0] == "note_type":
        content = format_freshdesk_note_message(ticket, event_info)
    elif event_info[0] in ("status", "priority"):
        content = format_freshdesk_property_change_message(ticket, event_info)
    else:
        # Not an event we know handle; do nothing.
        return json_success()

    check_send_webhook_message(request, user_profile, subject, content)
    return json_success()
Exemplo n.º 2
0
def api_travis_webhook(request: HttpRequest, user_profile: UserProfile,
                       ignore_pull_requests: bool = REQ(validator=check_bool, default=True),
                       message: Dict[str, str]=REQ('payload', validator=check_dict([
                           ('author_name', check_string),
                           ('status_message', check_string),
                           ('compare_url', check_string),
                       ]))) -> HttpResponse:

    message_status = message['status_message']
    if ignore_pull_requests and message['type'] == 'pull_request':
        return json_success()

    if message_status in GOOD_STATUSES:
        emoji = ':thumbs_up:'
    elif message_status in BAD_STATUSES:
        emoji = ':thumbs_down:'
    else:
        emoji = "(No emoji specified for status '{}'.)".format(message_status)

    body = MESSAGE_TEMPLATE.format(
        message['author_name'],
        message_status,
        emoji,
        message['compare_url'],
        message['build_url']
    )
    topic = 'builds'

    check_send_webhook_message(request, user_profile, topic, body)
    return json_success()
Exemplo n.º 3
0
def api_wordpress_webhook(request: HttpRequest, user_profile: UserProfile,
                          hook: str=REQ(default="WordPress Action"),
                          post_title: str=REQ(default="New WordPress Post"),
                          post_type: str=REQ(default="post"),
                          post_url: str=REQ(default="WordPress Post URL"),
                          display_name: str=REQ(default="New User Name"),
                          user_email: str=REQ(default="New User Email"),
                          user_login: str=REQ(default="Logged in User")) -> HttpResponse:
    # remove trailing whitespace (issue for some test fixtures)
    hook = hook.rstrip()

    if hook == 'publish_post' or hook == 'publish_page':
        data = PUBLISH_POST_OR_PAGE_TEMPLATE.format(type=post_type, title=post_title, url=post_url)

    elif hook == 'user_register':
        data = USER_REGISTER_TEMPLATE.format(name=display_name, email=user_email)

    elif hook == 'wp_login':
        data = WP_LOGIN_TEMPLATE.format(name=user_login)

    else:
        return json_error(_("Unknown WordPress webhook action: " + hook))

    topic = 'WordPress Notification'

    check_send_webhook_message(request, user_profile, topic, data)
    return json_success()
Exemplo n.º 4
0
def send_formated_pagerduty(request: HttpRequest,
                            user_profile: UserProfile,
                            message_type: Text,
                            format_dict: Dict[str, Any]) -> None:
    if message_type in ('incident.trigger', 'incident.unacknowledge'):
        template = (u':imp: Incident '
                    u'[{incident_num}]({incident_url}) {action} by '
                    u'[{service_name}]({service_url}) and assigned to '
                    u'[{assigned_to_username}@]({assigned_to_url})\n\n>{trigger_message}')

    elif message_type == 'incident.resolve' and format_dict['resolved_by_url']:
        template = (u':grinning: Incident '
                    u'[{incident_num}]({incident_url}) resolved by '
                    u'[{resolved_by_username}@]({resolved_by_url})\n\n>{trigger_message}')
    elif message_type == 'incident.resolve' and not format_dict['resolved_by_url']:
        template = (u':grinning: Incident '
                    u'[{incident_num}]({incident_url}) resolved\n\n>{trigger_message}')
    else:
        template = (u':no_good: Incident [{incident_num}]({incident_url}) '
                    u'{action} by [{assigned_to_username}@]({assigned_to_url})\n\n>{trigger_message}')

    subject = u'incident {incident_num}'.format(**format_dict)
    body = template.format(**format_dict)

    check_send_webhook_message(request, user_profile, subject, body)
Exemplo n.º 5
0
def api_jira_webhook(request: HttpRequest, user_profile: UserProfile,
                     payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:

    event = get_event_type(payload)
    if event == 'jira:issue_created':
        subject = get_issue_subject(payload)
        content = handle_created_issue_event(payload)
    elif event == 'jira:issue_deleted':
        subject = get_issue_subject(payload)
        content = handle_deleted_issue_event(payload)
    elif event == 'jira:issue_updated':
        subject = get_issue_subject(payload)
        content = handle_updated_issue_event(payload, user_profile)
    elif event in IGNORED_EVENTS:
        return json_success()
    else:
        if event is None:
            if not settings.TEST_SUITE:
                message = u"Got JIRA event with None event type: {}".format(payload)
                logging.warning(message)
            return json_error(_("Event is not given by JIRA"))
        else:
            if not settings.TEST_SUITE:
                logging.warning("Got JIRA event type we don't support: {}".format(event))
            return json_success()

    check_send_webhook_message(request, user_profile, subject, content)
    return json_success()
Exemplo n.º 6
0
def api_jira_webhook(request: HttpRequest, user_profile: UserProfile,
                     payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:

    event = get_event_type(payload)
    if event == 'jira:issue_created':
        subject = get_issue_subject(payload)
        content = handle_created_issue_event(payload)
    elif event == 'jira:issue_deleted':
        subject = get_issue_subject(payload)
        content = handle_deleted_issue_event(payload)
    elif event == 'jira:issue_updated':
        subject = get_issue_subject(payload)
        content = handle_updated_issue_event(payload, user_profile)
    elif event == 'comment_created':
        subject = get_issue_subject(payload)
        content = handle_updated_issue_event(payload, user_profile)
    elif event in IGNORED_EVENTS:
        return json_success()
    else:
        raise UnexpectedWebhookEventType('Jira', event)

    check_send_webhook_message(request, user_profile,
                               subject, content,
                               unquote_url_parameters=True)
    return json_success()
Exemplo n.º 7
0
def api_papertrail_webhook(request: HttpRequest, user_profile: UserProfile,
                           payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:

    # construct the message of the message
    message_template = '**"{}"** search found **{}** matches - {}\n```'
    message = [message_template.format(payload["saved_search"]["name"],
                                       str(len(payload["events"])),
                                       payload["saved_search"]["html_search_url"])]
    for i, event in enumerate(payload["events"]):
        event_text = '{} {} {}:\n  {}'.format(event["display_received_at"],
                                              event["source_name"],
                                              payload["saved_search"]["query"],
                                              event["message"])
        message.append(event_text)
        if i >= 3:
            message.append('```\n[See more]({})'.format(payload["saved_search"]["html_search_url"]))
            break
    else:
        message.append('```')
    post = '\n'.join(message)

    topic = 'logs'

    # send the message
    check_send_webhook_message(request, user_profile, topic, post)

    # return json result
    return json_success()
Exemplo n.º 8
0
Arquivo: view.py Projeto: jdherg/zulip
def api_zapier_webhook(request: HttpRequest, user_profile: UserProfile,
                       payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
    if payload.get('type') == 'auth':
        # The bot's details are used by our Zapier app to format a connection
        # label for users to be able to distinguish between different Zulip
        # bots and API keys in their UI
        return json_success({
            'full_name': user_profile.full_name,
            'email': user_profile.email,
            'id': user_profile.id
        })

    topic = payload.get('topic')
    content = payload.get('content')

    if topic is None:
        topic = payload.get('subject')  # Backwards-compatibility
        if topic is None:
            return json_error(_("Topic can't be empty"))

    if content is None:
        return json_error(_("Content can't be empty"))

    check_send_webhook_message(request, user_profile, topic, content)
    return json_success()
Exemplo n.º 9
0
def api_insping_webhook(
        request: HttpRequest, user_profile: UserProfile,
        payload: Dict[str, Dict[str, Any]]=REQ(argument_type='body')
) -> HttpResponse:

    data = payload['webhook_event_data']

    state_name = data['check_state_name']
    url_tested = data['request_url']
    response_time = data['response_time']
    timestamp = data['request_start_time']

    time_formatted = time.strftime("%c", time.strptime(timestamp,
                                   "%Y-%m-%dT%H:%M:%S.%f+00:00"))

    body = """State changed: {}
URL: {}
Response time: {} ms
Timestamp: {}
""".format(state_name, url_tested, response_time, time_formatted)
    topic = 'insping'

    check_send_webhook_message(request, user_profile, topic, body)

    return json_success()
Exemplo n.º 10
0
def api_raygun_webhook(request: HttpRequest, user_profile: UserProfile,
                       payload: Dict[str, Any] = REQ(argument_type='body')) -> HttpResponse:
    # The payload contains 'event' key. This 'event' key has a value of either
    # 'error_notification' or 'error_activity'. 'error_notification' happens
    # when an error is caught in an application, where as 'error_activity'
    # happens when an action is being taken for the error itself
    # (ignored/resolved/assigned/etc.).
    event = payload['event']

    # Because we wanted to create a message for all of the payloads, it is best
    # to handle them separately. This is because some payload keys don't exist
    # in the other event.

    if event == 'error_notification':
        message = compose_notification_message(payload)
    elif event == 'error_activity':
        message = compose_activity_message(payload)
    else:
        message = "Unsupported event type: {}".format(event)

    topic = 'test'

    check_send_webhook_message(request, user_profile, topic, message)

    return json_success()
Exemplo n.º 11
0
def api_bitbucket_webhook(request: HttpRequest, user_profile: UserProfile,
                          payload: Mapping[str, Any]=REQ(validator=check_dict([])),
                          branches: Optional[str]=REQ(default=None)) -> HttpResponse:
    repository = payload['repository']

    commits = [
        {
            'name': payload.get('user'),
            'sha': commit.get('raw_node'),
            'message': commit.get('message'),
            'url': u'{}{}commits/{}'.format(
                payload.get('canon_url'),
                repository.get('absolute_url'),
                commit.get('raw_node'))
        }
        for commit in payload['commits']
    ]

    if len(commits) == 0:
        # Bitbucket doesn't give us enough information to really give
        # a useful message :/
        subject = repository['name']
        content = (u"%s [force pushed](%s)"
                   % (payload['user'],
                      payload['canon_url'] + repository['absolute_url']))
    else:
        branch = payload['commits'][-1]['branch']
        if branches is not None and branches.find(branch) == -1:
            return json_success()
        content = get_push_commits_event_message(payload['user'], None, branch, commits)
        subject = SUBJECT_WITH_BRANCH_TEMPLATE.format(repo=repository['name'], branch=branch)

    check_send_webhook_message(request, user_profile, subject, content)
    return json_success()
Exemplo n.º 12
0
def api_gogs_webhook(request: HttpRequest, user_profile: UserProfile,
                     payload: Dict[str, Any]=REQ(argument_type='body'),
                     branches: Optional[Text]=REQ(default=None)) -> HttpResponse:

    repo = payload['repository']['name']
    event = request.META['HTTP_X_GOGS_EVENT']
    if event == 'push':
        branch = payload['ref'].replace('refs/heads/', '')
        if branches is not None and branches.find(branch) == -1:
            return json_success()
        body = format_push_event(payload)
        topic = SUBJECT_WITH_BRANCH_TEMPLATE.format(
            repo=repo,
            branch=branch
        )
    elif event == 'create':
        body = format_new_branch_event(payload)
        topic = SUBJECT_WITH_BRANCH_TEMPLATE.format(
            repo=repo,
            branch=payload['ref']
        )
    elif event == 'pull_request':
        body = format_pull_request_event(payload)
        topic = SUBJECT_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
            repo=repo,
            type='PR',
            id=payload['pull_request']['id'],
            title=payload['pull_request']['title']
        )
    else:
        return json_error(_('Invalid event "{}" in request headers').format(event))

    check_send_webhook_message(request, user_profile, topic, body)
    return json_success()
Exemplo n.º 13
0
def api_beanstalk_webhook(request: HttpRequest, user_profile: UserProfile,
                          payload: Dict[str, Any]=REQ(validator=check_dict([])),
                          branches: Optional[str]=REQ(default=None)) -> HttpResponse:
    # Beanstalk supports both SVN and git repositories
    # We distinguish between the two by checking for a
    # 'uri' key that is only present for git repos
    git_repo = 'uri' in payload
    if git_repo:
        if branches is not None and branches.find(payload['branch']) == -1:
            return json_success()
        # To get a linkable url,
        for commit in payload['commits']:
            commit['author'] = {'username': commit['author']['name']}

        subject, content = build_message_from_gitlog(user_profile, payload['repository']['name'],
                                                     payload['ref'], payload['commits'],
                                                     payload['before'], payload['after'],
                                                     payload['repository']['url'],
                                                     payload['pusher_name'])
    else:
        author = payload.get('author_full_name')
        url = payload.get('changeset_url')
        revision = payload.get('revision')
        (short_commit_msg, _, _) = payload['message'].partition("\n")

        subject = "svn r%s" % (revision,)
        content = "%s pushed [revision %s](%s):\n\n> %s" % (author, revision, url, short_commit_msg)

    check_send_webhook_message(request, user_profile, subject, content)
    return json_success()
Exemplo n.º 14
0
def api_basecamp_webhook(request: HttpRequest, user_profile: UserProfile,
                         payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
    event = get_event_type(payload)

    if event not in SUPPORT_EVENTS:
        raise UnexpectedWebhookEventType('Basecamp', event)

    subject = get_project_name(payload)
    if event.startswith('document_'):
        body = get_document_body(event, payload)
    elif event.startswith('question_answer_'):
        body = get_questions_answer_body(event, payload)
    elif event.startswith('question_'):
        body = get_questions_body(event, payload)
    elif event.startswith('message_'):
        body = get_message_body(event, payload)
    elif event.startswith('todolist_'):
        body = get_todo_list_body(event, payload)
    elif event.startswith('todo_'):
        body = get_todo_body(event, payload)
    elif event.startswith('comment_'):
        body = get_comment_body(event, payload)
    else:
        raise UnexpectedWebhookEventType('Basecamp', event)

    check_send_webhook_message(request, user_profile, subject, body)
    return json_success()
Exemplo n.º 15
0
def api_gocd_webhook(request: HttpRequest, user_profile: UserProfile,
                     payload: Dict[str, Any]=REQ(argument_type='body'),
                     ) -> HttpResponse:

    modifications = payload['build_cause']['material_revisions'][0]['modifications'][0]
    result = payload['stages'][0]['result']
    material = payload['build_cause']['material_revisions'][0]['material']

    if result == "Passed":
        emoji = ':thumbs_up:'
    elif result == "Failed":
        emoji = ':thumbs_down:'

    build_details_file = os.path.join(os.path.dirname(__file__), 'fixtures/build_details.json')

    with open(build_details_file, 'r') as f:
        contents = json.load(f)
        build_link = contents["build_details"]["_links"]["pipeline"]["href"]

    body = MESSAGE_TEMPLATE.format(
        modifications['user_name'],
        result,
        emoji,
        build_link,
        modifications['comment']
    )
    branch = material['description'].split(",")
    topic = branch[0].split(" ")[1]

    check_send_webhook_message(request, user_profile, topic, body)

    return json_success()
Exemplo n.º 16
0
def api_hellosign_webhook(request: HttpRequest, user_profile: UserProfile,
                          payload: Dict[str, Dict[str, Any]]=REQ(argument_type='body')) -> HttpResponse:
    model_payload = ready_payload(payload['signature_request']['signatures'], payload)
    body = format_body(payload['signature_request']['signatures'], model_payload)
    topic = model_payload['contract_title']
    check_send_webhook_message(request, user_profile, topic, body)
    return json_success()
Exemplo n.º 17
0
def api_basecamp_webhook(request: HttpRequest, user_profile: UserProfile,
                         payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
    event = get_event_type(payload)

    if event not in SUPPORT_EVENTS:
        logging.warning("Basecamp {} event is not supported".format(event))
        return json_success()

    subject = get_project_name(payload)
    if event.startswith('document_'):
        body = get_document_body(event, payload)
    elif event.startswith('question_answer_'):
        body = get_questions_answer_body(event, payload)
    elif event.startswith('question_'):
        body = get_questions_body(event, payload)
    elif event.startswith('message_'):
        body = get_message_body(event, payload)
    elif event.startswith('todolist_'):
        body = get_todo_list_body(event, payload)
    elif event.startswith('todo_'):
        body = get_todo_body(event, payload)
    elif event.startswith('comment_'):
        body = get_comment_body(event, payload)
    else:
        logging.warning("Basecamp handling of {} event is not implemented".format(event))
        return json_success()

    check_send_webhook_message(request, user_profile, subject, body)
    return json_success()
Exemplo n.º 18
0
def api_bitbucket2_webhook(request: HttpRequest, user_profile: UserProfile,
                           payload: Dict[str, Any]=REQ(argument_type='body'),
                           branches: Optional[str]=REQ(default=None),
                           user_specified_topic: Optional[str]=REQ("topic", default=None)) -> HttpResponse:
    type = get_type(request, payload)
    if type == 'push':
        # ignore push events with no changes
        if not payload['push']['changes']:
            return json_success()
        branch = get_branch_name_for_push_event(payload)
        if branch and branches:
            if branches.find(branch) == -1:
                return json_success()

    subject = get_subject_based_on_type(payload, type)
    body_function = get_body_based_on_type(type)
    if 'include_title' in signature(body_function).parameters:
        body = body_function(
            payload,
            include_title=user_specified_topic is not None
        )
    else:
        body = body_function(payload)

    if type != 'push':
        check_send_webhook_message(request, user_profile, subject, body)
    else:
        for b, s in zip(body, subject):
            check_send_webhook_message(request, user_profile, s, b)

    return json_success()
Exemplo n.º 19
0
def api_splunk_webhook(request: HttpRequest, user_profile: UserProfile,
                       payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:

    # use default values if expected data is not provided
    search_name = payload.get('search_name', 'Missing search_name')
    results_link = payload.get('results_link', 'Missing results_link')
    host = payload.get('result', {}).get('host', 'Missing host')
    source = payload.get('result', {}).get('source', 'Missing source')
    raw = payload.get('result', {}).get('_raw', 'Missing _raw')

    # for the default topic, use search name but truncate if too long
    if len(search_name) >= MAX_TOPIC_NAME_LENGTH:
        topic = "{}...".format(search_name[:(MAX_TOPIC_NAME_LENGTH - 3)])
    else:
        topic = search_name

    # construct the message body
    body = "Splunk alert from saved search"
    body_template = ('\n[{search}]({link})\nhost: {host}'
                     '\nsource: {source}\n\nraw: {raw}')
    body += body_template.format(search = search_name, link = results_link,
                                 host = host, source = source, raw = raw)

    # send the message
    check_send_webhook_message(request, user_profile, topic, body)

    return json_success()
Exemplo n.º 20
0
def api_gogs_webhook(request: HttpRequest, user_profile: UserProfile,
                     payload: Dict[str, Any]=REQ(argument_type='body'),
                     branches: Optional[str]=REQ(default=None)) -> HttpResponse:

    repo = payload['repository']['name']
    event = validate_extract_webhook_http_header(request, 'X_GOGS_EVENT', 'Gogs')
    if event == 'push':
        branch = payload['ref'].replace('refs/heads/', '')
        if branches is not None and branches.find(branch) == -1:
            return json_success()
        body = format_push_event(payload)
        topic = SUBJECT_WITH_BRANCH_TEMPLATE.format(
            repo=repo,
            branch=branch
        )
    elif event == 'create':
        body = format_new_branch_event(payload)
        topic = SUBJECT_WITH_BRANCH_TEMPLATE.format(
            repo=repo,
            branch=payload['ref']
        )
    elif event == 'pull_request':
        body = format_pull_request_event(payload)
        topic = SUBJECT_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
            repo=repo,
            type='PR',
            id=payload['pull_request']['id'],
            title=payload['pull_request']['title']
        )
    else:
        raise UnexpectedWebhookEventType('Gogs', event)

    check_send_webhook_message(request, user_profile, topic, body)
    return json_success()
Exemplo n.º 21
0
def api_heroku_webhook(request: HttpRequest, user_profile: UserProfile,
                       head: Text=REQ(), app: Text=REQ(), user: Text=REQ(),
                       url: Text=REQ(), git_log: Text=REQ()) -> HttpResponse:
    template = "{} deployed version {} of [{}]({})\n> {}"
    content = template.format(user, head, app, url, git_log)

    check_send_webhook_message(request, user_profile, app, content)
    return json_success()
Exemplo n.º 22
0
def api_dropbox_webhook(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
    if request.method == 'GET':
        return HttpResponse(request.GET['challenge'])
    elif request.method == 'POST':
        topic = 'Dropbox'
        check_send_webhook_message(request, user_profile, topic,
                                   "File has been updated on Dropbox!")
        return json_success()
Exemplo n.º 23
0
def api_zabbix_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)

    check_send_webhook_message(request, user_profile, subject, body)
    return json_success()
Exemplo n.º 24
0
def api_sentry_webhook(request: HttpRequest, user_profile: UserProfile,
                       payload: Dict[str, Any] = REQ(argument_type='body')) -> HttpResponse:
    subject = "{}".format(payload.get('project_name'))
    body = "New {} [issue]({}): {}.".format(payload['level'].upper(),
                                            payload.get('url'),
                                            payload.get('message'))
    check_send_webhook_message(request, user_profile, subject, body)
    return json_success()
Exemplo n.º 25
0
def api_ansibletower_webhook(request: HttpRequest, user_profile: UserProfile,
                             payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:

    body = get_body(payload)
    subject = payload['name']

    check_send_webhook_message(request, user_profile, subject, body)
    return json_success()
Exemplo n.º 26
0
def api_circleci_webhook(request: HttpRequest, user_profile: UserProfile,
                         payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
    payload = payload['payload']
    subject = get_subject(payload)
    body = get_body(payload)

    check_send_webhook_message(request, user_profile, subject, body)
    return json_success()
Exemplo n.º 27
0
def api_gitlab_webhook(request: HttpRequest, user_profile: UserProfile,
                       payload: Dict[str, Any]=REQ(argument_type='body'),
                       branches: Optional[Text]=REQ(default=None)) -> HttpResponse:
    event = get_event(request, payload, branches)
    if event is not None:
        body = get_body_based_on_event(event)(payload)
        topic = get_subject_based_on_event(event, payload)
        check_send_webhook_message(request, user_profile, topic, body)
    return json_success()
Exemplo n.º 28
0
def api_appfollow_webhook(request: HttpRequest, user_profile: UserProfile,
                          payload: Dict[str, Any]=REQ(argument_type="body")) -> HttpResponse:
    message = payload["text"]
    app_name = re.search('\A(.+)', message).group(0)
    topic = app_name

    check_send_webhook_message(request, user_profile, topic,
                               body=convert_markdown(message))
    return json_success()
Exemplo n.º 29
0
def api_stripe_webhook(request: HttpRequest, user_profile: UserProfile,
                       payload: Dict[str, Any]=REQ(argument_type='body'),
                       stream: str=REQ(default='test')) -> HttpResponse:
    try:
        topic, body = topic_and_body(payload)
    except SuppressedEvent:  # nocoverage
        return json_success()
    check_send_webhook_message(request, user_profile, topic, body)
    return json_success()
Exemplo n.º 30
0
def api_github_webhook(
        request: HttpRequest, user_profile: UserProfile,
        payload: Dict[str, Any]=REQ(argument_type='body'),
        branches: Text=REQ(default=None)) -> HttpResponse:
    event = get_event(request, payload, branches)
    if event is not None:
        subject = get_subject_based_on_type(payload, event)
        body = get_body_function_based_on_type(event)(payload)
        check_send_webhook_message(request, user_profile, subject, body)
    return json_success()
Exemplo n.º 31
0
def gogs_webhook_main(integration_name: str, http_header_name: str,
                      format_pull_request_event: Callable[..., Any],
                      request: HttpRequest, user_profile: UserProfile,
                      payload: Dict[str, Any], branches: Optional[str],
                      user_specified_topic: Optional[str]) -> HttpResponse:
    repo = payload['repository']['name']
    event = validate_extract_webhook_http_header(request, http_header_name,
                                                 integration_name)
    if event == 'push':
        branch = payload['ref'].replace('refs/heads/', '')
        if branches is not None and branch not in branches.split(','):
            return json_success()
        body = format_push_event(payload)
        topic = TOPIC_WITH_BRANCH_TEMPLATE.format(repo=repo, branch=branch)
    elif event == 'create':
        body = format_new_branch_event(payload)
        topic = TOPIC_WITH_BRANCH_TEMPLATE.format(repo=repo,
                                                  branch=payload['ref'])
    elif event == 'pull_request':
        body = format_pull_request_event(payload,
                                         include_title=user_specified_topic
                                         is not None)
        topic = TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
            repo=repo,
            type='PR',
            id=payload['pull_request']['id'],
            title=payload['pull_request']['title'])
    elif event == 'issues':
        body = format_issues_event(payload,
                                   include_title=user_specified_topic
                                   is not None)
        topic = TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
            repo=repo,
            type='Issue',
            id=payload['issue']['number'],
            title=payload['issue']['title'])
    elif event == 'issue_comment':
        body = format_issue_comment_event(payload,
                                          include_title=user_specified_topic
                                          is not None)
        topic = TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
            repo=repo,
            type='Issue',
            id=payload['issue']['number'],
            title=payload['issue']['title'])
    else:
        raise UnexpectedWebhookEventType('Gogs', event)

    check_send_webhook_message(request, user_profile, topic, body)
    return json_success()
Exemplo n.º 32
0
def api_alertmanager_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Any] = REQ(argument_type='body')
) -> HttpResponse:
    name_field = request.GET.get("name", "instance")
    desc_field = request.GET.get("desc", "alertname")
    topics = {}  # type: Dict[str, Dict[str, List[str]]]

    for alert in payload["alerts"]:
        labels = alert.get("labels", {})
        annotations = alert.get("annotations", {})

        name = labels.get(name_field, annotations.get(name_field, "(unknown)"))
        desc = labels.get(
            desc_field,
            annotations.get(desc_field,
                            "<missing field: {}>".format(desc_field)))

        url = alert.get("generatorURL").replace("tab=1", "tab=0")

        body = "{description} ([graph]({url}))".format(description=desc,
                                                       url=url)
        if name not in topics:
            topics[name] = {"firing": [], "resolved": []}
        topics[name][alert["status"]].append(body)

    for topic, statuses in topics.items():
        for status, messages in statuses.items():
            if len(messages) == 0:
                continue

            if status == "firing":
                icon = ":alert:"
                title = "FIRING"
            else:
                title = "Resolved"
                icon = ":squared_ok:"

            if len(messages) == 1:
                body = "{icon} **{title}** {message}".format(
                    icon=icon, title=title, message=messages[0])
            else:
                message_list = "\n".join(["* {}".format(m) for m in messages])
                body = "{icon} **{title}**\n{messages}".format(
                    icon=icon, title=title, messages=message_list)

            check_send_webhook_message(request, user_profile, topic, body)

    return json_success()
Exemplo n.º 33
0
Arquivo: view.py Projeto: zippyy/zulip
def api_heroku_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    head: Text = REQ(),
    app: Text = REQ(),
    user: Text = REQ(),
    url: Text = REQ(),
    git_log: Text = REQ()
) -> HttpResponse:
    template = "{} deployed version {} of [{}]({})\n> {}"
    content = template.format(user, head, app, url, git_log)

    check_send_webhook_message(request, user_profile, app, content)
    return json_success()
Exemplo n.º 34
0
def api_opbeat_webhook(request: HttpRequest, user_profile: UserProfile,
                       payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
    """
    This uses the subject name from opbeat to make the subject,
    and the summary from Opbeat as the message body, with
    details about the object mentioned.
    """

    message_subject = payload['title']

    message = format_object(payload, 'base', '')

    check_send_webhook_message(request, user_profile, message_subject, message)
    return json_success()
Exemplo n.º 35
0
def api_solano_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Any] = REQ(argument_type='body')
) -> HttpResponse:
    event = payload.get('event')
    topic = 'build update'
    if event == 'test':
        return handle_test_event(request, user_profile, topic)
    try:
        author = payload['committers'][0]
    except KeyError:
        author = 'Unknown'
    status = payload['status']
    build_log = payload['url']
    repository = payload['repository']['url']
    commit_id = payload['commit_id']

    good_status = ['passed']
    bad_status = ['failed', 'error']
    neutral_status = ['running']
    emoji = ''
    if status in good_status:
        emoji = ':thumbs_up:'
    elif status in bad_status:
        emoji = ':thumbs_down:'
    elif status in neutral_status:
        emoji = ':arrows_counterclockwise:'

    # If the service is not one of the following, the url is of the repository home, not the individual
    # commit itself.
    commit_url = repository.split('@')[1]
    if 'github' in repository:
        commit_url += f'/commit/{commit_id}'
    elif 'bitbucket' in repository:
        commit_url += f'/commits/{commit_id}'
    elif 'gitlab' in repository:
        commit_url += f'/pipelines/{commit_id}'

    body = MESSAGE_TEMPLATE.format(
        author=author,
        build_log_url=build_log,
        commit_id=commit_id[:7],
        commit_url=commit_url,
        status=status,
        emoji=emoji,
    )

    check_send_webhook_message(request, user_profile, topic, body)
    return json_success()
Exemplo n.º 36
0
def api_pivotal_webhook(request: HttpRequest,
                        user_profile: UserProfile) -> HttpResponse:
    subject = content = None
    try:
        subject, content = api_pivotal_webhook_v3(request, user_profile)
    except Exception:
        # Attempt to parse v5 JSON payload
        subject, content = api_pivotal_webhook_v5(request, user_profile)

    if subject is None or content is None:
        return json_error(_("Unable to handle Pivotal payload"))

    check_send_webhook_message(request, user_profile, subject, content)
    return json_success()
Exemplo n.º 37
0
def api_stripe_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Any] = REQ(argument_type='body'),
    stream: str = REQ(default='test')
) -> HttpResponse:
    topic, body = topic_and_body(payload)
    try:
        check_send_webhook_message(request, user_profile, topic, body)
    except NotImplementedEventType:  # nocoverage
        pass
    except SuppressedEvent:  # nocoverage
        pass
    return json_success()
Exemplo n.º 38
0
def api_taiga_webhook(request: HttpRequest, user_profile: UserProfile,
                      message: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
    parsed_events = parse_message(message)
    content_lines = []
    for event in parsed_events:
        content_lines.append(generate_content(event) + '\n')
    content = "".join(sorted(content_lines))
    topic = 'General'
    if message["data"].get("milestone") is not None:
        if message["data"]["milestone"].get("name") is not None:
            topic = message["data"]["milestone"]["name"]
    check_send_webhook_message(request, user_profile, topic, content)

    return json_success()
Exemplo n.º 39
0
def api_solano_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Any] = REQ(argument_type="body"),
) -> HttpResponse:
    event = payload.get("event")
    topic = "build update"
    if event == "test":
        return handle_test_event(request, user_profile, topic)
    try:
        author = payload["committers"][0]
    except KeyError:
        author = "Unknown"
    status = payload["status"]
    build_log = payload["url"]
    repository = payload["repository"]["url"]
    commit_id = payload["commit_id"]

    good_status = ["passed"]
    bad_status = ["failed", "error"]
    neutral_status = ["running"]
    emoji = ""
    if status in good_status:
        emoji = ":thumbs_up:"
    elif status in bad_status:
        emoji = ":thumbs_down:"
    elif status in neutral_status:
        emoji = ":arrows_counterclockwise:"

    # If the service is not one of the following, the URL is of the repository home, not the individual
    # commit itself.
    commit_url = repository.split("@")[1]
    if "github" in repository:
        commit_url += f"/commit/{commit_id}"
    elif "bitbucket" in repository:
        commit_url += f"/commits/{commit_id}"
    elif "gitlab" in repository:
        commit_url += f"/pipelines/{commit_id}"

    body = MESSAGE_TEMPLATE.format(
        author=author,
        build_log_url=build_log,
        commit_id=commit_id[:7],
        commit_url=commit_url,
        status=status,
        emoji=emoji,
    )

    check_send_webhook_message(request, user_profile, topic, body, event)
    return json_success(request)
Exemplo n.º 40
0
def api_grafana_webhook(
        request: HttpRequest,
        user_profile: UserProfile,
        payload: Dict[str, Any] = REQ(argument_type="body"),
) -> HttpResponse:

    topic = GRAFANA_TOPIC_TEMPLATE.format(alert_title=payload["title"])

    eval_matches_text = ""
    eval_matches = payload.get("evalMatches")
    if eval_matches is not None:
        for match in eval_matches:
            eval_matches_text += "**{}:** {}\n".format(match["metric"],
                                                       match["value"])

    message_text = ""
    if payload.get("message") is not None:
        message_text = payload["message"] + "\n\n"

    if payload.get("state") is not None:
        if payload.get("state") == "alerting":
            alert_status = GRAFANA_ALERT_STATUS_TEMPLATE.format(
                alert_icon=":alert:", alert_state=payload["state"].upper())
        elif payload.get("state") == "ok":
            alert_status = GRAFANA_ALERT_STATUS_TEMPLATE.format(
                alert_icon=":squared_ok:",
                alert_state=payload["state"].upper())
        else:
            alert_status = GRAFANA_ALERT_STATUS_TEMPLATE.format(
                alert_icon=":info:", alert_state=payload["state"].upper())

    body = GRAFANA_MESSAGE_TEMPLATE.format(
        alert_message=message_text,
        alert_status=alert_status,
        rule_name=payload["ruleName"],
        rule_url=payload["ruleUrl"],
        eval_matches=eval_matches_text,
    )

    if payload.get("imageUrl") is not None:
        body += "\n[Click to view visualization]({visualization})".format(
            visualization=payload["imageUrl"])

    body = body.strip()

    # send the message
    check_send_webhook_message(request, user_profile, topic, body)

    return json_success()
Exemplo n.º 41
0
def api_pingdom_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Any] = REQ(argument_type='body')
) -> HttpResponse:
    check_type = get_check_type(payload)

    if check_type in SUPPORTED_CHECK_TYPES:
        subject = get_subject_for_http_request(payload)
        body = get_body_for_http_request(payload)
    else:
        raise UnexpectedWebhookEventType('Pingdom', check_type)

    check_send_webhook_message(request, user_profile, subject, body)
    return json_success()
Exemplo n.º 42
0
def api_mention_webhook(
        request: HttpRequest, user_profile: UserProfile,
        payload: Dict[str, Iterable[Dict[str, Any]]] = REQ(argument_type='body'),
) -> HttpResponse:
    title = payload["title"]
    source_url = payload["url"]
    description = payload["description"]
    # construct the body of the message
    body = '**[%s](%s)**:\n%s' % (title, source_url, description)
    topic = 'news'

    # send the message
    check_send_webhook_message(request, user_profile, topic, body)

    return json_success()
Exemplo n.º 43
0
def api_iftt_app_webhook(request: HttpRequest, user_profile: UserProfile,
                         payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
    topic = payload.get('topic')
    content = payload.get('content')

    if topic is None:
        topic = payload.get('subject')  # Backwards-compatibility
        if topic is None:
            return json_error(_("Topic can't be empty"))

    if content is None:
        return json_error(_("Content can't be empty"))

    check_send_webhook_message(request, user_profile, topic, content)
    return json_success()
Exemplo n.º 44
0
def api_dropbox_webhook(
        request: HttpRequest,
        user_profile: UserProfile,
        challenge: Optional[str] = REQ(default=None),
) -> HttpResponse:
    if request.method == "POST":
        topic = "Dropbox"
        check_send_webhook_message(request, user_profile, topic,
                                   "File has been updated on Dropbox!")
        return json_success(request)
    else:
        if challenge is None:
            raise RequestVariableMissingError("challenge")
        return HttpResponse(challenge,
                            content_type="text/plain; charset=UTF-8")
Exemplo n.º 45
0
def api_front_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: WildValue = REQ(argument_type="body", converter=to_wild_value),
) -> HttpResponse:

    event = payload["type"].tame(check_string)
    if event not in EVENT_FUNCTION_MAPPER:
        raise JsonableError(_("Unknown webhook request"))

    topic = payload["conversation"]["id"].tame(check_string)
    body = get_body_based_on_event(event)(payload)
    check_send_webhook_message(request, user_profile, topic, body, event)

    return json_success(request)
Exemplo n.º 46
0
def api_trello_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Mapping[str, Any] = REQ(argument_type='body')
) -> HttpResponse:
    payload = orjson.loads(request.body)
    action_type = payload['action'].get('type')
    message = get_subject_and_body(payload, action_type)
    if message is None:
        return json_success()
    else:
        subject, body = message

    check_send_webhook_message(request, user_profile, subject, body)
    return json_success()
Exemplo n.º 47
0
def api_front_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Any] = REQ(argument_type="body"),
) -> HttpResponse:

    event = payload["type"]
    if event not in EVENT_FUNCTION_MAPPER:
        raise JsonableError(_("Unknown webhook request"))

    topic = payload["conversation"]["id"]
    body = get_body_based_on_event(event)(payload)
    check_send_webhook_message(request, user_profile, topic, body, event)

    return json_success()
Exemplo n.º 48
0
def api_clubhouse_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Any] = REQ(argument_type='body')
) -> HttpResponse:

    body_func = get_body_function_based_on_type(payload)
    topic_func = get_topic_function_based_on_type(payload)
    topic = topic_func(payload)
    body = body_func(payload)

    if topic and body:
        check_send_webhook_message(request, user_profile, topic, body)

    return json_success()
Exemplo n.º 49
0
def api_front_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Any] = REQ(argument_type='body')
) -> HttpResponse:

    event = payload['type']
    if event not in EVENT_FUNCTION_MAPPER:
        return json_error(_("Unknown webhook request"))

    topic = payload['conversation']['id']
    body = get_body_based_on_event(event)(payload)
    check_send_webhook_message(request, user_profile, topic, body)

    return json_success()
Exemplo n.º 50
0
def api_zendesk_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    ticket_title: str = REQ(),
    ticket_id: str = REQ(),
    message: str = REQ()
) -> HttpResponse:
    """
    Zendesk uses triggers with message templates. This webhook uses the
    ticket_id and ticket_title to create a subject. And passes with zendesk
    user's configured message to zulip.
    """
    subject = truncate(f'#{ticket_id}: {ticket_title}', 60)
    check_send_webhook_message(request, user_profile, subject, message)
    return json_success()
Exemplo n.º 51
0
def api_delighted_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Dict[str, Any]] = REQ(argument_type="body"),
) -> HttpResponse:
    person = payload["event_data"]["person"]
    selected_payload = {"email": person["email"]}
    selected_payload["score"] = payload["event_data"]["score"]
    selected_payload["comment"] = payload["event_data"]["comment"]

    BODY_TEMPLATE = body_template(selected_payload["score"])
    body = BODY_TEMPLATE.format(**selected_payload)
    topic = "Survey response"

    check_send_webhook_message(request, user_profile, topic, body)
    return json_success(request)
Exemplo n.º 52
0
def api_gosquared_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Dict[str, Any]] = REQ(argument_type='body')
) -> HttpResponse:
    domain_name = payload['siteDetails']['domain']
    user_num = payload['concurrents']
    user_acc = payload['siteDetails']['acct']
    acc_url = 'https://www.gosquared.com/now/' + user_acc
    body = BODY_TEMPLATE.format(website_name=domain_name,
                                website_url=acc_url,
                                user_num=user_num)
    topic = 'GoSquared - {website_name}'.format(website_name=domain_name)

    check_send_webhook_message(request, user_profile, topic, body)
    return json_success()
Exemplo n.º 53
0
def api_delighted_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Dict[str, Any]] = REQ(argument_type='body')
) -> HttpResponse:
    person = payload['event_data']['person']
    selected_payload = {'email': person['email']}
    selected_payload['score'] = payload['event_data']['score']
    selected_payload['comment'] = payload['event_data']['comment']

    BODY_TEMPLATE = body_template(selected_payload['score'])
    body = BODY_TEMPLATE.format(**selected_payload)
    topic = 'Survey Response'

    check_send_webhook_message(request, user_profile, topic, body)
    return json_success()
Exemplo n.º 54
0
def api_appfollow_webhook(
        request: HttpRequest,
        user_profile: UserProfile,
        payload: Dict[str, Any] = REQ(argument_type="body"),
) -> HttpResponse:
    message = payload["text"]
    app_name_search = re.search(r"\A(.+)", message)
    assert app_name_search is not None
    app_name = app_name_search.group(0)
    topic = app_name

    check_send_webhook_message(request,
                               user_profile,
                               topic,
                               body=convert_markdown(message))
    return json_success(request)
Exemplo n.º 55
0
def api_semaphore_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Any] = REQ(argument_type="body"),
) -> HttpResponse:

    content, project_name, branch_name = (
        semaphore_classic(payload) if "event" in payload else semaphore_2(payload)
    )
    subject = (
        TOPIC_TEMPLATE.format(project=project_name, branch=branch_name)
        if branch_name
        else project_name
    )
    check_send_webhook_message(request, user_profile, subject, content)
    return json_success()
Exemplo n.º 56
0
def api_intercom_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Any] = REQ(argument_type="body"),
) -> HttpResponse:
    event_type = payload["topic"]
    if event_type == "ping":
        return json_success()

    handler = EVENT_TO_FUNCTION_MAPPER.get(event_type)
    if handler is None:
        raise UnsupportedWebhookEventType(event_type)
    topic, body = handler(payload)

    check_send_webhook_message(request, user_profile, topic, body)
    return json_success()
Exemplo n.º 57
0
def api_papertrail_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Any] = REQ(
        json_validator=check_dict(
            [
                ("events", check_list(check_dict([]))),
                (
                    "saved_search",
                    check_dict(
                        [
                            ("name", check_string),
                            ("html_search_url", check_string),
                        ]
                    ),
                ),
            ]
        )
    ),
) -> HttpResponse:

    matches = MATCHES_TEMPLATE.format(
        name=payload["saved_search"]["name"],
        url=payload["saved_search"]["html_search_url"],
        number=str(len(payload["events"])),
    )
    message = [matches]

    for i, event in enumerate(payload["events"]):
        event_text = SEARCH_TEMPLATE.format(
            timestamp=event["display_received_at"],
            source=event["source_name"],
            query=payload["saved_search"]["query"],
            message=event["message"],
        )

        message.append(event_text)

        if i >= 3:
            message.append("[See more]({})".format(payload["saved_search"]["html_search_url"]))
            break

    post = "\n".join(message)
    topic = "logs"

    check_send_webhook_message(request, user_profile, topic, post)
    return json_success(request)
Exemplo n.º 58
0
def api_bitbucket_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Mapping[str, Any] = REQ(validator=check_dict([])),
    branches: Optional[str] = REQ(default=None)
) -> HttpResponse:
    repository = payload['repository']

    commits = [{
        'name':
        commit.get('author') or payload.get('user'),
        'sha':
        commit.get('raw_node'),
        'message':
        commit.get('message'),
        'url':
        '{}{}commits/{}'.format(payload.get('canon_url'),
                                repository.get('absolute_url'),
                                commit.get('raw_node')),
    } for commit in payload['commits']]

    if len(commits) == 0:
        # Bitbucket doesn't give us enough information to really give
        # a useful message :/
        subject = repository['name']
        content = "{} [force pushed]({}).".format(
            payload.get('user', 'Someone'),
            payload['canon_url'] + repository['absolute_url'],
        )
    else:
        branch = payload['commits'][-1]['branch']
        if branches is not None and branches.find(branch) == -1:
            return json_success()

        committer = payload.get('user')
        content = get_push_commits_event_message(
            committer if committer is not None else 'Someone', None, branch,
            commits)
        subject = TOPIC_WITH_BRANCH_TEMPLATE.format(repo=repository['name'],
                                                    branch=branch)

    check_send_webhook_message(request,
                               user_profile,
                               subject,
                               content,
                               unquote_url_parameters=True)
    return json_success()
Exemplo n.º 59
0
def api_zapier_webhook(
    request: HttpRequest,
    user_profile: UserProfile,
    payload: Dict[str, Any] = REQ(argument_type='body')
) -> HttpResponse:

    # A request with the ZapierZulipApp user agent is a request from
    # the official Zulip app for Zapier
    user_agent = validate_extract_webhook_http_header(request,
                                                      'USER_AGENT',
                                                      'Zapier',
                                                      fatal=False)
    if user_agent == 'ZapierZulipApp':
        event_type = payload.get('type')
        if event_type == 'auth':
            # The bot's details are used by Zapier to format a connection
            # label for users to be able to distinguish between different
            # Zulip bots and API keys in their UI
            return json_success({
                'bot_name': user_profile.full_name,
                'bot_email': user_profile.email,
                'bot_id': user_profile.id
            })
        elif event_type == 'stream':
            check_send_webhook_message(request, user_profile, payload['topic'],
                                       payload['content'])
        elif event_type == 'private':
            check_send_private_message_from_emails(user_profile,
                                                   request.client,
                                                   payload['to'],
                                                   payload['content'])

        return json_success()

    topic = payload.get('topic')
    content = payload.get('content')

    if topic is None:
        topic = payload.get('subject')  # Backwards-compatibility
        if topic is None:
            return json_error(_("Topic can't be empty"))

    if content is None:
        return json_error(_("Content can't be empty"))

    check_send_webhook_message(request, user_profile, topic, content)
    return json_success()
Exemplo n.º 60
0
def api_bitbucket_webhook(
        request: HttpRequest,
        user_profile: UserProfile,
        payload: Mapping[str, Any] = REQ(json_validator=check_dict([])),
        branches: Optional[str] = REQ(default=None),
) -> HttpResponse:
    repository = payload["repository"]

    commits = [{
        "name":
        commit.get("author") or payload.get("user"),
        "sha":
        commit.get("raw_node"),
        "message":
        commit.get("message"),
        "url":
        "{}{}commits/{}".format(payload.get("canon_url"),
                                repository.get("absolute_url"),
                                commit.get("raw_node")),
    } for commit in payload["commits"]]

    if len(commits) == 0:
        # Bitbucket doesn't give us enough information to really give
        # a useful message :/
        subject = repository["name"]
        content = "{} [force pushed]({}).".format(
            payload.get("user", "Someone"),
            payload["canon_url"] + repository["absolute_url"],
        )
    else:
        branch = payload["commits"][-1]["branch"]
        if branches is not None and branches.find(branch) == -1:
            return json_success()

        committer = payload.get("user")
        content = get_push_commits_event_message(
            committer if committer is not None else "Someone", None, branch,
            commits)
        subject = TOPIC_WITH_BRANCH_TEMPLATE.format(repo=repository["name"],
                                                    branch=branch)

    check_send_webhook_message(request,
                               user_profile,
                               subject,
                               content,
                               unquote_url_parameters=True)
    return json_success()