mypy: Convert zerver/views/webhooks/ to use typing.Text.

This commit is contained in:
Noel Tautges
2016-12-04 11:45:46 -06:00
parent cfa2987d27
commit 07a74a8d9c
20 changed files with 165 additions and 184 deletions

View File

@@ -1,7 +1,6 @@
from __future__ import absolute_import
from six import text_type
from typing import Any, Mapping
from typing import Any, Mapping, Text
from django.http import HttpRequest, HttpResponse
@@ -17,7 +16,7 @@ from zerver.lib.webhooks.git import get_push_commits_event_message, SUBJECT_WITH
@has_request_variables
def api_bitbucket_webhook(request, user_profile, payload=REQ(validator=check_dict([])),
stream=REQ(default='commits')):
# type: (HttpRequest, UserProfile, Mapping[text_type, Any], text_type) -> HttpResponse
# type: (HttpRequest, UserProfile, Mapping[Text, Any], Text) -> HttpResponse
repository = payload['repository']
commits = [

View File

@@ -2,9 +2,8 @@
from __future__ import absolute_import
import re
from functools import partial
from six import text_type
from six.moves import zip
from typing import Any, Callable, Optional
from typing import Any, Callable, Optional, Text
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _
from zerver.lib.actions import check_send_message
@@ -63,7 +62,7 @@ def api_bitbucket2_webhook(request, user_profile, client, payload=REQ(argument_t
return json_success()
def get_subject_for_branch_specified_events(payload, branch_name=None):
# type: (Dict[str, Any], Optional[text_type]) -> text_type
# type: (Dict[str, Any], Optional[Text]) -> Text
return SUBJECT_WITH_BRANCH_TEMPLATE.format(
repo=get_repository_name(payload['repository']),
branch=get_branch_name_for_push_event(payload) if branch_name is None else branch_name
@@ -89,7 +88,7 @@ def get_subject(payload):
return BITBUCKET_SUBJECT_TEMPLATE.format(repository_name=get_repository_name(payload['repository']))
def get_subject_based_on_type(payload, type):
# type: (Dict[str, Any], str) -> text_type
# type: (Dict[str, Any], str) -> Text
if type.startswith('pull_request'):
return SUBJECT_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
repo=get_repository_name(payload.get('repository')),
@@ -137,7 +136,7 @@ def get_body_based_on_type(type):
return GET_SINGLE_MESSAGE_BODY_DEPENDING_ON_TYPE_MAPPER.get(type)
def get_push_bodies(payload):
# type: (Dict[str, Any]) -> List[text_type]
# type: (Dict[str, Any]) -> List[Text]
messages_list = []
for change in payload['push']['changes']:
potential_tag = (change['new'] or change['old'] or {}).get('type')
@@ -152,14 +151,14 @@ def get_push_bodies(payload):
return messages_list
def get_remove_branch_push_body(payload, change):
# type: (Dict[str, Any], Dict[str, Any]) -> text_type
# type: (Dict[str, Any], Dict[str, Any]) -> Text
return get_remove_branch_event_message(
get_user_username(payload),
change['old']['name'],
)
def get_force_push_body(payload, change):
# type: (Dict[str, Any], Dict[str, Any]) -> text_type
# type: (Dict[str, Any], Dict[str, Any]) -> Text
return get_force_push_commits_event_message(
get_user_username(payload),
change['links']['html']['href'],
@@ -168,7 +167,7 @@ def get_force_push_body(payload, change):
)
def get_normal_push_body(payload, change):
# type: (Dict[str, Any], Dict[str, Any]) -> text_type
# type: (Dict[str, Any], Dict[str, Any]) -> Text
commits_data = [{
'sha': commit.get('hash'),
'url': commit.get('links').get('html').get('href'),
@@ -193,7 +192,7 @@ def get_fork_body(payload):
)
def get_commit_comment_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
comment = payload.get('comment')
action = u'[commented]({})'.format(comment['links']['html']['href'])
return get_commits_comment_action_message(
@@ -220,12 +219,12 @@ def get_commit_status_changed_body(payload):
)
def get_issue_commented_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
action = '[commented]({}) on'.format(payload['comment']['links']['html']['href'])
return get_issue_action_body(payload, action)
def get_issue_action_body(payload, action):
# type: (Dict[str, Any], str) -> text_type
# type: (Dict[str, Any], str) -> Text
issue = payload['issue']
assignee = None
message = None
@@ -244,7 +243,7 @@ def get_issue_action_body(payload, action):
)
def get_pull_request_action_body(payload, action):
# type: (Dict[str, Any], str) -> text_type
# type: (Dict[str, Any], str) -> Text
pull_request = payload['pullrequest']
return get_pull_request_event_message(
get_user_username(payload),
@@ -254,7 +253,7 @@ def get_pull_request_action_body(payload, action):
)
def get_pull_request_created_or_updated_body(payload, action):
# type: (Dict[str, Any], str) -> text_type
# type: (Dict[str, Any], str) -> Text
pull_request = payload['pullrequest']
assignee = None
if pull_request.get('reviewers'):
@@ -272,17 +271,17 @@ def get_pull_request_created_or_updated_body(payload, action):
)
def get_pull_request_comment_created_action_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
action = '[commented]({})'.format(payload['comment']['links']['html']['href'])
return get_pull_request_comment_action_body(payload, action)
def get_pull_request_deleted_or_updated_comment_action_body(payload, action):
# type: (Dict[str, Any], text_type) -> text_type
# type: (Dict[str, Any], Text) -> Text
action = "{} a [comment]({})".format(action, payload['comment']['links']['html']['href'])
return get_pull_request_comment_action_body(payload, action)
def get_pull_request_comment_action_body(payload, action):
# type: (Dict[str, Any], str) -> text_type
# type: (Dict[str, Any], str) -> Text
action += ' on'
return get_pull_request_event_message(
get_user_username(payload),
@@ -293,7 +292,7 @@ def get_pull_request_comment_action_body(payload, action):
)
def get_push_tag_body(payload, change):
# type: (Dict[str, Any], Dict[str, Any]) -> text_type
# type: (Dict[str, Any], Dict[str, Any]) -> Text
if change.get('created'):
tag = change.get('new')
action = 'pushed'

View File

@@ -2,8 +2,7 @@
from __future__ import absolute_import
from django.http import HttpRequest, HttpResponse
from six import text_type
from typing import Any
from typing import Any, Text
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success, json_error
@@ -22,7 +21,7 @@ FAILED_STATUS = 'failed'
@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_type) -> HttpResponse
# type: (HttpRequest, UserProfile, Client, Dict[str, Any], Text) -> HttpResponse
payload = payload['payload']
subject = get_subject(payload)
body = get_body(payload)
@@ -31,11 +30,11 @@ def api_circleci_webhook(request, user_profile, client, payload=REQ(argument_typ
return json_success()
def get_subject(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return CIRCLECI_SUBJECT_TEMPLATE.format(repository_name=payload['reponame'])
def get_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
data = {
'build_url': payload['build_url'],
'username': payload['username'],
@@ -45,7 +44,7 @@ def get_body(payload):
return CIRCLECI_MESSAGE_TEMPLATE.format(**data)
def get_status(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
status = payload['status']
if payload['previous']['status'] == FAILED_STATUS and status == FAILED_STATUS:
return u'is still failing'

View File

@@ -6,8 +6,7 @@ from zerver.lib.response import json_success, json_error
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
from zerver.models import Client, UserProfile
from django.http import HttpRequest, HttpResponse
from six import text_type
from typing import Any
from typing import Any, Text
CRASHLYTICS_SUBJECT_TEMPLATE = '{display_id}: {title}'
CRASHLYTICS_MESSAGE_TEMPLATE = '[Issue]({url}) impacts at least {impacted_devices_count} device(s).'
@@ -19,7 +18,7 @@ VERIFICATION_EVENT = 'verification'
@has_request_variables
def api_crashlytics_webhook(request, user_profile, client, payload=REQ(argument_type='body'),
stream=REQ(default='crashlytics')):
# type: (HttpRequest, UserProfile, Client, Dict[str, Any], text_type) -> HttpResponse
# type: (HttpRequest, UserProfile, Client, Dict[str, Any], Text) -> HttpResponse
try:
event = payload['event']
if event == VERIFICATION_EVENT:

View File

@@ -6,7 +6,7 @@ from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success
from zerver.decorator import REQ, has_request_variables, authenticated_rest_api_view
from six import text_type
from typing import Text
# Desk.com's integrations all make the user supply a template, where it fills
# in stuff like {{customer.name}} and posts the result as a "data" parameter.
@@ -18,7 +18,7 @@ from six import text_type
def api_deskdotcom_webhook(request, user_profile, data=REQ(),
topic=REQ(default="Desk.com notification"),
stream=REQ(default="desk.com")):
# type: (HttpRequest, UserProfile, text_type, text_type, text_type) -> HttpResponse
# type: (HttpRequest, UserProfile, Text, Text, Text) -> HttpResponse
check_send_message(user_profile, get_client("ZulipDeskWebhook"), "stream",
[stream], topic, data)
return json_success()

View File

@@ -13,8 +13,7 @@ from zerver.decorator import REQ, has_request_variables, authenticated_rest_api_
import logging
import ujson
from six import text_type
from typing import Any, Dict, Optional, Tuple, Union
from typing import Any, Dict, Optional, Tuple, Union, Text
class TicketDict(dict):
@@ -116,7 +115,7 @@ def format_freshdesk_ticket_creation_message(ticket):
@has_request_variables
def api_freshdesk_webhook(request, user_profile, payload=REQ(argument_type='body'),
stream=REQ(default='freshdesk')):
# type: (HttpRequest, UserProfile, Dict[str, Any], text_type) -> HttpResponse
# type: (HttpRequest, UserProfile, Dict[str, Any], Text) -> HttpResponse
ticket_data = payload["freshdesk_webhook"]
required_keys = [

View File

@@ -14,8 +14,7 @@ import logging
import re
import ujson
from six import text_type
from typing import Any, Mapping, Optional, Sequence, Tuple
from typing import Any, Mapping, Optional, Sequence, Tuple, Text
from zerver.lib.str_utils import force_str
from django.http import HttpRequest, HttpResponse
@@ -23,14 +22,14 @@ ZULIP_TEST_REPO_NAME = 'zulip-test'
ZULIP_TEST_REPO_ID = 6893087
def is_test_repository(repository):
# type: (Mapping[text_type, Any]) -> bool
# type: (Mapping[Text, Any]) -> bool
return repository['name'] == ZULIP_TEST_REPO_NAME and repository['id'] == ZULIP_TEST_REPO_ID
class UnknownEventType(Exception):
pass
def github_pull_request_content(payload):
# type: (Mapping[text_type, Any]) -> text_type
# type: (Mapping[Text, Any]) -> Text
pull_request = payload['pull_request']
action = get_pull_request_or_issue_action(payload)
@@ -53,7 +52,7 @@ def github_pull_request_content(payload):
)
def github_issues_content(payload):
# type: (Mapping[text_type, Any]) -> text_type
# type: (Mapping[Text, Any]) -> Text
issue = payload['issue']
action = get_pull_request_or_issue_action(payload)
@@ -74,7 +73,7 @@ def github_issues_content(payload):
)
def github_object_commented_content(payload, type):
# type: (Mapping[text_type, Any], text_type) -> text_type
# type: (Mapping[Text, Any], Text) -> Text
comment = payload['comment']
issue = payload['issue']
action = u'[commented]({}) on'.format(comment['html_url'])
@@ -89,17 +88,17 @@ def github_object_commented_content(payload, type):
)
def get_pull_request_or_issue_action(payload):
# type: (Mapping[text_type, Any]) -> text_type
# type: (Mapping[Text, Any]) -> Text
return 'synchronized' if payload['action'] == 'synchronize' else payload['action']
def get_pull_request_or_issue_assignee(object_payload):
# type: (Mapping[text_type, Any]) -> text_type
# type: (Mapping[Text, Any]) -> Text
assignee_dict = object_payload.get('assignee')
if assignee_dict:
return assignee_dict.get('login')
def get_pull_request_or_issue_subject(repository, payload_object, type):
# type: (Mapping[text_type, Any], Mapping[text_type, Any], text_type) -> text_type
# type: (Mapping[Text, Any], Mapping[Text, Any], Text) -> Text
return SUBJECT_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
repo=repository['name'],
type=type,
@@ -108,12 +107,12 @@ def get_pull_request_or_issue_subject(repository, payload_object, type):
)
def github_generic_subject(noun, topic_focus, blob):
# type: (text_type, text_type, Mapping[text_type, Any]) -> text_type
# type: (Text, Text, Mapping[Text, Any]) -> Text
# issue and pull_request objects have the same fields we're interested in
return u'%s: %s %d: %s' % (topic_focus, noun, blob['number'], blob['title'])
def api_github_v1(user_profile, event, payload, branches, stream, **kwargs):
# type: (UserProfile, text_type, Mapping[text_type, Any], text_type, text_type, **Any) -> Tuple[text_type, text_type, text_type]
# type: (UserProfile, Text, Mapping[Text, Any], Text, Text, **Any) -> Tuple[Text, Text, Text]
"""
processes github payload with version 1 field specification
`payload` comes in unmodified from github
@@ -126,7 +125,7 @@ def api_github_v1(user_profile, event, payload, branches, stream, **kwargs):
def api_github_v2(user_profile, event, payload, branches, default_stream,
commit_stream, issue_stream, topic_focus = None):
# type: (UserProfile, text_type, Mapping[text_type, Any], text_type, text_type, text_type, text_type, Optional[text_type]) -> Tuple[text_type, text_type, text_type]
# type: (UserProfile, Text, Mapping[Text, Any], Text, Text, Text, Text, Optional[Text]) -> Tuple[Text, Text, Text]
"""
processes github payload with version 2 field specification
`payload` comes in unmodified from github
@@ -205,7 +204,7 @@ def api_github_landing(request, user_profile, event=REQ(),
exclude_commits=REQ(converter=flexible_boolean, default=False),
emphasize_branch_in_topic=REQ(converter=flexible_boolean, default=False),
):
# type: (HttpRequest, UserProfile, text_type, Mapping[text_type, Any], text_type, text_type, int, text_type, text_type, bool, bool, bool, bool) -> HttpResponse
# type: (HttpRequest, UserProfile, Text, Mapping[Text, Any], Text, Text, int, Text, Text, bool, bool, bool, bool) -> HttpResponse
repository = payload['repository']
@@ -280,7 +279,7 @@ def api_github_landing(request, user_profile, event=REQ(),
message_content=content)
def build_message_from_gitlog(user_profile, name, ref, commits, before, after, url, pusher, forced=None, created=None):
# type: (UserProfile, text_type, text_type, List[Dict[str, str]], text_type, text_type, text_type, text_type, Optional[text_type], Optional[text_type]) -> Tuple[text_type, text_type]
# type: (UserProfile, Text, Text, List[Dict[str, str]], Text, Text, Text, Text, Optional[Text], Optional[Text]) -> Tuple[Text, Text]
short_ref = re.sub(r'^refs/heads/', '', ref)
subject = SUBJECT_WITH_BRANCH_TEMPLATE.format(repo=name, branch=short_ref)

View File

@@ -1,8 +1,7 @@
from __future__ import absolute_import
import re
from functools import partial
from six import text_type
from typing import Any, Callable
from typing import Any, Callable, Text
from django.http import HttpRequest, HttpResponse
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success
@@ -18,7 +17,7 @@ class UnknownEventType(Exception):
pass
def get_opened_or_update_pull_request_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
pull_request = payload['pull_request']
action = payload['action']
if action == 'synchronized':
@@ -38,7 +37,7 @@ def get_opened_or_update_pull_request_body(payload):
)
def get_closed_pull_request_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
pull_request = payload['pull_request']
action = 'merged' if pull_request['merged'] else 'closed without merge'
return get_pull_request_event_message(
@@ -48,7 +47,7 @@ def get_closed_pull_request_body(payload):
)
def get_membership_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
action = payload['action']
member = payload['member']
scope = payload['scope']
@@ -64,7 +63,7 @@ def get_membership_body(payload):
)
def get_member_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return u"{} {} [{}]({}) to [{}]({})".format(
get_sender_name(payload),
payload['action'],
@@ -75,7 +74,7 @@ def get_member_body(payload):
)
def get_issue_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
action = payload['action']
issue = payload['issue']
assignee = issue['assignee']
@@ -89,7 +88,7 @@ def get_issue_body(payload):
)
def get_issue_comment_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
action = payload['action']
comment = payload['comment']
issue = payload['issue']
@@ -109,7 +108,7 @@ def get_issue_comment_body(payload):
)
def get_fork_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
forkee = payload['forkee']
return u"{} forked [{}]({})".format(
get_sender_name(payload),
@@ -118,19 +117,19 @@ def get_fork_body(payload):
)
def get_deployment_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return u'{} created new deployment'.format(
get_sender_name(payload),
)
def get_change_deployment_status_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return u'Deployment changed status to {}'.format(
payload['deployment_status']['state'],
)
def get_create_or_delete_body(payload, action):
# type: (Dict[str, Any], text_type) -> text_type
# type: (Dict[str, Any], Text) -> Text
ref_type = payload['ref_type']
return u'{} {} {} {}'.format(
get_sender_name(payload),
@@ -140,7 +139,7 @@ def get_create_or_delete_body(payload, action):
).rstrip()
def get_commit_comment_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
comment = payload['comment']
comment_url = comment['html_url']
commit_url = comment_url.split('#', 1)[0]
@@ -154,7 +153,7 @@ def get_commit_comment_body(payload):
)
def get_push_tags_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return get_push_tag_event_message(
get_sender_name(payload),
get_tag_name_from_ref(payload['ref']),
@@ -162,7 +161,7 @@ def get_push_tags_body(payload):
)
def get_push_commits_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
commits_data = [{
'sha': commit['id'],
'url': commit['url'],
@@ -176,14 +175,14 @@ def get_push_commits_body(payload):
)
def get_public_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return u"{} made [the repository]({}) public".format(
get_sender_name(payload),
payload['repository']['html_url'],
)
def get_wiki_pages_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
wiki_page_info_template = u"* {action} [{title}]({url})\n"
wiki_info = u''
for page in payload['pages']:
@@ -195,14 +194,14 @@ def get_wiki_pages_body(payload):
return u"{}:\n{}".format(get_sender_name(payload), wiki_info.rstrip())
def get_watch_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return u"{} starred [the repository]({})".format(
get_sender_name(payload),
payload['repository']['html_url']
)
def get_repository_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return u"{} {} [the repository]({})".format(
get_sender_name(payload),
payload.get('action'),
@@ -210,21 +209,21 @@ def get_repository_body(payload):
)
def get_add_team_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return u"[The repository]({}) was added to team {}".format(
payload['repository']['html_url'],
payload['team']['name']
)
def get_release_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return u"{} published [the release]({})".format(
get_sender_name(payload),
payload['release']['html_url'],
)
def get_page_build_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
build = payload['build']
action = build['status']
if action == 'null':
@@ -243,7 +242,7 @@ def get_page_build_body(payload):
)
def get_status_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
if payload['target_url']:
status = '[{}]({})'.format(
payload['state'],
@@ -258,7 +257,7 @@ def get_status_body(payload):
)
def get_pull_request_review_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return get_pull_request_event_message(
get_sender_name(payload),
'submitted',
@@ -267,7 +266,7 @@ def get_pull_request_review_body(payload):
)
def get_pull_request_review_comment_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
action = payload['action']
message = None
if action == 'created':
@@ -282,19 +281,19 @@ def get_pull_request_review_comment_body(payload):
)
def get_repository_name(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return payload['repository']['name']
def get_sender_name(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return payload['sender']['login']
def get_branch_name_from_ref(ref_string):
# type: (text_type) -> text_type
# type: (Text) -> Text
return re.sub(r'^refs/heads/', '', ref_string)
def get_tag_name_from_ref(ref_string):
# type: (text_type) -> text_type
# type: (Text) -> Text
return re.sub(r'^refs/tags/', '', ref_string)
def is_commit_push_event(payload):
@@ -302,7 +301,7 @@ def is_commit_push_event(payload):
return bool(re.match(r'^refs/heads/', payload['ref']))
def get_subject_based_on_type(payload, event):
# type: (Dict[str, Any], text_type) -> text_type
# type: (Dict[str, Any], Text) -> Text
if 'pull_request' in event:
return SUBJECT_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
repo=get_repository_name(payload),
@@ -368,7 +367,7 @@ EVENT_FUNCTION_MAPPER = {
def api_github_webhook(
request, user_profile, client,
payload=REQ(argument_type='body'), stream=REQ(default='github')):
# type: (HttpRequest, UserProfile, Client, Dict[str, Any], text_type) -> HttpResponse
# type: (HttpRequest, UserProfile, Client, Dict[str, Any], Text) -> HttpResponse
event = get_event(request, payload)
subject = get_subject_based_on_type(payload, event)
body = get_body_function_based_on_type(event)(payload)

View File

@@ -10,8 +10,7 @@ from zerver.lib.webhooks.git import get_push_commits_event_message, EMPTY_SHA,\
from zerver.models import Client, UserProfile
from django.http import HttpRequest, HttpResponse
from six import text_type
from typing import Dict, Any, Iterable, Optional
from typing import Dict, Any, Iterable, Optional, Text
class UnknownEventType(Exception):
@@ -19,13 +18,13 @@ class UnknownEventType(Exception):
def get_push_event_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
if payload.get('after') == EMPTY_SHA:
return get_remove_branch_event_body(payload)
return get_normal_push_event_body(payload)
def get_normal_push_event_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
compare_url = u'{}/compare/{}...{}'.format(
get_repository_homepage(payload),
payload['before'],
@@ -49,14 +48,14 @@ def get_normal_push_event_body(payload):
)
def get_remove_branch_event_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return get_remove_branch_event_message(
get_user_name(payload),
get_branch_name(payload)
)
def get_tag_push_event_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return get_push_tag_event_message(
get_user_name(payload),
get_tag_name(payload),
@@ -64,7 +63,7 @@ def get_tag_push_event_body(payload):
)
def get_issue_created_event_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return get_issue_event_message(
get_issue_user_name(payload),
'created',
@@ -75,7 +74,7 @@ def get_issue_created_event_body(payload):
)
def get_issue_event_body(payload, action):
# type: (Dict[str, Any], text_type) -> text_type
# type: (Dict[str, Any], Text) -> Text
return get_issue_event_message(
get_issue_user_name(payload),
action,
@@ -84,13 +83,13 @@ def get_issue_event_body(payload, action):
)
def get_merge_request_updated_event_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
if payload.get('object_attributes').get('oldrev'):
return get_merge_request_event_body(payload, "added commit(s) to")
return get_merge_request_open_or_updated_body(payload, "updated")
def get_merge_request_event_body(payload, action):
# type: (Dict[str, Any], text_type) -> text_type
# type: (Dict[str, Any], Text) -> Text
pull_request = payload.get('object_attributes')
return get_pull_request_event_message(
get_issue_user_name(payload),
@@ -101,7 +100,7 @@ def get_merge_request_event_body(payload, action):
)
def get_merge_request_open_or_updated_body(payload, action):
# type: (Dict[str, Any], text_type) -> text_type
# type: (Dict[str, Any], Text) -> Text
pull_request = payload.get('object_attributes')
return get_pull_request_event_message(
get_issue_user_name(payload),
@@ -116,13 +115,13 @@ def get_merge_request_open_or_updated_body(payload, action):
)
def get_objects_assignee(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
assignee_object = payload.get('assignee')
if assignee_object:
return assignee_object.get('name')
def get_commented_commit_event_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
comment = payload.get('object_attributes')
action = u'[commented]({})'.format(comment['url'])
return get_commits_comment_action_message(
@@ -134,7 +133,7 @@ def get_commented_commit_event_body(payload):
)
def get_commented_merge_request_event_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
comment = payload.get('object_attributes')
action = u'[commented]({}) on'.format(comment['url'])
url = u'{}/merge_requests/{}'.format(
@@ -151,7 +150,7 @@ def get_commented_merge_request_event_body(payload):
)
def get_commented_issue_event_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
comment = payload.get('object_attributes')
action = u'[commented]({}) on'.format(comment['url'])
url = u'{}/issues/{}'.format(
@@ -168,7 +167,7 @@ def get_commented_issue_event_body(payload):
)
def get_commented_snippet_event_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
comment = payload.get('object_attributes')
action = u'[commented]({}) on'.format(comment['url'])
url = u'{}/snippets/{}'.format(
@@ -185,7 +184,7 @@ def get_commented_snippet_event_body(payload):
)
def get_wiki_page_event_body(payload, action):
# type: (Dict[str, Any], text_type) -> text_type
# type: (Dict[str, Any], Text) -> Text
return u"{} {} [Wiki Page \"{}\"]({}).".format(
get_issue_user_name(payload),
action,
@@ -194,7 +193,7 @@ def get_wiki_page_event_body(payload, action):
)
def get_build_hook_event_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
build_status = payload.get('build_status')
if build_status == 'created':
action = 'was created'
@@ -209,7 +208,7 @@ def get_build_hook_event_body(payload):
)
def get_pipeline_event_body(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
pipeline_status = payload.get('object_attributes').get('status')
if pipeline_status == 'pending':
action = 'was created'
@@ -224,35 +223,35 @@ def get_pipeline_event_body(payload):
return u"Pipeline {} with build(s):\n{}.".format(action, builds_status[:-1])
def get_repo_name(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return payload['project']['name']
def get_user_name(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return payload['user_name']
def get_issue_user_name(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return payload['user']['name']
def get_repository_homepage(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return payload['repository']['homepage']
def get_branch_name(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return payload['ref'].replace('refs/heads/', '')
def get_tag_name(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return payload['ref'].replace('refs/tags/', '')
def get_object_iid(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return payload['object_attributes']['iid']
def get_object_url(payload):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
return payload['object_attributes']['url']
EVENT_FUNCTION_MAPPER = {
@@ -281,7 +280,7 @@ EVENT_FUNCTION_MAPPER = {
def api_gitlab_webhook(request, user_profile, client,
stream=REQ(default='gitlab'),
payload=REQ(argument_type='body')):
# type: (HttpRequest, UserProfile, Client, text_type, Dict[str, Any]) -> HttpResponse
# type: (HttpRequest, UserProfile, Client, Text, Dict[str, Any]) -> HttpResponse
event = get_event(request, payload)
body = get_body_based_on_event(event)(payload)
subject = get_subject_based_on_event(event, payload)
@@ -293,7 +292,7 @@ def get_body_based_on_event(event):
return EVENT_FUNCTION_MAPPER[event]
def get_subject_based_on_event(event, payload):
# type: (str, Dict[str, Any]) -> text_type
# type: (str, Dict[str, Any]) -> Text
if event == 'Push Hook':
return u"{} / {}".format(get_repo_name(payload), get_branch_name(payload))
elif event == 'Build Hook':

View File

@@ -8,15 +8,14 @@ from zerver.lib.validator import check_dict, check_string
from zerver.models import Client, UserProfile
from django.http import HttpRequest, HttpResponse
from six import text_type
from typing import Dict, Any, Iterable, Optional
from typing import Dict, Any, Iterable, Optional, Text
@api_key_only_webhook_view('HelloWorld')
@has_request_variables
def api_helloworld_webhook(request, user_profile, client,
payload=REQ(argument_type='body'), stream=REQ(default='test'),
topic=REQ(default='Hello World')):
# type: (HttpRequest, UserProfile, Client, Dict[str, Iterable[Dict[str, Any]]], text_type, Optional[text_type]) -> HttpResponse
# type: (HttpRequest, UserProfile, Client, Dict[str, Iterable[Dict[str, Any]]], Text, Optional[Text]) -> HttpResponse
# construct the body of the message
body = 'Hello! I am happy to be here! :smile:'

View File

@@ -1,6 +1,6 @@
# Webhooks for external integrations.
from __future__ import absolute_import
from typing import Any, Optional
from typing import Any, Optional, Text
from django.utils.translation import ugettext as _
from django.db.models import Q
@@ -12,8 +12,6 @@ from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import api_key_only_webhook_view, has_request_variables, REQ
from six import text_type
import logging
import re
import ujson
@@ -92,7 +90,7 @@ def convert_jira_markup(content, realm):
def api_jira_webhook(request, user_profile, client,
payload=REQ(argument_type='body'),
stream=REQ(default='jira')):
# type: (HttpRequest, UserProfile, Client, Dict[str, Any], text_type) -> HttpResponse
# type: (HttpRequest, UserProfile, Client, Dict[str, Any], Text) -> HttpResponse
def get_in(payload, keys, default=''):
# type: (Dict[str, Any], List[str], str) -> Any
try:

View File

@@ -1,7 +1,6 @@
from __future__ import absolute_import
from typing import Any, Optional, Callable, Tuple
from six import text_type
from typing import Any, Optional, Callable, Tuple, Text
from six.moves import zip
from django.utils.translation import ugettext as _
@@ -28,17 +27,17 @@ class LibratoWebhookParser(object):
self.attachments = attachments
def generate_alert_url(self, alert_id):
# type: (int) -> text_type
# type: (int) -> Text
return self.ALERT_URL_TEMPLATE.format(alert_id=alert_id)
def parse_alert(self):
# type: () -> Tuple[int, text_type, text_type, text_type]
# type: () -> Tuple[int, Text, Text, Text]
alert = self.payload['alert']
alert_id = alert['id']
return alert_id, alert['name'], self.generate_alert_url(alert_id), alert['runbook_url']
def parse_condition(self, condition):
# type: (Dict[str, Any]) -> Tuple[text_type, text_type, text_type, text_type]
# type: (Dict[str, Any]) -> Tuple[Text, Text, Text, Text]
summary_function = condition['summary_function']
threshold = condition.get('threshold', '')
condition_type = condition['type']
@@ -46,7 +45,7 @@ class LibratoWebhookParser(object):
return summary_function, threshold, condition_type, duration
def parse_violation(self, violation):
# type: (Dict[str, Any]) -> Tuple[text_type, text_type]
# type: (Dict[str, Any]) -> Tuple[Text, Text]
metric_name = violation['metric']
recorded_at = datetime.fromtimestamp((violation['recorded_at']))
return metric_name, recorded_at
@@ -62,7 +61,7 @@ class LibratoWebhookParser(object):
return violations
def parse_snapshot(self, snapshot):
# type: (Dict[str, Any]) -> Tuple[text_type, text_type, text_type]
# type: (Dict[str, Any]) -> Tuple[Text, Text, Text]
author_name, image_url, title = snapshot['author_name'], snapshot['image_url'], snapshot['title']
return author_name, image_url, title
@@ -90,11 +89,11 @@ class LibratoWebhookHandler(LibratoWebhookParser):
raise Exception("Unexcepted message type")
def handle(self):
# type: () -> text_type
# type: () -> Text
return self.find_handle_method()()
def generate_topic(self):
# type: () -> text_type
# type: () -> Text
if self.attachments:
return "Snapshots"
topic_template = "Alert {alert_name}"
@@ -102,7 +101,7 @@ class LibratoWebhookHandler(LibratoWebhookParser):
return topic_template.format(alert_name=alert_name)
def handle_alert_clear_message(self):
# type: () -> text_type
# type: () -> Text
alert_clear_template = "Alert [alert_name]({alert_url}) has cleared at {trigger_time}!"
trigger_time = datetime.fromtimestamp((self.payload['trigger_time']))
alert_id, alert_name, alert_url, alert_runbook_url = self.parse_alert()
@@ -110,21 +109,21 @@ class LibratoWebhookHandler(LibratoWebhookParser):
return content
def handle_snapshots(self):
# type: () -> text_type
# type: () -> Text
content = u''
for attachment in self.attachments:
content += self.handle_snapshot(attachment)
return content
def handle_snapshot(self, snapshot):
# type: (Dict[str, Any]) -> text_type
# type: (Dict[str, Any]) -> Text
snapshot_template = u"**{author_name}** sent a [snapshot]({image_url}) of [metric]({title})"
author_name, image_url, title = self.parse_snapshot(snapshot)
content = snapshot_template.format(author_name=author_name, image_url=image_url, title=title)
return content
def handle_alert_violation_message(self):
# type: () -> text_type
# type: () -> Text
alert_violation_template = u"Alert [alert_name]({alert_url}) has triggered! "
alert_id, alert_name, alert_url, alert_runbook_url = self.parse_alert()
content = alert_violation_template.format(alert_name=alert_name, alert_url=alert_url)
@@ -135,7 +134,7 @@ class LibratoWebhookHandler(LibratoWebhookParser):
return content
def generate_conditions_and_violations(self):
# type: () -> text_type
# type: () -> Text
conditions = self.parse_conditions()
violations = self.parse_violations()
content = u""
@@ -144,7 +143,7 @@ class LibratoWebhookHandler(LibratoWebhookParser):
return content
def generate_violated_metric_condition(self, violation, condition):
# type: (Dict[str, Any], Dict[str, Any]) -> text_type
# type: (Dict[str, Any], Dict[str, Any]) -> Text
summary_function, threshold, condition_type, duration = self.parse_condition(condition)
metric_name, recorded_at = self.parse_violation(violation)
metric_condition_template = u"\n>Metric `{metric_name}`, {summary_function} was {condition_type} {threshold}"
@@ -160,7 +159,7 @@ class LibratoWebhookHandler(LibratoWebhookParser):
@has_request_variables
def api_librato_webhook(request, user_profile, client, payload=REQ(converter=ujson.loads, default={}),
stream=REQ(default='librato'), topic=REQ(default=None)):
# type: (HttpRequest, UserProfile, Client, Dict[str, Any], text_type, text_type) -> HttpResponse
# type: (HttpRequest, UserProfile, Client, Dict[str, Any], Text, Text) -> HttpResponse
try:
attachments = ujson.loads(request.body).get('attachments', [])
except ValueError:

View File

@@ -14,12 +14,11 @@ from defusedxml.ElementTree import fromstring as xml_fromstring
import logging
import re
import ujson
from six import text_type
from typing import List, Optional, Tuple
from typing import List, Optional, Tuple, Text
def api_pivotal_webhook_v3(request, user_profile, stream):
# type: (HttpRequest, UserProfile, text_type) -> Tuple[text_type, text_type]
# type: (HttpRequest, UserProfile, Text) -> Tuple[Text, Text]
payload = xml_fromstring(request.body)
def get_text(attrs):
@@ -73,7 +72,7 @@ def api_pivotal_webhook_v3(request, user_profile, stream):
return subject, content
def api_pivotal_webhook_v5(request, user_profile, stream):
# type: (HttpRequest, UserProfile, text_type) -> Tuple[text_type, text_type]
# type: (HttpRequest, UserProfile, Text) -> Tuple[Text, Text]
payload = ujson.loads(request.body)
event_type = payload["kind"]
@@ -98,7 +97,7 @@ def api_pivotal_webhook_v5(request, user_profile, stream):
subject = "#%s: %s" % (story_id, story_name)
def extract_comment(change):
# type: (Dict[str, Dict]) -> Optional[text_type]
# type: (Dict[str, Dict]) -> Optional[Text]
if change.get("kind") == "comment":
return change.get("new_values", {}).get("text", None)
return None
@@ -163,7 +162,7 @@ def api_pivotal_webhook_v5(request, user_profile, stream):
@api_key_only_webhook_view("Pivotal")
@has_request_variables
def api_pivotal_webhook(request, user_profile, client, stream=REQ()):
# type: (HttpRequest, UserProfile, Client, text_type) -> HttpResponse
# type: (HttpRequest, UserProfile, Client, Text) -> HttpResponse
subject = content = None
try:
subject, content = api_pivotal_webhook_v3(request, user_profile, stream)

View File

@@ -11,7 +11,6 @@ from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_vi
from zerver.models import UserProfile, Client
import ujson
from six import text_type
from typing import Any, Dict

View File

@@ -11,15 +11,14 @@ from zerver.decorator import REQ, has_request_variables, authenticated_rest_api_
from zerver.models import UserProfile
import ujson
from six import text_type
from typing import Any, Dict
from typing import Any, Dict, Text
@authenticated_rest_api_view(is_webhook=True)
@has_request_variables
def api_stash_webhook(request, user_profile, payload=REQ(argument_type='body'),
stream=REQ(default='commits')):
# type: (HttpRequest, UserProfile, Dict[str, Any], text_type) -> HttpResponse
# type: (HttpRequest, UserProfile, Dict[str, Any], Text) -> HttpResponse
# We don't get who did the push, or we'd try to report that.
try:
repo_name = payload["repository"]["name"]

View File

@@ -8,8 +8,7 @@ from zerver.lib.validator import check_dict, check_string
from zerver.models import Client, UserProfile
from django.http import HttpRequest, HttpResponse
from six import text_type
from typing import Dict, Any, Iterable, Optional
from typing import Dict, Any, Iterable, Optional, Text
from datetime import datetime
@@ -18,7 +17,7 @@ from datetime import datetime
def api_stripe_webhook(request, user_profile, client,
payload=REQ(argument_type='body'), stream=REQ(default='test'),
topic=REQ(default='stripe')):
# type: (HttpRequest, UserProfile, Client, Dict[str, Any], text_type, Optional[text_type]) -> HttpResponse
# type: (HttpRequest, UserProfile, Client, Dict[str, Any], Text, Optional[Text]) -> HttpResponse
body = ""
event_type = ""
try:

View File

@@ -1,8 +1,7 @@
# Webhooks for external integrations.
from __future__ import absolute_import
import ujson
from six import text_type
from typing import Mapping, Any, Tuple
from typing import Mapping, Any, Tuple, Text
from django.utils.translation import ugettext as _
from django.http import HttpRequest, HttpResponse
from zerver.lib.actions import check_send_message
@@ -19,7 +18,7 @@ from .exceptions import UnsupportedAction
@return_success_on_head_request
@has_request_variables
def api_trello_webhook(request, user_profile, client, payload=REQ(argument_type='body'), stream=REQ(default='trello')):
# type: (HttpRequest, UserProfile, Client, Mapping[str, Any], text_type) -> HttpResponse
# type: (HttpRequest, UserProfile, Client, Mapping[str, Any], Text) -> HttpResponse
payload = ujson.loads(request.body)
action_type = payload.get('action').get('type')
try:
@@ -31,7 +30,7 @@ def api_trello_webhook(request, user_profile, client, payload=REQ(argument_type=
return json_success()
def get_subject_and_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> Tuple[text_type, text_type]
# type: (Mapping[str, Any], Text) -> Tuple[Text, Text]
if action_type in SUPPORTED_CARD_ACTIONS:
return process_card_action(payload, action_type)
if action_type in SUPPORTED_BOARD_ACTIONS:

View File

@@ -1,5 +1,4 @@
from six import text_type
from typing import Mapping, Any, Tuple, Optional, MutableMapping
from typing import Mapping, Any, Tuple, Optional, MutableMapping, Text
from .exceptions import UnknownUpdateBoardAction
from .templates import TRELLO_SUBJECT_TEMPLATE, TRELLO_MESSAGE_TEMPLATE
@@ -25,12 +24,12 @@ ACTIONS_TO_MESSAGE_MAPPER = {
}
def process_board_action(payload, action_type):
# type: (Mapping[str, Any], text_type) -> Tuple[text_type, text_type]
# type: (Mapping[str, Any], Text) -> Tuple[Text, Text]
action_type = get_proper_action(payload, action_type)
return get_subject(payload), get_body(payload, action_type)
def get_proper_action(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
if action_type == 'updateBoard':
data = get_action_data(payload)
if data.get('old').get('name'):
@@ -39,34 +38,34 @@ def get_proper_action(payload, action_type):
return action_type
def get_subject(payload):
# type: (Mapping[str, Any]) -> text_type
# type: (Mapping[str, Any]) -> Text
data = {
'board_name': get_action_data(payload).get('board').get('name')
}
return TRELLO_SUBJECT_TEMPLATE.format(**data)
def get_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
message_body = ACTIONS_TO_FILL_BODY_MAPPER[action_type](payload, action_type)
creator = payload.get('action').get('memberCreator').get('fullName')
return TRELLO_MESSAGE_TEMPLATE.format(full_name=creator, rest=message_body)
def get_managed_member_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
data = {
'member_name': payload.get('action').get('member').get('fullName'),
}
return fill_appropriate_message_content(payload, action_type, data)
def get_create_list_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
data = {
'list_name': get_action_data(payload).get('list').get('name'),
}
return fill_appropriate_message_content(payload, action_type, data)
def get_change_name_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
data = {
'old_name': get_action_data(payload).get('old').get('name'),
}
@@ -74,26 +73,26 @@ def get_change_name_body(payload, action_type):
def fill_appropriate_message_content(payload, action_type, data=None):
# type: (Mapping[str, Any], text_type, Optional[Dict[str, Any]]) -> text_type
# type: (Mapping[str, Any], Text, Optional[Dict[str, Any]]) -> Text
data = {} if data is None else data
data['board_url_template'] = data.get('board_url_template', get_filled_board_url_template(payload))
message_body = get_message_body(action_type)
return message_body.format(**data)
def get_filled_board_url_template(payload):
# type: (Mapping[str, Any]) -> text_type
# type: (Mapping[str, Any]) -> Text
return TRELLO_BOARD_URL_TEMPLATE.format(board_name=get_board_name(payload), board_url=get_board_url(payload))
def get_board_name(payload):
# type: (Mapping[str, Any]) -> text_type
# type: (Mapping[str, Any]) -> Text
return get_action_data(payload).get('board').get('name')
def get_board_url(payload):
# type: (Mapping[str, Any]) -> text_type
# type: (Mapping[str, Any]) -> Text
return u'https://trello.com/b/{}'.format(get_action_data(payload).get('board').get('shortLink'))
def get_message_body(action_type):
# type: (text_type) -> text_type
# type: (Text) -> Text
return ACTIONS_TO_MESSAGE_MAPPER[action_type]
def get_action_data(payload):

View File

@@ -1,5 +1,4 @@
from six import text_type
from typing import Dict, Tuple, Any, Optional, MutableMapping, Mapping
from typing import Dict, Tuple, Any, Optional, MutableMapping, Mapping, Text
from datetime import datetime
from .exceptions import UnknownUpdateCardAction
from .templates import TRELLO_SUBJECT_TEMPLATE, TRELLO_MESSAGE_TEMPLATE
@@ -53,12 +52,12 @@ ACTIONS_TO_MESSAGE_MAPPER = {
}
def process_card_action(payload, action_type):
# type: (Mapping[str, Any], text_type) -> Tuple[text_type, text_type]
# type: (Mapping[str, Any], Text) -> Tuple[Text, Text]
action_type = get_proper_action(payload, action_type)
return get_subject(payload), get_body(payload, action_type)
def get_proper_action(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
if action_type == 'updateCard':
data = get_action_data(payload)
if data.get('listBefore'):
@@ -81,27 +80,27 @@ def get_proper_action(payload, action_type):
return action_type
def get_subject(payload):
# type: (Mapping[str, Any]) -> text_type
# type: (Mapping[str, Any]) -> Text
data = {
'board_name': get_action_data(payload).get('board').get('name')
}
return TRELLO_SUBJECT_TEMPLATE.format(**data)
def get_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
message_body = ACTIONS_TO_FILL_BODY_MAPPER.get(action_type)(payload, action_type)
creator = payload.get('action').get('memberCreator').get('fullName')
return TRELLO_MESSAGE_TEMPLATE.format(full_name=creator, rest=message_body)
def get_added_checklist_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
data = {
'checklist_name': get_action_data(payload).get('checklist').get('name'),
}
return fill_appropriate_message_content(payload, action_type, data)
def get_added_attachment_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
data = {
'attachment_url': get_action_data(payload).get('attachment').get('url'),
'attachment_name': get_action_data(payload).get('attachment').get('name'),
@@ -109,7 +108,7 @@ def get_added_attachment_body(payload, action_type):
return fill_appropriate_message_content(payload, action_type, data)
def get_updated_card_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
data = {
'card_name': get_card_name(payload),
'old_list': get_action_data(payload).get('listBefore').get('name'),
@@ -118,7 +117,7 @@ def get_updated_card_body(payload, action_type):
return fill_appropriate_message_content(payload, action_type, data)
def get_renamed_card_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
data = {
'old_name': get_action_data(payload).get('old').get('name'),
'new_name': get_action_data(payload).get('card').get('name'),
@@ -126,7 +125,7 @@ def get_renamed_card_body(payload, action_type):
return fill_appropriate_message_content(payload, action_type, data)
def get_added_label_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
data = {
'color': get_action_data(payload).get('value'),
'text': get_action_data(payload).get('text'),
@@ -134,14 +133,14 @@ def get_added_label_body(payload, action_type):
return fill_appropriate_message_content(payload, action_type, data)
def get_managed_member_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
data = {
'member_name': payload.get('action').get('member').get('fullName')
}
return fill_appropriate_message_content(payload, action_type, data)
def get_managed_due_date_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
date_format = "%Y-%m-%dT%H:%M:%S.000Z"
display_date_format = '%m/%d/%Y %I:%M%p'
new_date = datetime.strptime(get_action_data(payload).get('card').get('due'), date_format)
@@ -151,7 +150,7 @@ def get_managed_due_date_body(payload, action_type):
return fill_appropriate_message_content(payload, action_type, data)
def get_changed_due_date_body(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
date_format = "%Y-%m-%dT%H:%M:%S.000Z"
display_date_format = '%m/%d/%Y %I:%M%p'
new_date = datetime.strptime(get_action_data(payload).get('card').get('due'), date_format)
@@ -163,30 +162,30 @@ def get_changed_due_date_body(payload, action_type):
return fill_appropriate_message_content(payload, action_type, data)
def get_body_by_action_type_without_data(payload, action_type):
# type: (Mapping[str, Any], text_type) -> text_type
# type: (Mapping[str, Any], Text) -> Text
return fill_appropriate_message_content(payload, action_type)
def fill_appropriate_message_content(payload, action_type, data=None):
# type: (Mapping[str, Any], text_type, Optional[Dict[str, Any]]) -> text_type
# type: (Mapping[str, Any], Text, Optional[Dict[str, Any]]) -> Text
data = {} if data is None else data
data['card_url_template'] = data.get('card_url_template', get_filled_card_url_template(payload))
message_body = get_message_body(action_type)
return message_body.format(**data)
def get_filled_card_url_template(payload):
# type: (Mapping[str, Any]) -> text_type
# type: (Mapping[str, Any]) -> Text
return TRELLO_CARD_URL_TEMPLATE.format(card_name=get_card_name(payload), card_url=get_card_url(payload))
def get_card_url(payload):
# type: (Mapping[str, Any]) -> text_type
# type: (Mapping[str, Any]) -> Text
return u'https://trello.com/c/{}'.format(get_action_data(payload).get('card').get('shortLink'))
def get_message_body(action_type):
# type: (text_type) -> text_type
# type: (Text) -> Text
return ACTIONS_TO_MESSAGE_MAPPER.get(action_type)
def get_card_name(payload):
# type: (Mapping[str, Any]) -> text_type
# type: (Mapping[str, Any]) -> Text
return get_action_data(payload).get('card').get('name')
def get_action_data(payload):

View File

@@ -5,10 +5,10 @@ from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success
from zerver.decorator import authenticated_rest_api_view, REQ, has_request_variables
from django.http import HttpRequest, HttpResponse
from six import text_type
from typing import Text
def truncate(string, length):
# type: (text_type, int) -> text_type
# type: (Text, int) -> Text
if len(string) > length:
string = string[:length-3] + '...'
return string