tools: Capture incoming bot message screenshot using puppeteer.

This commit is contained in:
Puneeth Chaganti 2020-04-10 23:19:18 +05:30 committed by Tim Abbott
parent 4d2ce607c9
commit 464cbcd9c1
2 changed files with 81 additions and 4 deletions

View File

@ -23,12 +23,13 @@ import django
django.setup()
import argparse
import subprocess
from typing import Any, Dict
import requests
import ujson
from zerver.models import UserProfile, get_user_by_delivery_email, get_realm
from zerver.models import UserProfile, Message, get_user_by_delivery_email, get_realm
from zerver.lib.actions import do_create_user, notify_created_bot
from zerver.lib.upload import upload_avatar_image
from zerver.lib.actions import do_change_avatar_fields
@ -96,6 +97,8 @@ integration_name, fixture_name = split_fixture_path(options.fixture)
integration = get_integration(integration_name)
bot = create_integration_bot(integration.name)
assert isinstance(bot.bot_owner, UserProfile)
# Delete all messages, so new message is the only one it's message group
Message.objects.filter(sender=bot).delete()
url = "{}/{}?api_key={}&stream=devel".format(
bot.bot_owner.realm.uri, integration.url, bot.api_key
@ -104,7 +107,12 @@ with open(options.fixture) as f:
data = ujson.load(f)
headers = get_requests_headers(integration_name, fixture_name)
response = requests.post(url, json=data, headers=headers)
if response.status_code == 200:
print('Triggered {} webhook'.format(integration.name))
else:
if response.status_code != 200:
print(response.json())
print('Failed to trigger webhook')
sys.exit(1)
print('Triggered {} webhook'.format(integration.name))
message_id = str(Message.objects.filter(sender=bot).last().id)
screenshot_script = os.path.join(TOOLS_DIR, 'message-screenshot.js')
subprocess.check_call(['node', screenshot_script, integration.name, message_id])

View File

@ -0,0 +1,69 @@
const puppeteer = require("puppeteer");
const commander = require("commander");
const path = require("path");
const host = "localhost:9991";
const options = {};
commander
.arguments('<integration> <message_id>')
.action((integration, messageId) => {
options.integration = integration;
options.messageId = messageId;
console.log(`Capturing screenshot for ${integration} using message ${messageId}`);
})
.parse(process.argv);
if (options.integration === undefined) {
console.error('no integration specified!');
process.exit(1);
}
// TODO: Refactor to share code with frontend_tests/puppeteer_tests/00-realm-creation.js
async function run() {
const browser = await puppeteer.launch({
args: [
'--window-size=1400,1024',
'--no-sandbox', '--disable-setuid-sandbox',
// Helps render fonts correctly on Ubuntu: https://github.com/puppeteer/puppeteer/issues/661
'--font-render-hinting=none',
],
defaultViewport: null,
headless: true,
});
try {
const page = await browser.newPage();
// deviceScaleFactor:2 gives better quality screenshots (higher pixel density)
await page.setViewport({ width: 1280, height: 1024, deviceScaleFactor: 2 });
await page.goto('http://' + host);
// wait for devlogin admin button and click on it
await page.waitForSelector('.btn-admin');
await page.click('.btn-admin');
// Navigate to message and capture screenshot
await page.goto(`http://${host}/#narrow/near/${options.messageId}`);
const messageSelector = `#zfilt${options.messageId}`;
await page.waitForSelector(messageSelector);
// remove unread marker and don't select message
const marker = `#zfilt${options.messageId} .unread_marker`;
await page.evaluate((sel) => $(sel).remove(), marker); // eslint-disable-line no-undef
await page.evaluate(() => navigate.up()); // eslint-disable-line no-undef
const messageBox = await page.$(messageSelector);
const messageGroup = (await messageBox.$x('..'))[0];
// Compute screenshot area, with some padding around the message group
const clip = Object.assign({}, await messageGroup.boundingBox());
clip.y -= 5;
clip.x -= 5;
clip.width += 10;
clip.height += 10;
const imagePath = path.join(__dirname, '..', 'static', 'images', 'integrations', options.integration, '001.png');
await page.screenshot({ path: imagePath, clip: clip });
console.log(`Screenshot captured to: \x1B[1;31m${imagePath}\n`);
} catch (e) {
console.log(e);
process.exit(1);
} finally {
await browser.close();
}
}
run();