콘텐츠 공유 페이지 및 공유하기, 좋아요, 댓글 기능 추가
This commit is contained in:
1 parent
346b461e9c
commit
5f3e8ec341
27 files changed
+1546
-95
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
내부 전용 좋아요 반응 플러시 API
|
||||
|
||||
스케줄러가 1분마다 호출하여 Redis dirty SET의 좋아요 토글을 MySQL에 bulk write합니다.
|
||||
X-Internal-Secret 헤더로 인증합니다.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, status
|
||||
from sqlalchemy import delete, insert, tuple_
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.like_cache import (
|
||||
commit_dirty_processing,
|
||||
drain_dirty,
|
||||
is_user_liked,
|
||||
)
|
||||
from app.database.session import get_session
|
||||
from app.video.models import VideoReaction
|
||||
from config import internal_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/internal/video", tags=["Internal"])
|
||||
|
||||
|
||||
@router.post(
|
||||
"/reactions/flush",
|
||||
summary="[내부] 좋아요 반응 DB 플러시",
|
||||
description="스케줄러 서버에서 1분마다 호출하는 내부 전용 엔드포인트입니다. "
|
||||
"Redis dirty SET의 항목을 MySQL video_reaction 테이블에 bulk write합니다.",
|
||||
)
|
||||
async def flush_reactions(
|
||||
session: AsyncSession = Depends(get_session),
|
||||
x_internal_secret: str = Header(...),
|
||||
) -> dict:
|
||||
"""Redis dirty SET → MySQL bulk write.
|
||||
|
||||
1. drain_dirty(): dirty SET을 processing으로 RENAME 후 항목 조회
|
||||
2. 각 항목의 현재 Redis 상태(is_liked) 확인
|
||||
3. is_liked=True → INSERT IGNORE, is_liked=False → DELETE
|
||||
4. commit_dirty_processing(): processing SET 삭제
|
||||
"""
|
||||
if x_internal_secret != internal_settings.INTERNAL_SECRET_KEY:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Invalid internal secret",
|
||||
)
|
||||
|
||||
pairs = await drain_dirty()
|
||||
if not pairs:
|
||||
logger.info("[REACTION_FLUSH] dirty 항목 없음, 종료")
|
||||
return {"flushed": 0, "adds": 0, "dels": 0}
|
||||
|
||||
logger.info(f"[REACTION_FLUSH] START - dirty 항목 {len(pairs)}건")
|
||||
|
||||
adds: list[dict] = []
|
||||
dels: list[tuple[int, str]] = []
|
||||
|
||||
# Redis 현재 상태 기준으로 add / delete 분류
|
||||
for video_id, user_uuid in pairs:
|
||||
liked = await is_user_liked(video_id, user_uuid)
|
||||
if liked:
|
||||
adds.append({"video_id": video_id, "user_uuid": user_uuid})
|
||||
else:
|
||||
dels.append((video_id, user_uuid))
|
||||
|
||||
try:
|
||||
# Bulk INSERT IGNORE — UniqueConstraint 보장으로 멱등 처리
|
||||
if adds:
|
||||
await session.execute(
|
||||
insert(VideoReaction).prefix_with("IGNORE").values(adds)
|
||||
)
|
||||
|
||||
# Bulk DELETE
|
||||
if dels:
|
||||
await session.execute(
|
||||
delete(VideoReaction).where(
|
||||
tuple_(
|
||||
VideoReaction.video_id,
|
||||
VideoReaction.user_uuid,
|
||||
).in_(dels)
|
||||
)
|
||||
)
|
||||
|
||||
await session.commit()
|
||||
await commit_dirty_processing()
|
||||
|
||||
logger.info(
|
||||
f"[REACTION_FLUSH] SUCCESS - adds: {len(adds)}, dels: {len(dels)}"
|
||||
)
|
||||
return {"flushed": len(pairs), "adds": len(adds), "dels": len(dels)}
|
||||
|
||||
except Exception as e:
|
||||
await session.rollback()
|
||||
logger.error(f"[REACTION_FLUSH] EXCEPTION - error: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"플러시 실패: {str(e)}")
|
||||
@@ -14,28 +14,48 @@ Video API Router
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
from collections import defaultdict
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func, or_, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.session import get_session
|
||||
from app.user.dependencies.auth import get_current_user
|
||||
from app.dependencies.pagination import PaginationParams, get_pagination_params
|
||||
from app.user.dependencies.auth import get_current_user, get_current_user_optional
|
||||
from app.user.models import User
|
||||
from app.utils.pagination import PaginatedResponse
|
||||
from app.home.models import Image, Project, MarketingIntel, ImageTag
|
||||
from app.home.api.routers.v1.home import _extract_region_from_address
|
||||
from app.lyric.models import Lyric
|
||||
from app.song.models import Song, SongTimestamp
|
||||
from app.utils.creatomate import CreatomateService
|
||||
from app.utils.subtitles import SubtitleContentsGenerator
|
||||
|
||||
from app.comment.models import Comment
|
||||
from app.database.like_cache import (
|
||||
backfill_user_set,
|
||||
bulk_is_user_liked,
|
||||
get_like_count,
|
||||
get_like_counts,
|
||||
is_user_liked,
|
||||
is_user_set_exists,
|
||||
mark_dirty,
|
||||
mset_like_counts,
|
||||
set_like_count,
|
||||
toggle_like_atomic,
|
||||
)
|
||||
from app.utils.logger import get_logger
|
||||
from app.video.models import Video
|
||||
from app.video.models import Video, VideoReaction
|
||||
from app.video.schemas.video_schema import (
|
||||
DownloadVideoResponse,
|
||||
GenerateVideoResponse,
|
||||
LikeToggleResponse,
|
||||
PollingVideoResponse,
|
||||
VideoDetailResponse,
|
||||
VideoRenderData,
|
||||
VideoThumbnailItem,
|
||||
)
|
||||
from app.video.worker.video_task import download_and_upload_video_to_blob
|
||||
from app.video.services.video import get_image_tags_by_task_id
|
||||
@@ -147,42 +167,9 @@ async def generate_video(
|
||||
image_urls: list[str] = []
|
||||
|
||||
try:
|
||||
async with AsyncSessionLocal() as session:
|
||||
project_result = await session.execute(
|
||||
select(Project)
|
||||
.where(Project.task_id == task_id)
|
||||
.order_by(Project.created_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
project = project_result.scalar_one_or_none()
|
||||
|
||||
if not project:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 Project를 찾을 수 없습니다.",
|
||||
)
|
||||
|
||||
marketing_result = await session.execute(
|
||||
select(MarketingIntel).where(MarketingIntel.id == project.marketing_intelligence)
|
||||
)
|
||||
marketing_intelligence = marketing_result.scalar_one_or_none()
|
||||
|
||||
# subtitle 미완료 시 즉시 202 반환 — 클라이언트가 /lyric/subtitle/status/{task_id} 폴링 후 재시도
|
||||
if not marketing_intelligence.subtitle:
|
||||
logger.info(f"[generate_video] subtitle pending - task_id: {task_id}")
|
||||
return GenerateVideoResponse(
|
||||
success=False,
|
||||
status="subtitle_pending",
|
||||
task_id=task_id,
|
||||
creatomate_render_id=None,
|
||||
message="자막 생성이 아직 완료되지 않았습니다. /lyric/subtitle/status/{task_id}로 완료 확인 후 재요청하세요.",
|
||||
error_message=None,
|
||||
)
|
||||
|
||||
|
||||
# 세션을 명시적으로 열고 DB 작업 후 바로 닫음
|
||||
async with AsyncSessionLocal() as session:
|
||||
# ===== 순차 쿼리 실행: Project, Lyric, Song, Image =====
|
||||
# ===== 순차 쿼리 실행: Project, MarketingIntel, Lyric, Song, Image =====
|
||||
# Note: AsyncSession은 동일 세션에서 병렬 쿼리를 지원하지 않음
|
||||
|
||||
# Project 조회
|
||||
@@ -192,6 +179,44 @@ async def generate_video(
|
||||
.order_by(Project.created_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
project = project_result.scalar_one_or_none()
|
||||
if not project:
|
||||
logger.warning(f"[generate_video] Project NOT FOUND - task_id: {task_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 Project를 찾을 수 없습니다.",
|
||||
)
|
||||
project_id = project.id
|
||||
store_address = project.detail_region_info
|
||||
brand_name = project.store_name
|
||||
region = project.region
|
||||
|
||||
# MarketingIntel 조회
|
||||
marketing_result = await session.execute(
|
||||
select(MarketingIntel).where(MarketingIntel.id == project.marketing_intelligence)
|
||||
)
|
||||
marketing_intelligence: MarketingIntel = marketing_result.scalar_one_or_none()
|
||||
|
||||
# subtitle 미완료 시 즉시 반환 — Lyric/Song/Image 쿼리 전에 체크하여 불필요한 조회 방지
|
||||
# 클라이언트가 /lyric/subtitle/status/{task_id} 폴링 후 재시도
|
||||
if not marketing_intelligence.subtitle:
|
||||
logger.info(f"[generate_video] subtitle pending - task_id: {task_id}")
|
||||
return GenerateVideoResponse(
|
||||
success=False,
|
||||
status="subtitle_pending",
|
||||
task_id=task_id,
|
||||
creatomate_render_id=None,
|
||||
message="자막 생성이 아직 완료되지 않았습니다. /lyric/subtitle/status/{task_id}로 완료 확인 후 재요청하세요.",
|
||||
error_message=None,
|
||||
)
|
||||
|
||||
category_definition = marketing_intelligence.intel_result["market_positioning"]["category_definition"]
|
||||
target_keywords = marketing_intelligence.intel_result["target_keywords"]
|
||||
|
||||
brand_concept = ""
|
||||
for sp in marketing_intelligence.intel_result["selling_points"]:
|
||||
if "concept" in sp["english_category"].lower():
|
||||
brand_concept = sp["description"]
|
||||
|
||||
# Lyric 조회
|
||||
lyric_result = await session.execute(
|
||||
@@ -222,34 +247,6 @@ async def generate_video(
|
||||
f"elapsed: {(query_time - request_start) * 1000:.1f}ms"
|
||||
)
|
||||
|
||||
# ===== 결과 처리: Project =====
|
||||
project = project_result.scalar_one_or_none()
|
||||
if not project:
|
||||
logger.warning(
|
||||
f"[generate_video] Project NOT FOUND - task_id: {task_id}"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 Project를 찾을 수 없습니다.",
|
||||
)
|
||||
project_id = project.id
|
||||
store_address = project.detail_region_info
|
||||
brand_name = project.store_name
|
||||
region = project.region
|
||||
|
||||
marketing_result = await session.execute(
|
||||
select(MarketingIntel).where(MarketingIntel.id == project.marketing_intelligence)
|
||||
)
|
||||
marketing_intelligence : MarketingIntel = marketing_result.scalar_one_or_none()
|
||||
|
||||
category_definition= marketing_intelligence.intel_result["market_positioning"]["category_definition"]
|
||||
target_keywords=marketing_intelligence.intel_result["target_keywords"]
|
||||
|
||||
brand_concept = ""
|
||||
for sp in marketing_intelligence.intel_result["selling_points"]:
|
||||
if "concept" in sp["english_category"].lower():
|
||||
brand_concept = sp["description"]
|
||||
|
||||
# ===== 결과 처리: Lyric =====
|
||||
lyric = lyric_result.scalar_one_or_none()
|
||||
if not lyric:
|
||||
@@ -297,10 +294,19 @@ async def generate_video(
|
||||
)
|
||||
image_urls = [img.img_url for img in images]
|
||||
|
||||
# SongTimestamp 조회 (외부 API 호출 전 필요한 데이터이므로 1단계에서 수집)
|
||||
song_timestamp_result = await session.execute(
|
||||
select(SongTimestamp).where(
|
||||
SongTimestamp.suno_audio_id == song.suno_audio_id
|
||||
)
|
||||
)
|
||||
song_timestamp_list = song_timestamp_result.scalars().all()
|
||||
|
||||
logger.info(
|
||||
f"[generate_video] Data loaded - task_id: {task_id}, "
|
||||
f"project_id: {project_id}, lyric_id: {lyric_id}, "
|
||||
f"song_id: {song_id}, images: {len(image_urls)}"
|
||||
f"song_id: {song_id}, images: {len(image_urls)}, "
|
||||
f"timestamps: {len(song_timestamp_list)}"
|
||||
)
|
||||
|
||||
# ===== Video 테이블에 초기 데이터 저장 및 커밋 =====
|
||||
@@ -410,13 +416,6 @@ async def generate_video(
|
||||
|
||||
logger.debug(f"[generate_video] Duration extended - task_id: {task_id}")
|
||||
|
||||
song_timestamp_result = await session.execute(
|
||||
select(SongTimestamp).where(
|
||||
SongTimestamp.suno_audio_id == song.suno_audio_id
|
||||
)
|
||||
)
|
||||
song_timestamp_list = song_timestamp_result.scalars().all()
|
||||
|
||||
logger.debug(f"[generate_video] song_timestamp_list count: {len(song_timestamp_list)}")
|
||||
|
||||
for i, ts in enumerate(song_timestamp_list):
|
||||
@@ -678,7 +677,7 @@ async def get_video_status(
|
||||
import traceback
|
||||
|
||||
logger.error(
|
||||
f"[get_video_status] EXCEPTION - creatomate_render_id: {creatomate_render_id}, error: {e}"
|
||||
f"[get_video_status] EXCEPTION - creatomate_render_id: {creatomate_render_id}, error: {e}\n{traceback.format_exc()}"
|
||||
)
|
||||
return PollingVideoResponse(
|
||||
success=False,
|
||||
@@ -686,7 +685,7 @@ async def get_video_status(
|
||||
message="상태 조회에 실패했습니다.",
|
||||
render_data=None,
|
||||
raw_response=None,
|
||||
error_message=f"{type(e).__name__}: {e}\n{traceback.format_exc()}",
|
||||
error_message=f"{type(e).__name__}: {e}",
|
||||
)
|
||||
|
||||
|
||||
@@ -796,7 +795,7 @@ async def download_video(
|
||||
status="completed",
|
||||
message="영상 다운로드가 완료되었습니다.",
|
||||
store_name=project.store_name if project else None,
|
||||
region=project.region if project else None,
|
||||
region=project.region or _extract_region_from_address(project.detail_region_info) if project else None,
|
||||
task_id=task_id,
|
||||
result_movie_url=video.result_movie_url,
|
||||
created_at=video.created_at,
|
||||
@@ -810,3 +809,353 @@ async def download_video(
|
||||
message="영상 다운로드 조회에 실패했습니다.",
|
||||
error_message=str(e),
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/all",
|
||||
summary="ADO2 콘텐츠 - 전체 사용자 영상 갤러리",
|
||||
description="""
|
||||
## 개요
|
||||
모든 사용자가 생성 완료한 영상을 페이지네이션하여 반환합니다.
|
||||
|
||||
## 쿼리 파라미터
|
||||
- **page**: 페이지 번호 (1부터 시작, 기본값: 1)
|
||||
- **page_size**: 페이지당 데이터 수 (기본값: 10, 최대: 100)
|
||||
- **sort_by**: 정렬 기준 (created_at: 최신순, like_count: 좋아요순, comment_count: 댓글순, 기본값: created_at)
|
||||
- **order**: 정렬 방향 (desc: 내림차순, asc: 오름차순, 기본값: desc)
|
||||
- **store_name**: 업체명 검색 (부분 일치, 값이 있을 때만 전송)
|
||||
- **region**: 지역명 검색 (부분 일치, 값이 있을 때만 전송)
|
||||
""",
|
||||
response_model=PaginatedResponse[VideoThumbnailItem],
|
||||
responses={
|
||||
200: {"description": "갤러리 조회 성공"},
|
||||
500: {"description": "조회 실패"},
|
||||
},
|
||||
)
|
||||
async def get_all_videos(
|
||||
current_user: User | None = Depends(get_current_user_optional),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
pagination: PaginationParams = Depends(get_pagination_params),
|
||||
sort_by: str = Query(default="created_at", description="정렬 기준 (created_at, like_count, comment_count)"),
|
||||
order: str = Query(default="desc", description="정렬 방향 (desc, asc)"),
|
||||
store_name: str | None = Query(default=None, description="업체명 검색 (부분 일치)"),
|
||||
region: str | None = Query(default=None, description="지역명 검색 (부분 일치)"),
|
||||
) -> PaginatedResponse[VideoThumbnailItem]:
|
||||
"""전체 사용자의 완료된 영상 갤러리를 반환합니다."""
|
||||
logger.info(
|
||||
f"[get_all_videos] START - page: {pagination.page}, page_size: {pagination.page_size}, "
|
||||
f"sort_by: {sort_by}, order: {order}, store_name: {store_name}, region: {region}"
|
||||
)
|
||||
|
||||
try:
|
||||
offset = (pagination.page - 1) * pagination.page_size
|
||||
|
||||
where_clauses = [
|
||||
Video.status == "completed",
|
||||
Video.is_deleted == False, # noqa: E712
|
||||
Project.is_deleted == False, # noqa: E712
|
||||
Video.result_movie_url.is_not(None),
|
||||
]
|
||||
if store_name:
|
||||
where_clauses.append(Project.store_name.ilike(f"%{store_name}%"))
|
||||
if region:
|
||||
where_clauses.append(
|
||||
or_(
|
||||
Project.region.ilike(f"%{region}%"),
|
||||
Project.detail_region_info.ilike(f"%{region}%"),
|
||||
)
|
||||
)
|
||||
|
||||
count_q = (
|
||||
select(func.count(Video.id))
|
||||
.join(Project, Video.project_id == Project.id)
|
||||
.where(*where_clauses)
|
||||
)
|
||||
total = (await session.execute(count_q)).scalar() or 0
|
||||
|
||||
comment_count_subq = (
|
||||
select(func.count(Comment.id))
|
||||
.where(
|
||||
Comment.video_id == Video.id,
|
||||
Comment.is_deleted == False, # noqa: E712
|
||||
)
|
||||
.correlate(Video)
|
||||
.scalar_subquery()
|
||||
)
|
||||
|
||||
# like_count 정렬은 Redis 대신 서브쿼리로 처리 (ORDER BY에만 사용)
|
||||
like_count_subq_for_sort = (
|
||||
select(func.count(VideoReaction.id))
|
||||
.where(VideoReaction.video_id == Video.id)
|
||||
.correlate(Video)
|
||||
.scalar_subquery()
|
||||
)
|
||||
sort_col_map = {
|
||||
"like_count": like_count_subq_for_sort,
|
||||
"comment_count": comment_count_subq,
|
||||
"created_at": Video.created_at,
|
||||
}
|
||||
sort_col = sort_col_map.get(sort_by, Video.created_at)
|
||||
order_clause = sort_col.asc() if order == "asc" else sort_col.desc()
|
||||
|
||||
list_q = (
|
||||
select(
|
||||
Video,
|
||||
Project,
|
||||
comment_count_subq.label("comment_count"),
|
||||
)
|
||||
.join(Project, Video.project_id == Project.id)
|
||||
.where(*where_clauses)
|
||||
.order_by(order_clause)
|
||||
.offset(offset)
|
||||
.limit(pagination.page_size)
|
||||
)
|
||||
rows = (await session.execute(list_q)).all()
|
||||
|
||||
video_ids = [v.id for v, p, _ in rows]
|
||||
|
||||
# Redis mget으로 like_count 일괄 조회
|
||||
like_count_map = await get_like_counts(video_ids)
|
||||
|
||||
# 카운트 캐시 미스 보정
|
||||
missing_ids = [vid for vid, cnt in like_count_map.items() if cnt is None]
|
||||
if missing_ids:
|
||||
db_counts = (await session.execute(
|
||||
select(VideoReaction.video_id, func.count(VideoReaction.id))
|
||||
.where(VideoReaction.video_id.in_(missing_ids))
|
||||
.group_by(VideoReaction.video_id)
|
||||
)).all()
|
||||
db_found_ids = set()
|
||||
batch = {}
|
||||
for vid, cnt in db_counts:
|
||||
batch[vid] = cnt
|
||||
like_count_map[vid] = cnt
|
||||
db_found_ids.add(vid)
|
||||
await mset_like_counts(batch)
|
||||
for vid in missing_ids:
|
||||
if vid not in db_found_ids:
|
||||
like_count_map[vid] = 0
|
||||
|
||||
# is_liked_by_me: Redis user-set 기준, cold-start 시 DB backfill
|
||||
liked_map: dict[int, bool] = {}
|
||||
if current_user:
|
||||
raw_liked = await bulk_is_user_liked(video_ids, current_user.user_uuid)
|
||||
|
||||
# user-set이 없는(None) 영상 중 count > 0인 것만 backfill 필요
|
||||
needs_backfill = [
|
||||
vid for vid, liked in raw_liked.items()
|
||||
if liked is None and like_count_map.get(vid, 0) > 0
|
||||
]
|
||||
if needs_backfill:
|
||||
reaction_rows = (await session.execute(
|
||||
select(VideoReaction.video_id, VideoReaction.user_uuid)
|
||||
.where(VideoReaction.video_id.in_(needs_backfill))
|
||||
)).all()
|
||||
user_map: dict[int, list[str]] = defaultdict(list)
|
||||
for vid, uuid in reaction_rows:
|
||||
user_map[vid].append(uuid)
|
||||
for vid in needs_backfill:
|
||||
await backfill_user_set(vid, user_map.get(vid, []))
|
||||
|
||||
# backfill 후 재조회
|
||||
updated = await bulk_is_user_liked(needs_backfill, current_user.user_uuid)
|
||||
raw_liked.update(updated)
|
||||
|
||||
liked_map = {vid: bool(liked) for vid, liked in raw_liked.items()}
|
||||
|
||||
items = [
|
||||
VideoThumbnailItem(
|
||||
video_id=v.id,
|
||||
store_name=p.store_name,
|
||||
result_movie_url=v.result_movie_url,
|
||||
created_at=v.created_at,
|
||||
like_count=like_count_map.get(v.id) or 0,
|
||||
is_liked_by_me=liked_map.get(v.id, False),
|
||||
comment_count=comment_count or 0,
|
||||
)
|
||||
for v, p, comment_count in rows
|
||||
]
|
||||
|
||||
response = PaginatedResponse.create(
|
||||
items=items,
|
||||
total=total,
|
||||
page=pagination.page,
|
||||
page_size=pagination.page_size,
|
||||
)
|
||||
logger.info(f"[get_all_videos] SUCCESS - total: {total}, items: {len(items)}")
|
||||
return response
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[get_all_videos] EXCEPTION - error: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"갤러리 조회에 실패했습니다: {str(e)}")
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{video_id}/like",
|
||||
summary="영상 좋아요 토글",
|
||||
description="""
|
||||
## 개요
|
||||
영상에 좋아요를 토글합니다. 로그인 필수.
|
||||
|
||||
- 처음 호출: 좋아요 추가 (is_liked=true)
|
||||
- 다시 호출: 좋아요 취소 (is_liked=false)
|
||||
""",
|
||||
response_model=LikeToggleResponse,
|
||||
responses={
|
||||
200: {"description": "토글 성공"},
|
||||
401: {"description": "인증 실패"},
|
||||
404: {"description": "영상을 찾을 수 없음"},
|
||||
},
|
||||
)
|
||||
async def toggle_like(
|
||||
video_id: int,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> LikeToggleResponse:
|
||||
"""영상 좋아요를 토글합니다.
|
||||
|
||||
Write-Behind 패턴:
|
||||
1. Redis user-set / count를 즉시 원자적으로 업데이트 (Lua script)
|
||||
2. dirty SET에 표시 → 스케줄러가 1분마다 MySQL에 반영
|
||||
DB write가 없으므로 고트래픽에서도 응답 지연 없음.
|
||||
"""
|
||||
logger.info(f"[toggle_like] START - video_id: {video_id}, user: {current_user.user_uuid}")
|
||||
|
||||
try:
|
||||
# 영상 존재 확인 (DB read는 유지 — 404 처리 필수)
|
||||
video_result = await session.execute(
|
||||
select(Video).where(
|
||||
Video.id == video_id,
|
||||
Video.status == "completed",
|
||||
Video.is_deleted == False, # noqa: E712
|
||||
)
|
||||
)
|
||||
if video_result.scalar_one_or_none() is None:
|
||||
raise HTTPException(status_code=404, detail="영상을 찾을 수 없습니다.")
|
||||
|
||||
# Cold-start 보정: Redis에 데이터가 없으면 DB에서 backfill
|
||||
count = await get_like_count(video_id)
|
||||
if count is None:
|
||||
# 카운트와 user-set 모두 없음 → DB에서 전체 복구
|
||||
user_uuids = (await session.execute(
|
||||
select(VideoReaction.user_uuid)
|
||||
.where(VideoReaction.video_id == video_id)
|
||||
)).scalars().all()
|
||||
await backfill_user_set(video_id, list(user_uuids))
|
||||
await set_like_count(video_id, len(user_uuids))
|
||||
elif count > 0:
|
||||
if not await is_user_set_exists(video_id):
|
||||
# 카운트는 있지만 user-set이 증발한 경우 (부분 캐시 미스)
|
||||
user_uuids = (await session.execute(
|
||||
select(VideoReaction.user_uuid)
|
||||
.where(VideoReaction.video_id == video_id)
|
||||
)).scalars().all()
|
||||
await backfill_user_set(video_id, list(user_uuids))
|
||||
|
||||
# Lua 스크립트로 원자적 토글 (race condition 방지)
|
||||
is_liked, like_count = await toggle_like_atomic(video_id, current_user.user_uuid)
|
||||
|
||||
# dirty SET에 표시 → 스케줄러가 DB에 반영
|
||||
await mark_dirty(video_id, current_user.user_uuid)
|
||||
|
||||
logger.info(
|
||||
f"[toggle_like] SUCCESS - video_id: {video_id}, "
|
||||
f"is_liked: {is_liked}, count: {like_count}"
|
||||
)
|
||||
return LikeToggleResponse(video_id=video_id, is_liked=is_liked, like_count=like_count)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"[toggle_like] EXCEPTION - video_id: {video_id}, error: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"좋아요 처리에 실패했습니다: {str(e)}")
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{video_id}",
|
||||
summary="단일 영상 상세 조회",
|
||||
description="""
|
||||
## 개요
|
||||
video_id에 해당하는 완료된 영상의 상세 정보를 반환합니다.
|
||||
|
||||
## 경로 파라미터
|
||||
- **video_id**: 조회할 영상의 ID (Video.id)
|
||||
""",
|
||||
response_model=VideoDetailResponse,
|
||||
responses={
|
||||
200: {"description": "상세 조회 성공"},
|
||||
404: {"description": "영상을 찾을 수 없음"},
|
||||
500: {"description": "조회 실패"},
|
||||
},
|
||||
)
|
||||
async def get_video_detail(
|
||||
video_id: int,
|
||||
current_user: User | None = Depends(get_current_user_optional),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> VideoDetailResponse:
|
||||
"""video_id에 해당하는 완료된 영상 상세 정보를 반환합니다."""
|
||||
logger.info(f"[get_video_detail] START - video_id: {video_id}")
|
||||
|
||||
try:
|
||||
result = await session.execute(
|
||||
select(Video, Project)
|
||||
.join(Project, Video.project_id == Project.id)
|
||||
.where(
|
||||
Video.id == video_id,
|
||||
Video.status == "completed",
|
||||
Video.is_deleted == False, # noqa: E712
|
||||
Project.is_deleted == False, # noqa: E712
|
||||
)
|
||||
)
|
||||
row = result.one_or_none()
|
||||
|
||||
if row is None:
|
||||
logger.warning(f"[get_video_detail] NOT FOUND - video_id: {video_id}")
|
||||
raise HTTPException(status_code=404, detail="영상을 찾을 수 없습니다.")
|
||||
|
||||
video, project = row
|
||||
|
||||
# like_count: Redis 조회, 캐시 미스 시 DB backfill
|
||||
like_count = await get_like_count(video_id)
|
||||
if like_count is None:
|
||||
user_uuids = (await session.execute(
|
||||
select(VideoReaction.user_uuid)
|
||||
.where(VideoReaction.video_id == video_id)
|
||||
)).scalars().all()
|
||||
like_count = len(user_uuids)
|
||||
await backfill_user_set(video_id, list(user_uuids))
|
||||
await set_like_count(video_id, like_count)
|
||||
|
||||
# is_liked_by_me: Redis user-set 기준, cold-start 시 DB backfill
|
||||
is_liked_by_me = False
|
||||
if current_user:
|
||||
liked = await is_user_liked(video_id, current_user.user_uuid)
|
||||
if liked is None:
|
||||
# user-set 없음 → count key로 cold-start 여부 판별
|
||||
if like_count > 0:
|
||||
user_uuids = (await session.execute(
|
||||
select(VideoReaction.user_uuid)
|
||||
.where(VideoReaction.video_id == video_id)
|
||||
)).scalars().all()
|
||||
await backfill_user_set(video_id, list(user_uuids))
|
||||
liked = current_user.user_uuid in set(user_uuids)
|
||||
else:
|
||||
liked = False
|
||||
is_liked_by_me = liked
|
||||
|
||||
logger.info(f"[get_video_detail] SUCCESS - video_id: {video_id}")
|
||||
return VideoDetailResponse(
|
||||
video_id=video.id,
|
||||
result_movie_url=video.result_movie_url,
|
||||
store_name=project.store_name,
|
||||
region=project.region or _extract_region_from_address(project.detail_region_info),
|
||||
created_at=video.created_at,
|
||||
like_count=like_count,
|
||||
is_liked_by_me=is_liked_by_me,
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"[get_video_detail] EXCEPTION - video_id: {video_id}, error: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"영상 조회에 실패했습니다: {str(e)}")
|
||||
+67
-2
@@ -1,15 +1,17 @@
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING, Optional
|
||||
from typing import TYPE_CHECKING, List, Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, String, func
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, String, UniqueConstraint, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.database.session import Base
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.comment.models import Comment
|
||||
from app.home.models import Project
|
||||
from app.lyric.models import Lyric
|
||||
from app.song.models import Song
|
||||
from app.user.models import User
|
||||
|
||||
|
||||
class Video(Base):
|
||||
@@ -33,6 +35,8 @@ class Video(Base):
|
||||
project: 연결된 Project
|
||||
lyric: 연결된 Lyric
|
||||
song: 연결된 Song
|
||||
comments: 영상 댓글 목록
|
||||
likes: 영상 좋아요 목록
|
||||
"""
|
||||
|
||||
__tablename__ = "video"
|
||||
@@ -132,6 +136,20 @@ class Video(Base):
|
||||
back_populates="videos",
|
||||
)
|
||||
|
||||
comments: Mapped[List["Comment"]] = relationship(
|
||||
"Comment",
|
||||
back_populates="video",
|
||||
cascade="all, delete-orphan",
|
||||
lazy="noload",
|
||||
)
|
||||
|
||||
reactions: Mapped[List["VideoReaction"]] = relationship(
|
||||
"VideoReaction",
|
||||
back_populates="video",
|
||||
cascade="all, delete-orphan",
|
||||
lazy="noload",
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
def truncate(value: str | None, max_len: int = 10) -> str:
|
||||
if value is None:
|
||||
@@ -145,3 +163,50 @@ class Video(Base):
|
||||
f"status='{self.status}'"
|
||||
f")>"
|
||||
)
|
||||
|
||||
|
||||
class VideoReaction(Base):
|
||||
"""
|
||||
영상 반응 테이블
|
||||
|
||||
사용자가 영상에 반응(현재는 좋아요)을 남기면 생성, 다시 누르면 삭제(토글).
|
||||
(user_uuid, video_id) 유니크 제약으로 1인 1회 보장.
|
||||
향후 reaction_type 컬럼 추가로 다양한 반응 종류 확장 가능.
|
||||
"""
|
||||
|
||||
__tablename__ = "video_reaction"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("user_uuid", "video_id", name="uq_video_reaction_user_video"),
|
||||
Index("idx_video_reaction_video_id", "video_id"),
|
||||
Index("idx_video_reaction_user_uuid", "user_uuid"),
|
||||
{
|
||||
"mysql_engine": "InnoDB",
|
||||
"mysql_charset": "utf8mb4",
|
||||
"mysql_collate": "utf8mb4_unicode_ci",
|
||||
},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
Integer, primary_key=True, autoincrement=True, comment="고유 식별자"
|
||||
)
|
||||
video_id: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
ForeignKey("video.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
comment="연결된 Video의 id",
|
||||
)
|
||||
user_uuid: Mapped[str] = mapped_column(
|
||||
String(36),
|
||||
ForeignKey("user.user_uuid", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
comment="반응한 사용자 UUID",
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.now(),
|
||||
comment="반응 일시",
|
||||
)
|
||||
|
||||
video: Mapped["Video"] = relationship("Video", back_populates="reactions")
|
||||
user: Mapped["User"] = relationship("User", back_populates="video_reactions")
|
||||
@@ -158,5 +158,51 @@ class VideoListItem(BaseModel):
|
||||
task_id: str = Field(..., description="작업 고유 식별자")
|
||||
result_movie_url: Optional[str] = Field(None, description="영상 결과 URL")
|
||||
created_at: Optional[datetime] = Field(None, description="생성 일시")
|
||||
like_count: int = Field(0, description="좋아요 수")
|
||||
comment_count: int = Field(0, description="댓글 수 (대댓글 포함)")
|
||||
|
||||
|
||||
class VideoThumbnailItem(BaseModel):
|
||||
"""ADO2 콘텐츠 갤러리용 최소 영상 정보 (썸네일 표시 + 상세 페이지 이동용)
|
||||
|
||||
Usage:
|
||||
GET /video/all 응답의 개별 영상 정보
|
||||
"""
|
||||
|
||||
video_id: int = Field(..., description="영상 고유 ID (상세 페이지 라우팅 키)")
|
||||
store_name: str = Field(..., description="업체명")
|
||||
result_movie_url: str = Field(..., description="영상 URL — 프론트에서 <video> 태그 첫 프레임을 썸네일로 사용")
|
||||
created_at: datetime = Field(..., description="생성 일시")
|
||||
like_count: int = Field(..., description="좋아요 수")
|
||||
is_liked_by_me: bool = Field(..., description="현재 로그인 사용자가 좋아요를 눌렀는지 (비로그인은 항상 false)")
|
||||
comment_count: int = Field(..., description="댓글 수 (대댓글 포함)")
|
||||
|
||||
|
||||
class VideoDetailResponse(BaseModel):
|
||||
"""단일 영상 상세 응답
|
||||
|
||||
Usage:
|
||||
GET /video/{video_id}
|
||||
"""
|
||||
|
||||
video_id: int = Field(..., description="영상 고유 ID")
|
||||
result_movie_url: str = Field(..., description="영상 URL")
|
||||
store_name: Optional[str] = Field(None, description="업체명")
|
||||
region: Optional[str] = Field(None, description="지역명")
|
||||
created_at: datetime = Field(..., description="생성 일시")
|
||||
like_count: int = Field(..., description="좋아요 수")
|
||||
is_liked_by_me: bool = Field(..., description="현재 로그인 사용자가 좋아요를 눌렀는지 (비로그인은 항상 false)")
|
||||
|
||||
|
||||
class LikeToggleResponse(BaseModel):
|
||||
"""좋아요 토글 응답
|
||||
|
||||
Usage:
|
||||
POST /video/{video_id}/like
|
||||
"""
|
||||
|
||||
video_id: int = Field(..., description="영상 고유 ID")
|
||||
is_liked: bool = Field(..., description="토글 후 상태 (true=좋아요 누름, false=취소됨)")
|
||||
like_count: int = Field(..., description="토글 후 전체 좋아요 수")
|
||||
|
||||
|
||||
Reference in new issue
Block a user