mirror of
https://github.com/suyiiyii/nonebot-bison.git
synced 2025-06-02 09:26:12 +08:00
update render
This commit is contained in:
parent
a43289f1da
commit
70551e23b8
@ -23,24 +23,33 @@ class Render(metaclass=Singleton):
|
||||
def __init__(self):
|
||||
self.lock = asyncio.Lock()
|
||||
|
||||
async def text_to_pic(self, text: str) -> str:
|
||||
async def render(self, url: str, viewport: dict = None, target: str = None) -> str:
|
||||
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.goto(url)
|
||||
if viewport:
|
||||
await page.setViewport(target)
|
||||
if target:
|
||||
target_ele = await page.querySelector(target)
|
||||
data = await target_ele.screenshot(type='jpeg', encoding='base64')
|
||||
else:
|
||||
data = await page.screenshot(type='jpeg', encoding='base64')
|
||||
await page.close()
|
||||
await browser.close()
|
||||
return data
|
||||
|
||||
async def text_to_pic(self, text: str) -> str:
|
||||
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)
|
||||
data = await self.render('file:///tmp/text-{}.html'.format(hash_text), target='div')
|
||||
os.remove('/tmp/text-{}.html'.format(hash_text))
|
||||
return data
|
||||
|
||||
@ -57,5 +66,4 @@ async def parse_text(text: str):
|
||||
return await r.text_to_pic_cqcode(text)
|
||||
else:
|
||||
return text
|
||||
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user