2020-05-30 14:15:47 +02:00
|
|
|
import abc
|
2016-07-23 08:13:33 +02:00
|
|
|
import json
|
|
|
|
import logging
|
2021-04-29 00:28:43 +02:00
|
|
|
from time import perf_counter
|
2020-06-11 00:54:34 +02:00
|
|
|
from typing import Any, AnyStr, Dict, Optional
|
2016-07-23 08:13:33 +02:00
|
|
|
|
2020-06-11 00:54:34 +02:00
|
|
|
import requests
|
2021-05-05 09:22:41 +02:00
|
|
|
from django.conf import settings
|
2021-04-16 00:57:30 +02:00
|
|
|
from django.utils.translation import gettext as _
|
2021-05-07 01:56:31 +02:00
|
|
|
from requests import Response
|
2016-07-23 08:13:33 +02:00
|
|
|
|
2020-06-11 00:54:34 +02:00
|
|
|
from version import ZULIP_VERSION
|
2016-07-23 08:13:33 +02:00
|
|
|
from zerver.lib.actions import check_send_message
|
2021-07-16 22:11:10 +02:00
|
|
|
from zerver.lib.exceptions import JsonableError
|
2019-11-05 20:35:47 +01:00
|
|
|
from zerver.lib.message import MessageDict
|
2021-05-07 01:56:31 +02:00
|
|
|
from zerver.lib.outgoing_http import OutgoingSession
|
2017-10-19 14:52:06 +02:00
|
|
|
from zerver.lib.queue import retry_event
|
2018-11-10 22:50:28 +01:00
|
|
|
from zerver.lib.topic import get_topic_from_message_info
|
2018-10-27 16:37:29 +02:00
|
|
|
from zerver.lib.url_encoding import near_message_url
|
2020-06-11 00:54:34 +02:00
|
|
|
from zerver.models import (
|
|
|
|
GENERIC_INTERFACE,
|
|
|
|
SLACK_INTERFACE,
|
2021-09-17 21:22:23 +02:00
|
|
|
Realm,
|
2020-06-11 00:54:34 +02:00
|
|
|
Service,
|
|
|
|
UserProfile,
|
|
|
|
get_client,
|
|
|
|
get_user_profile_by_id,
|
|
|
|
)
|
2016-07-23 08:13:33 +02:00
|
|
|
|
2019-01-09 15:29:17 +01:00
|
|
|
|
2020-05-30 14:15:47 +02:00
|
|
|
class OutgoingWebhookServiceInterface(metaclass=abc.ABCMeta):
|
2018-10-11 00:24:55 +02:00
|
|
|
def __init__(self, token: str, user_profile: UserProfile, service_name: str) -> None:
|
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
|
|
|
self.token: str = token
|
|
|
|
self.user_profile: UserProfile = user_profile
|
|
|
|
self.service_name: str = service_name
|
2021-05-07 01:56:31 +02:00
|
|
|
self.session: requests.Session = OutgoingSession(
|
2021-05-07 01:57:30 +02:00
|
|
|
role="webhook",
|
2021-05-07 01:56:31 +02:00
|
|
|
timeout=10,
|
2021-05-07 01:57:46 +02:00
|
|
|
headers={"User-Agent": "ZulipOutgoingWebhook/" + ZULIP_VERSION},
|
2021-03-27 05:36:31 +01:00
|
|
|
)
|
2017-05-25 19:16:40 +02:00
|
|
|
|
2020-05-30 14:15:47 +02:00
|
|
|
@abc.abstractmethod
|
2021-09-17 21:22:23 +02:00
|
|
|
def make_request(
|
|
|
|
self, base_url: str, event: Dict[str, Any], realm: Realm
|
|
|
|
) -> Optional[Response]:
|
2020-05-30 14:15:47 +02:00
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
@abc.abstractmethod
|
|
|
|
def process_success(self, response_json: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
|
|
raise NotImplementedError
|
|
|
|
|
2017-07-24 07:51:18 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
class GenericOutgoingWebhookService(OutgoingWebhookServiceInterface):
|
2021-09-17 21:22:23 +02:00
|
|
|
def make_request(
|
|
|
|
self, base_url: str, event: Dict[str, Any], realm: Realm
|
|
|
|
) -> Optional[Response]:
|
2021-02-12 08:19:30 +01:00
|
|
|
"""
|
2020-03-27 21:50:56 +01:00
|
|
|
We send a simple version of the message to outgoing
|
|
|
|
webhooks, since most of them really only need
|
|
|
|
`content` and a few other fields. We may eventually
|
|
|
|
allow certain bots to get more information, but
|
|
|
|
that's not a high priority. We do send the gravatar
|
|
|
|
info to the clients (so they don't have to compute
|
|
|
|
it themselves).
|
2021-02-12 08:19:30 +01:00
|
|
|
"""
|
2020-03-26 23:16:23 +01:00
|
|
|
message_dict = MessageDict.finalize_payload(
|
2021-02-12 08:20:45 +01:00
|
|
|
event["message"],
|
2020-03-27 21:50:56 +01:00
|
|
|
apply_markdown=False,
|
|
|
|
client_gravatar=False,
|
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
|
|
|
keep_rendered_content=True,
|
2020-03-27 21:50:56 +01:00
|
|
|
)
|
2019-11-05 20:35:47 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
request_data = {
|
2021-02-12 08:20:45 +01:00
|
|
|
"data": event["command"],
|
2021-02-12 08:19:30 +01:00
|
|
|
"message": message_dict,
|
|
|
|
"bot_email": self.user_profile.email,
|
2021-04-06 21:24:57 +02:00
|
|
|
"bot_full_name": self.user_profile.full_name,
|
2021-02-12 08:19:30 +01:00
|
|
|
"token": self.token,
|
2021-02-12 08:20:45 +01:00
|
|
|
"trigger": event["trigger"],
|
2021-02-12 08:19:30 +01:00
|
|
|
}
|
2017-07-24 07:51:18 +02:00
|
|
|
|
2021-03-27 04:59:47 +01:00
|
|
|
return self.session.post(base_url, json=request_data)
|
2018-10-11 14:11:52 +02:00
|
|
|
|
2020-03-27 22:55:51 +01:00
|
|
|
def process_success(self, response_json: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
2021-02-12 08:20:45 +01: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.
|
2021-02-12 08:20:45 +01:00
|
|
|
content = str(response_json["response_string"])
|
2018-10-10 01:36:31 +02:00
|
|
|
success_data = dict(content=content)
|
2018-10-09 21:16:36 +02:00
|
|
|
return success_data
|
|
|
|
|
|
|
|
if "content" in response_json:
|
2021-02-12 08:20:45 +01:00
|
|
|
content = str(response_json["content"])
|
2018-10-09 21:16:36 +02:00
|
|
|
success_data = dict(content=content)
|
2021-02-12 08:20:45 +01:00
|
|
|
if "widget_content" in response_json:
|
|
|
|
success_data["widget_content"] = response_json["widget_content"]
|
2018-10-09 17:12:57 +02:00
|
|
|
return success_data
|
|
|
|
|
|
|
|
return None
|
2017-07-24 07:51:18 +02:00
|
|
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
class SlackOutgoingWebhookService(OutgoingWebhookServiceInterface):
|
2021-09-17 21:22:23 +02:00
|
|
|
def make_request(
|
|
|
|
self, base_url: str, event: Dict[str, Any], realm: Realm
|
|
|
|
) -> Optional[Response]:
|
2021-02-12 08:20:45 +01: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
|
|
|
|
2021-09-17 21:22:23 +02:00
|
|
|
# https://api.slack.com/legacy/custom-integrations/outgoing-webhooks#legacy-info__post-data
|
|
|
|
# documents the Slack outgoing webhook format:
|
|
|
|
#
|
|
|
|
# token=XXXXXXXXXXXXXXXXXX
|
|
|
|
# team_id=T0001
|
|
|
|
# team_domain=example
|
|
|
|
# channel_id=C2147483705
|
|
|
|
# channel_name=test
|
|
|
|
# thread_ts=1504640714.003543
|
|
|
|
# timestamp=1504640775.000005
|
|
|
|
# user_id=U2147483697
|
|
|
|
# user_name=Steve
|
|
|
|
# text=googlebot: What is the air-speed velocity of an unladen swallow?
|
|
|
|
# trigger_word=googlebot:
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
request_data = [
|
|
|
|
("token", self.token),
|
2021-09-17 21:22:23 +02:00
|
|
|
("team_id", f"T{realm.id}"),
|
|
|
|
("team_domain", realm.host),
|
|
|
|
("channel_id", f"C{event['message']['stream_id']}"),
|
2021-02-12 08:20:45 +01:00
|
|
|
("channel_name", event["message"]["display_recipient"]),
|
2021-09-17 21:22:23 +02:00
|
|
|
("thread_ts", event["message"]["timestamp"]),
|
2021-02-12 08:20:45 +01:00
|
|
|
("timestamp", event["message"]["timestamp"]),
|
2021-09-17 21:22:23 +02:00
|
|
|
("user_id", f"U{event['message']['sender_id']}"),
|
2021-02-12 08:20:45 +01:00
|
|
|
("user_name", event["message"]["sender_full_name"]),
|
|
|
|
("text", event["command"]),
|
|
|
|
("trigger_word", event["trigger"]),
|
|
|
|
("service_id", event["user_profile_id"]),
|
2021-02-12 08:19:30 +01:00
|
|
|
]
|
2021-03-27 04:59:27 +01:00
|
|
|
return self.session.post(base_url, data=request_data)
|
2018-10-11 14:11:52 +02:00
|
|
|
|
2020-03-27 22:55:51 +01:00
|
|
|
def process_success(self, response_json: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
2017-07-24 07:51:18 +02:00
|
|
|
if "text" in response_json:
|
2021-02-12 08:20:45 +01: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
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
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
|
|
|
AVAILABLE_OUTGOING_WEBHOOK_INTERFACES: Dict[str, Any] = {
|
2017-07-24 07:51:18 +02:00
|
|
|
GENERIC_INTERFACE: GenericOutgoingWebhookService,
|
|
|
|
SLACK_INTERFACE: SlackOutgoingWebhookService,
|
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
|
|
|
}
|
2017-07-24 07:51:18 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2018-05-11 01:40:23 +02:00
|
|
|
def get_service_interface_class(interface: str) -> Any:
|
2020-07-05 02:32:47 +02:00
|
|
|
if interface not in AVAILABLE_OUTGOING_WEBHOOK_INTERFACES:
|
2017-07-24 07:51:18 +02:00
|
|
|
return AVAILABLE_OUTGOING_WEBHOOK_INTERFACES[GENERIC_INTERFACE]
|
|
|
|
else:
|
|
|
|
return AVAILABLE_OUTGOING_WEBHOOK_INTERFACES[interface]
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
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())
|
2021-02-12 08:19:30 +01:00
|
|
|
service_interface = service_interface_class(
|
|
|
|
token=service.token, user_profile=service.user_profile, service_name=service.name
|
|
|
|
)
|
2017-07-24 07:51:18 +02:00
|
|
|
return service_interface
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def send_response_message(
|
|
|
|
bot_id: int, message_info: Dict[str, Any], response_data: Dict[str, Any]
|
|
|
|
) -> None:
|
2018-10-09 19:32:43 +02:00
|
|
|
"""
|
|
|
|
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
|
2018-11-10 22:50:28 +01:00
|
|
|
topic - see get_topic_from_message_info
|
2018-10-09 19:32:43 +02:00
|
|
|
|
|
|
|
response_data is what the bot wants to send back and has these fields:
|
2020-08-11 01:47:49 +02:00
|
|
|
content - raw Markdown content for Zulip to render
|
2021-04-02 21:54:34 +02:00
|
|
|
|
|
|
|
WARNING: This function sends messages bypassing the stream access check
|
|
|
|
for the bot - so use with caution to not call this in codepaths
|
|
|
|
that might let someone send arbitrary messages to any stream through this.
|
2018-10-09 19:32:43 +02:00
|
|
|
"""
|
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
message_type = message_info["type"]
|
|
|
|
display_recipient = message_info["display_recipient"]
|
2018-11-10 22:50:28 +01:00
|
|
|
try:
|
2020-07-05 02:32:47 +02:00
|
|
|
topic_name: Optional[str] = get_topic_from_message_info(message_info)
|
2018-11-10 22:50:28 +01:00
|
|
|
except KeyError:
|
|
|
|
topic_name = None
|
2018-10-09 19:32:43 +02:00
|
|
|
|
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
|
2021-02-12 08:20:45 +01:00
|
|
|
client = get_client("OutgoingWebhookResponse")
|
2016-07-23 08:13:33 +02:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
content = response_data.get("content")
|
2020-06-09 07:58:12 +02:00
|
|
|
assert content
|
2018-10-09 19:32:43 +02:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
widget_content = response_data.get("widget_content")
|
2018-10-26 18:08:08 +02:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
if message_type == "stream":
|
2018-10-09 19:32:43 +02:00
|
|
|
message_to = [display_recipient]
|
2021-02-12 08:20:45 +01:00
|
|
|
elif message_type == "private":
|
|
|
|
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-26 18:08:08 +02:00
|
|
|
widget_content=widget_content,
|
2018-10-09 13:45:39 +02:00
|
|
|
realm=realm,
|
2021-04-02 21:54:34 +02:00
|
|
|
skip_stream_access_check=True,
|
2018-10-09 13:45:39 +02:00
|
|
|
)
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2018-05-11 01:40:23 +02:00
|
|
|
def fail_with_message(event: Dict[str, Any], failure_message: str) -> None:
|
2021-02-12 08:20:45 +01:00
|
|
|
bot_id = event["user_profile_id"]
|
|
|
|
message_info = event["message"]
|
2018-10-09 19:32:43 +02:00
|
|
|
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
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2018-10-27 17:40:07 +02:00
|
|
|
def get_message_url(event: Dict[str, Any]) -> str:
|
2021-02-12 08:20:45 +01:00
|
|
|
bot_user = get_user_profile_by_id(event["user_profile_id"])
|
|
|
|
message = event["message"]
|
2018-10-27 16:37:29 +02:00
|
|
|
realm = bot_user.realm
|
|
|
|
|
|
|
|
return near_message_url(
|
|
|
|
realm=realm,
|
|
|
|
message=message,
|
|
|
|
)
|
2017-08-29 15:21:25 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def notify_bot_owner(
|
|
|
|
event: Dict[str, Any],
|
|
|
|
status_code: Optional[int] = None,
|
|
|
|
response_content: Optional[AnyStr] = None,
|
|
|
|
failure_message: Optional[str] = None,
|
|
|
|
exception: Optional[Exception] = None,
|
|
|
|
) -> None:
|
2018-10-27 17:40:07 +02:00
|
|
|
message_url = get_message_url(event)
|
2021-02-12 08:20:45 +01:00
|
|
|
bot_id = event["user_profile_id"]
|
2021-03-15 08:03:07 +01:00
|
|
|
bot = get_user_profile_by_id(bot_id)
|
|
|
|
bot_owner = bot.bot_owner
|
2020-07-05 02:32:47 +02:00
|
|
|
assert bot_owner is not None
|
2018-10-09 19:32:43 +02:00
|
|
|
|
2021-03-15 08:03:07 +01:00
|
|
|
notification_message = f"[A message]({message_url}) to your bot @_**{bot.full_name}** triggered an outgoing webhook."
|
2021-03-18 22:41:27 +01:00
|
|
|
if exception:
|
|
|
|
notification_message += (
|
|
|
|
"\nWhen trying to send a request to the webhook service, an exception "
|
|
|
|
f"of type {type(exception).__name__} occurred:\n```\n{exception}\n```"
|
|
|
|
)
|
|
|
|
elif failure_message:
|
2018-10-10 19:52:32 +02:00
|
|
|
notification_message += "\n" + failure_message
|
2021-03-18 22:41:27 +01:00
|
|
|
elif status_code == 407:
|
2021-03-16 07:54:33 +01:00
|
|
|
notification_message += (
|
|
|
|
"\nThe URL configured for the webhook is for a private or disallowed network."
|
|
|
|
)
|
|
|
|
elif status_code:
|
2020-06-10 06:41:04 +02:00
|
|
|
notification_message += f"\nThe webhook got a response with status code *{status_code}*."
|
2021-05-11 22:53:58 +02:00
|
|
|
|
|
|
|
if response_content:
|
|
|
|
notification_message += (
|
|
|
|
f"\nThe response contains the following payload:\n```\n{response_content!r}\n```"
|
|
|
|
)
|
2018-10-09 19:32:43 +02:00
|
|
|
|
|
|
|
message_info = dict(
|
2021-02-12 08:20:45 +01:00
|
|
|
type="private",
|
2018-10-09 19:32:43 +02:00
|
|
|
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
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def request_retry(event: Dict[str, Any], 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.
|
|
|
|
"""
|
2021-02-12 08:20:45 +01: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")
|
2020-05-31 08:29:30 +02:00
|
|
|
notify_bot_owner(event, failure_message=failure_message)
|
2020-05-02 08:44:14 +02:00
|
|
|
logging.warning(
|
|
|
|
"Maximum retries exceeded for trigger:%s event:%s",
|
2021-02-12 08:19:30 +01:00
|
|
|
bot_user.email,
|
2021-02-12 08:20:45 +01:00
|
|
|
event["command"],
|
2020-05-02 08:44:14 +02:00
|
|
|
)
|
2017-08-18 07:56:53 +02:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
retry_event("outgoing_webhooks", event, failure_processor)
|
2016-07-23 08:13:33 +02:00
|
|
|
|
2021-02-12 08:19:30 +01: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)
|
2020-08-12 20:23:23 +02:00
|
|
|
except json.JSONDecodeError:
|
2021-04-25 21:23:52 +02:00
|
|
|
raise JsonableError(_("Invalid JSON in response"))
|
2018-10-10 15:11:50 +02:00
|
|
|
|
2021-05-13 15:09:58 +02:00
|
|
|
if response_json == "":
|
|
|
|
# Versions of zulip_botserver before 2021-05 used
|
|
|
|
# json.dumps("") as their "no response required" success
|
|
|
|
# response; handle that for backwards-compatibility.
|
|
|
|
return
|
|
|
|
|
2021-04-25 20:54:32 +02:00
|
|
|
if not isinstance(response_json, dict):
|
|
|
|
raise JsonableError(_("Invalid response format"))
|
|
|
|
|
2020-03-27 22:55:51 +01:00
|
|
|
success_data = service_handler.process_success(response_json)
|
2018-10-09 16:12:32 +02:00
|
|
|
|
|
|
|
if success_data is None:
|
|
|
|
return
|
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
content = success_data.get("content")
|
2018-10-09 16:12:32 +02:00
|
|
|
|
2020-06-09 07:58:12 +02:00
|
|
|
if content is None or content.strip() == "":
|
2018-10-09 21:16:36 +02:00
|
|
|
return
|
2018-10-09 19:32:43 +02:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
widget_content = success_data.get("widget_content")
|
|
|
|
bot_id = event["user_profile_id"]
|
|
|
|
message_info = event["message"]
|
2018-10-26 18:08:08 +02:00
|
|
|
response_data = dict(content=content, widget_content=widget_content)
|
2018-10-09 19:32:43 +02:00
|
|
|
send_response_message(bot_id=bot_id, message_info=message_info, response_data=response_data)
|
2018-05-01 12:36:49 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def do_rest_call(
|
2021-03-27 04:54:31 +01:00
|
|
|
base_url: str,
|
|
|
|
event: Dict[str, Any],
|
|
|
|
service_handler: OutgoingWebhookServiceInterface,
|
2021-02-12 08:19:30 +01:00
|
|
|
) -> Optional[Response]:
|
2020-10-29 20:21:18 +01:00
|
|
|
"""Returns response of call if no exception occurs."""
|
2016-07-23 08:13:33 +02:00
|
|
|
try:
|
2021-04-29 00:28:43 +02:00
|
|
|
start_time = perf_counter()
|
2021-09-17 21:22:23 +02:00
|
|
|
bot_profile = service_handler.user_profile
|
2021-03-27 03:11:40 +01:00
|
|
|
response = service_handler.make_request(
|
|
|
|
base_url,
|
|
|
|
event,
|
2021-09-17 21:22:23 +02:00
|
|
|
bot_profile.realm,
|
2018-10-11 14:11:52 +02:00
|
|
|
)
|
2021-04-29 00:28:43 +02:00
|
|
|
logging.info(
|
|
|
|
"Outgoing webhook request from %s@%s took %f seconds",
|
|
|
|
bot_profile.id,
|
|
|
|
bot_profile.realm.string_id,
|
|
|
|
perf_counter() - start_time,
|
|
|
|
)
|
2021-05-07 03:00:26 +02:00
|
|
|
if response is None:
|
2021-03-27 03:11:40 +01:00
|
|
|
return None
|
2021-02-12 08:20:45 +01:00
|
|
|
if str(response.status_code).startswith("2"):
|
2021-03-22 05:18:35 +01:00
|
|
|
try:
|
|
|
|
process_success_response(event, service_handler, response)
|
|
|
|
except JsonableError as e:
|
|
|
|
response_message = e.msg
|
|
|
|
logging.info("Outhook trigger failed:", stack_info=True)
|
|
|
|
fail_with_message(event, response_message)
|
|
|
|
response_message = f"The outgoing webhook server attempted to send a message in Zulip, but that request resulted in the following error:\n> {e}"
|
2021-05-11 22:53:58 +02:00
|
|
|
notify_bot_owner(
|
|
|
|
event, response_content=response.text, failure_message=response_message
|
|
|
|
)
|
2021-03-22 05:18:35 +01:00
|
|
|
return None
|
2016-07-23 08:13:33 +02:00
|
|
|
else:
|
2021-02-12 08:19:30 +01:00
|
|
|
logging.warning(
|
|
|
|
"Message %(message_url)s triggered an outgoing webhook, returning status "
|
2021-02-12 08:20:45 +01:00
|
|
|
'code %(status_code)s.\n Content of response (in quotes): "'
|
|
|
|
'%(response)s"',
|
2021-02-12 08:19:30 +01:00
|
|
|
{
|
2021-02-12 08:20:45 +01:00
|
|
|
"message_url": get_message_url(event),
|
|
|
|
"status_code": response.status_code,
|
|
|
|
"response": response.text,
|
2021-02-12 08:19:30 +01:00
|
|
|
},
|
|
|
|
)
|
2020-06-13 08:59:37 +02:00
|
|
|
failure_message = f"Third party responded with {response.status_code}"
|
2017-09-25 16:49:28 +02:00
|
|
|
fail_with_message(event, failure_message)
|
2020-05-31 08:29:30 +02:00
|
|
|
notify_bot_owner(event, response.status_code, response.content)
|
2020-10-29 20:21:18 +01:00
|
|
|
return response
|
2018-10-10 19:52:32 +02:00
|
|
|
except requests.exceptions.Timeout:
|
2020-05-02 08:44:14 +02:00
|
|
|
logging.info(
|
|
|
|
"Trigger event %s on %s timed out. Retrying",
|
2021-02-12 08:19:30 +01:00
|
|
|
event["command"],
|
2021-02-12 08:20:45 +01:00
|
|
|
event["service_name"],
|
2020-05-02 08:44:14 +02:00
|
|
|
)
|
2021-05-05 09:22:41 +02:00
|
|
|
failure_message = (
|
|
|
|
f"Request timed out after {settings.OUTGOING_WEBHOOK_TIMEOUT_SECONDS} seconds."
|
|
|
|
)
|
2020-05-31 08:29:30 +02:00
|
|
|
request_retry(event, failure_message=failure_message)
|
2020-10-29 20:21:18 +01:00
|
|
|
return None
|
2017-08-16 13:30:47 +02:00
|
|
|
|
2018-10-10 19:52:32 +02:00
|
|
|
except requests.exceptions.ConnectionError:
|
2021-02-12 08:19:30 +01:00
|
|
|
logging.info(
|
|
|
|
"Trigger event %s on %s resulted in a connection error. Retrying",
|
|
|
|
event["command"],
|
2021-02-12 08:20:45 +01:00
|
|
|
event["service_name"],
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
2018-10-10 19:52:32 +02:00
|
|
|
failure_message = "A connection error occurred. Is my bot server down?"
|
2020-05-31 08:29:30 +02:00
|
|
|
request_retry(event, failure_message=failure_message)
|
2020-10-29 20:21:18 +01:00
|
|
|
return None
|
2016-07-23 08:13:33 +02:00
|
|
|
|
|
|
|
except requests.exceptions.RequestException as e:
|
2020-06-14 02:57:50 +02:00
|
|
|
response_message = (
|
|
|
|
f"An exception of type *{type(e).__name__}* occurred for message `{event['command']}`! "
|
|
|
|
"See the Zulip server logs for more information."
|
|
|
|
)
|
2020-08-11 03:19:00 +02:00
|
|
|
logging.exception("Outhook trigger failed:", stack_info=True)
|
2016-07-23 08:13:33 +02:00
|
|
|
fail_with_message(event, response_message)
|
2020-05-31 08:29:30 +02:00
|
|
|
notify_bot_owner(event, exception=e)
|
2020-10-29 20:21:18 +01:00
|
|
|
return None
|