feat: P2V 파이프라인 연동 및 좋아요·댓글·공유 지원

- 무빙 포스터(p2v_video)·롱컷(p2v_playreel) 파이프라인과 워커, 갤러리·내 콘텐츠 노출
- 좋아요·댓글: comment/video_reaction에 p2v_playreel_id 추가, 종류별 CHECK 확장
- P2V 소프트 삭제(is_deleted), queued/running 삭제 차단
- 공개 상세·공유 OG 페이지 추가
- 삭제된 부모 댓글이 목록에서 사라지던 has_live_reply 서브쿼리 버그 수정
- 마이그레이션: migration_2026-10-15_p2v_reactions.sql
This commit is contained in:
skkim committed 2026-10-15 10:42:30 +09:00
1 parent bb1ea12958
commit b16d4a8f1b
126 files changed
+6921 -62

No files matched your search

+15 -7
View File
@@ -12,6 +12,8 @@ from sqlalchemy import delete, insert, tuple_
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.like_cache import (
CT_P2V_PLAYREEL,
CT_P2V_VIDEO,
CT_SSUL,
CT_VIDEO,
commit_dirty_processing,
@@ -19,7 +21,7 @@ from app.database.like_cache import (
is_user_liked,
)
from app.database.session import get_session
# 썰박스 좋아요도 같은 Redis write-behind 큐 + **같은 테이블**(video_reaction)을
# 썰박스·P2V 좋아요도 같은 Redis write-behind 큐 + **같은 테이블**(video_reaction)을
# 쓰므로 여기서 함께 플러시한다. 큐가 하나라 스케줄러를 늘릴 필요가 없다.
from app.video.models import VideoReaction
from config import internal_settings
@@ -59,12 +61,18 @@ async def flush_reactions(
logger.info(f"[REACTION_FLUSH] START - dirty 항목 {len(entries)}건")
# 두 종류가 **같은 테이블**(video_reaction)에 들어간다. 대상 컬럼만 다르다.
# ADO2 는 video_id, 썰박스는 content_id 를 채운다(나머지는 NULL, CHECK 로 강제).
id_col_of = {CT_VIDEO: "video_id", CT_SSUL: "content_id"}
# 모든 종류가 **같은 테이블**(video_reaction)에 들어간다. 대상 컬럼만 다르다.
# 종류마다 자기 컬럼만 채운다(나머지는 NULL, CHECK 로 정확히 하나를 강제).
id_col_of = {
CT_VIDEO: "video_id",
CT_SSUL: "content_id",
CT_P2V_VIDEO: "p2v_video_id",
CT_P2V_PLAYREEL: "p2v_playreel_id",
}
id_cols = tuple(id_col_of.values())
adds: list[dict] = []
# (컬럼명, 대상 id, user_uuid) — 삭제는 컬럼이 달라 종류별로 묶어야 한다
dels: dict[str, list[tuple[int, str]]] = {"video_id": [], "content_id": []}
dels: dict[str, list[tuple[int, str]]] = {col: [] for col in id_cols}
# Redis 현재 상태 기준으로 add / delete 분류
for ctype, content_id, user_uuid in entries:
@@ -87,10 +95,10 @@ async def flush_reactions(
# 부분 반영이 나면 Redis processing SET 이 남아 다음 회차에 재시도되는데,
# INSERT IGNORE + UNIQUE 로 멱등이라 중복 반영은 안전하다.
#
# ⚠️ adds 는 종류별로 키가 달라(video_id vs content_id) 한 번의
# ⚠️ adds 는 종류별로 키가 달라(video_id, content_id, p2v_*_id) 한 번의
# `values(adds)` 로 묶으면 안 된다 — SQLAlchEmy 가 첫 dict 의 키로
# 컬럼 목록을 정하므로 다른 종류의 값이 누락된다. 종류별로 나눠 실행한다.
for id_col in ("video_id", "content_id"):
for id_col in id_cols:
rows = [a for a in adds if id_col in a]
if rows:
await session.execute(
+14 -3
View File
@@ -44,6 +44,11 @@ from app.database.like_cache import (
from app.credit.exceptions import InsufficientCreditError
from app.credit.services.credit_service import deduct_credit_for_job
from app.ssulbox.constants import JOB_TYPE_VIDEO as CREDIT_JOB_TYPE_VIDEO
from app.p2v.services.public_content import (
P2V_TYPES,
REACTION_COLUMN,
public_exists_query,
)
from app.ssulbox.models import SsulContent
from app.utils.logger import get_logger
from app.video.models import Video, VideoReaction
@@ -1055,14 +1060,17 @@ async def get_all_videos(
)
async def toggle_like(
video_id: int,
type: Literal["video", "ssul"] = Query(
type: Literal["video", "ssul", "p2v_video", "p2v_playreel"] = Query(
default="video",
description="콘텐츠 종류. video.id 와 ssul_content.id 가 겹치므로 반드시 함께 보낼 것",
description=(
"콘텐츠 종류 (video: ADO2 영상, ssul: 썰박스, p2v_video: 무빙 포스터, "
"p2v_playreel: 롱컷). id 가 종류별로 겹치므로 반드시 함께 보낼 것"
),
),
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
) -> LikeToggleResponse:
"""영상/썰박스 좋아요를 토글합니다.
"""영상/썰박스/P2V 좋아요를 토글합니다.
Write-Behind 패턴:
1. Redis user-set / count를 즉시 원자적으로 업데이트 (Lua script)
@@ -1088,6 +1096,9 @@ async def toggle_like(
)
# DB backfill 시 반응 행을 찾는 컬럼 — 썰박스 행은 content_id 가 채워져 있다
target_col = VideoReaction.content_id
elif type in P2V_TYPES:
exists_q = public_exists_query(type, video_id)
target_col = REACTION_COLUMN[type]
else:
exists_q = select(Video.id).where(
Video.id == video_id,
+29 -6
View File
@@ -217,28 +217,39 @@ class VideoReaction(Base):
사용자가 영상에 반응(현재는 좋아요)을 남기면 생성, 다시 누르면 삭제(토글).
향후 reaction_type 컬럼 추가로 다양한 반응 종류 확장 가능.
**ADO2 영상과 썰박스 콘텐츠를 모두 담는다.** 대상은 `video_id` 또는 `content_id`
중 **정확히 하나**만 채워지며 DB `CHECK` 로 강제한다.
**ADO2 영상·썰박스·P2V(무빙 포스터·롱컷)를 모두 담는다.** 대상은 `video_id`,
`content_id`, `p2v_video_id`, `p2v_playreel_id` 중 **정확히 하나**만 채워지며
DB `CHECK` 로 강제한다. (DB 에는 옛 `p2v_poster_id` 도 남아 CHECK 에 포함돼 있으나
대응 테이블이 모델에 없어 여기서는 매핑하지 않는다.)
1인 1회 보장은 유니크 두 개로 나눠서 한다. MySQL 은 NULL 을 서로 다른 값으로
취급하므로, 썰박스 행(video_id IS NULL)이 아무리 많아도
1인 1회 보장은 종류별 유니크로 나눠서 한다. MySQL 은 NULL 을 서로 다른 값으로
취급하므로, 다른 종류 행(video_id IS NULL)이 아무리 많아도
`uq_video_reaction_user_video` 에 걸리지 않는다 — 각자 자기 유니크만 지킨다.
"""
__tablename__ = "video_reaction"
__table_args__ = (
CheckConstraint(
"(video_id IS NULL) <> (content_id IS NULL)",
"(video_id IS NOT NULL) + (content_id IS NOT NULL) "
"+ (p2v_video_id IS NOT NULL) + (p2v_playreel_id IS NOT NULL) = 1",
name="ck_video_reaction_one_target",
),
UniqueConstraint("user_uuid", "video_id", name="uq_video_reaction_user_video"),
UniqueConstraint(
"user_uuid", "content_id", name="uq_video_reaction_user_content"
),
UniqueConstraint(
"user_uuid", "p2v_video_id", name="uq_video_reaction_user_p2v_video"
),
UniqueConstraint(
"user_uuid", "p2v_playreel_id", name="uq_video_reaction_user_p2v_playreel"
),
Index("idx_video_reaction_video_id", "video_id"),
# 카운트 집계가 content_id 로 묶으므로 선행 컬럼 인덱스가 필요하다
# (유니크는 user_uuid 가 앞이라 이 용도로 못 쓴다).
Index("idx_video_reaction_content_id", "content_id"),
Index("idx_video_reaction_p2v_video_id", "p2v_video_id"),
Index("idx_video_reaction_p2v_playreel_id", "p2v_playreel_id"),
Index("idx_video_reaction_user_uuid", "user_uuid"),
{
"mysql_engine": "InnoDB",
@@ -250,7 +261,7 @@ class VideoReaction(Base):
id: Mapped[int] = mapped_column(
Integer, primary_key=True, autoincrement=True, comment="고유 식별자"
)
# 대상은 아래 둘 중 **정확히 하나**만 채워진다 (ck_video_reaction_one_target).
# 대상은 아래 넷 중 **정확히 하나**만 채워진다 (ck_video_reaction_one_target).
video_id: Mapped[Optional[int]] = mapped_column(
Integer,
ForeignKey("video.id", ondelete="CASCADE"),
@@ -264,6 +275,18 @@ class VideoReaction(Base):
nullable=True,
comment="썰박스 콘텐츠 id (ADO2 반응이면 NULL)",
)
p2v_video_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("p2v_video.id", ondelete="CASCADE"),
nullable=True,
comment="무빙 포스터 id (다른 종류 반응이면 NULL)",
)
p2v_playreel_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("p2v_playreel.id", ondelete="CASCADE"),
nullable=True,
comment="롱컷 id (다른 종류 반응이면 NULL)",
)
user_uuid: Mapped[str] = mapped_column(
String(36),
ForeignKey("user.user_uuid", ondelete="CASCADE"),
+4 -4
View File
@@ -158,9 +158,9 @@ class VideoListItem(BaseModel):
# **`(type, video_id)` 쌍**으로 다뤄야 한다.
# 특히 `DELETE /archive/videos/{id}` 는 `Video.id` 로 지우므로,
# 썰박스 항목의 id 를 그대로 넘기면 **엉뚱한 ADO2 영상이 삭제된다.**
type: Literal["video", "ssul"] = Field(
type: Literal["video", "ssul", "p2v_video", "p2v_playreel"] = Field(
default="video",
description="콘텐츠 종류 (video: ADO2 영상, ssul: 썰박스)",
description="콘텐츠 종류 (video: ADO2 영상, ssul: 썰박스, p2v_video: 무빙 포스터, p2v_playreel: 롱컷)",
)
video_id: int = Field(..., description="콘텐츠 고유 ID (type 안에서만 유일)")
store_name: Optional[str] = Field(None, description="업체명")
@@ -193,9 +193,9 @@ class VideoThumbnailItem(BaseModel):
# ⚠️ `video_id` 는 종류 안에서만 유일하다. `video.id` 와 `ssul_content.id` 가
# **둘 다 1부터 시작**하므로 식별자는 반드시 `(type, video_id)` 쌍으로 다뤄야 한다.
# 한 곳이라도 id 만 쓰면 다른 종류의 콘텐츠가 열린다.
type: Literal["video", "ssul"] = Field(
type: Literal["video", "ssul", "p2v_video", "p2v_playreel"] = Field(
default="video",
description="콘텐츠 종류 (video: ADO2 영상, ssul: 썰박스). video_id 와 쌍으로 식별한다",
description="콘텐츠 종류 (video: ADO2 영상, ssul: 썰박스, p2v_video: 무빙 포스터, p2v_playreel: 롱컷). video_id 와 쌍으로 식별한다",
)
video_id: int = Field(..., description="콘텐츠 고유 ID (type 안에서만 유일)")
store_name: str = Field(..., description="업체명")
+38
View File
@@ -150,6 +150,44 @@ def build_ssul_share_html(
)
#: P2V 종류 → (이름이 없을 때 쓰는 제목, 프론트 상세 경로 접두사).
#: 접두사는 공유 API 와 같다(썰박스 `/ssul/share/{id}` → `/ssul/{id}` 와 같은 규칙).
P2V_SHARE_META = {
"p2v_video": ("ADO2 무빙 포스터", "/p2v/f1"),
"p2v_playreel": ("ADO2 롱컷", "/p2v/playreel"),
}
@dataclass(frozen=True, slots=True)
class P2vShareData:
"""공유 페이지에 필요한 P2V 콘텐츠 정보."""
ctype: str
content_id: int
poster_url: str | None
name: str | None = None
def build_p2v_share_html(
data: P2vShareData,
*,
share_url: str,
frontend_base_url: str,
configured_default_image_url: str = "",
) -> str:
"""P2V OG 메타데이터와 상세 화면 이동 기능을 포함한 HTML을 생성합니다."""
fallback_title, path_prefix = P2V_SHARE_META[data.ctype]
return _build_share_html(
detail_path=f"{path_prefix}/{data.content_id}",
poster_url=data.poster_url,
title=_share_title(data.name, fallback_title, fallback_store=fallback_title),
description=_share_description(None),
share_url=share_url,
frontend_base_url=frontend_base_url,
configured_default_image_url=configured_default_image_url,
)
def _build_share_html(
*,
detail_path: str,
+127 -10
View File
@@ -27,7 +27,7 @@ from dataclasses import dataclass
from datetime import datetime
from typing import Literal, Optional
from sqlalchemy import Select, func, literal, or_, select, union_all
from sqlalchemy import Select, String, false, func, literal, or_, select, union_all
from sqlalchemy.ext.asyncio import AsyncSession
from app.comment.models import Comment
@@ -40,11 +40,21 @@ from app.database.like_cache import (
mset_like_counts,
)
from app.home.models import Project
from app.p2v.constants import JOB_TYPE_PLAYREEL, JOB_TYPE_VIDEO
from app.p2v.models import PlayreelTask, PosterAliveTask
from app.p2v.worker.artifact import THUMBNAIL, artifact_url
from app.p2v.worker.playreel import PIPELINE as PLAYREEL_PIPELINE
from app.ssulbox.models import SsulContent
from app.utils.address_parser import SIDO_CITIES, SIDO_SEARCH_ALIASES
from app.video.models import Video, VideoReaction
from config import p2v_settings
ContentType = Literal["video", "ssul"]
ContentType = Literal["video", "ssul", "p2v_video", "p2v_playreel"]
#: P2V 종류. 좋아요·댓글은 `video_reaction.p2v_*_id` / `comment.p2v_*_id` 에 쌓인다.
#: 종류 문자열은 like_cache 의 ctype 과 같다.
CT_P2V_VIDEO = JOB_TYPE_VIDEO
CT_P2V_PLAYREEL = JOB_TYPE_PLAYREEL
#: 정렬 가능한 키. 그 외 값은 created_at 으로 떨어진다.
SORT_CREATED = "created_at"
@@ -124,6 +134,24 @@ def _ssul_comment_subq():
)
def _p2v_like_subq(ctype: str, model):
return (
select(func.count(VideoReaction.id))
.where(_reaction_target(ctype) == model.id)
.correlate(model)
.scalar_subquery()
)
def _p2v_comment_subq(ctype: str, model):
return (
select(func.count(Comment.id))
.where(_comment_target(ctype) == model.id, Comment.is_deleted.is_(False))
.correlate(model)
.scalar_subquery()
)
# ──────────────────────────────────────────────
# 필터
# ──────────────────────────────────────────────
@@ -181,6 +209,19 @@ def _ssul_where(store_name: Optional[str], region: Optional[str]) -> list:
return clauses
def _p2v_where(model, video_col, store_name: Optional[str], region: Optional[str],
user_uuid: Optional[str] = None) -> list:
clauses = [model.status == "done", model.is_deleted.is_(False), video_col.is_not(None)]
if user_uuid:
clauses.append(model.user_id == user_uuid)
if store_name:
clauses.append(model.name.ilike(f"%{store_name}%"))
if region:
# P2V 는 지역 정보가 없다. 지역 검색에는 걸리지 않는다
clauses.append(false())
return clauses
# ──────────────────────────────────────────────
# 브랜치
# ──────────────────────────────────────────────
@@ -228,6 +269,38 @@ def _ssul_branch(where: list, sort_by: str) -> Select:
return select(*cols).where(*where)
def _p2v_branch(ctype: str, model, video_col, poster_col, sort_by: str) -> Select:
"""무빙 포스터·롱컷 공용. 포스터 컬럼이 없는 종류(롱컷)는 NULL 로 두고 `_to_items` 가 채운다."""
cols = [
literal(ctype).label("ctype"),
model.id.label("cid"),
model.name.label("store_name"),
literal(None, String).label("region"),
video_col.label("movie_url"),
model.created_at.label("created_at"),
literal("").label("task_id"),
(poster_col if poster_col is not None else literal(None, String)).label("poster_url"),
model.name.label("title"),
literal(None, String).label("description"),
literal(None, String).label("hashtags"),
]
if sort_by == SORT_LIKE:
cols.append(_p2v_like_subq(ctype, model).label("sort_value"))
elif sort_by == SORT_COMMENT:
cols.append(_p2v_comment_subq(ctype, model).label("sort_value"))
return select(*cols)
def _p2v_video_branch(where: list, sort_by: str) -> Select:
return _p2v_branch(CT_P2V_VIDEO, PosterAliveTask, PosterAliveTask.video_url,
PosterAliveTask.thumbnail_url, sort_by).where(*where)
def _p2v_playreel_branch(where: list, sort_by: str) -> Select:
return _p2v_branch(CT_P2V_PLAYREEL, PlayreelTask, PlayreelTask.video_url,
None, sort_by).where(*where)
# ──────────────────────────────────────────────
# 페이지 확정 후 집계
# ──────────────────────────────────────────────
@@ -235,14 +308,24 @@ def _ssul_branch(where: list, sort_by: str) -> Select:
def _reaction_target(ctype: str):
"""반응 테이블에서 이 종류가 쓰는 대상 컬럼.
`comment` / `video_reaction` 은 두 종류를 함께 담고 `video_id` 또는 `content_id`
중 하나만 채운다(CHECK 로 강제). 어느 컬럼을 볼지만 갈아끼우면 된다.
`comment` / `video_reaction` 은 모든 종류를 함께 담고 종류별 컬럼 중 하나만
채운다(CHECK 로 강제). 어느 컬럼을 볼지만 갈아끼우면 된다.
"""
return VideoReaction.video_id if ctype == CT_VIDEO else VideoReaction.content_id
return {
CT_VIDEO: VideoReaction.video_id,
CT_SSUL: VideoReaction.content_id,
CT_P2V_VIDEO: VideoReaction.p2v_video_id,
CT_P2V_PLAYREEL: VideoReaction.p2v_playreel_id,
}[ctype]
def _comment_target(ctype: str):
return Comment.video_id if ctype == CT_VIDEO else Comment.content_id
return {
CT_VIDEO: Comment.video_id,
CT_SSUL: Comment.content_id,
CT_P2V_VIDEO: Comment.p2v_video_id,
CT_P2V_PLAYREEL: Comment.p2v_playreel_id,
}[ctype]
async def _like_counts_for(
@@ -319,7 +402,7 @@ async def enrich(
user_uuid: Optional[str],
) -> list[UnifiedItem]:
"""페이지에 실린 항목에만 좋아요·댓글 수와 내 좋아요 여부를 채운다."""
for ctype in (CT_VIDEO, CT_SSUL):
for ctype in (CT_VIDEO, CT_SSUL, CT_P2V_VIDEO, CT_P2V_PLAYREEL):
ids = [it.id for it in items if it.ctype == ctype]
if not ids:
continue
@@ -358,6 +441,8 @@ async def fetch_gallery(
"""전체 갤러리(`/video/all`). (항목, 전체 개수) 반환."""
v_where = _video_where(store_name, region)
s_where = _ssul_where(store_name, region)
p_video_where = _p2v_where(PosterAliveTask, PosterAliveTask.video_url, store_name, region)
p_reel_where = _p2v_where(PlayreelTask, PlayreelTask.video_url, store_name, region)
# 전체 개수는 브랜치별로 센다 — UNION 을 만들어 세는 것보다 싸다.
total = (
@@ -374,9 +459,24 @@ async def fetch_gallery(
)
).scalar() or 0
if p2v_settings.P2V_ENABLED:
total += (
await session.execute(
select(func.count(PosterAliveTask.id)).where(*p_video_where)
)
).scalar() or 0
total += (
await session.execute(
select(func.count(PlayreelTask.id)).where(*p_reel_where)
)
).scalar() or 0
branches = [_video_branch(v_where, sort_by)]
if include_ssul:
branches.append(_ssul_branch(s_where, sort_by))
if p2v_settings.P2V_ENABLED:
branches.append(_p2v_video_branch(p_video_where, sort_by))
branches.append(_p2v_playreel_branch(p_reel_where, sort_by))
u = union_all(*branches).subquery() if len(branches) > 1 else branches[0].subquery()
@@ -411,7 +511,9 @@ def _to_items(rows) -> list[UnifiedItem]:
movie_url=r.movie_url,
created_at=r.created_at,
task_id=r.task_id or "",
poster_url=r.poster_url,
# 롱컷의 정지컷은 컬럼이 아니라 정해진 경로에 있다
poster_url=(artifact_url(PLAYREEL_PIPELINE, r.cid, THUMBNAIL)
if r.ctype == CT_P2V_PLAYREEL else r.poster_url),
title=r.title,
description=r.description,
hashtags=list(r.hashtags) if r.hashtags else None,
@@ -459,16 +561,31 @@ async def fetch_my_contents(
SsulContent.video_url.is_not(None),
]
p_video_where = _p2v_where(PosterAliveTask, PosterAliveTask.video_url, None, None, user_uuid)
p_reel_where = _p2v_where(PlayreelTask, PlayreelTask.video_url, None, None, user_uuid)
total = ((await session.execute(
select(func.count(Video.id)).where(*v_where)
)).scalar() or 0) + ((await session.execute(
select(func.count(SsulContent.id)).where(*s_where)
)).scalar() or 0)
u = union_all(
branches = [
_video_branch(v_where, SORT_CREATED),
_ssul_branch(s_where, SORT_CREATED),
).subquery()
]
if p2v_settings.P2V_ENABLED:
total += ((await session.execute(
select(func.count(PosterAliveTask.id)).where(*p_video_where)
)).scalar() or 0) + ((await session.execute(
select(func.count(PlayreelTask.id)).where(*p_reel_where)
)).scalar() or 0)
branches += [
_p2v_video_branch(p_video_where, SORT_CREATED),
_p2v_playreel_branch(p_reel_where, SORT_CREATED),
]
u = union_all(*branches).subquery()
rows = (
await session.execute(