2018-01-07 12:05:44 +01:00
|
|
|
# Webhooks for external integrations.
|
2019-04-18 22:23:36 +02:00
|
|
|
from functools import partial
|
2020-01-14 22:06:24 +01:00
|
|
|
from typing import Any, Callable, Dict, Optional
|
2018-01-07 12:05:44 +01:00
|
|
|
|
|
|
|
from django.http import HttpRequest, HttpResponse
|
|
|
|
|
|
|
|
from zerver.decorator import api_key_only_webhook_view
|
2020-08-19 22:26:38 +02:00
|
|
|
from zerver.lib.exceptions import UnsupportedWebhookEventType
|
2018-01-07 12:05:44 +01:00
|
|
|
from zerver.lib.request import REQ, has_request_variables
|
2019-04-18 22:23:36 +02:00
|
|
|
from zerver.lib.response import json_success
|
2020-06-11 00:54:34 +02:00
|
|
|
from zerver.lib.webhooks.common import (
|
|
|
|
check_send_webhook_message,
|
|
|
|
get_http_headers_from_filename,
|
|
|
|
validate_extract_webhook_http_header,
|
|
|
|
)
|
2018-01-07 12:05:44 +01:00
|
|
|
from zerver.models import UserProfile
|
|
|
|
|
2019-04-18 22:23:36 +02:00
|
|
|
TICKET_STARTED_TEMPLATE = """
|
|
|
|
{customer_name} submitted new ticket [#{number}: {title}]({app_url}):
|
|
|
|
|
|
|
|
``` quote
|
|
|
|
{summary}
|
|
|
|
```
|
|
|
|
""".strip()
|
|
|
|
|
|
|
|
TICKET_ASSIGNED_TEMPLATE = "[#{number}: {title}]({app_url}) ({state}) assigned to {assignee_info}."
|
|
|
|
|
|
|
|
AGENT_REPLIED_TEMPLATE = """
|
|
|
|
{actor} {action} [ticket #{number}]({app_ticket_url}):
|
|
|
|
|
|
|
|
``` quote
|
|
|
|
{plain_text_body}
|
|
|
|
```
|
|
|
|
""".strip()
|
|
|
|
|
2018-05-10 19:34:01 +02:00
|
|
|
def ticket_started_body(payload: Dict[str, Any]) -> str:
|
2019-04-18 22:23:36 +02:00
|
|
|
return TICKET_STARTED_TEMPLATE.format(**payload)
|
2018-01-07 12:05:44 +01:00
|
|
|
|
2018-05-10 19:34:01 +02:00
|
|
|
def ticket_assigned_body(payload: Dict[str, Any]) -> Optional[str]:
|
2018-01-07 12:05:44 +01:00
|
|
|
state = payload['state']
|
2019-04-18 22:23:36 +02:00
|
|
|
kwargs = {
|
|
|
|
'state': 'open' if state == 'opened' else state,
|
|
|
|
'number': payload['number'],
|
|
|
|
'title': payload['title'],
|
python: Use trailing commas consistently.
Automatically generated by the following script, based on the output
of lint with flake8-comma:
import re
import sys
last_filename = None
last_row = None
lines = []
for msg in sys.stdin:
m = re.match(
r"\x1b\[35mflake8 \|\x1b\[0m \x1b\[1;31m(.+):(\d+):(\d+): (\w+)", msg
)
if m:
filename, row_str, col_str, err = m.groups()
row, col = int(row_str), int(col_str)
if filename == last_filename:
assert last_row != row
else:
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
with open(filename) as f:
lines = f.readlines()
last_filename = filename
last_row = row
line = lines[row - 1]
if err in ["C812", "C815"]:
lines[row - 1] = line[: col - 1] + "," + line[col - 1 :]
elif err in ["C819"]:
assert line[col - 2] == ","
lines[row - 1] = line[: col - 2] + line[col - 1 :].lstrip(" ")
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-10 05:23:40 +02:00
|
|
|
'app_url': payload['app_url'],
|
2019-04-18 22:23:36 +02:00
|
|
|
}
|
|
|
|
|
2018-01-07 12:05:44 +01:00
|
|
|
assignee = payload['assignee']
|
|
|
|
assigned_group = payload['assigned_group']
|
|
|
|
|
|
|
|
if assignee or assigned_group:
|
|
|
|
if assignee and assigned_group:
|
2019-04-18 22:23:36 +02:00
|
|
|
kwargs['assignee_info'] = '{assignee} from {assigned_group}'.format(**payload)
|
2018-01-07 12:05:44 +01:00
|
|
|
elif assignee:
|
2019-04-18 22:23:36 +02:00
|
|
|
kwargs['assignee_info'] = '{assignee}'.format(**payload)
|
2018-01-07 12:05:44 +01:00
|
|
|
elif assigned_group:
|
2019-04-18 22:23:36 +02:00
|
|
|
kwargs['assignee_info'] = '{assigned_group}'.format(**payload)
|
|
|
|
|
|
|
|
return TICKET_ASSIGNED_TEMPLATE.format(**kwargs)
|
2018-01-07 12:05:44 +01:00
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
2019-04-18 22:23:36 +02:00
|
|
|
def replied_body(payload: Dict[str, Any], actor: str, action: str) -> str:
|
|
|
|
actor_url = "http://api.groovehq.com/v1/{}/".format(actor + 's')
|
|
|
|
actor = payload['links']['author']['href'].split(actor_url)[1]
|
2018-01-07 12:05:44 +01:00
|
|
|
number = payload['links']['ticket']['href'].split("http://api.groovehq.com/v1/tickets/")[1]
|
|
|
|
|
2019-04-18 22:23:36 +02:00
|
|
|
body = AGENT_REPLIED_TEMPLATE.format(
|
|
|
|
actor=actor,
|
|
|
|
action=action,
|
|
|
|
number=number,
|
|
|
|
app_ticket_url=payload['app_ticket_url'],
|
python: Use trailing commas consistently.
Automatically generated by the following script, based on the output
of lint with flake8-comma:
import re
import sys
last_filename = None
last_row = None
lines = []
for msg in sys.stdin:
m = re.match(
r"\x1b\[35mflake8 \|\x1b\[0m \x1b\[1;31m(.+):(\d+):(\d+): (\w+)", msg
)
if m:
filename, row_str, col_str, err = m.groups()
row, col = int(row_str), int(col_str)
if filename == last_filename:
assert last_row != row
else:
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
with open(filename) as f:
lines = f.readlines()
last_filename = filename
last_row = row
line = lines[row - 1]
if err in ["C812", "C815"]:
lines[row - 1] = line[: col - 1] + "," + line[col - 1 :]
elif err in ["C819"]:
assert line[col - 2] == ","
lines[row - 1] = line[: col - 2] + line[col - 1 :].lstrip(" ")
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-10 05:23:40 +02:00
|
|
|
plain_text_body=payload['plain_text_body'],
|
2019-04-18 22:23:36 +02:00
|
|
|
)
|
2018-01-07 12:05:44 +01:00
|
|
|
|
2019-04-18 22:23:36 +02:00
|
|
|
return body
|
2018-01-07 12:05:44 +01:00
|
|
|
|
2019-04-18 22:23:36 +02:00
|
|
|
def get_event_handler(event: str) -> Callable[..., str]:
|
2020-03-28 01:25:56 +01:00
|
|
|
# The main reason for this function existence is because of mypy
|
python: Convert assignment type annotations to Python 3.6 style.
This commit was split by tabbott; this piece covers the vast majority
of files in Zulip, but excludes scripts/, tools/, and puppet/ to help
ensure we at least show the right error messages for Xenial systems.
We can likely further refine the remaining pieces with some testing.
Generated by com2ann, with whitespace fixes and various manual fixes
for runtime issues:
- invoiced_through: Optional[LicenseLedger] = models.ForeignKey(
+ invoiced_through: Optional["LicenseLedger"] = models.ForeignKey(
-_apns_client: Optional[APNsClient] = None
+_apns_client: Optional["APNsClient"] = None
- notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
- signup_notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+ notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+ signup_notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
- author: Optional[UserProfile] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)
+ author: Optional["UserProfile"] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)
- bot_owner: Optional[UserProfile] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
+ bot_owner: Optional["UserProfile"] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
- default_sending_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
- default_events_register_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+ default_sending_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+ default_events_register_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
-descriptors_by_handler_id: Dict[int, ClientDescriptor] = {}
+descriptors_by_handler_id: Dict[int, "ClientDescriptor"] = {}
-worker_classes: Dict[str, Type[QueueProcessingWorker]] = {}
-queues: Dict[str, Dict[str, Type[QueueProcessingWorker]]] = {}
+worker_classes: Dict[str, Type["QueueProcessingWorker"]] = {}
+queues: Dict[str, Dict[str, Type["QueueProcessingWorker"]]] = {}
-AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional[LDAPSearch] = None
+AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional["LDAPSearch"] = None
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-22 01:09:50 +02:00
|
|
|
handler: Any = EVENTS_FUNCTION_MAPPER.get(event)
|
2019-04-18 22:23:36 +02:00
|
|
|
if handler is None:
|
2020-08-19 22:26:38 +02:00
|
|
|
raise UnsupportedWebhookEventType("Groove", event)
|
2019-04-18 22:23:36 +02:00
|
|
|
return handler
|
2018-01-07 12:05:44 +01:00
|
|
|
|
|
|
|
@api_key_only_webhook_view('Groove')
|
|
|
|
@has_request_variables
|
|
|
|
def api_groove_webhook(request: HttpRequest, user_profile: UserProfile,
|
2018-03-16 22:53:50 +01:00
|
|
|
payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
|
2018-04-24 20:54:13 +02:00
|
|
|
event = validate_extract_webhook_http_header(request, 'X_GROOVE_EVENT', 'Groove')
|
2019-04-18 22:23:36 +02:00
|
|
|
assert event is not None
|
|
|
|
handler = get_event_handler(event)
|
|
|
|
|
|
|
|
body = handler(payload)
|
|
|
|
topic = 'notifications'
|
2018-04-24 20:54:13 +02:00
|
|
|
|
2019-04-18 22:23:36 +02:00
|
|
|
if body is not None:
|
|
|
|
check_send_webhook_message(request, user_profile, topic, body)
|
2018-01-07 12:05:44 +01:00
|
|
|
|
|
|
|
return json_success()
|
|
|
|
|
|
|
|
EVENTS_FUNCTION_MAPPER = {
|
|
|
|
'ticket_started': ticket_started_body,
|
|
|
|
'ticket_assigned': ticket_assigned_body,
|
2019-04-18 22:23:36 +02:00
|
|
|
'agent_replied': partial(replied_body, actor='agent', action='replied to'),
|
|
|
|
'customer_replied': partial(replied_body, actor='customer', action='replied to'),
|
python: Use trailing commas consistently.
Automatically generated by the following script, based on the output
of lint with flake8-comma:
import re
import sys
last_filename = None
last_row = None
lines = []
for msg in sys.stdin:
m = re.match(
r"\x1b\[35mflake8 \|\x1b\[0m \x1b\[1;31m(.+):(\d+):(\d+): (\w+)", msg
)
if m:
filename, row_str, col_str, err = m.groups()
row, col = int(row_str), int(col_str)
if filename == last_filename:
assert last_row != row
else:
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
with open(filename) as f:
lines = f.readlines()
last_filename = filename
last_row = row
line = lines[row - 1]
if err in ["C812", "C815"]:
lines[row - 1] = line[: col - 1] + "," + line[col - 1 :]
elif err in ["C819"]:
assert line[col - 2] == ","
lines[row - 1] = line[: col - 2] + line[col - 1 :].lstrip(" ")
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-10 05:23:40 +02:00
|
|
|
'note_added': partial(replied_body, actor='agent', action='left a note on'),
|
2018-01-07 12:05:44 +01:00
|
|
|
}
|
2019-07-04 20:56:14 +02:00
|
|
|
|
|
|
|
fixture_to_headers = get_http_headers_from_filename("HTTP_X_GROOVE_EVENT")
|