2023-03-14 01:27:22 +00:00
|
|
|
|
import asyncio
|
2022-10-12 13:39:47 +00:00
|
|
|
|
from typing import Optional
|
2023-03-14 01:27:22 +00:00
|
|
|
|
from urllib.parse import urlencode, urljoin, urlsplit
|
2022-10-12 13:39:47 +00:00
|
|
|
|
from uuid import uuid4
|
|
|
|
|
|
2023-03-14 01:27:22 +00:00
|
|
|
|
from fastapi import FastAPI, HTTPException
|
|
|
|
|
from fastapi.responses import FileResponse, HTMLResponse
|
2022-10-12 13:39:47 +00:00
|
|
|
|
from fastapi.staticfiles import StaticFiles
|
2023-03-14 01:27:22 +00:00
|
|
|
|
from jinja2 import Environment, FileSystemLoader, Template
|
2022-10-22 07:03:59 +00:00
|
|
|
|
from playwright.async_api import ViewportSize
|
2022-07-26 10:07:31 +00:00
|
|
|
|
|
2023-03-14 01:27:22 +00:00
|
|
|
|
from core.application import Application
|
|
|
|
|
from core.base_service import BaseService
|
|
|
|
|
from core.config import config as application_config
|
|
|
|
|
from core.dependence.aiobrowser import AioBrowser
|
|
|
|
|
from core.services.template.cache import HtmlToFileIdCache, TemplatePreviewCache
|
|
|
|
|
from core.services.template.error import QuerySelectorNotFound
|
|
|
|
|
from core.services.template.models import FileType, RenderResult
|
2022-10-12 13:39:47 +00:00
|
|
|
|
from utils.const import PROJECT_ROOT
|
2022-09-08 01:08:37 +00:00
|
|
|
|
from utils.log import logger
|
2022-10-11 06:45:07 +00:00
|
|
|
|
|
2023-03-14 01:27:22 +00:00
|
|
|
|
__all__ = ("TemplateService", "TemplatePreviewer")
|
2022-10-11 06:45:07 +00:00
|
|
|
|
|
2023-03-14 01:27:22 +00:00
|
|
|
|
|
|
|
|
|
class TemplateService(BaseService):
|
2022-10-22 07:03:59 +00:00
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
2023-03-14 01:27:22 +00:00
|
|
|
|
app: Application,
|
2022-10-22 07:03:59 +00:00
|
|
|
|
browser: AioBrowser,
|
|
|
|
|
html_to_file_id_cache: HtmlToFileIdCache,
|
|
|
|
|
preview_cache: TemplatePreviewCache,
|
|
|
|
|
template_dir: str = "resources",
|
|
|
|
|
):
|
2022-07-26 10:07:31 +00:00
|
|
|
|
self._browser = browser
|
2022-10-12 13:39:47 +00:00
|
|
|
|
self.template_dir = PROJECT_ROOT / template_dir
|
|
|
|
|
|
|
|
|
|
self._jinja2_env = Environment(
|
|
|
|
|
loader=FileSystemLoader(template_dir),
|
|
|
|
|
enable_async=True,
|
|
|
|
|
autoescape=True,
|
2023-03-14 01:27:22 +00:00
|
|
|
|
auto_reload=application_config.debug,
|
2022-10-12 13:39:47 +00:00
|
|
|
|
)
|
2023-03-14 01:27:22 +00:00
|
|
|
|
self.using_preview = application_config.debug and application_config.webserver.enable
|
2022-10-12 13:39:47 +00:00
|
|
|
|
|
2023-03-14 01:27:22 +00:00
|
|
|
|
if self.using_preview:
|
|
|
|
|
self.previewer = TemplatePreviewer(self, preview_cache, app.web_app)
|
2022-10-12 13:39:47 +00:00
|
|
|
|
|
2022-10-22 07:03:59 +00:00
|
|
|
|
self.html_to_file_id_cache = html_to_file_id_cache
|
|
|
|
|
|
2022-10-12 13:39:47 +00:00
|
|
|
|
def get_template(self, template_name: str) -> Template:
|
|
|
|
|
return self._jinja2_env.get_template(template_name)
|
|
|
|
|
|
2022-10-22 07:03:59 +00:00
|
|
|
|
async def render_async(self, template_name: str, template_data: dict) -> str:
|
2022-09-08 01:08:37 +00:00
|
|
|
|
"""模板渲染
|
|
|
|
|
:param template_name: 模板文件名
|
|
|
|
|
:param template_data: 模板数据
|
|
|
|
|
"""
|
2023-03-14 01:27:22 +00:00
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
|
start_time = loop.time()
|
2022-10-12 13:39:47 +00:00
|
|
|
|
template = self.get_template(template_name)
|
2022-09-08 01:08:37 +00:00
|
|
|
|
html = await template.render_async(**template_data)
|
2023-03-14 01:27:22 +00:00
|
|
|
|
logger.debug("%s 模板渲染使用了 %s", template_name, str(loop.time() - start_time))
|
2022-09-08 01:08:37 +00:00
|
|
|
|
return html
|
|
|
|
|
|
2022-10-10 11:07:28 +00:00
|
|
|
|
async def render(
|
|
|
|
|
self,
|
|
|
|
|
template_name: str,
|
|
|
|
|
template_data: dict,
|
2022-10-22 07:03:59 +00:00
|
|
|
|
viewport: Optional[ViewportSize] = None,
|
2022-10-10 11:07:28 +00:00
|
|
|
|
full_page: bool = True,
|
|
|
|
|
evaluate: Optional[str] = None,
|
2022-10-22 07:03:59 +00:00
|
|
|
|
query_selector: Optional[str] = None,
|
|
|
|
|
file_type: FileType = FileType.PHOTO,
|
|
|
|
|
ttl: int = 24 * 60 * 60,
|
|
|
|
|
caption: Optional[str] = None,
|
|
|
|
|
parse_mode: Optional[str] = None,
|
|
|
|
|
filename: Optional[str] = None,
|
|
|
|
|
) -> RenderResult:
|
2022-09-08 01:08:37 +00:00
|
|
|
|
"""模板渲染成图片
|
2022-07-26 10:07:31 +00:00
|
|
|
|
:param template_name: 模板文件名
|
|
|
|
|
:param template_data: 模板数据
|
|
|
|
|
:param viewport: 截图大小
|
|
|
|
|
:param full_page: 是否长截图
|
|
|
|
|
:param evaluate: 页面加载后运行的 js
|
2022-10-08 01:53:22 +00:00
|
|
|
|
:param query_selector: 截图选择器
|
2022-10-22 07:03:59 +00:00
|
|
|
|
:param file_type: 缓存的文件类型
|
|
|
|
|
:param ttl: 缓存时间
|
|
|
|
|
:param caption: 图片描述
|
|
|
|
|
:param parse_mode: 图片描述解析模式
|
|
|
|
|
:param filename: 文件名字
|
2022-07-26 10:07:31 +00:00
|
|
|
|
:return:
|
|
|
|
|
"""
|
2023-03-14 01:27:22 +00:00
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
|
start_time = loop.time()
|
2022-10-12 13:39:47 +00:00
|
|
|
|
template = self.get_template(template_name)
|
|
|
|
|
|
2023-03-14 01:27:22 +00:00
|
|
|
|
if self.using_preview:
|
2022-10-12 13:39:47 +00:00
|
|
|
|
preview_url = await self.previewer.get_preview_url(template_name, template_data)
|
2023-03-14 01:27:22 +00:00
|
|
|
|
logger.debug("调试模板 URL: \n%s", preview_url)
|
2022-10-12 13:39:47 +00:00
|
|
|
|
|
2022-07-26 10:07:31 +00:00
|
|
|
|
html = await template.render_async(**template_data)
|
2023-03-14 01:27:22 +00:00
|
|
|
|
logger.debug("%s 模板渲染使用了 %s", template_name, str(loop.time() - start_time))
|
2022-10-12 13:39:47 +00:00
|
|
|
|
|
2022-10-22 07:03:59 +00:00
|
|
|
|
file_id = await self.html_to_file_id_cache.get_data(html, file_type.name)
|
2023-03-14 01:27:22 +00:00
|
|
|
|
if file_id and not application_config.debug:
|
|
|
|
|
logger.debug("%s 命中缓存,返回 file_id[%s]", template_name, file_id)
|
2022-10-22 07:03:59 +00:00
|
|
|
|
return RenderResult(
|
|
|
|
|
html=html,
|
|
|
|
|
photo=file_id,
|
|
|
|
|
file_type=file_type,
|
|
|
|
|
cache=self.html_to_file_id_cache,
|
|
|
|
|
ttl=ttl,
|
|
|
|
|
caption=caption,
|
|
|
|
|
parse_mode=parse_mode,
|
|
|
|
|
filename=filename,
|
|
|
|
|
)
|
|
|
|
|
|
2022-07-26 10:07:31 +00:00
|
|
|
|
browser = await self._browser.get_browser()
|
2023-03-14 01:27:22 +00:00
|
|
|
|
start_time = loop.time()
|
2022-07-26 10:07:31 +00:00
|
|
|
|
page = await browser.new_page(viewport=viewport)
|
2022-10-12 13:39:47 +00:00
|
|
|
|
uri = (PROJECT_ROOT / template.filename).as_uri()
|
|
|
|
|
await page.goto(uri)
|
2022-07-26 10:07:31 +00:00
|
|
|
|
await page.set_content(html, wait_until="networkidle")
|
|
|
|
|
if evaluate:
|
|
|
|
|
await page.evaluate(evaluate)
|
2022-10-08 01:53:22 +00:00
|
|
|
|
clip = None
|
|
|
|
|
if query_selector:
|
|
|
|
|
try:
|
|
|
|
|
card = await page.query_selector(query_selector)
|
2022-10-11 06:45:07 +00:00
|
|
|
|
if not card:
|
2022-10-22 07:03:59 +00:00
|
|
|
|
raise QuerySelectorNotFound
|
2022-10-08 01:53:22 +00:00
|
|
|
|
clip = await card.bounding_box()
|
2022-10-11 06:45:07 +00:00
|
|
|
|
if not clip:
|
2022-10-22 07:03:59 +00:00
|
|
|
|
raise QuerySelectorNotFound
|
|
|
|
|
except QuerySelectorNotFound:
|
2023-03-14 01:27:22 +00:00
|
|
|
|
logger.warning("未找到 %s 元素", query_selector)
|
2022-10-08 01:53:22 +00:00
|
|
|
|
png_data = await page.screenshot(clip=clip, full_page=full_page)
|
2022-07-26 10:07:31 +00:00
|
|
|
|
await page.close()
|
2023-03-14 01:27:22 +00:00
|
|
|
|
logger.debug("%s 图片渲染使用了 %s", template_name, str(loop.time() - start_time))
|
2022-10-22 07:03:59 +00:00
|
|
|
|
return RenderResult(
|
|
|
|
|
html=html,
|
|
|
|
|
photo=png_data,
|
|
|
|
|
file_type=file_type,
|
|
|
|
|
cache=self.html_to_file_id_cache,
|
|
|
|
|
ttl=ttl,
|
|
|
|
|
caption=caption,
|
|
|
|
|
parse_mode=parse_mode,
|
|
|
|
|
filename=filename,
|
|
|
|
|
)
|
2022-10-12 13:39:47 +00:00
|
|
|
|
|
|
|
|
|
|
2023-03-14 01:27:22 +00:00
|
|
|
|
class TemplatePreviewer(BaseService, load=application_config.webserver.enable and application_config.debug):
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
template_service: TemplateService,
|
|
|
|
|
cache: TemplatePreviewCache,
|
|
|
|
|
web_app: FastAPI,
|
|
|
|
|
):
|
|
|
|
|
self.web_app = web_app
|
2022-10-12 13:39:47 +00:00
|
|
|
|
self.template_service = template_service
|
|
|
|
|
self.cache = cache
|
|
|
|
|
self.register_routes()
|
|
|
|
|
|
|
|
|
|
async def get_preview_url(self, template: str, data: dict):
|
|
|
|
|
"""获取预览 URL"""
|
2023-03-14 01:27:22 +00:00
|
|
|
|
components = urlsplit(application_config.webserver.url)
|
2022-10-12 13:39:47 +00:00
|
|
|
|
path = urljoin("/preview/", template)
|
|
|
|
|
query = {}
|
|
|
|
|
|
|
|
|
|
# 如果有数据,暂存在 redis 中
|
|
|
|
|
if data:
|
|
|
|
|
key = str(uuid4())
|
|
|
|
|
await self.cache.set_data(key, data)
|
|
|
|
|
query["key"] = key
|
|
|
|
|
|
2023-03-14 01:27:22 +00:00
|
|
|
|
# noinspection PyProtectedMember
|
2022-10-12 13:39:47 +00:00
|
|
|
|
return components._replace(path=path, query=urlencode(query)).geturl()
|
|
|
|
|
|
|
|
|
|
def register_routes(self):
|
|
|
|
|
"""注册预览用到的路由"""
|
|
|
|
|
|
2023-03-14 01:27:22 +00:00
|
|
|
|
@self.web_app.get("/preview/{path:path}")
|
2022-10-22 07:03:59 +00:00
|
|
|
|
async def preview_template(path: str, key: Optional[str] = None): # pylint: disable=W0612
|
2022-10-12 13:39:47 +00:00
|
|
|
|
# 如果是 /preview/ 开头的静态文件,直接返回内容。比如使用相对链接 ../ 引入的静态资源
|
2023-05-12 01:57:03 +00:00
|
|
|
|
if not path.endswith((".html", ".jinja2")):
|
2022-10-12 13:39:47 +00:00
|
|
|
|
full_path = self.template_service.template_dir / path
|
|
|
|
|
if not full_path.is_file():
|
|
|
|
|
raise HTTPException(status_code=404, detail=f"Template '{path}' not found")
|
|
|
|
|
return FileResponse(full_path)
|
|
|
|
|
|
|
|
|
|
# 取回暂存的渲染数据
|
|
|
|
|
data = await self.cache.get_data(key) if key else {}
|
|
|
|
|
if key and data is None:
|
|
|
|
|
raise HTTPException(status_code=404, detail=f"Template data {key} not found")
|
|
|
|
|
|
|
|
|
|
# 渲染 jinja2 模板
|
|
|
|
|
html = await self.template_service.render_async(path, data)
|
|
|
|
|
# 将本地 URL file:// 修改为 HTTP url,因为浏览器内不允许加载本地文件
|
|
|
|
|
# file:///project_dir/cache/image.jpg => /cache/image.jpg
|
|
|
|
|
html = html.replace(PROJECT_ROOT.as_uri(), "")
|
|
|
|
|
return HTMLResponse(html)
|
|
|
|
|
|
|
|
|
|
# 其他静态资源
|
|
|
|
|
for name in ["cache", "resources"]:
|
2022-10-28 07:11:14 +00:00
|
|
|
|
directory = PROJECT_ROOT / name
|
|
|
|
|
directory.mkdir(exist_ok=True)
|
2023-03-14 01:27:22 +00:00
|
|
|
|
self.web_app.mount(f"/{name}", StaticFiles(directory=PROJECT_ROOT / name), name=name)
|