init: 썰박스(SSULBOX) 마케팅 쇼츠 플랫폼

- frontend: React+Vite+TS+Tailwind (모바일 우선 인스타형 피드/뷰어/채널)
- backend: FastAPI + SQLAlchemy async + SQLite, 카카오 로그인/유튜브 연동/크레딧
- generator: 네이버 크롤 기반 AI 쇼츠 생성기(애니메이션 3종)
- 시크릿(.env)·DB·node_modules·output·bgm 은 커밋 제외

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
JinwooKimandClaude Opus 4.8 committed 2026-07-08 14:55:47 +09:00
commit 9ab618db10
64 files changed
+14967

No files matched your search

View File
Whitespace-only changes.
+172
View File
@@ -0,0 +1,172 @@
# -*- coding: utf-8 -*-
"""인증 라우터. 카카오 로그인(실연동) + 개발용 dev-login + me + refresh."""
from datetime import datetime, timezone
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import RedirectResponse
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from .. import credit_service, kakao_client
from ..config import settings
from ..database import get_session
from ..deps import get_current_user
from ..models import User
from ..schemas import ProfileUpdate, TokenResponse, UserOut
from ..security import create_access_token, create_refresh_token, decode_token, new_uuid
router = APIRouter(prefix="/api/auth", tags=["Auth"])
# 카카오 앱에 등록된 redirect 경로(prefix 밖)를 그대로 받기 위한 보조 라우터.
compat_router = APIRouter(tags=["Auth"])
async def _get_or_create_kakao_user(info: dict, session: AsyncSession) -> tuple[User, bool]:
"""카카오 사용자 정보로 사용자 조회/생성. (User, 신규여부) 반환. 신규엔 가입 크레딧 지급."""
user = (
await session.execute(select(User).where(User.kakao_id == info["kakao_id"]))
).scalar_one_or_none()
if user is not None:
if info.get("nickname"):
user.nickname = info["nickname"]
if info.get("email"):
user.email = info["email"]
# 기본 아바타 = 카카오 프로필 사진. 단, 사용자가 직접 바꾼 이미지는 덮어쓰지 않음.
if info.get("profile_image") and not user.profile_image_url:
user.profile_image_url = info["profile_image"]
user.last_login_at = datetime.now(timezone.utc)
return user, False
user = User(
user_uuid=new_uuid(), kakao_id=info["kakao_id"],
nickname=info.get("nickname") or "사용자", email=info.get("email"),
profile_image_url=info.get("profile_image"), # 기본 아바타 = 카카오 프로필 사진
credits=0, last_login_at=datetime.now(timezone.utc),
)
session.add(user)
await session.flush()
await credit_service.charge(session, user.user_uuid, settings.SIGNUP_CREDITS, type_="signup", reason="가입 지급")
return user, True
async def _kakao_login(code: str, session: AsyncSession) -> tuple[str, str, bool]:
"""인가코드 → (access, refresh, 신규여부). 카카오 토큰교환+사용자조회/생성."""
access = await kakao_client.get_access_token(code)
info = await kakao_client.get_user_info(access)
user, is_new = await _get_or_create_kakao_user(info, session)
if not user.is_active:
raise HTTPException(403, "비활성화된 계정입니다.")
tokens = (create_access_token(user.user_uuid), create_refresh_token(user.user_uuid))
await session.commit()
return tokens[0], tokens[1], is_new
class DevLoginReq(BaseModel):
nickname: str | None = None
@router.post("/dev-login", response_model=TokenResponse)
async def dev_login(body: DevLoginReq, session: AsyncSession = Depends(get_session)):
"""개발용 로그인: 닉네임으로 사용자 재사용/생성 + 가입 크레딧. (DEBUG 전용)"""
if not settings.DEBUG:
raise HTTPException(403, "DEBUG 모드에서만 사용 가능합니다.")
nickname = (body.nickname or "테스터").strip() or "테스터"
user = (
await session.execute(
select(User).where(User.nickname == nickname, User.kakao_id.is_(None))
)
).scalars().first()
if user is None:
user = User(user_uuid=new_uuid(), nickname=nickname, credits=0)
session.add(user)
await session.flush()
await credit_service.charge(session, user.user_uuid, settings.SIGNUP_CREDITS, type_="signup", reason="가입 지급")
user.last_login_at = datetime.now(timezone.utc)
await session.commit()
return TokenResponse(
access_token=create_access_token(user.user_uuid),
refresh_token=create_refresh_token(user.user_uuid),
)
def _user_out(user: User) -> UserOut:
return UserOut(user_uuid=user.user_uuid, nickname=user.nickname, email=user.email,
profile_image_url=user.profile_image_url, bio=user.bio,
credits=user.credits, is_admin=user.is_admin)
@router.get("/me", response_model=UserOut)
async def me(user: User = Depends(get_current_user)):
return _user_out(user)
@router.patch("/me", response_model=UserOut)
async def update_me(body: ProfileUpdate, user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session)):
"""프로필 편집 — 닉네임·프로필 이미지·한 줄 소개."""
if body.nickname is not None:
nn = body.nickname.strip()
if not (1 <= len(nn) <= 20):
raise HTTPException(400, "닉네임은 1~20자여야 합니다.")
user.nickname = nn
if body.bio is not None:
user.bio = body.bio.strip()[:200] or None
if body.profile_image_url is not None:
img = body.profile_image_url.strip()
if img and not (img.startswith("data:image/") or img.startswith("http")):
raise HTTPException(400, "이미지 형식이 올바르지 않습니다.")
if len(img) > 3_000_000: # data URL 과대 방지(~3MB)
raise HTTPException(400, "이미지가 너무 큽니다. 더 작은 사진을 사용해주세요.")
user.profile_image_url = img or None
await session.commit()
return _user_out(user)
class RefreshReq(BaseModel):
refresh_token: str
@router.post("/refresh", response_model=TokenResponse)
async def refresh(body: RefreshReq, session: AsyncSession = Depends(get_session)):
payload = decode_token(body.refresh_token)
if not payload or payload.get("type") != "refresh":
raise HTTPException(401, "유효하지 않은 refresh 토큰입니다.")
uuid_ = payload.get("sub")
user = (await session.execute(select(User).where(User.user_uuid == uuid_))).scalar_one_or_none()
if user is None:
raise HTTPException(401, "사용자를 찾을 수 없습니다.")
return TokenResponse(access_token=create_access_token(uuid_), refresh_token=create_refresh_token(uuid_))
@router.get("/kakao/login")
async def kakao_login():
"""카카오 인증 페이지 URL 반환. 프론트가 이 URL로 이동시킨다."""
return {"auth_url": kakao_client.get_authorization_url()}
async def _kakao_callback(code: str, session: AsyncSession):
"""카카오 콜백 공통: 코드 → 로그인 → 토큰을 프론트 URL 쿼리로 붙여 리다이렉트."""
access, refresh, _is_new = await _kakao_login(code, session)
url = f"{settings.FRONTEND_URL}/?access_token={access}&refresh_token={refresh}"
return RedirectResponse(url=url, status_code=302)
@router.get("/kakao/callback")
async def kakao_callback(code: str, session: AsyncSession = Depends(get_session)):
return await _kakao_callback(code, session)
@compat_router.get("/user/auth/kakao/callback")
async def kakao_callback_compat(code: str, session: AsyncSession = Depends(get_session)):
"""카카오 앱에 등록된 경로(/user/auth/kakao/callback)로 오는 콜백."""
return await _kakao_callback(code, session)
class KakaoVerifyReq(BaseModel):
code: str
@router.post("/kakao/verify", response_model=TokenResponse)
async def kakao_verify(body: KakaoVerifyReq, session: AsyncSession = Depends(get_session)):
"""SPA용: 프론트가 받은 인가코드를 검증해 JSON 토큰으로 발급."""
access, refresh, _is_new = await _kakao_login(body.code, session)
return TokenResponse(access_token=access, refresh_token=refresh)
+88
View File
@@ -0,0 +1,88 @@
# -*- coding: utf-8 -*-
"""댓글 라우터 (2-depth: 댓글+대댓글, 익명, 소프트 삭제)."""
from collections import defaultdict
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from ..database import get_session
from ..deps import Pagination, get_current_user, get_current_user_optional, get_pagination
from ..models import Comment, Content, User
from ..schemas import CommentItem, CommentReq, PaginatedResponse, ReplyItem
router = APIRouter(prefix="/api/comment", tags=["Comment"])
@router.post("/content/{cid}")
async def create_comment(cid: str, body: CommentReq, user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session)):
if not body.body.strip():
raise HTTPException(400, "내용을 입력해주세요.")
content = await session.get(Content, cid)
if content is None or content.is_deleted:
raise HTTPException(404, "콘텐츠를 찾을 수 없습니다.")
if body.parent_id is not None:
parent = await session.get(Comment, body.parent_id)
if parent is None or parent.content_id != cid:
raise HTTPException(400, "원 댓글을 찾을 수 없습니다.")
if parent.parent_id is not None:
raise HTTPException(400, "대댓글에는 답글을 달 수 없습니다 (최대 2-depth).")
c = Comment(
content_id=cid, user_uuid=user.user_uuid, parent_id=body.parent_id,
nickname=(body.nickname or user.nickname or "익명")[:50], body=body.body.strip()[:300],
)
session.add(c)
await session.commit()
return {"id": c.id}
@router.get("/content/{cid}", response_model=PaginatedResponse[CommentItem])
async def list_comments(cid: str, pg: Pagination = Depends(get_pagination),
user: User | None = Depends(get_current_user_optional),
session: AsyncSession = Depends(get_session)):
me = user.user_uuid if user else None
top_where = [Comment.content_id == cid, Comment.parent_id.is_(None)]
total = (await session.execute(select(func.count(Comment.id)).where(*top_where))).scalar() or 0
tops = (
await session.execute(
select(Comment).where(*top_where).order_by(Comment.created_at.desc())
.offset(pg.offset).limit(pg.page_size)
)
).scalars().all()
parent_ids = [c.id for c in tops]
replies_by_parent: dict[int, list[Comment]] = defaultdict(list)
if parent_ids:
reps = (
await session.execute(
select(Comment).where(Comment.parent_id.in_(parent_ids)).order_by(Comment.created_at.asc())
)
).scalars().all()
for r in reps:
replies_by_parent[r.parent_id].append(r)
def out(c: Comment):
return dict(
id=c.id, body=(None if c.is_deleted else c.body),
nickname=c.nickname, is_mine=(c.user_uuid == me), created_at=c.created_at,
)
items = [
CommentItem(**out(c), replies=[ReplyItem(**out(r)) for r in replies_by_parent.get(c.id, [])])
for c in tops
]
return PaginatedResponse.create(items, total, pg.page, pg.page_size)
@router.delete("/{comment_id}")
async def delete_comment(comment_id: int, user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session)):
c = await session.get(Comment, comment_id)
if c is None or c.is_deleted:
raise HTTPException(404, "댓글을 찾을 수 없습니다.")
if c.user_uuid != user.user_uuid:
raise HTTPException(403, "본인 댓글만 삭제할 수 있습니다.")
c.is_deleted = True
await session.commit()
return {"ok": True}
+136
View File
@@ -0,0 +1,136 @@
# -*- coding: utf-8 -*-
"""콘텐츠(피드)·생성·좋아요·업장명 자동완성 라우터."""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from .. import credit_service, jobs
from ..config import GEMINI_API_KEY, SCENARIO_ENGINE, settings
from ..content_sync import sync_output
from ..database import get_session
from ..deps import Pagination, get_current_user, get_current_user_optional, get_pagination
from ..models import Comment, Content, Like, User
from ..schemas import CreateReq, FeedItem, PaginatedResponse
router = APIRouter(prefix="/api", tags=["Content"])
@router.get("/feed", response_model=PaginatedResponse[FeedItem])
async def feed(
sort: str = Query("latest", pattern="^(latest|likes)$"),
owner: str | None = None, # "me" → 내 채널
pg: Pagination = Depends(get_pagination),
user: User | None = Depends(get_current_user_optional),
session: AsyncSession = Depends(get_session),
):
like_ct = (
select(func.count(Like.id)).where(Like.content_id == Content.id).correlate(Content).scalar_subquery()
)
cmt_ct = (
select(func.count(Comment.id))
.where(Comment.content_id == Content.id, Comment.is_deleted == False) # noqa: E712
.correlate(Content).scalar_subquery()
)
where = [Content.is_deleted == False] # noqa: E712
if owner == "me":
if user is None:
return PaginatedResponse.create([], 0, pg.page, pg.page_size)
where.append(Content.owner_uuid == user.user_uuid)
total = (await session.execute(select(func.count(Content.id)).where(*where))).scalar() or 0
order = like_ct.desc() if sort == "likes" else Content.created_at.desc()
rows = (
await session.execute(
select(Content, like_ct.label("likes"), cmt_ct.label("comments"))
.where(*where).order_by(order).offset(pg.offset).limit(pg.page_size)
)
).all()
ids = [r[0].id for r in rows]
liked = set()
if user and ids:
liked = set(
(await session.execute(
select(Like.content_id).where(Like.user_uuid == user.user_uuid, Like.content_id.in_(ids))
)).scalars().all()
)
items = [
FeedItem(
id=c.id, sc=c.scenario, title=c.title, video=c.video, views=c.views,
likes=likes, comments=comments, liked=(c.id in liked),
mine=(user is not None and c.owner_uuid == user.user_uuid), createdAt=c.created_at,
)
for (c, likes, comments) in rows
]
return PaginatedResponse.create(items, total, pg.page, pg.page_size)
@router.post("/create")
async def create(body: CreateReq, user: User = Depends(get_current_user)):
if body.scenario not in SCENARIO_ENGINE:
raise HTTPException(400, f"알 수 없는 시나리오: {body.scenario}")
if not body.input.strip():
raise HTTPException(400, "링크 또는 업장명이 필요합니다.")
if not GEMINI_API_KEY:
raise HTTPException(400, "GEMINI_API_KEY 가 설정되지 않았습니다.")
if user.credits < settings.CREDITS_PER_VIDEO:
raise HTTPException(402, "크레딧이 부족합니다. 충전 후 이용해주세요.")
job = jobs.create_job(
body.scenario, body.input.strip(),
max(4, min(20, body.scenes)), max(20, min(90, body.seconds)),
owner_uuid=user.user_uuid,
)
return {"id": job["id"], "status": job["status"]}
@router.get("/jobs/{jid}")
async def job_status(jid: str, session: AsyncSession = Depends(get_session)):
job = jobs.get_job(jid)
if not job:
raise HTTPException(404, "잡을 찾을 수 없습니다.")
# 완료 최초 관측 시 1회: 새 output → content 삽입 + 크레딧 차감
if job["status"] == "done" and not job["finalized"]:
job["finalized"] = True
try:
await sync_output(session, owner_uuid=job["owner_uuid"])
if job["owner_uuid"]:
await credit_service.deduct(session, job["owner_uuid"], settings.CREDITS_PER_VIDEO, reason="영상 생성")
await session.commit()
except Exception:
await session.rollback()
return {
"id": job["id"], "status": job["status"], "step": job["step"],
"stepName": jobs.STEP_NAMES[job["step"] - 1] if job["step"] else "대기 중",
"output": job["output"], "error": job["error"], "log": job["log"][-15:],
}
@router.post("/content/{cid}/like")
async def toggle_like(cid: str, user: User = Depends(get_current_user), session: AsyncSession = Depends(get_session)):
c = await session.get(Content, cid)
if c is None or c.is_deleted:
raise HTTPException(404, "콘텐츠를 찾을 수 없습니다.")
existing = (
await session.execute(select(Like).where(Like.content_id == cid, Like.user_uuid == user.user_uuid))
).scalar_one_or_none()
if existing:
await session.delete(existing)
liked = False
else:
session.add(Like(content_id=cid, user_uuid=user.user_uuid))
liked = True
await session.commit()
count = (await session.execute(select(func.count(Like.id)).where(Like.content_id == cid))).scalar() or 0
return {"liked": liked, "likes": count}
@router.get("/search/place", tags=["Search"])
async def search_place(query: str = Query(..., min_length=2)):
"""업장명 → 네이버 지도 후보 목록(동명 업장 주소로 구분). 키 불필요(Playwright).
각 후보는 place_url 을 가지므로, 프론트에서 하나를 고르면 그 URL 로 정확히 크롤링한다.
"""
from .. import place_service
items = await place_service.search_places(query, limit=8)
return {"query": query, "count": len(items), "items": items}
+89
View File
@@ -0,0 +1,89 @@
# -*- coding: utf-8 -*-
"""크레딧 라우터: 잔액·원장 조회 + (개발용) 충전. 실서비스 충전은 관리자 승인 워크플로 필요."""
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from .. import credit_service
from ..config import settings
from ..database import get_session
from ..deps import Pagination, get_current_user, get_pagination
from ..models import CreditTransaction, User
from ..schemas import CreditTx, PaginatedResponse
router = APIRouter(prefix="/api/credits", tags=["Credit"])
@router.get("/balance")
async def balance(user: User = Depends(get_current_user)):
return {"credits": user.credits}
@router.get("/transactions", response_model=PaginatedResponse[CreditTx])
async def transactions(pg: Pagination = Depends(get_pagination), user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session)):
where = [CreditTransaction.user_uuid == user.user_uuid]
total = (await session.execute(select(func.count(CreditTransaction.id)).where(*where))).scalar() or 0
rows = (
await session.execute(
select(CreditTransaction).where(*where).order_by(CreditTransaction.created_at.desc())
.offset(pg.offset).limit(pg.page_size)
)
).scalars().all()
items = [CreditTx(amount=r.amount, balance_after=r.balance_after, type=r.type, reason=r.reason,
created_at=r.created_at) for r in rows]
return PaginatedResponse.create(items, total, pg.page, pg.page_size)
class ChargeReq(BaseModel):
amount: int = 10
@router.post("/charge")
async def charge(body: ChargeReq, user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session)):
"""개발용 즉시 충전. 실서비스에선 결제/관리자 승인으로 대체."""
if not settings.DEBUG:
raise HTTPException(403, "충전은 결제 연동 후 제공됩니다.")
if body.amount <= 0 or body.amount > 1000:
raise HTTPException(400, "충전 금액이 올바르지 않습니다.")
await credit_service.charge(session, user.user_uuid, body.amount, type_="charge", reason="개발 충전")
await session.commit()
return {"credits": user.credits}
# ── 크레딧 충전 상품 ─────────────────────────────────────────────
# 편당 1크레딧 소모. bonus 는 덤으로 주는 크레딧.
PRODUCTS = [
{"id": "p10", "label": "스타터", "credits": 10, "bonus": 0, "price": 3900, "best": False},
{"id": "p30", "label": "베이직", "credits": 30, "bonus": 5, "price": 9900, "best": True},
{"id": "p100", "label": "프로", "credits": 100, "bonus": 25, "price": 29900, "best": False},
]
_PRODUCTS_BY_ID = {p["id"]: p for p in PRODUCTS}
@router.get("/products")
async def products():
"""충전 상품 목록. price 는 원(₩)."""
return {"items": PRODUCTS}
class PurchaseReq(BaseModel):
product_id: str
@router.post("/purchase")
async def purchase(body: PurchaseReq, user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session)):
"""상품 구매 → 크레딧 지급. 결제(PG) 미연동이라 개발 모드에서 즉시 지급."""
p = _PRODUCTS_BY_ID.get(body.product_id)
if not p:
raise HTTPException(404, "존재하지 않는 상품입니다.")
if not settings.DEBUG:
raise HTTPException(501, "결제 연동 준비 중입니다.") # 실서비스: PG 결제 검증 후 지급
total = p["credits"] + p["bonus"]
await credit_service.charge(session, user.user_uuid, total, type_="purchase",
reason=f"{p['label']} 상품({p['credits']}+{p['bonus']})")
await session.commit()
return {"credits": user.credits, "added": total, "product": p["label"]}
+142
View File
@@ -0,0 +1,142 @@
# -*- coding: utf-8 -*-
"""SNS 연동 라우터 — 유튜브(Google OAuth + YouTube Data API v3) 실연동.
- 연결: /youtube/connect → Google 동의 URL → 콜백에서 토큰 저장(채널명 포함)
- 업로드: 완성 mp4 를 연동 채널에 resumable 업로드
(castad app/social 패턴 이식)
"""
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import RedirectResponse
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from .. import youtube_client
from ..config import OUTPUT_DIR, settings
from ..database import get_session
from ..deps import get_current_user
from ..models import Content, SocialAccount, User
from ..security import create_access_token, decode_token
router = APIRouter(prefix="/api/social", tags=["Social"])
# Google OAuth 앱에 등록된 콜백 경로(prefix 밖)를 그대로 받기 위한 보조 라우터.
compat_router = APIRouter(tags=["Social"])
SUPPORTED = {"youtube"}
@router.get("/config")
async def social_config():
"""플랫폼별 연동 활성(키 설정) 여부. 프론트가 '곧 지원' 배지 판단에 사용."""
return settings.social_enabled
@router.get("/accounts")
async def list_accounts(user: User = Depends(get_current_user), session: AsyncSession = Depends(get_session)):
rows = (
await session.execute(
select(SocialAccount).where(SocialAccount.user_uuid == user.user_uuid, SocialAccount.is_active == True) # noqa: E712
)
).scalars().all()
return [{"id": a.id, "platform": a.platform, "account_name": a.account_name} for a in rows]
@router.get("/youtube/connect")
async def youtube_connect(user: User = Depends(get_current_user)):
"""Google OAuth 동의 URL 반환. state 에 로그인 사용자 토큰을 실어 콜백에서 식별."""
state = create_access_token(user.user_uuid) # 짧은 수명 서명 토큰을 state 로 사용
return {"auth_url": youtube_client.get_authorization_url(state)}
@compat_router.get("/social/oauth/youtube/callback")
async def youtube_callback(code: str, state: str, session: AsyncSession = Depends(get_session)):
"""Google 콜백: state→사용자 식별, 코드→토큰 교환, 채널명 조회 후 계정 upsert."""
payload = decode_token(state)
if not payload or not payload.get("sub"):
raise HTTPException(400, "유효하지 않은 state")
user_uuid = payload["sub"]
tokens = await youtube_client.exchange_code(code)
channel = await youtube_client.get_channel_info(tokens["access_token"])
acc = (
await session.execute(
select(SocialAccount).where(
SocialAccount.user_uuid == user_uuid, SocialAccount.platform == "youtube"
)
)
).scalar_one_or_none()
if acc is None:
acc = SocialAccount(user_uuid=user_uuid, platform="youtube")
session.add(acc)
acc.account_name = channel.get("title") or "내 채널"
acc.access_token = tokens.get("access_token")
if tokens.get("refresh_token"): # Google 은 재동의 때만 refresh 재발급
acc.refresh_token = tokens["refresh_token"]
acc.is_active = True
await session.commit()
return RedirectResponse(url=f"{settings.FRONTEND_URL}/?tab=channel&connected=youtube", status_code=302)
@router.delete("/{platform}/disconnect")
async def disconnect(platform: str, user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session)):
acc = (
await session.execute(
select(SocialAccount).where(
SocialAccount.user_uuid == user.user_uuid, SocialAccount.platform == platform
)
)
).scalar_one_or_none()
if acc is None:
raise HTTPException(404, "연동된 계정이 없습니다.")
acc.is_active = False
await session.commit()
return {"ok": True}
def _video_file_path(content: Content):
"""Content.video(/videos/...) → 디스크 실제 경로(OUTPUT_DIR 기준)."""
if not content.video:
return None
rel = content.video.removeprefix("/videos/")
return OUTPUT_DIR / rel
@router.post("/upload/{platform}/{content_id}")
async def upload(platform: str, content_id: str, user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session)):
if platform != "youtube":
raise HTTPException(400, f"지원하지 않는 플랫폼: {platform}")
content = await session.get(Content, content_id)
if content is None or not content.video:
raise HTTPException(404, "업로드할 영상을 찾을 수 없습니다.")
acc = (
await session.execute(
select(SocialAccount).where(
SocialAccount.user_uuid == user.user_uuid, SocialAccount.platform == "youtube",
SocialAccount.is_active == True, # noqa: E712
)
)
).scalar_one_or_none()
if acc is None:
raise HTTPException(400, "유튜브 계정을 먼저 연동해주세요.")
path = _video_file_path(content)
if path is None or not path.exists():
raise HTTPException(404, "영상 파일을 찾을 수 없습니다.")
access_token = acc.access_token
desc = f"{content.title}\n\n#썰박스 로 만든 병맛 역사 홍보 쇼츠"
try:
result = await youtube_client.upload_video(str(path), access_token, content.title, desc)
except HTTPException as e:
# 401 이면 refresh 로 재시도
if e.status_code in (401, 403) and acc.refresh_token:
access_token = await youtube_client.refresh_access_token(acc.refresh_token)
acc.access_token = access_token
await session.commit()
result = await youtube_client.upload_video(str(path), access_token, content.title, desc)
else:
raise
return {"ok": True, "platform": "youtube", **result}