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 asyncio
import nonebot
from nonebot import logger
import base64
@ -20,27 +21,26 @@ supported_target_type = ('weibo', 'bilibili', 'rss')
class Render(metaclass=Singleton):
def __init__(self):
self.browser = None
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()
self.lock = asyncio.Lock()
async def text_to_pic(self, text: str) -> str:
page = await self.browser.newPage()
hash_text = sha256(text.encode()).hexdigest()[:20]
lines = text.split('\n')
parsed_lines = list(map(lambda x: '<p>{}</p>'.format(escape(x)), lines))
html_text = '<div style="width:17em;padding:1em">{}</div>'.format(''.join(parsed_lines))
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()
async with self.lock:
if plugin_config.hk_reporter_use_local:
browser = await launch(executablePath='/usr/bin/chromium', args=['--no-sandbox'])
else:
browser = await launch(args=['--no-sandbox'])
page = await browser.newPage()
hash_text = sha256(text.encode()).hexdigest()[:20]
lines = text.split('\n')
parsed_lines = list(map(lambda x: '<p>{}</p>'.format(escape(x)), lines))
html_text = '<div style="width:17em;padding:1em">{}</div>'.format(''.join(parsed_lines))
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))
return data