From 829d741158efd3b200c8f79033213dee5d9c4ed5 Mon Sep 17 00:00:00 2001 From: felinae98 <731499577@qq.com> Date: Mon, 8 Feb 2021 14:54:04 +0800 Subject: [PATCH] close chromium after screen shot --- src/plugins/hk_reporter/utils.py | 38 ++++++++++++++++---------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/plugins/hk_reporter/utils.py b/src/plugins/hk_reporter/utils.py index edccc64..21e6180 100644 --- a/src/plugins/hk_reporter/utils.py +++ b/src/plugins/hk_reporter/utils.py @@ -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: '

{}

'.format(escape(x)), lines)) - html_text = '
{}
'.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: '

{}

'.format(escape(x)), lines)) + html_text = '
{}
'.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