2020-04-09 19:33:49 +02:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
"""Create or update a webhook integration screenshot using a test fixture."""
|
|
|
|
|
|
|
|
# check for the venv
|
|
|
|
from lib import sanity_check
|
|
|
|
|
|
|
|
sanity_check.check_venv(__file__)
|
|
|
|
|
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
|
|
|
|
TOOLS_DIR = os.path.abspath(os.path.dirname(__file__))
|
|
|
|
ROOT_DIR = os.path.dirname(TOOLS_DIR)
|
|
|
|
|
|
|
|
sys.path.insert(0, ROOT_DIR)
|
|
|
|
from scripts.lib.setup_path import setup_path
|
|
|
|
|
|
|
|
setup_path()
|
|
|
|
|
|
|
|
os.environ["DJANGO_SETTINGS_MODULE"] = "zproject.settings"
|
|
|
|
import django
|
|
|
|
|
|
|
|
django.setup()
|
|
|
|
|
|
|
|
import argparse
|
2020-04-10 19:49:18 +02:00
|
|
|
import subprocess
|
2020-04-17 11:27:53 +02:00
|
|
|
from typing import Any, Dict, Optional
|
2020-04-09 19:33:49 +02:00
|
|
|
|
|
|
|
import requests
|
|
|
|
import ujson
|
|
|
|
|
2020-04-24 11:30:24 +02:00
|
|
|
from tools.lib.test_script import prepare_puppeteer_run
|
2020-04-10 19:49:18 +02:00
|
|
|
from zerver.models import UserProfile, Message, get_user_by_delivery_email, get_realm
|
2020-04-24 11:30:24 +02:00
|
|
|
from zerver.lib.actions import (
|
|
|
|
do_create_user, notify_created_bot, bulk_add_subscriptions, do_change_avatar_fields)
|
|
|
|
from zerver.lib.streams import create_stream_if_needed
|
2020-04-09 19:33:49 +02:00
|
|
|
from zerver.lib.upload import upload_avatar_image
|
|
|
|
from zerver.lib.integrations import WebhookIntegration, INTEGRATIONS, split_fixture_path
|
|
|
|
from zerver.lib.webhooks.common import get_fixture_http_headers
|
2020-04-21 16:01:41 +02:00
|
|
|
from zerver.lib.storage import static_path
|
2020-04-09 19:33:49 +02:00
|
|
|
|
2020-04-17 10:14:13 +02:00
|
|
|
def create_integration_bot(integration: WebhookIntegration) -> UserProfile:
|
2020-04-09 19:33:49 +02:00
|
|
|
realm = get_realm('zulip')
|
|
|
|
owner = get_user_by_delivery_email("iago@zulip.com", realm)
|
2020-04-17 10:14:13 +02:00
|
|
|
bot_email = "{}-bot@example.com".format(integration.name)
|
|
|
|
bot_name = "{} Bot".format(integration.name.capitalize())
|
2020-04-09 19:33:49 +02:00
|
|
|
try:
|
|
|
|
bot = UserProfile.objects.get(email=bot_email)
|
|
|
|
except UserProfile.DoesNotExist:
|
|
|
|
bot = do_create_user(
|
|
|
|
email=bot_email,
|
|
|
|
password="123",
|
|
|
|
realm=owner.realm,
|
|
|
|
full_name=bot_name,
|
|
|
|
short_name=bot_name,
|
|
|
|
bot_type=UserProfile.INCOMING_WEBHOOK_BOT,
|
|
|
|
bot_owner=owner,
|
|
|
|
)
|
|
|
|
notify_created_bot(bot)
|
|
|
|
|
2020-04-21 16:01:41 +02:00
|
|
|
bot_avatar_path = static_path(integration.DEFAULT_BOT_AVATAR_PATH.format(name=integration.name))
|
|
|
|
if os.path.isfile(bot_avatar_path):
|
|
|
|
with open(bot_avatar_path, "rb") as f:
|
|
|
|
upload_avatar_image(f, owner, bot)
|
|
|
|
do_change_avatar_fields(bot, UserProfile.AVATAR_FROM_USER)
|
2020-04-09 19:33:49 +02:00
|
|
|
|
|
|
|
return bot
|
|
|
|
|
2020-04-24 11:30:24 +02:00
|
|
|
def create_integration_stream(integration: WebhookIntegration, bot: UserProfile) -> None:
|
|
|
|
assert isinstance(bot.bot_owner, UserProfile)
|
|
|
|
stream, created = create_stream_if_needed(bot.bot_owner.realm, integration.stream_name)
|
|
|
|
bulk_add_subscriptions([stream], [bot, bot.bot_owner], from_stream_creation=created)
|
|
|
|
|
2020-04-09 19:33:49 +02:00
|
|
|
def get_integration(integration_name: str) -> WebhookIntegration:
|
|
|
|
integration = INTEGRATIONS[integration_name]
|
|
|
|
assert isinstance(integration, WebhookIntegration), "Not a WebhookIntegration"
|
|
|
|
return integration
|
|
|
|
|
|
|
|
def get_requests_headers(integration_name: str, fixture_name: str) -> Dict[str, Any]:
|
|
|
|
headers = get_fixture_http_headers(integration_name, fixture_name)
|
|
|
|
|
|
|
|
def fix_name(header: str) -> str:
|
|
|
|
header = header if not header.startswith('HTTP_') else header[len('HTTP_'):]
|
|
|
|
return header.replace('_', '-')
|
|
|
|
|
|
|
|
return {fix_name(k): v for k, v in headers.items()}
|
|
|
|
|
|
|
|
def webhook_json_fixture(path: str) -> str:
|
|
|
|
path = os.path.abspath(path)
|
|
|
|
if not (os.path.exists(path) and path.endswith('.json') and 'webhooks' in path):
|
2020-04-17 11:19:54 +02:00
|
|
|
raise argparse.ArgumentTypeError('Not a valid webhook JSON fixture')
|
2020-04-09 19:33:49 +02:00
|
|
|
return path
|
|
|
|
|
2020-04-17 11:27:53 +02:00
|
|
|
def custom_headers(headers_json: str) -> Dict[str, str]:
|
|
|
|
if not headers_json:
|
|
|
|
return {}
|
|
|
|
try:
|
|
|
|
return ujson.loads(headers_json)
|
|
|
|
except ValueError as ve:
|
|
|
|
raise argparse.ArgumentTypeError(
|
|
|
|
'Encountered an error while attempting to parse custom headers: {}\n'
|
|
|
|
'Note: all strings must be enclosed within "" instead of \'\''.format(ve))
|
|
|
|
|
|
|
|
def send_bot_payload_message(bot: UserProfile, integration: WebhookIntegration, fixture_path: str,
|
2020-04-24 12:21:26 +02:00
|
|
|
extra_headers: Optional[Dict[str, str]]) -> bool:
|
2020-04-17 10:14:13 +02:00
|
|
|
# Delete all messages, so new message is the only one it's message group
|
|
|
|
Message.objects.filter(sender=bot).delete()
|
|
|
|
|
|
|
|
assert isinstance(bot.bot_owner, UserProfile)
|
2020-04-24 11:30:24 +02:00
|
|
|
stream = integration.stream_name or 'devel'
|
|
|
|
url = "{}/{}?api_key={}&stream={}".format(
|
|
|
|
bot.bot_owner.realm.uri, integration.url, bot.api_key, stream
|
2020-04-17 10:14:13 +02:00
|
|
|
)
|
|
|
|
with open(fixture_path) as f:
|
|
|
|
data = ujson.load(f)
|
|
|
|
_, fixture_name = split_fixture_path(fixture_path)
|
|
|
|
headers = get_requests_headers(integration.name, fixture_name)
|
2020-04-17 11:27:53 +02:00
|
|
|
if extra_headers:
|
|
|
|
headers.update(extra_headers)
|
2020-04-17 10:56:08 +02:00
|
|
|
try:
|
|
|
|
response = requests.post(url, json=data, headers=headers)
|
|
|
|
except requests.exceptions.ConnectionError:
|
|
|
|
print('This tool needs the local dev server to be running. '
|
|
|
|
'Please start it using tools/run-dev.py before running this tool.')
|
|
|
|
sys.exit(1)
|
2020-04-17 10:14:13 +02:00
|
|
|
if response.status_code != 200:
|
|
|
|
print(response.json())
|
|
|
|
print('Failed to trigger webhook')
|
2020-04-24 12:21:26 +02:00
|
|
|
return False
|
|
|
|
else:
|
|
|
|
print('Triggered {} webhook'.format(integration.name))
|
|
|
|
return True
|
2020-04-17 10:14:13 +02:00
|
|
|
|
2020-04-24 14:48:28 +02:00
|
|
|
def capture_last_message_screenshot(bot: UserProfile, image_path: str) -> None:
|
2020-04-17 13:25:05 +02:00
|
|
|
message = Message.objects.filter(sender=bot).last()
|
|
|
|
if message is None:
|
2020-04-24 14:48:28 +02:00
|
|
|
print('No message found for {}'.format(bot.full_name))
|
2020-04-17 13:25:05 +02:00
|
|
|
return
|
|
|
|
message_id = str(message.id)
|
2020-04-17 10:14:13 +02:00
|
|
|
screenshot_script = os.path.join(TOOLS_DIR, 'message-screenshot.js')
|
2020-04-24 14:48:28 +02:00
|
|
|
subprocess.check_call(['node', screenshot_script, message_id, image_path])
|
2020-04-17 10:14:13 +02:00
|
|
|
|
2020-04-09 19:33:49 +02:00
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser.add_argument('fixture', type=webhook_json_fixture, help='Path to the fixture to use')
|
2020-04-17 11:27:53 +02:00
|
|
|
parser.add_argument('-H', '--custom-headers',
|
|
|
|
type=custom_headers,
|
|
|
|
help='Any additional headers to be sent with the request.')
|
2020-04-09 19:33:49 +02:00
|
|
|
options = parser.parse_args()
|
|
|
|
|
2020-04-17 09:31:49 +02:00
|
|
|
prepare_puppeteer_run()
|
2020-04-09 19:33:49 +02:00
|
|
|
integration_name, fixture_name = split_fixture_path(options.fixture)
|
|
|
|
integration = get_integration(integration_name)
|
2020-04-17 10:14:13 +02:00
|
|
|
bot = create_integration_bot(integration)
|
2020-04-24 11:30:24 +02:00
|
|
|
create_integration_stream(integration, bot)
|
2020-04-24 12:21:26 +02:00
|
|
|
message_sent = send_bot_payload_message(bot, integration, options.fixture, options.custom_headers)
|
|
|
|
if message_sent:
|
2020-04-24 14:48:28 +02:00
|
|
|
image_path = static_path('images/integrations/{name}/001.png'.format(name=integration.name))
|
|
|
|
capture_last_message_screenshot(bot, image_path)
|