close chromium after screen shot

This commit is contained in:
felinae98 2021-02-08 14:54:04 +08:00
parent 27dd2482f8
commit 829d741158
No known key found for this signature in database
GPG Key ID: 00C8B010587FF610

View File

@ -1,4 +1,5 @@
import os import os
import asyncio
import nonebot import nonebot
from nonebot import logger from nonebot import logger
import base64 import base64
@ -20,27 +21,26 @@ supported_target_type = ('weibo', 'bilibili', 'rss')
class Render(metaclass=Singleton): class Render(metaclass=Singleton):
def __init__(self): def __init__(self):
self.browser = None self.lock = asyncio.Lock()
async def init(self):
if plugin_config.hk_reporter_use_local:
self.browser = await launch(executablePath='/usr/bin/chromium', args=['--no-sandbox'])
else:
self.browser = await launch(args=['--no-sandbox'])
# self.page = await browser.newPage()
async def text_to_pic(self, text: str) -> str: async def text_to_pic(self, text: str) -> str:
page = await self.browser.newPage() async with self.lock:
hash_text = sha256(text.encode()).hexdigest()[:20] if plugin_config.hk_reporter_use_local:
lines = text.split('\n') browser = await launch(executablePath='/usr/bin/chromium', args=['--no-sandbox'])
parsed_lines = list(map(lambda x: '<p>{}</p>'.format(escape(x)), lines)) else:
html_text = '<div style="width:17em;padding:1em">{}</div>'.format(''.join(parsed_lines)) browser = await launch(args=['--no-sandbox'])
with open('/tmp/text-{}.html'.format(hash_text), 'w') as f: page = await browser.newPage()
f.write(html_text) hash_text = sha256(text.encode()).hexdigest()[:20]
await page.goto('file:///tmp/text-{}.html'.format(hash_text)) lines = text.split('\n')
div = await page.querySelector('div') parsed_lines = list(map(lambda x: '<p>{}</p>'.format(escape(x)), lines))
data = await div.screenshot(type='jpeg', encoding='base64') html_text = '<div style="width:17em;padding:1em">{}</div>'.format(''.join(parsed_lines))
await page.close() with open('/tmp/text-{}.html'.format(hash_text), 'w') as f:
f.write(html_text)
await page.goto('file:///tmp/text-{}.html'.format(hash_text))
div = await page.querySelector('div')
data = await div.screenshot(type='jpeg', encoding='base64')
await page.close()
await browser.close()
os.remove('/tmp/text-{}.html'.format(hash_text)) os.remove('/tmp/text-{}.html'.format(hash_text))
return data return data