validhtmlfix

This commit is contained in:
Untone 2025-04-26 17:02:55 +03:00
parent 0939e91700
commit 4cd8883d72

View File

@ -314,6 +314,41 @@ async def delete_draft(_, info, draft_id: int):
return {"draft": draft} return {"draft": draft}
def validate_html_content(html_content: str) -> tuple[bool, str]:
"""
Проверяет валидность HTML контента через trafilatura.
Args:
html_content: HTML строка для проверки
Returns:
tuple[bool, str]: (валидность, сообщение об ошибке)
Example:
>>> is_valid, error = validate_html_content("<p>Valid HTML</p>")
>>> is_valid
True
>>> error
''
>>> is_valid, error = validate_html_content("Invalid < HTML")
>>> is_valid
False
>>> 'Invalid HTML' in error
True
"""
if not html_content or not html_content.strip():
return False, "Content is empty"
try:
extracted = trafilatura.extract(html_content)
if not extracted:
return False, "Invalid HTML structure or empty content"
return True, ""
except Exception as e:
logger.error(f"HTML validation error: {e}", exc_info=True)
return False, f"Invalid HTML content: {str(e)}"
@mutation.field("publish_draft") @mutation.field("publish_draft")
@login_required @login_required
async def publish_draft(_, info, draft_id: int): async def publish_draft(_, info, draft_id: int):
@ -343,9 +378,10 @@ async def publish_draft(_, info, draft_id: int):
if not draft: if not draft:
return {"error": "Draft not found"} return {"error": "Draft not found"}
# Проверка на пустой body # Проверка валидности HTML в body
if not draft.body or not draft.body.strip(): is_valid, error = validate_html_content(draft.body)
return {"error": "Draft body is empty, cannot publish."} if not is_valid:
return {"error": f"Cannot publish draft: {error}"}
# Ищем существующий shout для этого черновика # Ищем существующий shout для этого черновика
shout = session.query(Shout).filter(Shout.draft == draft_id).first() shout = session.query(Shout).filter(Shout.draft == draft_id).first()