1363 lines
50 KiB
Python
1363 lines
50 KiB
Python
|
|
import hashlib
|
||
|
|
import json
|
||
|
|
import logging
|
||
|
|
import re
|
||
|
|
import subprocess
|
||
|
|
import uuid
|
||
|
|
from datetime import datetime
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
import httpx
|
||
|
|
from celery import Celery
|
||
|
|
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont, ImageOps
|
||
|
|
from sqlalchemy import select
|
||
|
|
|
||
|
|
from app.config import get_settings
|
||
|
|
from app.database import SessionLocal, init_db
|
||
|
|
from app.models import Post, PostMedia, Video, VkEvent
|
||
|
|
from app.ok_api import (
|
||
|
|
OkApiError,
|
||
|
|
commit_group_moment,
|
||
|
|
edit_mediatopic,
|
||
|
|
post_group_mediatopic,
|
||
|
|
upload_moment_photo,
|
||
|
|
upload_photo_to_group,
|
||
|
|
upload_video_to_group,
|
||
|
|
)
|
||
|
|
|
||
|
|
logger = logging.getLogger(__name__)
|
||
|
|
settings = get_settings()
|
||
|
|
SCHOOL_APP_URL = "https://ok.ru/app/512004845113"
|
||
|
|
SCHOOL_APP_PHRASE = "мини-приложение Школы Геополитики"
|
||
|
|
REMOVED_HASHTAGS = {"#подкаст"}
|
||
|
|
VK_CLIP_TITLE = "Clip by @nstarikov_club"
|
||
|
|
MOMENT_WIDTH = 1080
|
||
|
|
MOMENT_HEIGHT = 1920
|
||
|
|
|
||
|
|
celery_app = Celery(
|
||
|
|
"vk2ok",
|
||
|
|
broker=settings.celery_broker_url,
|
||
|
|
backend=settings.celery_result_backend,
|
||
|
|
)
|
||
|
|
celery_app.conf.beat_schedule = {
|
||
|
|
"recover-queued-work-every-minute": {
|
||
|
|
"task": "app.worker.recover_queued_work",
|
||
|
|
"schedule": 60.0,
|
||
|
|
},
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
def build_vk_post_url(owner_id: str | int | None, post_id: str | int | None) -> str | None:
|
||
|
|
if owner_id is None or post_id is None:
|
||
|
|
return None
|
||
|
|
return f"https://vk.com/wall{owner_id}_{post_id}"
|
||
|
|
|
||
|
|
|
||
|
|
def extract_video_download_url(video: dict) -> str | None:
|
||
|
|
if video.get("player"):
|
||
|
|
return str(video["player"])
|
||
|
|
owner_id = video.get("owner_id")
|
||
|
|
video_id = video.get("id")
|
||
|
|
access_key = video.get("access_key")
|
||
|
|
if owner_id is None or video_id is None:
|
||
|
|
return None
|
||
|
|
url = f"https://vk.com/video{owner_id}_{video_id}"
|
||
|
|
if access_key:
|
||
|
|
return f"{url}_{access_key}"
|
||
|
|
return url
|
||
|
|
|
||
|
|
|
||
|
|
def extract_video_public_url(video: dict) -> str | None:
|
||
|
|
owner_id = video.get("owner_id")
|
||
|
|
video_id = video.get("id")
|
||
|
|
if owner_id is None or video_id is None:
|
||
|
|
return None
|
||
|
|
return f"https://vk.com/video{owner_id}_{video_id}"
|
||
|
|
|
||
|
|
|
||
|
|
def extract_largest_image_url(items: list[dict]) -> str | None:
|
||
|
|
largest = max(items, key=lambda item: item.get("width", 0) * item.get("height", 0), default={})
|
||
|
|
return largest.get("url")
|
||
|
|
|
||
|
|
|
||
|
|
def extract_video_identity(video: dict) -> str:
|
||
|
|
owner_id = video.get("owner_id")
|
||
|
|
video_id = video.get("id")
|
||
|
|
if owner_id is None or video_id is None:
|
||
|
|
return str(video.get("id") or "")
|
||
|
|
return f"{owner_id}_{video_id}"
|
||
|
|
|
||
|
|
|
||
|
|
def video_identity_candidates(video_id: str | None) -> list[str]:
|
||
|
|
if not video_id:
|
||
|
|
return []
|
||
|
|
candidates = [video_id]
|
||
|
|
short_id = video_id.rsplit("_", 1)[-1]
|
||
|
|
if short_id and short_id != video_id:
|
||
|
|
candidates.append(short_id)
|
||
|
|
return candidates
|
||
|
|
|
||
|
|
|
||
|
|
def create_or_get_video(session, video_data: dict) -> Video:
|
||
|
|
video_url = extract_video_download_url(video_data)
|
||
|
|
vk_video_id = extract_video_identity(video_data)
|
||
|
|
existing_video = None
|
||
|
|
if vk_video_id:
|
||
|
|
existing_video = session.scalar(
|
||
|
|
select(Video)
|
||
|
|
.where(Video.vk_video_id.in_(video_identity_candidates(vk_video_id)))
|
||
|
|
.order_by(Video.ok_video_id.is_(None), Video.id.asc())
|
||
|
|
)
|
||
|
|
if not existing_video and video_url:
|
||
|
|
public_url = extract_video_public_url(video_data)
|
||
|
|
url_candidates = [candidate for candidate in {video_url, public_url} if candidate]
|
||
|
|
existing_video = session.scalar(
|
||
|
|
select(Video)
|
||
|
|
.where(Video.vk_video_url.in_(url_candidates))
|
||
|
|
.order_by(Video.ok_video_id.is_(None), Video.id.asc())
|
||
|
|
)
|
||
|
|
if existing_video:
|
||
|
|
if vk_video_id and existing_video.vk_video_id != vk_video_id:
|
||
|
|
existing_video.vk_video_id = vk_video_id
|
||
|
|
if video_url and not existing_video.vk_video_url:
|
||
|
|
existing_video.vk_video_url = video_url
|
||
|
|
existing_video.title = existing_video.title or video_data.get("title")
|
||
|
|
existing_video.description = existing_video.description or video_data.get("description")
|
||
|
|
return existing_video
|
||
|
|
|
||
|
|
video = Video(
|
||
|
|
vk_video_id=vk_video_id,
|
||
|
|
vk_video_url=video_url or "",
|
||
|
|
title=video_data.get("title"),
|
||
|
|
description=video_data.get("description"),
|
||
|
|
status="pending",
|
||
|
|
)
|
||
|
|
session.add(video)
|
||
|
|
session.flush()
|
||
|
|
return video
|
||
|
|
|
||
|
|
|
||
|
|
def queue_task(task, args: list, queue: str) -> None:
|
||
|
|
task.delay(*args)
|
||
|
|
|
||
|
|
|
||
|
|
def download_file(url: str, target_path: Path) -> None:
|
||
|
|
target_path.parent.mkdir(parents=True, exist_ok=True)
|
||
|
|
with httpx.Client(follow_redirects=True, timeout=120) as client:
|
||
|
|
response = client.get(url)
|
||
|
|
response.raise_for_status()
|
||
|
|
target_path.write_bytes(response.content)
|
||
|
|
|
||
|
|
|
||
|
|
def normalize_vk_link_markup(match: re.Match[str]) -> str:
|
||
|
|
parts = [part.strip() for part in match.group(1).split("|") if part.strip()]
|
||
|
|
if not parts:
|
||
|
|
return ""
|
||
|
|
|
||
|
|
for part in reversed(parts):
|
||
|
|
if part.startswith(("http://", "https://")):
|
||
|
|
return part
|
||
|
|
|
||
|
|
return parts[-1]
|
||
|
|
|
||
|
|
|
||
|
|
def normalize_post_text(text: str) -> str:
|
||
|
|
normalized = re.sub(r"\[([^\[\]\n]+?\|[^\[\]\n]+?)\]", normalize_vk_link_markup, text)
|
||
|
|
normalized = re.sub(r"(?<!\s)(https?://)", r"\n\1", normalized)
|
||
|
|
normalized = re.sub(r"(\#[^\s#]+)(https?://)", r"\1\n\2", normalized)
|
||
|
|
normalized = "\n".join(
|
||
|
|
line for line in normalized.splitlines() if line.strip().lower() not in REMOVED_HASHTAGS
|
||
|
|
)
|
||
|
|
normalized = re.sub(r"[ \t]+\n", "\n", normalized)
|
||
|
|
normalized = re.sub(r"\n{3,}", "\n\n", normalized)
|
||
|
|
return normalized.strip()
|
||
|
|
|
||
|
|
|
||
|
|
def build_post_content_key(text: str, attachments: list[dict]) -> str:
|
||
|
|
video_ids: list[str] = []
|
||
|
|
photo_ids: list[str] = []
|
||
|
|
for attachment in attachments:
|
||
|
|
attachment_type = attachment.get("type")
|
||
|
|
data = attachment.get(attachment_type) or {}
|
||
|
|
if attachment_type == "video":
|
||
|
|
video_id = extract_video_identity(data)
|
||
|
|
if video_id:
|
||
|
|
video_ids.append(video_id.rsplit("_", 1)[-1])
|
||
|
|
elif attachment_type == "photo":
|
||
|
|
owner_id = data.get("owner_id")
|
||
|
|
photo_id = data.get("id")
|
||
|
|
if owner_id is not None and photo_id is not None:
|
||
|
|
photo_ids.append(f"{owner_id}_{photo_id}")
|
||
|
|
|
||
|
|
if video_ids:
|
||
|
|
return "video:" + ",".join(sorted(set(video_ids)))
|
||
|
|
if photo_ids:
|
||
|
|
return "photo:" + ",".join(sorted(set(photo_ids)))
|
||
|
|
|
||
|
|
normalized = re.sub(r"\s+", " ", normalize_post_text(text)).strip().lower()
|
||
|
|
if not normalized:
|
||
|
|
return ""
|
||
|
|
digest = hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:32]
|
||
|
|
return "text:" + digest
|
||
|
|
|
||
|
|
|
||
|
|
def append_video_links(text: str, media_items: list[PostMedia]) -> str:
|
||
|
|
video_urls = [item.source_url for item in media_items if item.media_type == "video" and item.source_url]
|
||
|
|
normalized_text = normalize_post_text(text)
|
||
|
|
if not video_urls:
|
||
|
|
return normalized_text
|
||
|
|
lines = [normalized_text] if normalized_text else []
|
||
|
|
lines.extend(str(url) for url in video_urls)
|
||
|
|
return "\n\n".join(lines)
|
||
|
|
|
||
|
|
|
||
|
|
def build_text_media(text: str) -> dict:
|
||
|
|
normalized_text = text.strip()
|
||
|
|
return {"type": "text", "text": normalized_text}
|
||
|
|
|
||
|
|
|
||
|
|
def build_bold_text_media(text: str) -> dict:
|
||
|
|
normalized_text = text.strip()
|
||
|
|
return {
|
||
|
|
"type": "text",
|
||
|
|
"text": "",
|
||
|
|
"text_tokens": [
|
||
|
|
{"text": normalized_text, "font_styles": ["bold"]},
|
||
|
|
],
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
def split_text_media_blocks(text: str) -> list[dict]:
|
||
|
|
blocks: list[dict] = []
|
||
|
|
buffer: list[str] = []
|
||
|
|
lines = text.splitlines()
|
||
|
|
title_line_index = None
|
||
|
|
for index, line in enumerate(lines[:-1]):
|
||
|
|
stripped = line.strip()
|
||
|
|
if not stripped:
|
||
|
|
continue
|
||
|
|
if lines[index + 1].strip() == "" and not stripped.startswith(("http://", "https://", "#")):
|
||
|
|
title_line_index = index
|
||
|
|
break
|
||
|
|
|
||
|
|
def flush_buffer() -> None:
|
||
|
|
normalized_buffer = "\n".join(buffer).strip()
|
||
|
|
if normalized_buffer:
|
||
|
|
blocks.append(build_text_media(normalized_buffer))
|
||
|
|
buffer.clear()
|
||
|
|
|
||
|
|
for index, line in enumerate(lines):
|
||
|
|
stripped = line.strip()
|
||
|
|
if stripped.lower() in REMOVED_HASHTAGS:
|
||
|
|
continue
|
||
|
|
if index == title_line_index:
|
||
|
|
flush_buffer()
|
||
|
|
blocks.append(build_bold_text_media(stripped))
|
||
|
|
continue
|
||
|
|
if stripped.startswith(("http://", "https://", "#")):
|
||
|
|
flush_buffer()
|
||
|
|
blocks.append(build_text_media(stripped))
|
||
|
|
continue
|
||
|
|
buffer.append(line)
|
||
|
|
|
||
|
|
flush_buffer()
|
||
|
|
return blocks
|
||
|
|
|
||
|
|
|
||
|
|
def build_school_quote_media() -> dict:
|
||
|
|
return {
|
||
|
|
"type": "text",
|
||
|
|
"text": "",
|
||
|
|
"text_tokens": [
|
||
|
|
{"text": "│ Хотите знать больше? Открывайте "},
|
||
|
|
{"text": SCHOOL_APP_PHRASE, "link": SCHOOL_APP_URL},
|
||
|
|
{"text": "!"},
|
||
|
|
],
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
def video_media_items(media_items: list[PostMedia]) -> list[dict]:
|
||
|
|
video_ids = [item.ok_media_id for item in media_items if item.media_type == "video" and item.ok_media_id]
|
||
|
|
if not video_ids:
|
||
|
|
return []
|
||
|
|
return [{"type": "movie", "list": [{"id": video_id} for video_id in video_ids]}]
|
||
|
|
|
||
|
|
|
||
|
|
def video_for_media(session, media: PostMedia) -> Video | None:
|
||
|
|
if media.media_type != "video":
|
||
|
|
return None
|
||
|
|
if media.vk_attachment_id:
|
||
|
|
video = session.scalar(
|
||
|
|
select(Video)
|
||
|
|
.where(Video.vk_video_id.in_(video_identity_candidates(media.vk_attachment_id)))
|
||
|
|
.order_by(Video.ok_video_id.is_(None), Video.id.asc())
|
||
|
|
)
|
||
|
|
if video:
|
||
|
|
return video
|
||
|
|
if media.source_url:
|
||
|
|
return session.scalar(
|
||
|
|
select(Video)
|
||
|
|
.where(Video.vk_video_url == media.source_url)
|
||
|
|
.order_by(Video.ok_video_id.is_(None), Video.id.asc())
|
||
|
|
)
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def duplicate_video_query(session, video: Video):
|
||
|
|
candidates = video_identity_candidates(video.vk_video_id)
|
||
|
|
conditions = []
|
||
|
|
if candidates:
|
||
|
|
conditions.append(Video.vk_video_id.in_(candidates))
|
||
|
|
if video.vk_video_url:
|
||
|
|
conditions.append(Video.vk_video_url == video.vk_video_url)
|
||
|
|
if not conditions:
|
||
|
|
return session.query(Video).filter(Video.id == video.id)
|
||
|
|
condition = conditions[0]
|
||
|
|
for next_condition in conditions[1:]:
|
||
|
|
condition = condition | next_condition
|
||
|
|
return session.query(Video).filter(condition)
|
||
|
|
|
||
|
|
|
||
|
|
def canonical_video_for_upload(session, video: Video) -> Video:
|
||
|
|
return (
|
||
|
|
duplicate_video_query(session, video)
|
||
|
|
.order_by(
|
||
|
|
Video.ok_video_id.is_(None),
|
||
|
|
Video.upload_lock.is_(None),
|
||
|
|
Video.id.asc(),
|
||
|
|
)
|
||
|
|
.first()
|
||
|
|
or video
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
def attach_ok_video_to_duplicate_rows(session, video: Video, ok_video_id: str) -> set[int]:
|
||
|
|
waiting_posts: set[int] = set()
|
||
|
|
videos = duplicate_video_query(session, video).all()
|
||
|
|
for duplicate in videos:
|
||
|
|
duplicate.ok_video_id = duplicate.ok_video_id or ok_video_id
|
||
|
|
duplicate.status = "ok_uploaded"
|
||
|
|
duplicate.upload_lock = None
|
||
|
|
|
||
|
|
candidate_ids: set[str] = set()
|
||
|
|
for duplicate in videos:
|
||
|
|
candidate_ids.update(video_identity_candidates(duplicate.vk_video_id))
|
||
|
|
if duplicate.vk_video_url:
|
||
|
|
candidate_ids.add(duplicate.vk_video_url)
|
||
|
|
|
||
|
|
if not candidate_ids:
|
||
|
|
return waiting_posts
|
||
|
|
|
||
|
|
media_rows = session.scalars(
|
||
|
|
select(PostMedia).where(
|
||
|
|
PostMedia.media_type == "video",
|
||
|
|
(
|
||
|
|
PostMedia.vk_attachment_id.in_(candidate_ids)
|
||
|
|
| PostMedia.source_url.in_(candidate_ids)
|
||
|
|
),
|
||
|
|
)
|
||
|
|
).all()
|
||
|
|
for media in media_rows:
|
||
|
|
media.ok_media_id = ok_video_id
|
||
|
|
media.status = "uploaded"
|
||
|
|
if media.post and media.post.status in {"waiting_video", "queued", "ok_publish_pending"}:
|
||
|
|
waiting_posts.add(media.post_id)
|
||
|
|
return waiting_posts
|
||
|
|
|
||
|
|
|
||
|
|
def queue_video_if_needed(video: Video) -> None:
|
||
|
|
if video.ok_video_id:
|
||
|
|
return
|
||
|
|
if video.upload_lock:
|
||
|
|
return
|
||
|
|
if video.status in {"pending", "vk_link_only"}:
|
||
|
|
download_vk_video.delay(video.id)
|
||
|
|
elif video.status == "downloaded":
|
||
|
|
upload_video_to_ok.delay(video.id)
|
||
|
|
|
||
|
|
|
||
|
|
def should_publish_to_group_video(video: Video) -> bool:
|
||
|
|
return (video.title or "").strip() != VK_CLIP_TITLE
|
||
|
|
|
||
|
|
|
||
|
|
def all_post_videos_ready(session, media_items: list[PostMedia]) -> bool:
|
||
|
|
for item in media_items:
|
||
|
|
if item.media_type != "video":
|
||
|
|
continue
|
||
|
|
if item.ok_media_id:
|
||
|
|
continue
|
||
|
|
video = video_for_media(session, item)
|
||
|
|
if video and video.ok_video_id:
|
||
|
|
item.ok_media_id = video.ok_video_id
|
||
|
|
item.status = "uploaded"
|
||
|
|
continue
|
||
|
|
if video:
|
||
|
|
queue_video_if_needed(video)
|
||
|
|
return False
|
||
|
|
return True
|
||
|
|
|
||
|
|
|
||
|
|
def normalize_video_match_text(value: str | None) -> str:
|
||
|
|
return re.sub(r"\s+", " ", (value or "").casefold()).strip()
|
||
|
|
|
||
|
|
|
||
|
|
def uploaded_video_fallback(session, video: Video) -> Video | None:
|
||
|
|
description = normalize_video_match_text(video.description)
|
||
|
|
title = normalize_video_match_text(video.title)
|
||
|
|
candidates = (
|
||
|
|
session.query(Video)
|
||
|
|
.filter(
|
||
|
|
Video.id != video.id,
|
||
|
|
Video.ok_video_id.is_not(None),
|
||
|
|
Video.status == "ok_uploaded",
|
||
|
|
)
|
||
|
|
.order_by(Video.id.desc())
|
||
|
|
.limit(100)
|
||
|
|
.all()
|
||
|
|
)
|
||
|
|
for candidate in candidates:
|
||
|
|
candidate_description = normalize_video_match_text(candidate.description)
|
||
|
|
if len(description) >= 160 and candidate_description[:160] == description[:160]:
|
||
|
|
return candidate
|
||
|
|
candidate_title = normalize_video_match_text(candidate.title)
|
||
|
|
if len(title) >= 80 and candidate_title[:80] == title[:80]:
|
||
|
|
return candidate
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def apply_uploaded_video_fallbacks(session, media_items: list[PostMedia]) -> None:
|
||
|
|
for item in media_items:
|
||
|
|
if item.media_type != "video" or item.ok_media_id:
|
||
|
|
continue
|
||
|
|
video = video_for_media(session, item)
|
||
|
|
if not video or video.ok_video_id:
|
||
|
|
continue
|
||
|
|
fallback = uploaded_video_fallback(session, video)
|
||
|
|
if not fallback or not fallback.ok_video_id:
|
||
|
|
continue
|
||
|
|
attach_ok_video_to_duplicate_rows(session, video, fallback.ok_video_id)
|
||
|
|
item.ok_media_id = fallback.ok_video_id
|
||
|
|
item.status = "uploaded"
|
||
|
|
|
||
|
|
|
||
|
|
def failed_post_video_message(session, media_items: list[PostMedia]) -> str | None:
|
||
|
|
for item in media_items:
|
||
|
|
if item.media_type != "video" or item.ok_media_id:
|
||
|
|
continue
|
||
|
|
video = video_for_media(session, item)
|
||
|
|
if video and video.status == "failed":
|
||
|
|
detail = video.error_message or video.title or video.vk_video_id or "unknown video"
|
||
|
|
return f"Video failed before OK upload: {detail}"[-4000:]
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def format_duration(seconds: int | None) -> str | None:
|
||
|
|
if seconds is None or seconds <= 0:
|
||
|
|
return None
|
||
|
|
minutes, remainder = divmod(int(seconds), 60)
|
||
|
|
hours, minutes = divmod(minutes, 60)
|
||
|
|
if hours:
|
||
|
|
return f"{hours}:{minutes:02d}:{remainder:02d}"
|
||
|
|
return f"{minutes}:{remainder:02d}"
|
||
|
|
|
||
|
|
|
||
|
|
def video_duration_seconds(media_items: list[PostMedia]) -> int | None:
|
||
|
|
for item in media_items:
|
||
|
|
if item.media_type == "video" and item.duration_seconds:
|
||
|
|
return item.duration_seconds
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def extract_video_playlist_title(video: dict) -> str | None:
|
||
|
|
for key in ("playlist", "album"):
|
||
|
|
value = video.get(key)
|
||
|
|
if isinstance(value, dict) and value.get("title"):
|
||
|
|
return str(value["title"]).strip()
|
||
|
|
if isinstance(value, str) and value.strip():
|
||
|
|
return value.strip()
|
||
|
|
|
||
|
|
for key in ("playlist_title", "album_title", "category_name", "section_title"):
|
||
|
|
value = video.get(key)
|
||
|
|
if isinstance(value, str) and value.strip():
|
||
|
|
return value.strip()
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def video_playlist_title(media_items: list[PostMedia]) -> str | None:
|
||
|
|
for item in media_items:
|
||
|
|
if item.media_type == "video" and item.playlist_title:
|
||
|
|
return item.playlist_title
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def font(size: int, bold: bool = False, serif: bool = False, italic: bool = False) -> ImageFont.FreeTypeFont:
|
||
|
|
if serif:
|
||
|
|
linux_name = "DejaVuSerif-BoldItalic.ttf" if bold and italic else "DejaVuSerif-Bold.ttf" if bold else "DejaVuSerif-Italic.ttf" if italic else "DejaVuSerif.ttf"
|
||
|
|
mac_name = "Times New Roman Bold Italic.ttf" if bold and italic else "Times New Roman Bold.ttf" if bold else "Times New Roman Italic.ttf" if italic else "Times New Roman.ttf"
|
||
|
|
candidates = [
|
||
|
|
f"/usr/share/fonts/truetype/dejavu/{linux_name}",
|
||
|
|
f"/System/Library/Fonts/Supplemental/{mac_name}",
|
||
|
|
"/Library/Fonts/Georgia.ttf",
|
||
|
|
]
|
||
|
|
for candidate in candidates:
|
||
|
|
if Path(candidate).exists():
|
||
|
|
return ImageFont.truetype(candidate, size=size)
|
||
|
|
|
||
|
|
candidates = [
|
||
|
|
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||
|
|
"/System/Library/Fonts/Supplemental/Arial Bold.ttf" if bold else "/System/Library/Fonts/Supplemental/Arial.ttf",
|
||
|
|
"/Library/Fonts/Arial Unicode.ttf",
|
||
|
|
]
|
||
|
|
for candidate in candidates:
|
||
|
|
if Path(candidate).exists():
|
||
|
|
return ImageFont.truetype(candidate, size=size)
|
||
|
|
return ImageFont.load_default()
|
||
|
|
|
||
|
|
|
||
|
|
def text_width(draw: ImageDraw.ImageDraw, text: str, text_font: ImageFont.ImageFont) -> int:
|
||
|
|
box = draw.textbbox((0, 0), text, font=text_font)
|
||
|
|
return box[2] - box[0]
|
||
|
|
|
||
|
|
|
||
|
|
def wrap_text(draw: ImageDraw.ImageDraw, text: str, text_font: ImageFont.ImageFont, max_width: int) -> list[str]:
|
||
|
|
lines: list[str] = []
|
||
|
|
for paragraph in text.splitlines():
|
||
|
|
words = paragraph.split()
|
||
|
|
if not words:
|
||
|
|
lines.append("")
|
||
|
|
continue
|
||
|
|
current = words[0]
|
||
|
|
for word in words[1:]:
|
||
|
|
candidate = f"{current} {word}"
|
||
|
|
if text_width(draw, candidate, text_font) <= max_width:
|
||
|
|
current = candidate
|
||
|
|
else:
|
||
|
|
lines.append(current)
|
||
|
|
current = word
|
||
|
|
lines.append(current)
|
||
|
|
return lines
|
||
|
|
|
||
|
|
|
||
|
|
def truncate_to_width(draw: ImageDraw.ImageDraw, text: str, text_font: ImageFont.ImageFont, max_width: int) -> str:
|
||
|
|
if text_width(draw, text, text_font) <= max_width:
|
||
|
|
return text
|
||
|
|
suffix = "..."
|
||
|
|
trimmed = text
|
||
|
|
while trimmed and text_width(draw, f"{trimmed}{suffix}", text_font) > max_width:
|
||
|
|
trimmed = trimmed[:-1].rstrip()
|
||
|
|
return f"{trimmed}{suffix}" if trimmed else suffix
|
||
|
|
|
||
|
|
|
||
|
|
def first_content_image_url(media_items: list[PostMedia]) -> str | None:
|
||
|
|
for item in media_items:
|
||
|
|
if item.media_type == "photo" and item.source_url:
|
||
|
|
return item.source_url
|
||
|
|
if item.media_type == "video" and item.local_cover_path:
|
||
|
|
return item.local_cover_path
|
||
|
|
if item.media_type == "video" and item.source_url:
|
||
|
|
preview_url = fetch_page_preview_image(item.source_url)
|
||
|
|
if preview_url:
|
||
|
|
return preview_url
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def fetch_page_preview_image(url: str) -> str | None:
|
||
|
|
try:
|
||
|
|
with httpx.Client(follow_redirects=True, timeout=20) as client:
|
||
|
|
response = client.get(url, headers={"User-Agent": "Mozilla/5.0"})
|
||
|
|
response.raise_for_status()
|
||
|
|
except Exception:
|
||
|
|
return None
|
||
|
|
|
||
|
|
match = re.search(r'<meta\s+property=["\']og:image["\']\s+content=["\']([^"\']+)["\']', response.text)
|
||
|
|
if not match:
|
||
|
|
match = re.search(r'<meta\s+content=["\']([^"\']+)["\']\s+property=["\']og:image["\']', response.text)
|
||
|
|
if not match:
|
||
|
|
return None
|
||
|
|
return match.group(1).replace("&", "&")
|
||
|
|
|
||
|
|
|
||
|
|
def draw_wrapped_text(
|
||
|
|
draw: ImageDraw.ImageDraw,
|
||
|
|
text: str,
|
||
|
|
xy: tuple[int, int],
|
||
|
|
text_font: ImageFont.ImageFont,
|
||
|
|
fill: str,
|
||
|
|
max_width: int,
|
||
|
|
line_gap: int,
|
||
|
|
max_lines: int | None = None,
|
||
|
|
) -> int:
|
||
|
|
x, y = xy
|
||
|
|
lines = wrap_text(draw, text, text_font, max_width)
|
||
|
|
if max_lines and len(lines) > max_lines:
|
||
|
|
lines = lines[:max_lines]
|
||
|
|
if lines:
|
||
|
|
lines[-1] = lines[-1].rstrip(".,;: ") + "..."
|
||
|
|
for line in lines:
|
||
|
|
draw.text((x, y), line, font=text_font, fill=fill)
|
||
|
|
box = draw.textbbox((x, y), line or " ", font=text_font)
|
||
|
|
y += box[3] - box[1] + line_gap
|
||
|
|
return y
|
||
|
|
|
||
|
|
|
||
|
|
def wrapped_text_lines(
|
||
|
|
draw: ImageDraw.ImageDraw,
|
||
|
|
text: str,
|
||
|
|
text_font: ImageFont.ImageFont,
|
||
|
|
max_width: int,
|
||
|
|
max_lines: int | None = None,
|
||
|
|
) -> list[str]:
|
||
|
|
lines = wrap_text(draw, text, text_font, max_width)
|
||
|
|
if max_lines and len(lines) > max_lines:
|
||
|
|
lines = lines[:max_lines]
|
||
|
|
if lines:
|
||
|
|
lines[-1] = lines[-1].rstrip(".,;: ") + "..."
|
||
|
|
return lines
|
||
|
|
|
||
|
|
|
||
|
|
def wrapped_text_height(
|
||
|
|
draw: ImageDraw.ImageDraw,
|
||
|
|
lines: list[str],
|
||
|
|
text_font: ImageFont.ImageFont,
|
||
|
|
line_gap: int,
|
||
|
|
) -> int:
|
||
|
|
height = 0
|
||
|
|
for line in lines:
|
||
|
|
box = draw.textbbox((0, 0), line or " ", font=text_font)
|
||
|
|
height += box[3] - box[1] + line_gap
|
||
|
|
return max(0, height - line_gap)
|
||
|
|
|
||
|
|
|
||
|
|
def rounded_image(image: Image.Image, size: tuple[int, int], radius: int) -> Image.Image:
|
||
|
|
image = ImageOps.fit(image.convert("RGB"), size, method=Image.Resampling.LANCZOS, centering=(0.5, 0.5))
|
||
|
|
mask = Image.new("L", size, 0)
|
||
|
|
mask_draw = ImageDraw.Draw(mask)
|
||
|
|
mask_draw.rounded_rectangle((0, 0, size[0], size[1]), radius=radius, fill=255)
|
||
|
|
image.putalpha(mask)
|
||
|
|
return image
|
||
|
|
|
||
|
|
|
||
|
|
def load_remote_image(url: str, target_path: Path) -> Image.Image | None:
|
||
|
|
try:
|
||
|
|
download_file(url, target_path)
|
||
|
|
return Image.open(target_path).convert("RGB")
|
||
|
|
except Exception:
|
||
|
|
logger.exception("Failed to load image for OK moment: %s", url)
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def moment_image_urls(media_items: list[PostMedia]) -> list[str]:
|
||
|
|
urls: list[str] = []
|
||
|
|
for item in media_items:
|
||
|
|
if item.media_type == "video":
|
||
|
|
if item.local_cover_path:
|
||
|
|
urls.append(item.local_cover_path)
|
||
|
|
elif item.source_url:
|
||
|
|
preview_url = fetch_page_preview_image(item.source_url)
|
||
|
|
if preview_url:
|
||
|
|
urls.append(preview_url)
|
||
|
|
elif item.media_type == "photo" and item.source_url:
|
||
|
|
urls.append(item.source_url)
|
||
|
|
|
||
|
|
unique_urls: list[str] = []
|
||
|
|
for url in urls:
|
||
|
|
if url and url not in unique_urls:
|
||
|
|
unique_urls.append(url)
|
||
|
|
return unique_urls
|
||
|
|
|
||
|
|
|
||
|
|
def load_moment_images(urls: list[str], target_dir: Path) -> list[Image.Image]:
|
||
|
|
images: list[Image.Image] = []
|
||
|
|
for index, url in enumerate(urls[:6]):
|
||
|
|
image = load_remote_image(url, target_dir / f"cover-{index + 1}.jpg")
|
||
|
|
if image:
|
||
|
|
images.append(image)
|
||
|
|
return images
|
||
|
|
|
||
|
|
|
||
|
|
def moment_base() -> Image.Image:
|
||
|
|
background = Image.new("RGB", (MOMENT_WIDTH, MOMENT_HEIGHT), "#0D141B")
|
||
|
|
draw = ImageDraw.Draw(background)
|
||
|
|
for y in range(MOMENT_HEIGHT):
|
||
|
|
ratio = y / MOMENT_HEIGHT
|
||
|
|
r = int(10 + 18 * ratio)
|
||
|
|
g = int(17 + 29 * ratio)
|
||
|
|
b = int(25 + 38 * ratio)
|
||
|
|
draw.line((0, y, MOMENT_WIDTH, y), fill=(r, g, b))
|
||
|
|
return background.convert("RGBA")
|
||
|
|
|
||
|
|
|
||
|
|
def add_editorial_fade(image: Image.Image, bottom_start: int = 900, bottom_alpha: int = 220) -> Image.Image:
|
||
|
|
fade = Image.new("RGBA", (MOMENT_WIDTH, MOMENT_HEIGHT), (0, 0, 0, 0))
|
||
|
|
fade_draw = ImageDraw.Draw(fade)
|
||
|
|
for y in range(MOMENT_HEIGHT):
|
||
|
|
if y < 220:
|
||
|
|
alpha = int(116 * (1 - y / 220))
|
||
|
|
elif y > bottom_start:
|
||
|
|
alpha = int(min(bottom_alpha, (y - bottom_start) / (MOMENT_HEIGHT - bottom_start) * bottom_alpha))
|
||
|
|
else:
|
||
|
|
alpha = 0
|
||
|
|
if alpha:
|
||
|
|
fade_draw.line((0, y, MOMENT_WIDTH, y), fill=(3, 7, 10, alpha))
|
||
|
|
return Image.alpha_composite(image.convert("RGBA"), fade)
|
||
|
|
|
||
|
|
|
||
|
|
def full_bleed_image(image: Image.Image) -> Image.Image:
|
||
|
|
cover = ImageOps.fit(image.convert("RGB"), (MOMENT_WIDTH, MOMENT_HEIGHT), method=Image.Resampling.LANCZOS)
|
||
|
|
cover = ImageEnhance.Contrast(cover).enhance(1.05)
|
||
|
|
return ImageEnhance.Color(cover).enhance(0.96).convert("RGBA")
|
||
|
|
|
||
|
|
|
||
|
|
def abstract_text_background() -> Image.Image:
|
||
|
|
background = moment_base()
|
||
|
|
draw = ImageDraw.Draw(background)
|
||
|
|
for radius in range(120, 1420, 150):
|
||
|
|
color = (220, 178, 91, max(8, 52 - radius // 42))
|
||
|
|
draw.ellipse(
|
||
|
|
(MOMENT_WIDTH // 2 - radius, 470 - radius, MOMENT_WIDTH // 2 + radius, 470 + radius),
|
||
|
|
outline=color,
|
||
|
|
width=3,
|
||
|
|
)
|
||
|
|
for x in range(-MOMENT_HEIGHT, MOMENT_WIDTH, 64):
|
||
|
|
draw.line((x, MOMENT_HEIGHT, x + MOMENT_HEIGHT, 0), fill=(230, 194, 112, 24), width=2)
|
||
|
|
return background
|
||
|
|
|
||
|
|
|
||
|
|
def paste_framed_image(
|
||
|
|
canvas: Image.Image,
|
||
|
|
image: Image.Image,
|
||
|
|
box: tuple[int, int, int, int],
|
||
|
|
radius: int = 28,
|
||
|
|
shadow: bool = True,
|
||
|
|
) -> None:
|
||
|
|
x1, y1, x2, y2 = box
|
||
|
|
size = (x2 - x1, y2 - y1)
|
||
|
|
if shadow:
|
||
|
|
shadow_layer = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
|
||
|
|
shadow_draw = ImageDraw.Draw(shadow_layer)
|
||
|
|
shadow_draw.rounded_rectangle((x1 + 14, y1 + 22, x2 + 14, y2 + 22), radius=radius, fill=(0, 0, 0, 118))
|
||
|
|
shadow_layer = shadow_layer.filter(ImageFilter.GaussianBlur(20))
|
||
|
|
canvas.alpha_composite(shadow_layer)
|
||
|
|
|
||
|
|
framed = rounded_image(image, size, radius)
|
||
|
|
canvas.alpha_composite(framed, (x1, y1))
|
||
|
|
|
||
|
|
|
||
|
|
def paste_contained_image(
|
||
|
|
canvas: Image.Image,
|
||
|
|
image: Image.Image,
|
||
|
|
box: tuple[int, int, int, int],
|
||
|
|
radius: int = 28,
|
||
|
|
) -> tuple[int, int, int, int]:
|
||
|
|
x1, y1, x2, y2 = box
|
||
|
|
max_size = (x2 - x1, y2 - y1)
|
||
|
|
contained = ImageOps.contain(image.convert("RGB"), max_size, method=Image.Resampling.LANCZOS)
|
||
|
|
image_x = x1 + (max_size[0] - contained.width) // 2
|
||
|
|
image_y = y1 + (max_size[1] - contained.height) // 2
|
||
|
|
image_box = (image_x, image_y, image_x + contained.width, image_y + contained.height)
|
||
|
|
paste_framed_image(canvas, contained, image_box, radius=radius)
|
||
|
|
return image_box
|
||
|
|
|
||
|
|
|
||
|
|
def build_video_background(image: Image.Image) -> tuple[Image.Image, tuple[int, int, int, int]]:
|
||
|
|
base = moment_base()
|
||
|
|
blurred = ImageOps.fit(image.convert("RGB"), (MOMENT_WIDTH, MOMENT_HEIGHT), method=Image.Resampling.LANCZOS)
|
||
|
|
blurred = blurred.filter(ImageFilter.GaussianBlur(32))
|
||
|
|
blurred = ImageEnhance.Brightness(blurred).enhance(0.34)
|
||
|
|
blurred = ImageEnhance.Color(blurred).enhance(0.78).convert("RGBA")
|
||
|
|
base = Image.alpha_composite(base, blurred)
|
||
|
|
base = Image.alpha_composite(base, Image.new("RGBA", (MOMENT_WIDTH, MOMENT_HEIGHT), (5, 9, 12, 126)))
|
||
|
|
image_box = paste_contained_image(base, image, (62, 150, 1018, 920), radius=32)
|
||
|
|
return base, image_box
|
||
|
|
|
||
|
|
|
||
|
|
def build_gallery_background(images: list[Image.Image], total_count: int) -> Image.Image:
|
||
|
|
base = moment_base()
|
||
|
|
blurred = ImageOps.fit(images[0], (MOMENT_WIDTH, MOMENT_HEIGHT), method=Image.Resampling.LANCZOS)
|
||
|
|
blurred = blurred.filter(ImageFilter.GaussianBlur(36))
|
||
|
|
blurred = ImageEnhance.Brightness(blurred).enhance(0.36).convert("RGBA")
|
||
|
|
base = Image.alpha_composite(base, blurred)
|
||
|
|
overlay = Image.new("RGBA", (MOMENT_WIDTH, MOMENT_HEIGHT), (5, 9, 12, 72))
|
||
|
|
base = Image.alpha_composite(base, overlay)
|
||
|
|
|
||
|
|
if len(images) <= 3:
|
||
|
|
paste_framed_image(base, images[0], (70, 150, 1010, 920), radius=34)
|
||
|
|
if len(images) > 1:
|
||
|
|
paste_framed_image(base, images[1], (90, 820, 525, 1170), radius=24)
|
||
|
|
if len(images) > 2:
|
||
|
|
paste_framed_image(base, images[2], (555, 820, 990, 1170), radius=24)
|
||
|
|
else:
|
||
|
|
paste_framed_image(base, images[0], (64, 132, 680, 820), radius=32)
|
||
|
|
paste_framed_image(base, images[1], (704, 178, 1016, 520), radius=24)
|
||
|
|
paste_framed_image(base, images[2], (704, 548, 1016, 890), radius=24)
|
||
|
|
paste_framed_image(base, images[3], (112, 860, 972, 1175), radius=28)
|
||
|
|
if total_count > 4:
|
||
|
|
draw = ImageDraw.Draw(base)
|
||
|
|
draw.rounded_rectangle((815, 1062, 965, 1128), radius=20, fill=(7, 12, 16, 176))
|
||
|
|
draw.text((842, 1074), f"+{total_count - 4} фото", font=font(28, bold=True), fill="#F5E7C2")
|
||
|
|
return base
|
||
|
|
|
||
|
|
|
||
|
|
def draw_clock_icon(draw: ImageDraw.ImageDraw, center: tuple[int, int], color: str) -> None:
|
||
|
|
x, y = center
|
||
|
|
radius = 11
|
||
|
|
draw.ellipse((x - radius, y - radius, x + radius, y + radius), outline=color, width=3)
|
||
|
|
draw.line((x, y, x, y - 7), fill=color, width=3)
|
||
|
|
draw.line((x, y, x + 6, y + 4), fill=color, width=3)
|
||
|
|
|
||
|
|
|
||
|
|
def draw_moment_text(
|
||
|
|
canvas: Image.Image,
|
||
|
|
title: str,
|
||
|
|
body: str,
|
||
|
|
text_top: int,
|
||
|
|
title_lines: int = 4,
|
||
|
|
body_lines: int = 5,
|
||
|
|
badges: list[str] | None = None,
|
||
|
|
) -> None:
|
||
|
|
draw = ImageDraw.Draw(canvas)
|
||
|
|
margin = 74
|
||
|
|
content_width = MOMENT_WIDTH - margin * 2
|
||
|
|
rule_top = text_top - 34
|
||
|
|
title_font = font(64, serif=True)
|
||
|
|
body_font = font(35, serif=True)
|
||
|
|
title_gap = 16
|
||
|
|
body_gap = 12
|
||
|
|
title_text_lines = wrapped_text_lines(draw, title, title_font, content_width, title_lines)
|
||
|
|
body_text_lines = wrapped_text_lines(draw, body, body_font, content_width, body_lines) if body else []
|
||
|
|
title_height = wrapped_text_height(draw, title_text_lines, title_font, title_gap)
|
||
|
|
body_height = wrapped_text_height(draw, body_text_lines, body_font, body_gap) if body_text_lines else 0
|
||
|
|
text_bottom = text_top + title_height + (30 + body_height if body_text_lines else 0)
|
||
|
|
panel_padding_x = 28
|
||
|
|
panel_padding_y = 26
|
||
|
|
panel_top = rule_top - panel_padding_y
|
||
|
|
panel_bottom = min(MOMENT_HEIGHT - 96, text_bottom + panel_padding_y)
|
||
|
|
panel_layer = Image.new("RGBA", (MOMENT_WIDTH, MOMENT_HEIGHT), (0, 0, 0, 0))
|
||
|
|
panel_draw = ImageDraw.Draw(panel_layer)
|
||
|
|
panel_draw.rounded_rectangle(
|
||
|
|
(
|
||
|
|
margin - panel_padding_x,
|
||
|
|
panel_top,
|
||
|
|
MOMENT_WIDTH - margin + panel_padding_x,
|
||
|
|
panel_bottom,
|
||
|
|
),
|
||
|
|
radius=30,
|
||
|
|
fill=(0, 0, 0, 102),
|
||
|
|
)
|
||
|
|
panel_layer = panel_layer.filter(ImageFilter.GaussianBlur(0.6))
|
||
|
|
canvas.alpha_composite(panel_layer)
|
||
|
|
draw = ImageDraw.Draw(canvas)
|
||
|
|
|
||
|
|
badge_x = margin
|
||
|
|
badge_y = rule_top - 62
|
||
|
|
for index, badge in enumerate(badges or []):
|
||
|
|
badge_font = font(25, bold=True)
|
||
|
|
has_clock = index == 1
|
||
|
|
max_badge_width = MOMENT_WIDTH - margin - badge_x
|
||
|
|
label = truncate_to_width(draw, badge, badge_font, max_badge_width - (62 if has_clock else 32))
|
||
|
|
badge_width = text_width(draw, label, badge_font) + (62 if has_clock else 32)
|
||
|
|
if index == 0:
|
||
|
|
fill = (238, 192, 88, 236)
|
||
|
|
outline = None
|
||
|
|
text_fill = "#10161C"
|
||
|
|
else:
|
||
|
|
fill = (9, 14, 18, 180)
|
||
|
|
outline = (238, 192, 88, 170)
|
||
|
|
text_fill = "#F5E7C2"
|
||
|
|
draw.rounded_rectangle(
|
||
|
|
(badge_x, badge_y, badge_x + badge_width, badge_y + 40),
|
||
|
|
radius=16,
|
||
|
|
fill=fill,
|
||
|
|
outline=outline,
|
||
|
|
width=1,
|
||
|
|
)
|
||
|
|
text_x = badge_x + 16
|
||
|
|
if has_clock:
|
||
|
|
draw_clock_icon(draw, (badge_x + 26, badge_y + 20), "#F5E7C2")
|
||
|
|
text_x = badge_x + 46
|
||
|
|
draw.text((text_x, badge_y + 7), label, font=badge_font, fill=text_fill)
|
||
|
|
badge_x += badge_width + 14
|
||
|
|
draw.line((margin, rule_top + 4, MOMENT_WIDTH - margin, rule_top + 4), fill=(238, 192, 88, 92), width=2)
|
||
|
|
y = text_top
|
||
|
|
for line in title_text_lines:
|
||
|
|
draw.text((margin, y), line, font=title_font, fill="#F6F0E7")
|
||
|
|
box = draw.textbbox((margin, y), line or " ", font=title_font)
|
||
|
|
y += box[3] - box[1] + title_gap
|
||
|
|
if body_text_lines:
|
||
|
|
y += 30
|
||
|
|
for line in body_text_lines:
|
||
|
|
draw.text((margin, y), line, font=body_font, fill="#EEE2D1")
|
||
|
|
box = draw.textbbox((margin, y), line or " ", font=body_font)
|
||
|
|
y += box[3] - box[1] + body_gap
|
||
|
|
|
||
|
|
|
||
|
|
def create_moment_card(post: Post, media_items: list[PostMedia]) -> Path:
|
||
|
|
target_path = Path(settings.storage_dir) / "moments" / str(post.id) / "miniapp.jpg"
|
||
|
|
target_path.parent.mkdir(parents=True, exist_ok=True)
|
||
|
|
|
||
|
|
normalized_post_text = normalize_post_text(post.text)
|
||
|
|
title = normalized_post_text.splitlines()[0].strip() if normalized_post_text else "Школа Геополитики"
|
||
|
|
body = normalized_post_text
|
||
|
|
if body.startswith(title):
|
||
|
|
body = body[len(title):].strip()
|
||
|
|
|
||
|
|
has_video = any(item.media_type == "video" for item in media_items)
|
||
|
|
video_duration = format_duration(video_duration_seconds(media_items))
|
||
|
|
playlist_title = video_playlist_title(media_items)
|
||
|
|
video_badges = ["ВИДЕО"] + ([video_duration] if video_duration else []) + ([playlist_title] if playlist_title else [])
|
||
|
|
image_urls = moment_image_urls(media_items)
|
||
|
|
images = load_moment_images(image_urls, target_path.parent)
|
||
|
|
|
||
|
|
if not images:
|
||
|
|
background = abstract_text_background()
|
||
|
|
background = add_editorial_fade(background, bottom_start=760, bottom_alpha=190)
|
||
|
|
draw_moment_text(background, title, body, text_top=760, title_lines=5, body_lines=8)
|
||
|
|
elif has_video:
|
||
|
|
background, video_box = build_video_background(images[0])
|
||
|
|
background = add_editorial_fade(background, bottom_start=930, bottom_alpha=224)
|
||
|
|
draw_moment_text(background, title, body, text_top=1065, title_lines=4, body_lines=5, badges=video_badges)
|
||
|
|
elif len(images) == 1:
|
||
|
|
background = full_bleed_image(images[0])
|
||
|
|
background = add_editorial_fade(background, bottom_start=900, bottom_alpha=224)
|
||
|
|
draw_moment_text(background, title, body, text_top=1110, title_lines=4, body_lines=5)
|
||
|
|
else:
|
||
|
|
background = build_gallery_background(images, len(image_urls))
|
||
|
|
background = add_editorial_fade(background, bottom_start=990, bottom_alpha=222)
|
||
|
|
draw_moment_text(background, title, body, text_top=1235, title_lines=3, body_lines=4)
|
||
|
|
|
||
|
|
background.convert("RGB").save(target_path, "JPEG", quality=94, optimize=True)
|
||
|
|
return target_path
|
||
|
|
|
||
|
|
|
||
|
|
def publish_moment_for_post(post: Post, media_items: list[PostMedia]) -> dict:
|
||
|
|
image_path = create_moment_card(post, media_items)
|
||
|
|
photo_id, token = upload_moment_photo(settings, image_path)
|
||
|
|
return commit_group_moment(settings, photo_id, token)
|
||
|
|
|
||
|
|
|
||
|
|
def topic_id_from_result(result) -> str:
|
||
|
|
if isinstance(result, dict):
|
||
|
|
return str(result.get("id") or result.get("topic_id") or result.get("media_topic_id") or result)
|
||
|
|
return str(result)
|
||
|
|
|
||
|
|
|
||
|
|
@celery_app.task(bind=True, autoretry_for=(Exception,), retry_backoff=True, retry_kwargs={"max_retries": 3})
|
||
|
|
def process_vk_event(self, event_id: int) -> str:
|
||
|
|
init_db()
|
||
|
|
with SessionLocal() as session:
|
||
|
|
event = session.get(VkEvent, event_id)
|
||
|
|
if event is None:
|
||
|
|
return "missing"
|
||
|
|
|
||
|
|
payload = json.loads(event.raw_payload_json)
|
||
|
|
obj = payload.get("object") or {}
|
||
|
|
if event.event_type == "video_new":
|
||
|
|
video = create_or_get_video(session, obj)
|
||
|
|
event.status = "processed"
|
||
|
|
event.processed_at = datetime.utcnow()
|
||
|
|
session.commit()
|
||
|
|
queue_video_if_needed(video)
|
||
|
|
return "processed"
|
||
|
|
|
||
|
|
if event.event_type not in {"wall_post_new", "wall_repost"}:
|
||
|
|
event.status = "ignored"
|
||
|
|
event.processed_at = datetime.utcnow()
|
||
|
|
session.commit()
|
||
|
|
return "ignored"
|
||
|
|
|
||
|
|
vk_group_id = str(payload.get("group_id") or settings.vk_group_id)
|
||
|
|
vk_post_id = str(obj.get("id") or obj.get("post_id") or "")
|
||
|
|
owner_id = obj.get("owner_id") or f"-{vk_group_id}"
|
||
|
|
|
||
|
|
if not vk_post_id:
|
||
|
|
event.status = "failed"
|
||
|
|
event.error_message = "VK post id is missing"
|
||
|
|
session.commit()
|
||
|
|
return "failed"
|
||
|
|
|
||
|
|
existing_post = session.scalar(
|
||
|
|
select(Post).where(Post.vk_group_id == vk_group_id, Post.vk_post_id == vk_post_id)
|
||
|
|
)
|
||
|
|
if existing_post:
|
||
|
|
event.status = "duplicate"
|
||
|
|
event.processed_at = datetime.utcnow()
|
||
|
|
session.commit()
|
||
|
|
return "duplicate"
|
||
|
|
|
||
|
|
attachments = obj.get("attachments") or []
|
||
|
|
content_key = build_post_content_key(str(obj.get("text") or ""), attachments)
|
||
|
|
if content_key and content_key.startswith("video:"):
|
||
|
|
existing_content_post = session.scalar(
|
||
|
|
select(Post)
|
||
|
|
.where(
|
||
|
|
Post.vk_group_id == vk_group_id,
|
||
|
|
Post.content_key == content_key,
|
||
|
|
Post.status.notin_(["failed", "skipped", "duplicate"]),
|
||
|
|
)
|
||
|
|
.order_by(Post.id.desc())
|
||
|
|
)
|
||
|
|
if existing_content_post:
|
||
|
|
event.status = "duplicate"
|
||
|
|
event.error_message = (
|
||
|
|
f"Duplicate content_key={content_key}; "
|
||
|
|
f"existing_post_id={existing_content_post.id}; "
|
||
|
|
f"existing_ok_topic_id={existing_content_post.ok_topic_id}"
|
||
|
|
)
|
||
|
|
event.processed_at = datetime.utcnow()
|
||
|
|
session.commit()
|
||
|
|
return "duplicate"
|
||
|
|
|
||
|
|
post = Post(
|
||
|
|
vk_group_id=vk_group_id,
|
||
|
|
vk_post_id=vk_post_id,
|
||
|
|
vk_post_url=build_vk_post_url(owner_id, vk_post_id),
|
||
|
|
text=str(obj.get("text") or ""),
|
||
|
|
content_key=content_key or None,
|
||
|
|
)
|
||
|
|
session.add(post)
|
||
|
|
session.flush()
|
||
|
|
|
||
|
|
created_media: list[PostMedia] = []
|
||
|
|
for index, attachment in enumerate(attachments):
|
||
|
|
attachment_type = attachment.get("type")
|
||
|
|
data = attachment.get(attachment_type) or {}
|
||
|
|
media = PostMedia(
|
||
|
|
post_id=post.id,
|
||
|
|
media_type=str(attachment_type or "unknown"),
|
||
|
|
vk_attachment_id=str(data.get("id") or ""),
|
||
|
|
sort_order=index,
|
||
|
|
)
|
||
|
|
|
||
|
|
if attachment_type == "video":
|
||
|
|
media.vk_attachment_id = extract_video_identity(data)
|
||
|
|
video_url = extract_video_public_url(data)
|
||
|
|
media.source_url = video_url
|
||
|
|
media.local_cover_path = extract_largest_image_url(data.get("image") or [])
|
||
|
|
media.duration_seconds = data.get("duration")
|
||
|
|
media.playlist_title = extract_video_playlist_title(data)
|
||
|
|
video = create_or_get_video(session, data)
|
||
|
|
if not video.description and post.text:
|
||
|
|
video.description = post.text
|
||
|
|
if video.ok_video_id:
|
||
|
|
media.ok_media_id = video.ok_video_id
|
||
|
|
media.status = "uploaded"
|
||
|
|
|
||
|
|
if attachment_type == "photo":
|
||
|
|
media.source_url = extract_largest_image_url(data.get("sizes") or [])
|
||
|
|
|
||
|
|
session.add(media)
|
||
|
|
created_media.append(media)
|
||
|
|
|
||
|
|
media_items = sorted(created_media, key=lambda item: item.sort_order)
|
||
|
|
if all_post_videos_ready(session, media_items):
|
||
|
|
post.status = "queued"
|
||
|
|
should_publish = True
|
||
|
|
else:
|
||
|
|
post.status = "waiting_video"
|
||
|
|
should_publish = False
|
||
|
|
event.status = "processed"
|
||
|
|
event.processed_at = datetime.utcnow()
|
||
|
|
session.commit()
|
||
|
|
if should_publish:
|
||
|
|
publish_post_to_ok.delay(post.id)
|
||
|
|
return "processed"
|
||
|
|
|
||
|
|
|
||
|
|
@celery_app.task(bind=True, autoretry_for=(Exception,), retry_backoff=True, retry_kwargs={"max_retries": 2})
|
||
|
|
def download_vk_video(self, video_id: int) -> str:
|
||
|
|
init_db()
|
||
|
|
with SessionLocal() as session:
|
||
|
|
video = session.get(Video, video_id)
|
||
|
|
if video is None or not video.vk_video_url:
|
||
|
|
return "missing"
|
||
|
|
if video.ok_video_id:
|
||
|
|
return "uploaded"
|
||
|
|
if video.local_video_path and Path(video.local_video_path).exists():
|
||
|
|
if video.status != "downloaded":
|
||
|
|
video.status = "downloaded"
|
||
|
|
session.commit()
|
||
|
|
upload_video_to_ok.delay(video.id)
|
||
|
|
return "downloaded"
|
||
|
|
|
||
|
|
target_dir = settings.storage_path / "vk" / str(video.id)
|
||
|
|
target_dir.mkdir(parents=True, exist_ok=True)
|
||
|
|
output_template = str(target_dir / "%(id)s.%(ext)s")
|
||
|
|
command = [
|
||
|
|
"yt-dlp",
|
||
|
|
"--write-thumbnail",
|
||
|
|
"--convert-thumbnails",
|
||
|
|
"jpg",
|
||
|
|
"--write-info-json",
|
||
|
|
"--write-description",
|
||
|
|
"--no-playlist",
|
||
|
|
"-f",
|
||
|
|
"bv*+ba/b",
|
||
|
|
"--merge-output-format",
|
||
|
|
"mp4",
|
||
|
|
"-o",
|
||
|
|
output_template,
|
||
|
|
]
|
||
|
|
cookies_path = Path(settings.ytdlp_cookies_path)
|
||
|
|
if cookies_path.exists():
|
||
|
|
command.extend(["--cookies", str(cookies_path)])
|
||
|
|
command.append(video.vk_video_url)
|
||
|
|
|
||
|
|
video.status = "downloading"
|
||
|
|
session.commit()
|
||
|
|
result = subprocess.run(command, capture_output=True, text=True, check=False, timeout=3600)
|
||
|
|
if result.returncode != 0:
|
||
|
|
video.status = "failed"
|
||
|
|
video.error_message = result.stderr[-4000:]
|
||
|
|
session.commit()
|
||
|
|
raise RuntimeError(result.stderr)
|
||
|
|
|
||
|
|
mp4_files = sorted(target_dir.glob("*.mp4"))
|
||
|
|
jpg_files = sorted(target_dir.glob("*.jpg"))
|
||
|
|
video.local_video_path = str(mp4_files[0]) if mp4_files else None
|
||
|
|
video.local_cover_path = str(jpg_files[0]) if jpg_files else None
|
||
|
|
video.status = "downloaded"
|
||
|
|
session.commit()
|
||
|
|
upload_video_to_ok.delay(video.id)
|
||
|
|
return "downloaded"
|
||
|
|
|
||
|
|
|
||
|
|
@celery_app.task(bind=True, autoretry_for=(Exception,), retry_backoff=True, retry_kwargs={"max_retries": 2})
|
||
|
|
def upload_video_to_ok(self, video_id: int) -> str:
|
||
|
|
init_db()
|
||
|
|
with SessionLocal() as session:
|
||
|
|
video = session.get(Video, video_id)
|
||
|
|
if video is None:
|
||
|
|
return "missing"
|
||
|
|
if video.ok_video_id:
|
||
|
|
return "uploaded"
|
||
|
|
canonical_video = canonical_video_for_upload(session, video)
|
||
|
|
if canonical_video.id != video.id:
|
||
|
|
if canonical_video.ok_video_id:
|
||
|
|
waiting_posts = attach_ok_video_to_duplicate_rows(session, canonical_video, canonical_video.ok_video_id)
|
||
|
|
session.commit()
|
||
|
|
for post_id in waiting_posts:
|
||
|
|
publish_post_to_ok.delay(post_id)
|
||
|
|
return "reused_duplicate"
|
||
|
|
queue_video_if_needed(canonical_video)
|
||
|
|
return "duplicate_waiting"
|
||
|
|
|
||
|
|
lock_id = str(uuid.uuid4())
|
||
|
|
locked = session.query(Video).filter(
|
||
|
|
Video.id == video_id,
|
||
|
|
Video.ok_video_id.is_(None),
|
||
|
|
Video.upload_lock.is_(None),
|
||
|
|
).update(
|
||
|
|
{
|
||
|
|
Video.upload_lock: lock_id,
|
||
|
|
Video.status: "ok_uploading",
|
||
|
|
Video.error_message: None,
|
||
|
|
},
|
||
|
|
synchronize_session=False,
|
||
|
|
)
|
||
|
|
session.commit()
|
||
|
|
if not locked:
|
||
|
|
return "upload_locked"
|
||
|
|
video = session.get(Video, video_id)
|
||
|
|
if video is not None:
|
||
|
|
session.refresh(video)
|
||
|
|
if video is None or video.upload_lock != lock_id or video.ok_video_id:
|
||
|
|
return "upload_locked"
|
||
|
|
if not video.local_video_path:
|
||
|
|
video.status = "pending"
|
||
|
|
video.upload_lock = None
|
||
|
|
session.commit()
|
||
|
|
download_vk_video.delay(video.id)
|
||
|
|
return "download_queued"
|
||
|
|
|
||
|
|
video_path = Path(video.local_video_path)
|
||
|
|
if not video_path.exists():
|
||
|
|
video.status = "pending"
|
||
|
|
video.error_message = f"Local video file is missing: {video.local_video_path}"
|
||
|
|
video.upload_lock = None
|
||
|
|
session.commit()
|
||
|
|
download_vk_video.delay(video.id)
|
||
|
|
return "download_queued"
|
||
|
|
|
||
|
|
try:
|
||
|
|
cover_path = Path(video.local_cover_path) if video.local_cover_path else None
|
||
|
|
ok_video_id = upload_video_to_group(
|
||
|
|
settings,
|
||
|
|
video_path,
|
||
|
|
video.title,
|
||
|
|
video.description,
|
||
|
|
cover_path=cover_path,
|
||
|
|
publish_to_group_video=should_publish_to_group_video(video),
|
||
|
|
)
|
||
|
|
except Exception as exc:
|
||
|
|
video.status = "failed"
|
||
|
|
video.error_message = str(exc)
|
||
|
|
video.upload_lock = None
|
||
|
|
session.commit()
|
||
|
|
raise
|
||
|
|
|
||
|
|
video.ok_video_id = ok_video_id
|
||
|
|
video.upload_lock = None
|
||
|
|
video.status = "ok_uploaded"
|
||
|
|
|
||
|
|
waiting_posts = attach_ok_video_to_duplicate_rows(session, video, ok_video_id)
|
||
|
|
|
||
|
|
session.commit()
|
||
|
|
|
||
|
|
for post_id in waiting_posts:
|
||
|
|
publish_post_to_ok.delay(post_id)
|
||
|
|
return "uploaded"
|
||
|
|
|
||
|
|
|
||
|
|
@celery_app.task(bind=True)
|
||
|
|
def publish_post_to_ok(self, post_id: int) -> str:
|
||
|
|
init_db()
|
||
|
|
with SessionLocal() as session:
|
||
|
|
post = session.get(Post, post_id)
|
||
|
|
if post is None:
|
||
|
|
return "missing"
|
||
|
|
if post.ok_topic_id:
|
||
|
|
return "already_published"
|
||
|
|
if post.status in {"published", "published_edit_failed", "moment_failed"}:
|
||
|
|
return "already_published"
|
||
|
|
lock_id = str(uuid.uuid4())
|
||
|
|
locked = session.query(Post).filter(
|
||
|
|
Post.id == post_id,
|
||
|
|
Post.ok_topic_id.is_(None),
|
||
|
|
Post.publish_lock.is_(None),
|
||
|
|
).update(
|
||
|
|
{
|
||
|
|
Post.publish_lock: lock_id,
|
||
|
|
Post.status: "publishing",
|
||
|
|
Post.error_message: None,
|
||
|
|
},
|
||
|
|
synchronize_session=False,
|
||
|
|
)
|
||
|
|
session.commit()
|
||
|
|
if not locked:
|
||
|
|
return "publish_locked"
|
||
|
|
post = session.get(Post, post_id)
|
||
|
|
if post is not None:
|
||
|
|
session.refresh(post)
|
||
|
|
if post is None or post.publish_lock != lock_id or post.ok_topic_id:
|
||
|
|
return "publish_locked"
|
||
|
|
post.status = "publishing"
|
||
|
|
post.error_message = None
|
||
|
|
session.commit()
|
||
|
|
|
||
|
|
try:
|
||
|
|
media_items = sorted(post.media, key=lambda item: item.sort_order)
|
||
|
|
apply_uploaded_video_fallbacks(session, media_items)
|
||
|
|
video_error = failed_post_video_message(session, media_items)
|
||
|
|
if video_error:
|
||
|
|
post.status = "failed"
|
||
|
|
post.publish_lock = None
|
||
|
|
post.error_message = video_error
|
||
|
|
session.commit()
|
||
|
|
return "video_failed"
|
||
|
|
if not all_post_videos_ready(session, media_items):
|
||
|
|
post.status = "waiting_video"
|
||
|
|
post.publish_lock = None
|
||
|
|
post.error_message = "Waiting for OK video upload"
|
||
|
|
session.commit()
|
||
|
|
return "waiting_video"
|
||
|
|
|
||
|
|
ok_media: list[dict] = []
|
||
|
|
text = normalize_post_text(post.text)
|
||
|
|
if text:
|
||
|
|
ok_media.extend(split_text_media_blocks(text))
|
||
|
|
ok_media.extend(video_media_items(media_items))
|
||
|
|
|
||
|
|
for item in media_items:
|
||
|
|
if item.media_type != "photo" or not item.source_url:
|
||
|
|
continue
|
||
|
|
local_path = Path(settings.storage_dir) / "photos" / str(post.id) / f"{item.id}.jpg"
|
||
|
|
download_file(item.source_url, local_path)
|
||
|
|
token = upload_photo_to_group(settings, local_path)
|
||
|
|
item.local_path = str(local_path)
|
||
|
|
item.ok_media_id = token
|
||
|
|
item.status = "uploaded"
|
||
|
|
ok_media.append({"type": "photo", "list": [{"id": token}]})
|
||
|
|
session.commit()
|
||
|
|
|
||
|
|
if not ok_media:
|
||
|
|
post.status = "skipped"
|
||
|
|
post.publish_lock = None
|
||
|
|
post.error_message = "Post has no publishable media"
|
||
|
|
session.commit()
|
||
|
|
return "skipped"
|
||
|
|
|
||
|
|
attachment = {"media": ok_media}
|
||
|
|
result = post_group_mediatopic(settings, attachment)
|
||
|
|
post.ok_topic_id = topic_id_from_result(result)
|
||
|
|
post.status = "published"
|
||
|
|
post.publish_lock = None
|
||
|
|
post.published_at = datetime.utcnow()
|
||
|
|
session.commit()
|
||
|
|
|
||
|
|
edited_media = []
|
||
|
|
for media in ok_media:
|
||
|
|
if media.get("type") == "text":
|
||
|
|
media_text = str(media.get("text") or "")
|
||
|
|
if media.get("text_tokens"):
|
||
|
|
edited_media.append(media)
|
||
|
|
elif media_text:
|
||
|
|
edited_media.extend(split_text_media_blocks(media_text))
|
||
|
|
else:
|
||
|
|
edited_media.append(media)
|
||
|
|
edited_media.append(build_school_quote_media())
|
||
|
|
|
||
|
|
try:
|
||
|
|
edit_mediatopic(settings, post.ok_topic_id, {"media": edited_media})
|
||
|
|
except (httpx.HTTPError, OkApiError) as exc:
|
||
|
|
post.status = "published_edit_failed"
|
||
|
|
post.publish_lock = None
|
||
|
|
post.error_message = str(exc)[-4000:]
|
||
|
|
session.commit()
|
||
|
|
logger.exception("OK post was published but quote edit failed for post_id=%s", post.id)
|
||
|
|
return "published_edit_failed"
|
||
|
|
|
||
|
|
try:
|
||
|
|
publish_moment_for_post(post, media_items)
|
||
|
|
except (httpx.HTTPError, OkApiError, OSError) as exc:
|
||
|
|
logger.exception("OK moment publishing failed for post_id=%s: %s", post.id, exc)
|
||
|
|
|
||
|
|
session.commit()
|
||
|
|
return "published"
|
||
|
|
except (httpx.HTTPError, OkApiError, OSError) as exc:
|
||
|
|
post.status = "failed"
|
||
|
|
post.publish_lock = None
|
||
|
|
post.error_message = str(exc)[-4000:]
|
||
|
|
session.commit()
|
||
|
|
raise
|
||
|
|
|
||
|
|
|
||
|
|
@celery_app.task
|
||
|
|
def recover_queued_work() -> str:
|
||
|
|
init_db()
|
||
|
|
recovered = 0
|
||
|
|
with SessionLocal() as session:
|
||
|
|
queued_events = (
|
||
|
|
session.query(VkEvent)
|
||
|
|
.filter(VkEvent.status == "queued")
|
||
|
|
.order_by(VkEvent.id)
|
||
|
|
.limit(20)
|
||
|
|
.all()
|
||
|
|
)
|
||
|
|
queued_posts = (
|
||
|
|
session.query(Post)
|
||
|
|
.filter(Post.status.in_(["queued", "ok_publish_pending", "waiting_video"]))
|
||
|
|
.order_by(Post.id)
|
||
|
|
.limit(20)
|
||
|
|
.all()
|
||
|
|
)
|
||
|
|
event_ids = [event.id for event in queued_events]
|
||
|
|
post_ids = [post.id for post in queued_posts]
|
||
|
|
|
||
|
|
for event_id in event_ids:
|
||
|
|
process_vk_event.delay(event_id)
|
||
|
|
recovered += 1
|
||
|
|
for post_id in post_ids:
|
||
|
|
publish_post_to_ok.delay(post_id)
|
||
|
|
recovered += 1
|
||
|
|
return f"recovered:{recovered}"
|