2018-05-11 01:40:23 +02:00
|
|
|
from typing import Any, AnyStr, Iterable, Dict, Tuple, Callable, Mapping, Optional
|
2016-07-23 08:13:33 +02:00
|
|
|
|
|
|
|
import requests
|
|
|
|
import json
|
|
|
|
import sys
|
|
|
|
import inspect
|
|
|
|
import logging
|
2017-07-21 06:49:00 +02:00
|
|
|
import re
|
2017-11-05 05:30:31 +01:00
|
|
|
import urllib
|
2016-07-23 08:13:33 +02:00
|
|
|
from functools import reduce
|
2017-05-25 19:16:40 +02:00
|
|
|
from requests import Response
|
2016-07-23 08:13:33 +02:00
|
|
|
|
|
|
|
from django.utils.translation import ugettext as _
|
|
|
|
|
2017-08-25 05:26:31 +02:00
|
|
|
from zerver.models import Realm, UserProfile, get_user_profile_by_id, get_client, \
|
2017-07-24 07:51:18 +02:00
|
|
|
GENERIC_INTERFACE, Service, SLACK_INTERFACE, email_to_domain, get_service_profile
|
2016-07-23 08:13:33 +02:00
|
|
|
from zerver.lib.actions import check_send_message
|
2017-10-19 14:52:06 +02:00
|
|
|
from zerver.lib.queue import retry_event
|
2018-07-29 00:05:45 +02:00
|
|
|
from zerver.lib.url_encoding import encode_stream
|
2016-07-23 08:13:33 +02:00
|
|
|
from zerver.lib.validator import check_dict, check_string
|
|
|
|
from zerver.decorator import JsonableError
|
|
|
|
|
2017-11-05 11:37:41 +01:00
|
|
|
class OutgoingWebhookServiceInterface:
|
2017-05-25 19:16:40 +02:00
|
|
|
|
2018-10-11 00:24:55 +02:00
|
|
|
def __init__(self, token: str, user_profile: UserProfile, service_name: str) -> None:
|
2018-05-11 01:40:23 +02:00
|
|
|
self.token = token # type: str
|
2018-05-23 16:12:44 +02:00
|
|
|
self.user_profile = user_profile # type: UserProfile
|
2018-05-11 01:40:23 +02:00
|
|
|
self.service_name = service_name # type: str
|
2017-05-25 19:16:40 +02:00
|
|
|
|
2017-07-24 07:51:18 +02:00
|
|
|
class GenericOutgoingWebhookService(OutgoingWebhookServiceInterface):
|
|
|
|
|
2018-10-11 00:45:19 +02:00
|
|
|
def build_bot_request(self, event: Dict[str, Any]) -> Optional[Any]:
|
2017-07-24 07:51:18 +02:00
|
|
|
request_data = {"data": event['command'],
|
|
|
|
"message": event['message'],
|
2018-05-23 16:14:22 +02:00
|
|
|
"bot_email": self.user_profile.email,
|
|
|
|
"token": self.token,
|
|
|
|
"trigger": event['trigger']}
|
2018-10-11 00:45:19 +02:00
|
|
|
return json.dumps(request_data)
|
2017-07-24 07:51:18 +02:00
|
|
|
|
2018-10-11 14:11:52 +02:00
|
|
|
def send_data_to_server(self,
|
|
|
|
base_url: str,
|
|
|
|
request_data: Any) -> Response:
|
|
|
|
headers = {'content-type': 'application/json'}
|
|
|
|
response = requests.request('POST', base_url, data=request_data, headers=headers)
|
|
|
|
return response
|
|
|
|
|
2018-10-10 13:16:42 +02:00
|
|
|
def process_success(self, response_json: Dict[str, Any],
|
2018-10-09 17:12:57 +02:00
|
|
|
event: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
2017-07-24 07:51:18 +02:00
|
|
|
if "response_not_required" in response_json and response_json['response_not_required']:
|
2018-10-09 17:12:57 +02:00
|
|
|
return None
|
|
|
|
|
2017-07-24 07:51:18 +02:00
|
|
|
if "response_string" in response_json:
|
2018-10-10 01:36:31 +02:00
|
|
|
# We are deprecating response_string.
|
|
|
|
content = str(response_json['response_string'])
|
|
|
|
success_data = dict(content=content)
|
2018-10-09 21:16:36 +02:00
|
|
|
return success_data
|
|
|
|
|
|
|
|
if "content" in response_json:
|
|
|
|
content = str(response_json['content'])
|
|
|
|
success_data = dict(content=content)
|
2018-10-09 17:12:57 +02:00
|
|
|
return success_data
|
|
|
|
|
|
|
|
return None
|
2017-07-24 07:51:18 +02:00
|
|
|
|
|
|
|
class SlackOutgoingWebhookService(OutgoingWebhookServiceInterface):
|
|
|
|
|
2018-10-11 00:45:19 +02:00
|
|
|
def build_bot_request(self, event: Dict[str, Any]) -> Optional[Any]:
|
2017-07-24 07:51:18 +02:00
|
|
|
if event['message']['type'] == 'private':
|
2018-06-24 08:51:47 +02:00
|
|
|
failure_message = "Slack outgoing webhooks don't support private messages."
|
|
|
|
fail_with_message(event, failure_message)
|
2018-10-11 00:45:19 +02:00
|
|
|
return None
|
2017-07-24 07:51:18 +02:00
|
|
|
|
|
|
|
request_data = [("token", self.token),
|
|
|
|
("team_id", event['message']['sender_realm_str']),
|
|
|
|
("team_domain", email_to_domain(event['message']['sender_email'])),
|
|
|
|
("channel_id", event['message']['stream_id']),
|
|
|
|
("channel_name", event['message']['display_recipient']),
|
|
|
|
("timestamp", event['message']['timestamp']),
|
|
|
|
("user_id", event['message']['sender_id']),
|
|
|
|
("user_name", event['message']['sender_full_name']),
|
|
|
|
("text", event['command']),
|
|
|
|
("trigger_word", event['trigger']),
|
2018-07-23 17:12:08 +02:00
|
|
|
("service_id", event['user_profile_id']),
|
2017-07-24 07:51:18 +02:00
|
|
|
]
|
|
|
|
|
2018-10-11 00:45:19 +02:00
|
|
|
return request_data
|
2017-07-24 07:51:18 +02:00
|
|
|
|
2018-10-11 14:11:52 +02:00
|
|
|
def send_data_to_server(self,
|
|
|
|
base_url: str,
|
|
|
|
request_data: Any) -> Response:
|
|
|
|
response = requests.request('POST', base_url, data=request_data)
|
|
|
|
return response
|
|
|
|
|
2018-10-10 13:16:42 +02:00
|
|
|
def process_success(self, response_json: Dict[str, Any],
|
2018-10-09 17:12:57 +02:00
|
|
|
event: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
2017-07-24 07:51:18 +02:00
|
|
|
if "text" in response_json:
|
2018-10-09 17:12:57 +02:00
|
|
|
content = response_json['text']
|
2018-10-10 01:36:31 +02:00
|
|
|
success_data = dict(content=content)
|
2018-10-09 17:12:57 +02:00
|
|
|
return success_data
|
|
|
|
|
|
|
|
return None
|
2017-07-24 07:51:18 +02:00
|
|
|
|
|
|
|
AVAILABLE_OUTGOING_WEBHOOK_INTERFACES = {
|
|
|
|
GENERIC_INTERFACE: GenericOutgoingWebhookService,
|
|
|
|
SLACK_INTERFACE: SlackOutgoingWebhookService,
|
2018-05-11 01:40:23 +02:00
|
|
|
} # type: Dict[str, Any]
|
2017-07-24 07:51:18 +02:00
|
|
|
|
2018-05-11 01:40:23 +02:00
|
|
|
def get_service_interface_class(interface: str) -> Any:
|
2017-07-24 07:51:18 +02:00
|
|
|
if interface is None or interface not in AVAILABLE_OUTGOING_WEBHOOK_INTERFACES:
|
|
|
|
return AVAILABLE_OUTGOING_WEBHOOK_INTERFACES[GENERIC_INTERFACE]
|
|
|
|
else:
|
|
|
|
return AVAILABLE_OUTGOING_WEBHOOK_INTERFACES[interface]
|
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def get_outgoing_webhook_service_handler(service: Service) -> Any:
|
2017-07-24 07:51:18 +02:00
|
|
|
|
|
|
|
service_interface_class = get_service_interface_class(service.interface_name())
|
2018-10-11 00:24:55 +02:00
|
|
|
service_interface = service_interface_class(token=service.token,
|
2017-07-24 07:51:18 +02:00
|
|
|
user_profile=service.user_profile,
|
|
|
|
service_name=service.name)
|
|
|
|
return service_interface
|
|
|
|
|
2018-10-09 19:32:43 +02:00
|
|
|
def send_response_message(bot_id: str, message_info: Dict[str, Any], response_data: Dict[str, Any]) -> None:
|
|
|
|
"""
|
|
|
|
bot_id is the user_id of the bot sending the response
|
|
|
|
|
|
|
|
message_info is used to address the message and should have these fields:
|
|
|
|
type - "stream" or "private"
|
|
|
|
display_recipient - like we have in other message events
|
|
|
|
subject - the topic name (if relevant)
|
|
|
|
|
|
|
|
response_data is what the bot wants to send back and has these fields:
|
|
|
|
content - raw markdown content for Zulip to render
|
|
|
|
"""
|
|
|
|
|
|
|
|
message_type = message_info['type']
|
|
|
|
display_recipient = message_info['display_recipient']
|
|
|
|
topic_name = message_info.get('subject')
|
|
|
|
|
2016-07-23 08:13:33 +02:00
|
|
|
bot_user = get_user_profile_by_id(bot_id)
|
2017-08-25 05:26:31 +02:00
|
|
|
realm = bot_user.realm
|
2018-10-09 13:28:41 +02:00
|
|
|
client = get_client('OutgoingWebhookResponse')
|
2016-07-23 08:13:33 +02:00
|
|
|
|
2018-10-09 19:32:43 +02:00
|
|
|
content = response_data.get('content')
|
|
|
|
if not content:
|
|
|
|
raise JsonableError(_("Missing content"))
|
|
|
|
|
2018-10-09 13:33:15 +02:00
|
|
|
if message_type == 'stream':
|
2018-10-09 19:32:43 +02:00
|
|
|
message_to = [display_recipient]
|
2018-10-09 13:33:15 +02:00
|
|
|
elif message_type == 'private':
|
2018-10-09 19:32:43 +02:00
|
|
|
message_to = [recipient['email'] for recipient in display_recipient]
|
2017-09-25 13:03:10 +02:00
|
|
|
else:
|
|
|
|
raise JsonableError(_("Invalid message type"))
|
2016-07-23 08:13:33 +02:00
|
|
|
|
2018-10-09 13:45:39 +02:00
|
|
|
check_send_message(
|
|
|
|
sender=bot_user,
|
|
|
|
client=client,
|
|
|
|
message_type_name=message_type,
|
2018-10-09 19:32:43 +02:00
|
|
|
message_to=message_to,
|
2018-10-09 13:45:39 +02:00
|
|
|
topic_name=topic_name,
|
2018-10-09 19:32:43 +02:00
|
|
|
message_content=content,
|
2018-10-09 13:45:39 +02:00
|
|
|
realm=realm,
|
|
|
|
)
|
|
|
|
|
2018-05-11 01:40:23 +02:00
|
|
|
def fail_with_message(event: Dict[str, Any], failure_message: str) -> None:
|
2018-10-09 19:32:43 +02:00
|
|
|
bot_id = event['user_profile_id']
|
|
|
|
message_info = event['message']
|
|
|
|
content = "Failure! " + failure_message
|
|
|
|
response_data = dict(content=content)
|
|
|
|
send_response_message(bot_id=bot_id, message_info=message_info, response_data=response_data)
|
2016-07-23 08:13:33 +02:00
|
|
|
|
2018-05-11 01:40:23 +02:00
|
|
|
def get_message_url(event: Dict[str, Any], request_data: Dict[str, Any]) -> str:
|
2017-08-29 15:21:25 +02:00
|
|
|
bot_user = get_user_profile_by_id(event['user_profile_id'])
|
|
|
|
message = event['message']
|
|
|
|
if message['type'] == 'stream':
|
2018-02-15 21:02:47 +01:00
|
|
|
stream_url_frag = encode_stream(message.get('stream_id'), message['display_recipient'])
|
2017-08-29 15:21:25 +02:00
|
|
|
message_url = ("%(server)s/#narrow/stream/%(stream)s/subject/%(subject)s/near/%(id)s"
|
|
|
|
% {'server': bot_user.realm.uri,
|
2018-02-15 21:02:47 +01:00
|
|
|
'stream': stream_url_frag,
|
2017-08-29 15:21:25 +02:00
|
|
|
'subject': message['subject'],
|
|
|
|
'id': str(message['id'])})
|
|
|
|
else:
|
|
|
|
recipient_emails = ','.join([recipient['email'] for recipient in message['display_recipient']])
|
|
|
|
recipient_email_encoded = urllib.parse.quote(recipient_emails).replace('.', '%2E').replace('%', '.')
|
|
|
|
message_url = ("%(server)s/#narrow/pm-with/%(recipient_emails)s/near/%(id)s"
|
|
|
|
% {'server': bot_user.realm.uri,
|
|
|
|
'recipient_emails': recipient_email_encoded,
|
|
|
|
'id': str(message['id'])})
|
|
|
|
return message_url
|
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def notify_bot_owner(event: Dict[str, Any],
|
|
|
|
request_data: Dict[str, Any],
|
|
|
|
status_code: Optional[int]=None,
|
|
|
|
response_content: Optional[AnyStr]=None,
|
2018-10-10 19:52:32 +02:00
|
|
|
failure_message: Optional[str]=None,
|
2017-11-05 11:15:10 +01:00
|
|
|
exception: Optional[Exception]=None) -> None:
|
2017-08-29 15:21:25 +02:00
|
|
|
message_url = get_message_url(event, request_data)
|
|
|
|
bot_id = event['user_profile_id']
|
|
|
|
bot_owner = get_user_profile_by_id(bot_id).bot_owner
|
2018-10-09 19:32:43 +02:00
|
|
|
|
2017-08-29 15:21:25 +02:00
|
|
|
notification_message = "[A message](%s) triggered an outgoing webhook." % (message_url,)
|
2018-10-10 19:52:32 +02:00
|
|
|
if failure_message:
|
|
|
|
notification_message += "\n" + failure_message
|
2017-08-29 15:21:25 +02:00
|
|
|
if status_code:
|
|
|
|
notification_message += "\nThe webhook got a response with status code *%s*." % (status_code,)
|
|
|
|
if response_content:
|
|
|
|
notification_message += "\nThe response contains the following payload:\n" \
|
|
|
|
"```\n%s\n```" % (response_content,)
|
|
|
|
if exception:
|
|
|
|
notification_message += "\nWhen trying to send a request to the webhook service, an exception " \
|
2017-11-10 03:34:13 +01:00
|
|
|
"of type %s occurred:\n```\n%s\n```" % (
|
|
|
|
type(exception).__name__, str(exception))
|
2018-10-09 19:32:43 +02:00
|
|
|
|
|
|
|
message_info = dict(
|
|
|
|
type='private',
|
|
|
|
display_recipient=[dict(email=bot_owner.email)],
|
|
|
|
)
|
|
|
|
response_data = dict(content=notification_message)
|
|
|
|
send_response_message(bot_id=bot_id, message_info=message_info, response_data=response_data)
|
2017-08-29 15:21:25 +02:00
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def request_retry(event: Dict[str, Any],
|
|
|
|
request_data: Dict[str, Any],
|
2018-10-10 19:52:32 +02:00
|
|
|
failure_message: Optional[str]=None) -> None:
|
2017-11-05 11:15:10 +01:00
|
|
|
def failure_processor(event: Dict[str, Any]) -> None:
|
2017-08-18 07:56:53 +02:00
|
|
|
"""
|
|
|
|
The name of the argument is 'event' on purpose. This argument will hide
|
|
|
|
the 'event' argument of the request_retry function. Keeping the same name
|
|
|
|
results in a smaller diff.
|
|
|
|
"""
|
2016-07-23 08:13:33 +02:00
|
|
|
bot_user = get_user_profile_by_id(event['user_profile_id'])
|
2018-10-10 19:52:32 +02:00
|
|
|
fail_with_message(event, "Bot is unavailable")
|
|
|
|
notify_bot_owner(event, request_data, failure_message=failure_message)
|
2017-11-10 03:34:13 +01:00
|
|
|
logging.warning("Maximum retries exceeded for trigger:%s event:%s" % (
|
|
|
|
bot_user.email, event['command']))
|
2017-08-18 07:56:53 +02:00
|
|
|
|
|
|
|
retry_event('outgoing_webhooks', event, failure_processor)
|
2016-07-23 08:13:33 +02:00
|
|
|
|
2018-05-01 12:36:49 +02:00
|
|
|
def process_success_response(event: Dict[str, Any],
|
|
|
|
service_handler: Any,
|
|
|
|
response: Response) -> None:
|
2018-10-10 15:11:50 +02:00
|
|
|
try:
|
|
|
|
response_json = json.loads(response.text)
|
|
|
|
except ValueError:
|
|
|
|
fail_with_message(event, "Invalid JSON in response")
|
|
|
|
return
|
|
|
|
|
2018-10-10 13:16:42 +02:00
|
|
|
success_data = service_handler.process_success(response_json, event)
|
2018-10-09 16:12:32 +02:00
|
|
|
|
|
|
|
if success_data is None:
|
|
|
|
return
|
|
|
|
|
2018-10-10 01:36:31 +02:00
|
|
|
content = success_data.get('content')
|
2018-10-09 16:12:32 +02:00
|
|
|
|
2018-10-09 21:16:36 +02:00
|
|
|
if content is None:
|
|
|
|
return
|
2018-10-09 19:32:43 +02:00
|
|
|
|
|
|
|
bot_id = event['user_profile_id']
|
|
|
|
message_info = event['message']
|
|
|
|
response_data = dict(content=content)
|
|
|
|
send_response_message(bot_id=bot_id, message_info=message_info, response_data=response_data)
|
2018-05-01 12:36:49 +02:00
|
|
|
|
2018-10-11 00:24:55 +02:00
|
|
|
def do_rest_call(base_url: str,
|
2018-10-11 00:45:19 +02:00
|
|
|
request_data: Any,
|
2017-11-05 11:15:10 +01:00
|
|
|
event: Dict[str, Any],
|
2018-10-11 14:38:08 +02:00
|
|
|
service_handler: Any) -> None:
|
2016-07-23 08:13:33 +02:00
|
|
|
try:
|
2018-10-11 14:11:52 +02:00
|
|
|
response = service_handler.send_data_to_server(
|
|
|
|
base_url=base_url,
|
|
|
|
request_data=request_data,
|
|
|
|
)
|
2016-07-23 08:13:33 +02:00
|
|
|
if str(response.status_code).startswith('2'):
|
2018-05-01 12:36:49 +02:00
|
|
|
process_success_response(event, service_handler, response)
|
2016-07-23 08:13:33 +02:00
|
|
|
else:
|
2017-08-28 18:51:13 +02:00
|
|
|
logging.warning("Message %(message_url)s triggered an outgoing webhook, returning status "
|
|
|
|
"code %(status_code)s.\n Content of response (in quotes): \""
|
|
|
|
"%(response)s\""
|
2017-08-29 15:21:25 +02:00
|
|
|
% {'message_url': get_message_url(event, request_data),
|
2017-08-28 18:51:13 +02:00
|
|
|
'status_code': response.status_code,
|
|
|
|
'response': response.content})
|
2017-09-25 16:49:28 +02:00
|
|
|
failure_message = "Third party responded with %d" % (response.status_code)
|
|
|
|
fail_with_message(event, failure_message)
|
|
|
|
notify_bot_owner(event, request_data, response.status_code, response.content)
|
2016-07-23 08:13:33 +02:00
|
|
|
|
2018-10-10 19:52:32 +02:00
|
|
|
except requests.exceptions.Timeout:
|
2017-11-10 03:34:13 +01:00
|
|
|
logging.info("Trigger event %s on %s timed out. Retrying" % (
|
|
|
|
event["command"], event['service_name']))
|
2018-10-10 19:52:32 +02:00
|
|
|
failure_message = "A timeout occurred."
|
|
|
|
request_retry(event, request_data, failure_message=failure_message)
|
2017-08-16 13:30:47 +02:00
|
|
|
|
2018-10-10 19:52:32 +02:00
|
|
|
except requests.exceptions.ConnectionError:
|
2017-08-16 13:30:47 +02:00
|
|
|
logging.info("Trigger event %s on %s resulted in a connection error. Retrying"
|
|
|
|
% (event["command"], event['service_name']))
|
2018-10-10 19:52:32 +02:00
|
|
|
failure_message = "A connection error occurred. Is my bot server down?"
|
|
|
|
request_retry(event, request_data, failure_message=failure_message)
|
2016-07-23 08:13:33 +02:00
|
|
|
|
|
|
|
except requests.exceptions.RequestException as e:
|
2017-11-10 03:34:13 +01:00
|
|
|
response_message = ("An exception of type *%s* occurred for message `%s`! "
|
|
|
|
"See the Zulip server logs for more information." % (
|
|
|
|
type(e).__name__, event["command"],))
|
2016-07-23 08:13:33 +02:00
|
|
|
logging.exception("Outhook trigger failed:\n %s" % (e,))
|
|
|
|
fail_with_message(event, response_message)
|
2017-08-29 15:21:25 +02:00
|
|
|
notify_bot_owner(event, request_data, exception=e)
|