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:
commit
9ab618db10
64 files changed
+14967
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,83 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""환경·경로 설정 (pydantic-settings).
|
||||
|
||||
castad 패턴을 따르되, 개발이 바로 되도록 DB 기본값은 SQLite.
|
||||
생성 엔진은 저장소 내장(backend/generator/).
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
BACKEND_DIR = Path(__file__).resolve().parents[1] # backend/
|
||||
REPO_ROOT = BACKEND_DIR.parent # o2o-ssulbox/
|
||||
GENERATOR_DIR = BACKEND_DIR / "generator" # 내장 생성 엔진
|
||||
OUTPUT_DIR = GENERATOR_DIR / "output" # 완성 mp4
|
||||
|
||||
# 프론트 시나리오 코드 ↔ 엔진 폴더
|
||||
SCENARIO_ENGINE = {
|
||||
"joseon": "animation",
|
||||
"samgukji": "animation_samgukji",
|
||||
"greek": "animation_greekroman",
|
||||
}
|
||||
ENGINE_SCENARIO = {v: k for k, v in SCENARIO_ENGINE.items()}
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=str(BACKEND_DIR / ".env"), env_ignore_empty=True, extra="ignore"
|
||||
)
|
||||
|
||||
DEBUG: bool = True
|
||||
|
||||
# DB — 개발 기본 SQLite. 운영은 DATABASE_URL 로 MySQL 지정 가능.
|
||||
DATABASE_URL: str = f"sqlite+aiosqlite:///{(BACKEND_DIR / 'ssulbox.db').as_posix()}"
|
||||
|
||||
# JWT
|
||||
JWT_SECRET: str = "dev-secret-change-me"
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 60
|
||||
JWT_REFRESH_TOKEN_EXPIRE_DAYS: int = 7
|
||||
|
||||
# 크레딧
|
||||
SIGNUP_CREDITS: int = 10 # 신규 가입 지급
|
||||
CREDITS_PER_VIDEO: int = 1 # 영상 1편 생성 소모
|
||||
|
||||
# 생성(Gemini)
|
||||
GEMINI_API_KEY: str | None = None
|
||||
MAX_CONCURRENT_JOBS: int = 1
|
||||
|
||||
# 네이버 업장명 자동완성(선택 — 키 없으면 비활성)
|
||||
NAVER_CLIENT_ID: str | None = None
|
||||
NAVER_CLIENT_SECRET: str | None = None
|
||||
NAVER_LOCAL_API_URL: str = "https://openapi.naver.com/v1/search/local.json"
|
||||
|
||||
# 카카오 로그인(선택 — 키 없으면 dev-login 사용)
|
||||
KAKAO_CLIENT_ID: str | None = None
|
||||
KAKAO_CLIENT_SECRET: str | None = None
|
||||
# castad 카카오 앱에 이미 등록된 경로에 맞춤(콘솔 수정 불필요). 자체 앱 쓰면 아무 경로나 등록 후 변경.
|
||||
KAKAO_REDIRECT_URI: str = "http://localhost:8000/user/auth/kakao/callback"
|
||||
# 카카오 콜백이 토큰을 붙여 되돌려보낼 프론트 주소
|
||||
FRONTEND_URL: str = "http://localhost:5173"
|
||||
|
||||
@property
|
||||
def kakao_enabled(self) -> bool:
|
||||
return bool(self.KAKAO_CLIENT_ID)
|
||||
|
||||
# SNS 연동/업로드 — 유튜브(Google OAuth + YouTube Data API v3)만 지원
|
||||
YOUTUBE_CLIENT_ID: str | None = None
|
||||
YOUTUBE_CLIENT_SECRET: str | None = None
|
||||
# castad Google OAuth 앱에 등록된 콜백 경로에 맞춤(콘솔 수정 불필요)
|
||||
YOUTUBE_REDIRECT_URI: str = "http://localhost:8000/social/oauth/youtube/callback"
|
||||
SNS_REDIRECT_BASE: str | None = None # OAuth 콜백 베이스 URL
|
||||
|
||||
@property
|
||||
def social_enabled(self) -> dict[str, bool]:
|
||||
"""플랫폼별 키 설정 여부. 프론트/라우터에서 활성 판단에 사용."""
|
||||
return {"youtube": bool(self.YOUTUBE_CLIENT_ID and self.YOUTUBE_CLIENT_SECRET)}
|
||||
|
||||
|
||||
settings = Settings()
|
||||
|
||||
# OS 환경변수 GEMINI_API_KEY/GOOGLE_API_KEY 폴백
|
||||
GEMINI_API_KEY = settings.GEMINI_API_KEY or os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")
|
||||
@@ -0,0 +1,67 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""generator/output 스캔 → content 테이블 upsert.
|
||||
|
||||
디스크의 완성 mp4 와 DB 를 잇는다. 시작 시 + 잡 완료 시 호출.
|
||||
"""
|
||||
import re
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from .config import OUTPUT_DIR, ENGINE_SCENARIO
|
||||
from .database import SessionLocal
|
||||
from .models import Content
|
||||
|
||||
_TITLE_RE = re.compile(r"\[제목\]\s*(.+)")
|
||||
|
||||
|
||||
def _title(job_dir) -> str:
|
||||
txt = job_dir / "narration.txt"
|
||||
if txt.exists():
|
||||
for line in txt.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||
m = _TITLE_RE.match(line.strip())
|
||||
if m:
|
||||
return m.group(1).strip()
|
||||
return job_dir.name
|
||||
|
||||
|
||||
def _scan() -> list[dict]:
|
||||
rows = []
|
||||
if not OUTPUT_DIR.is_dir():
|
||||
return rows
|
||||
for engine, sc in ENGINE_SCENARIO.items():
|
||||
d = OUTPUT_DIR / engine
|
||||
if not d.is_dir():
|
||||
continue
|
||||
for job in d.iterdir():
|
||||
if not job.is_dir():
|
||||
continue
|
||||
mp4s = sorted(job.glob("*.mp4"))
|
||||
if not mp4s:
|
||||
continue
|
||||
rel = mp4s[0].relative_to(OUTPUT_DIR).as_posix()
|
||||
rows.append({"id": job.name, "sc": sc, "title": _title(job), "video": f"/videos/{rel}"})
|
||||
return rows
|
||||
|
||||
|
||||
async def sync_output(session: AsyncSession | None = None, owner_uuid: str | None = None) -> int:
|
||||
"""새 output 폴더를 content 로 삽입. 삽입 개수 반환."""
|
||||
own = session is None
|
||||
session = session or SessionLocal()
|
||||
try:
|
||||
existing = set((await session.execute(select(Content.id))).scalars().all())
|
||||
added = 0
|
||||
for r in _scan():
|
||||
if r["id"] in existing:
|
||||
continue
|
||||
session.add(Content(
|
||||
id=r["id"], scenario=r["sc"], title=r["title"], video=r["video"],
|
||||
owner_uuid=owner_uuid,
|
||||
))
|
||||
added += 1
|
||||
if added:
|
||||
await session.commit()
|
||||
return added
|
||||
finally:
|
||||
if own:
|
||||
await session.close()
|
||||
@@ -0,0 +1,38 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""크레딧 충전/차감 (원장 기록). castad credit_service 패턴 축약."""
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from .models import CreditTransaction, User
|
||||
|
||||
|
||||
class InsufficientCreditError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
async def _record(session, user_uuid, amount, balance_after, type_, reason):
|
||||
tx = CreditTransaction(
|
||||
user_uuid=user_uuid, amount=amount, balance_after=balance_after, type=type_, reason=reason,
|
||||
)
|
||||
session.add(tx)
|
||||
return tx
|
||||
|
||||
|
||||
async def charge(session: AsyncSession, user_uuid: str, amount: int, type_: str = "charge", reason: str | None = None):
|
||||
user = (await session.execute(select(User).where(User.user_uuid == user_uuid).with_for_update())).scalar_one_or_none()
|
||||
if user is None:
|
||||
raise ValueError("user not found")
|
||||
user.credits += amount
|
||||
await session.flush()
|
||||
return await _record(session, user_uuid, amount, user.credits, type_, reason)
|
||||
|
||||
|
||||
async def deduct(session: AsyncSession, user_uuid: str, amount: int, type_: str = "consume", reason: str | None = None):
|
||||
user = (await session.execute(select(User).where(User.user_uuid == user_uuid).with_for_update())).scalar_one_or_none()
|
||||
if user is None:
|
||||
raise ValueError("user not found")
|
||||
if user.credits < amount:
|
||||
raise InsufficientCreditError()
|
||||
user.credits -= amount
|
||||
await session.flush()
|
||||
return await _record(session, user_uuid, -amount, user.credits, type_, reason)
|
||||
@@ -0,0 +1,63 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""비동기 DB 세션 + Base + 공통 타임스탬프 믹스인.
|
||||
|
||||
castad 는 공통 base 가 없어 컬럼을 매번 반복하지만, 여기선 TimestampMixin 으로 정리.
|
||||
"""
|
||||
from collections.abc import AsyncGenerator
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, func
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
from .config import settings
|
||||
|
||||
engine = create_async_engine(settings.DATABASE_URL, echo=False, future=True)
|
||||
SessionLocal = async_sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False, autoflush=False)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class TimestampMixin:
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with SessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
|
||||
|
||||
async def create_tables() -> None:
|
||||
from . import models # noqa: F401 (테이블 메타데이터 등록)
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
await _lightweight_migrate(conn)
|
||||
|
||||
|
||||
# create_all 은 기존 테이블에 새 컬럼을 추가하지 않는다. 개발용 SQLite 를 위한 최소 마이그레이션.
|
||||
# (운영 MySQL 은 Alembic 등 정식 마이그레이션 사용 권장)
|
||||
_ADD_COLUMNS = {
|
||||
"user": [
|
||||
("profile_image_url", "TEXT"),
|
||||
("bio", "VARCHAR(200)"),
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
async def _lightweight_migrate(conn) -> None:
|
||||
from sqlalchemy import text
|
||||
dialect = conn.dialect.name
|
||||
if dialect != "sqlite":
|
||||
return # 운영 DB 는 정식 마이그레이션으로 처리
|
||||
for table, cols in _ADD_COLUMNS.items():
|
||||
rows = (await conn.exec_driver_sql(f"PRAGMA table_info({table})")).fetchall()
|
||||
existing = {r[1] for r in rows}
|
||||
for name, ddl in cols:
|
||||
if name not in existing:
|
||||
await conn.exec_driver_sql(f"ALTER TABLE {table} ADD COLUMN {name} {ddl}")
|
||||
@@ -0,0 +1,64 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""공통 FastAPI 의존성: 현재 사용자(필수/선택) + 페이지네이션."""
|
||||
from dataclasses import dataclass
|
||||
|
||||
from fastapi import Depends, HTTPException, Query
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from .database import get_session
|
||||
from .models import User
|
||||
from .security import decode_token
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
async def _user_from_token(creds: HTTPAuthorizationCredentials | None, session: AsyncSession) -> User | None:
|
||||
if creds is None:
|
||||
return None
|
||||
payload = decode_token(creds.credentials)
|
||||
if not payload or payload.get("type") != "access":
|
||||
return None
|
||||
user = (
|
||||
await session.execute(
|
||||
select(User).where(User.user_uuid == payload.get("sub"), User.is_deleted == False) # noqa: E712
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if user is None or not user.is_active:
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
creds: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> User:
|
||||
user = await _user_from_token(creds, session)
|
||||
if user is None:
|
||||
raise HTTPException(401, "로그인이 필요합니다.")
|
||||
return user
|
||||
|
||||
|
||||
async def get_current_user_optional(
|
||||
creds: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> User | None:
|
||||
return await _user_from_token(creds, session)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Pagination:
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
@property
|
||||
def offset(self) -> int:
|
||||
return (self.page - 1) * self.page_size
|
||||
|
||||
|
||||
def get_pagination(
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(20, ge=1, le=100),
|
||||
) -> Pagination:
|
||||
return Pagination(page=page, page_size=page_size)
|
||||
@@ -0,0 +1,101 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""썰박스 생성 잡 매니저 (subprocess → 내장 generator 엔진).
|
||||
|
||||
편당 2~4분·과금이 크므로 동시 실행 제한. stdout 진행 마커([1/4]…, "완성: ...mp4")를 파싱.
|
||||
DB 작업은 하지 않는다 — 완료 후 처리(content 삽입·크레딧 차감)는 잡 상태 조회 엔드포인트가 1회 수행.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from collections import deque
|
||||
from datetime import datetime
|
||||
|
||||
from .config import GENERATOR_DIR, SCENARIO_ENGINE, GEMINI_API_KEY, settings
|
||||
|
||||
_jobs: dict[str, dict] = {}
|
||||
_queue: deque[str] = deque()
|
||||
_lock = threading.Lock()
|
||||
_running = 0
|
||||
|
||||
_STEP_RE = re.compile(r"\[(\d)\s*/\s*4\]")
|
||||
_DONE_RE = re.compile(r"완성[::]\s*(.+\.mp4)")
|
||||
STEP_NAMES = ["대본 생성", "스토리보드", "이미지·음성", "영상 합성"]
|
||||
|
||||
|
||||
def create_job(scenario: str, input_text: str, scenes: int, seconds: int, owner_uuid: str | None) -> dict:
|
||||
jid = uuid.uuid4().hex[:12]
|
||||
_jobs[jid] = {
|
||||
"id": jid, "scenario": scenario, "input": input_text,
|
||||
"scenes": scenes, "seconds": seconds, "owner_uuid": owner_uuid,
|
||||
"status": "queued", "step": 0, "log": [], "output": None, "error": None,
|
||||
"finalized": False, "created": datetime.now().isoformat(timespec="seconds"),
|
||||
}
|
||||
with _lock:
|
||||
_queue.append(jid)
|
||||
_pump()
|
||||
return _jobs[jid]
|
||||
|
||||
|
||||
def get_job(jid: str) -> dict | None:
|
||||
return _jobs.get(jid)
|
||||
|
||||
|
||||
def _pump():
|
||||
global _running
|
||||
with _lock:
|
||||
while _queue and _running < settings.MAX_CONCURRENT_JOBS:
|
||||
jid = _queue.popleft()
|
||||
_running += 1
|
||||
threading.Thread(target=_run, args=(jid,), daemon=True).start()
|
||||
|
||||
|
||||
def _run(jid: str):
|
||||
global _running
|
||||
job = _jobs[jid]
|
||||
try:
|
||||
engine = SCENARIO_ENGINE[job["scenario"]]
|
||||
engine_dir = GENERATOR_DIR / engine
|
||||
main_py = engine_dir / "main.py"
|
||||
if not main_py.exists():
|
||||
raise FileNotFoundError(f"generator not found: {main_py}")
|
||||
|
||||
cmd = [sys.executable, "-u", str(main_py), job["input"],
|
||||
"--scenes", str(job["scenes"]), "--seconds", str(job["seconds"])]
|
||||
env = dict(os.environ)
|
||||
env["PYTHONIOENCODING"] = "utf-8"
|
||||
if GEMINI_API_KEY:
|
||||
env["GEMINI_API_KEY"] = GEMINI_API_KEY
|
||||
|
||||
job["status"] = "running"
|
||||
p = subprocess.Popen(
|
||||
cmd, cwd=str(engine_dir), env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True, encoding="utf-8", errors="replace", bufsize=1,
|
||||
)
|
||||
for line in p.stdout:
|
||||
line = line.rstrip()
|
||||
if not line:
|
||||
continue
|
||||
job["log"].append(line)
|
||||
if len(job["log"]) > 300:
|
||||
del job["log"][:-300]
|
||||
m = _STEP_RE.search(line)
|
||||
if m:
|
||||
job["step"] = int(m.group(1))
|
||||
d = _DONE_RE.search(line)
|
||||
if d:
|
||||
job["output"] = d.group(1).strip()
|
||||
code = p.wait()
|
||||
if code == 0:
|
||||
job["status"] = "done"; job["step"] = 4
|
||||
else:
|
||||
job["status"] = "error"; job["error"] = f"생성 프로세스 종료코드 {code}"
|
||||
except Exception as e:
|
||||
job["status"] = "error"; job["error"] = f"{type(e).__name__}: {e}"
|
||||
finally:
|
||||
with _lock:
|
||||
_running -= 1
|
||||
_pump()
|
||||
@@ -0,0 +1,58 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""카카오 OAuth 클라이언트 (castad app/user/services/kakao.py 이식·축약).
|
||||
|
||||
흐름: get_authorization_url() → 사용자 카카오 로그인 → 인가코드(code)
|
||||
→ get_access_token(code) → get_user_info(token) → (id, nickname, email)
|
||||
"""
|
||||
from fastapi import HTTPException
|
||||
|
||||
import aiohttp
|
||||
|
||||
from .config import settings
|
||||
|
||||
AUTH_URL = "https://kauth.kakao.com/oauth/authorize"
|
||||
TOKEN_URL = "https://kauth.kakao.com/oauth/token"
|
||||
USER_INFO_URL = "https://kapi.kakao.com/v2/user/me"
|
||||
|
||||
|
||||
def get_authorization_url() -> str:
|
||||
if not settings.KAKAO_CLIENT_ID:
|
||||
raise HTTPException(501, "카카오 로그인 미설정 — KAKAO_CLIENT_ID 필요")
|
||||
return (
|
||||
f"{AUTH_URL}?client_id={settings.KAKAO_CLIENT_ID}"
|
||||
f"&redirect_uri={settings.KAKAO_REDIRECT_URI}&response_type=code"
|
||||
)
|
||||
|
||||
|
||||
async def get_access_token(code: str) -> str:
|
||||
data = {
|
||||
"grant_type": "authorization_code",
|
||||
"client_id": settings.KAKAO_CLIENT_ID,
|
||||
"redirect_uri": settings.KAKAO_REDIRECT_URI,
|
||||
"code": code,
|
||||
}
|
||||
if settings.KAKAO_CLIENT_SECRET:
|
||||
data["client_secret"] = settings.KAKAO_CLIENT_SECRET
|
||||
async with aiohttp.ClientSession() as s:
|
||||
async with s.post(TOKEN_URL, data=data) as r:
|
||||
res = await r.json()
|
||||
if "error" in res:
|
||||
raise HTTPException(400, f"카카오 토큰 발급 실패: {res.get('error_description', res.get('error'))}")
|
||||
return res["access_token"]
|
||||
|
||||
|
||||
async def get_user_info(access_token: str) -> dict:
|
||||
"""카카오 사용자 → {kakao_id:int, nickname:str|None, email:str|None, profile_image:str|None}."""
|
||||
async with aiohttp.ClientSession() as s:
|
||||
async with s.get(USER_INFO_URL, headers={"Authorization": f"Bearer {access_token}"}) as r:
|
||||
if r.status != 200:
|
||||
raise HTTPException(500, "카카오 사용자 정보 조회 실패")
|
||||
info = await r.json()
|
||||
acc = info.get("kakao_account") or {}
|
||||
prof = acc.get("profile") or {}
|
||||
return {
|
||||
"kakao_id": int(info["id"]),
|
||||
"nickname": prof.get("nickname"),
|
||||
"email": acc.get("email"),
|
||||
"profile_image": prof.get("profile_image_url"),
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""o2o-ssulbox 백엔드 (FastAPI, API 전용).
|
||||
|
||||
인증(dev/카카오) · 피드/생성 · 좋아요 · 댓글 · 크레딧 · 업장명 자동완성 · SNS 연동.
|
||||
DB는 개발 기본 SQLite. 생성 엔진은 저장소 내장(backend/generator/).
|
||||
프론트(React/Vite)는 별도 실행하며 dev 프록시(/api,/videos)로 붙는다.
|
||||
"""
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from .config import GEMINI_API_KEY, GENERATOR_DIR, OUTPUT_DIR, SCENARIO_ENGINE, settings
|
||||
from .content_sync import sync_output
|
||||
from .database import create_tables
|
||||
from .routers import auth, comments, content, credit, sns
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
await create_tables() # SQLite: 없으면 생성
|
||||
await sync_output() # 기존 output → content 반영
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="o2o-ssulbox API", version="0.1.0", lifespan=lifespan)
|
||||
app.add_middleware(
|
||||
CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], allow_credentials=True,
|
||||
)
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(auth.compat_router) # /user/auth/kakao/callback (카카오 앱 등록 경로)
|
||||
app.include_router(content.router)
|
||||
app.include_router(comments.router)
|
||||
app.include_router(credit.router)
|
||||
app.include_router(sns.router)
|
||||
app.include_router(sns.compat_router) # /social/oauth/youtube/callback (Google 앱 등록 경로)
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def health():
|
||||
return {
|
||||
"ok": True,
|
||||
"gemini_key": bool(GEMINI_API_KEY),
|
||||
"generator_dir": str(GENERATOR_DIR),
|
||||
"output_exists": OUTPUT_DIR.is_dir(),
|
||||
"db": settings.DATABASE_URL.split("://")[0],
|
||||
"scenarios": list(SCENARIO_ENGINE),
|
||||
}
|
||||
|
||||
|
||||
# 완성 mp4 정적 서빙
|
||||
if OUTPUT_DIR.is_dir():
|
||||
app.mount("/videos", StaticFiles(directory=str(OUTPUT_DIR)), name="videos")
|
||||
@@ -0,0 +1,91 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""SQLAlchemy 모델. 사용자·콘텐츠(썰박스)·좋아요·댓글·크레딧 원장.
|
||||
|
||||
castad 컨벤션대로 소셜/크레딧 FK 는 숫자 PK 가 아니라 user_uuid(String36) 기준.
|
||||
콘텐츠 id 는 생성 잡 폴더명(문자열)을 그대로 PK 로 쓴다.
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import (
|
||||
BigInteger, Boolean, DateTime, ForeignKey, Integer, String, Text,
|
||||
UniqueConstraint, func,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from .database import Base, TimestampMixin
|
||||
|
||||
# SQLite 에서 BIGINT 는 rowid 별칭이 안 돼 autoincrement 가 동작하지 않는다 → sqlite 는 INTEGER 로.
|
||||
BIGPK = BigInteger().with_variant(Integer, "sqlite")
|
||||
|
||||
|
||||
class User(Base, TimestampMixin):
|
||||
__tablename__ = "user"
|
||||
id: Mapped[int] = mapped_column(BIGPK, primary_key=True, autoincrement=True)
|
||||
user_uuid: Mapped[str] = mapped_column(String(36), unique=True, index=True)
|
||||
nickname: Mapped[str] = mapped_column(String(50), default="사용자")
|
||||
email: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
profile_image_url: Mapped[str | None] = mapped_column(Text, nullable=True) # data URL 또는 외부 URL
|
||||
bio: Mapped[str | None] = mapped_column(String(200), nullable=True) # 한 줄 소개
|
||||
kakao_id: Mapped[int | None] = mapped_column(BigInteger, unique=True, nullable=True)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
is_admin: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
is_deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
credits: Mapped[int] = mapped_column(Integer, default=10)
|
||||
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
|
||||
class Content(Base, TimestampMixin):
|
||||
"""생성된 썰박스 1편. id = output 잡 폴더명."""
|
||||
__tablename__ = "content"
|
||||
id: Mapped[str] = mapped_column(String(120), primary_key=True)
|
||||
scenario: Mapped[str] = mapped_column(String(20), index=True) # joseon|samgukji|greek
|
||||
title: Mapped[str] = mapped_column(String(200), default="")
|
||||
video: Mapped[str | None] = mapped_column(String(300), nullable=True) # /videos/... url
|
||||
owner_uuid: Mapped[str | None] = mapped_column(String(36), index=True, nullable=True)
|
||||
views: Mapped[int] = mapped_column(Integer, default=0)
|
||||
is_deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class Like(Base, TimestampMixin):
|
||||
__tablename__ = "content_like"
|
||||
__table_args__ = (UniqueConstraint("content_id", "user_uuid", name="uq_like_user_content"),)
|
||||
id: Mapped[int] = mapped_column(BIGPK, primary_key=True, autoincrement=True)
|
||||
content_id: Mapped[str] = mapped_column(String(120), ForeignKey("content.id"), index=True)
|
||||
user_uuid: Mapped[str] = mapped_column(String(36), index=True)
|
||||
|
||||
|
||||
class Comment(Base, TimestampMixin):
|
||||
"""2-depth 댓글(댓글+대댓글). 익명 정책 — user_uuid 는 저장만, 응답에 노출 X."""
|
||||
__tablename__ = "comment"
|
||||
id: Mapped[int] = mapped_column(BIGPK, primary_key=True, autoincrement=True)
|
||||
content_id: Mapped[str] = mapped_column(String(120), ForeignKey("content.id"), index=True)
|
||||
user_uuid: Mapped[str] = mapped_column(String(36), index=True)
|
||||
parent_id: Mapped[int | None] = mapped_column(BigInteger, ForeignKey("comment.id"), nullable=True, index=True)
|
||||
nickname: Mapped[str] = mapped_column(String(50), default="익명")
|
||||
body: Mapped[str] = mapped_column(String(300))
|
||||
is_deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
parent = relationship("Comment", remote_side=[id], backref="replies")
|
||||
|
||||
|
||||
class CreditTransaction(Base, TimestampMixin):
|
||||
"""크레딧 원장. amount +충전/-소모, balance_after 스냅샷."""
|
||||
__tablename__ = "credit_transaction"
|
||||
id: Mapped[int] = mapped_column(BIGPK, primary_key=True, autoincrement=True)
|
||||
user_uuid: Mapped[str] = mapped_column(String(36), index=True)
|
||||
amount: Mapped[int] = mapped_column(Integer)
|
||||
balance_after: Mapped[int] = mapped_column(Integer)
|
||||
type: Mapped[str] = mapped_column(String(20)) # charge|consume|refund|signup
|
||||
reason: Mapped[str | None] = mapped_column(String(200), nullable=True)
|
||||
|
||||
|
||||
class SocialAccount(Base, TimestampMixin):
|
||||
"""SNS 연동 계정 (유튜브/인스타 등). OAuth 토큰은 실제 연동 시 채운다."""
|
||||
__tablename__ = "social_account"
|
||||
__table_args__ = (UniqueConstraint("user_uuid", "platform", name="uq_social_user_platform"),)
|
||||
id: Mapped[int] = mapped_column(BIGPK, primary_key=True, autoincrement=True)
|
||||
user_uuid: Mapped[str] = mapped_column(String(36), index=True)
|
||||
platform: Mapped[str] = mapped_column(String(20)) # youtube|instagram|tiktok|facebook
|
||||
account_name: Mapped[str] = mapped_column(String(120), default="")
|
||||
access_token: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
refresh_token: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
@@ -0,0 +1,160 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""네이버 지도 업장 검색 (키 불필요, Playwright).
|
||||
|
||||
`map.naver.com/p/search/{query}` 의 검색 리스트 iframe(`pcmap.place.naver.com/place/list`)
|
||||
안에 있는 `__APOLLO_STATE__` 를 파싱해, 동명 업장들을 주소로 구분한 후보 목록을 만든다.
|
||||
각 후보는 `place_url`(map.naver.com/p/entry/place/{id})을 가지므로, 사용자가 하나를 고르면
|
||||
그 URL 을 그대로 생성 파이프라인(generator/naver.py)에 넘겨 정확히 그 가게를 크롤링한다.
|
||||
|
||||
castad 의 NvMapPwScraper 와 같은 목적이지만, NAVER 검색 API 키 없이 지도만으로 후보+place_id 를
|
||||
동시에 얻는다(castad 는 후보=NAVER API, place_id 해석=Playwright 2단계).
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from urllib.parse import quote
|
||||
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
DESKTOP_UA = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
|
||||
)
|
||||
|
||||
|
||||
def _extract_apollo_state(html: str) -> dict | None:
|
||||
"""HTML 안의 `__APOLLO_STATE__ = { ... };` 객체를 중괄호 균형으로 안전하게 추출."""
|
||||
i = html.find("__APOLLO_STATE__")
|
||||
if i < 0:
|
||||
return None
|
||||
j = html.find("{", i)
|
||||
if j < 0:
|
||||
return None
|
||||
depth = 0
|
||||
in_str = False
|
||||
esc = False
|
||||
for k in range(j, len(html)):
|
||||
c = html[k]
|
||||
if in_str:
|
||||
if esc:
|
||||
esc = False
|
||||
elif c == "\\":
|
||||
esc = True
|
||||
elif c == '"':
|
||||
in_str = False
|
||||
else:
|
||||
if c == '"':
|
||||
in_str = True
|
||||
elif c == "{":
|
||||
depth += 1
|
||||
elif c == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
try:
|
||||
return json.loads(html[j : k + 1])
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _candidates_from_state(state: dict, limit: int) -> list[dict]:
|
||||
out: list[dict] = []
|
||||
for key, obj in state.items():
|
||||
if not key.startswith("PlaceListBusinessesItem:"):
|
||||
continue
|
||||
if not isinstance(obj, dict):
|
||||
continue
|
||||
name = obj.get("name")
|
||||
pid = obj.get("id")
|
||||
if not (name and pid and str(pid).isdigit()):
|
||||
continue
|
||||
out.append(
|
||||
{
|
||||
"title": name,
|
||||
"category": obj.get("category") or "",
|
||||
# 표시용 주소는 '서울 성동구 금호동3가' 같은 commonAddress 를 우선(동명 구분에 최적)
|
||||
"address": obj.get("commonAddress") or obj.get("fullAddress") or "",
|
||||
"roadAddress": obj.get("fullAddress") or obj.get("roadAddress") or "",
|
||||
"place_url": f"https://map.naver.com/p/entry/place/{pid}",
|
||||
}
|
||||
)
|
||||
if len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
async def _search(query: str, limit: int) -> list[dict]:
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(
|
||||
headless=True,
|
||||
args=["--disable-blink-features=AutomationControlled", "--no-sandbox"],
|
||||
)
|
||||
try:
|
||||
ctx = await browser.new_context(
|
||||
user_agent=DESKTOP_UA, locale="ko-KR", timezone_id="Asia/Seoul",
|
||||
viewport={"width": 1280, "height": 800},
|
||||
extra_http_headers={"Accept-Language": "ko-KR,ko;q=0.9"},
|
||||
)
|
||||
page = await ctx.new_page()
|
||||
await page.goto(
|
||||
f"https://map.naver.com/p/search/{quote(query)}",
|
||||
wait_until="domcontentloaded", timeout=40000,
|
||||
)
|
||||
# 검색 리스트 iframe 이 뜰 때까지 대기(최대 ~12초)
|
||||
frame = None
|
||||
for _ in range(24):
|
||||
for f in page.frames:
|
||||
if "pcmap.place.naver.com/place/list" in f.url:
|
||||
frame = f
|
||||
break
|
||||
if frame:
|
||||
break
|
||||
# 단일 결과면 곧바로 place 상세로 리다이렉트됨 → 후보 1개로 처리
|
||||
if "/place/" in page.url and "/search/" not in page.url:
|
||||
return [{"title": query, "category": "", "address": "",
|
||||
"roadAddress": "", "place_url": page.url}]
|
||||
await page.wait_for_timeout(500)
|
||||
if not frame:
|
||||
return []
|
||||
# apollo state 가 채워질 시간을 조금 더 준다
|
||||
html = await frame.content()
|
||||
state = _extract_apollo_state(html)
|
||||
for _ in range(6):
|
||||
if state and any(k.startswith("PlaceListBusinessesItem:") for k in state):
|
||||
break
|
||||
await page.wait_for_timeout(600)
|
||||
html = await frame.content()
|
||||
state = _extract_apollo_state(html)
|
||||
if not state:
|
||||
return []
|
||||
return _candidates_from_state(state, limit)
|
||||
finally:
|
||||
await browser.close()
|
||||
|
||||
|
||||
def _search_blocking(query: str, limit: int) -> list[dict]:
|
||||
"""별도 스레드에서 자체 이벤트 루프로 Playwright 실행.
|
||||
|
||||
Windows 의 웹서버 루프(Selector)는 서브프로세스를 못 띄워 Playwright 가 즉시 실패한다.
|
||||
→ 이 함수는 워커 스레드에서 Proactor 루프(윈도우) 를 새로 만들어 그 위에서 돌린다.
|
||||
"""
|
||||
if sys.platform == "win32":
|
||||
loop = asyncio.ProactorEventLoop()
|
||||
else:
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
return loop.run_until_complete(_search(query, limit))
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
|
||||
async def search_places(query: str, limit: int = 8, timeout: float = 35.0) -> list[dict]:
|
||||
"""업장명으로 네이버 지도 후보 목록을 반환. 실패/타임아웃이면 빈 리스트."""
|
||||
query = (query or "").strip()
|
||||
if len(query) < 2:
|
||||
return []
|
||||
try:
|
||||
return await asyncio.wait_for(asyncio.to_thread(_search_blocking, query, limit), timeout=timeout)
|
||||
except Exception:
|
||||
return []
|
||||
Whitespace-only changes.
@@ -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)
|
||||
@@ -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}
|
||||
@@ -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}
|
||||
@@ -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"]}
|
||||
@@ -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}
|
||||
@@ -0,0 +1,109 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Pydantic 스키마 + 공통 페이지네이션 응답."""
|
||||
from datetime import datetime
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class PaginatedResponse(BaseModel, Generic[T]):
|
||||
items: list[T]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
total_pages: int
|
||||
has_next: bool
|
||||
has_prev: bool
|
||||
|
||||
@classmethod
|
||||
def create(cls, items: list[T], total: int, page: int, page_size: int) -> "PaginatedResponse[T]":
|
||||
total_pages = (total + page_size - 1) // page_size if page_size else 0
|
||||
return cls(
|
||||
items=items, total=total, page=page, page_size=page_size, total_pages=total_pages,
|
||||
has_next=page < total_pages, has_prev=page > 1,
|
||||
)
|
||||
|
||||
|
||||
# ---- auth ----
|
||||
class UserOut(BaseModel):
|
||||
user_uuid: str
|
||||
nickname: str
|
||||
email: str | None = None
|
||||
profile_image_url: str | None = None
|
||||
bio: str | None = None
|
||||
credits: int
|
||||
is_admin: bool = False
|
||||
|
||||
|
||||
class ProfileUpdate(BaseModel):
|
||||
nickname: str | None = None
|
||||
profile_image_url: str | None = None # data URL 또는 외부 URL, ""=기본으로 되돌림
|
||||
bio: str | None = None
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
refresh_token: str
|
||||
token_type: str = "bearer"
|
||||
|
||||
|
||||
# ---- content / feed ----
|
||||
class FeedItem(BaseModel):
|
||||
id: str
|
||||
sc: str
|
||||
title: str
|
||||
video: str | None
|
||||
views: int
|
||||
likes: int
|
||||
liked: bool = False
|
||||
comments: int = 0
|
||||
mine: bool = False
|
||||
createdAt: datetime | None = None
|
||||
|
||||
|
||||
# ---- create ----
|
||||
class CreateReq(BaseModel):
|
||||
scenario: str
|
||||
input: str
|
||||
scenes: int = 12
|
||||
seconds: int = 45
|
||||
|
||||
|
||||
# ---- comment ----
|
||||
class CommentReq(BaseModel):
|
||||
body: str
|
||||
parent_id: int | None = None
|
||||
nickname: str | None = None
|
||||
|
||||
|
||||
class ReplyItem(BaseModel):
|
||||
id: int
|
||||
body: str | None
|
||||
nickname: str
|
||||
is_mine: bool
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class CommentItem(BaseModel):
|
||||
id: int
|
||||
body: str | None
|
||||
nickname: str
|
||||
is_mine: bool
|
||||
created_at: datetime
|
||||
replies: list[ReplyItem] = []
|
||||
|
||||
|
||||
# ---- credit ----
|
||||
class CreditTx(BaseModel):
|
||||
amount: int
|
||||
balance_after: int
|
||||
type: str
|
||||
reason: str | None
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class ChargeReq(BaseModel):
|
||||
amount: int
|
||||
message: str | None = None
|
||||
@@ -0,0 +1,39 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""JWT 발급·검증 + uuid. castad app/user/services/jwt.py 패턴 축약."""
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from jose import JWTError, jwt
|
||||
|
||||
from .config import settings
|
||||
|
||||
|
||||
def new_uuid() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def create_access_token(user_uuid: str) -> str:
|
||||
payload = {
|
||||
"sub": user_uuid, "type": "access",
|
||||
"exp": _now() + timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES),
|
||||
}
|
||||
return jwt.encode(payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM)
|
||||
|
||||
|
||||
def create_refresh_token(user_uuid: str) -> str:
|
||||
payload = {
|
||||
"sub": user_uuid, "type": "refresh",
|
||||
"exp": _now() + timedelta(days=settings.JWT_REFRESH_TOKEN_EXPIRE_DAYS),
|
||||
}
|
||||
return jwt.encode(payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM)
|
||||
|
||||
|
||||
def decode_token(token: str) -> dict | None:
|
||||
try:
|
||||
return jwt.decode(token, settings.JWT_SECRET, algorithms=[settings.JWT_ALGORITHM])
|
||||
except JWTError:
|
||||
return None
|
||||
@@ -0,0 +1,132 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""유튜브(Google OAuth + YouTube Data API v3) 클라이언트.
|
||||
|
||||
castad app/social/oauth/youtube.py + uploader/youtube.py 이식·축약.
|
||||
- OAuth: 인증 URL 생성 → 코드 교환(access/refresh) → 리프레시 → 내 채널 정보
|
||||
- 업로드: resumable upload 세션 시작 → 파일 PUT → video_id
|
||||
"""
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import aiohttp
|
||||
from fastapi import HTTPException
|
||||
|
||||
from .config import settings
|
||||
|
||||
AUTHORIZATION_URL = "https://accounts.google.com/o/oauth2/v2/auth"
|
||||
TOKEN_URL = "https://oauth2.googleapis.com/token"
|
||||
CHANNELS_URL = "https://www.googleapis.com/youtube/v3/channels"
|
||||
UPLOAD_URL = "https://www.googleapis.com/upload/youtube/v3/videos"
|
||||
|
||||
SCOPES = [
|
||||
"https://www.googleapis.com/auth/youtube.upload",
|
||||
"https://www.googleapis.com/auth/youtube.readonly",
|
||||
]
|
||||
|
||||
|
||||
def get_authorization_url(state: str) -> str:
|
||||
if not (settings.YOUTUBE_CLIENT_ID and settings.YOUTUBE_CLIENT_SECRET):
|
||||
raise HTTPException(501, "유튜브 연동 미설정 — YOUTUBE_CLIENT_ID/SECRET 필요")
|
||||
params = {
|
||||
"client_id": settings.YOUTUBE_CLIENT_ID,
|
||||
"redirect_uri": settings.YOUTUBE_REDIRECT_URI,
|
||||
"response_type": "code",
|
||||
"scope": " ".join(SCOPES),
|
||||
"access_type": "offline", # refresh_token 발급
|
||||
"prompt": "consent", # 매번 동의 → refresh_token 보장
|
||||
"state": state,
|
||||
}
|
||||
return f"{AUTHORIZATION_URL}?{urlencode(params)}"
|
||||
|
||||
|
||||
async def exchange_code(code: str) -> dict:
|
||||
"""인가코드 → {access_token, refresh_token, expires_in}."""
|
||||
data = {
|
||||
"client_id": settings.YOUTUBE_CLIENT_ID,
|
||||
"client_secret": settings.YOUTUBE_CLIENT_SECRET,
|
||||
"code": code,
|
||||
"grant_type": "authorization_code",
|
||||
"redirect_uri": settings.YOUTUBE_REDIRECT_URI,
|
||||
}
|
||||
async with aiohttp.ClientSession() as s:
|
||||
async with s.post(TOKEN_URL, data=data) as r:
|
||||
res = await r.json()
|
||||
if "error" in res:
|
||||
raise HTTPException(400, f"유튜브 토큰 교환 실패: {res.get('error_description', res.get('error'))}")
|
||||
return res
|
||||
|
||||
|
||||
async def refresh_access_token(refresh_token: str) -> str:
|
||||
data = {
|
||||
"client_id": settings.YOUTUBE_CLIENT_ID,
|
||||
"client_secret": settings.YOUTUBE_CLIENT_SECRET,
|
||||
"refresh_token": refresh_token,
|
||||
"grant_type": "refresh_token",
|
||||
}
|
||||
async with aiohttp.ClientSession() as s:
|
||||
async with s.post(TOKEN_URL, data=data) as r:
|
||||
res = await r.json()
|
||||
if "error" in res:
|
||||
raise HTTPException(401, f"유튜브 토큰 갱신 실패: {res.get('error_description', res.get('error'))}")
|
||||
return res["access_token"]
|
||||
|
||||
|
||||
async def get_channel_info(access_token: str) -> dict:
|
||||
"""내 유튜브 채널 → {id, title}."""
|
||||
headers = {"Authorization": f"Bearer {access_token}"}
|
||||
params = {"part": "snippet", "mine": "true"}
|
||||
async with aiohttp.ClientSession() as s:
|
||||
async with s.get(CHANNELS_URL, headers=headers, params=params) as r:
|
||||
data = await r.json()
|
||||
items = data.get("items") or []
|
||||
if not items:
|
||||
return {"id": "", "title": "내 채널"}
|
||||
return {"id": items[0]["id"], "title": items[0]["snippet"]["title"]}
|
||||
|
||||
|
||||
async def upload_video(video_path: str, access_token: str, title: str,
|
||||
description: str = "", tags: list[str] | None = None,
|
||||
privacy: str = "public") -> dict:
|
||||
"""영상 업로드(resumable). → {video_id, url}."""
|
||||
import os
|
||||
if not os.path.exists(video_path):
|
||||
raise HTTPException(404, f"업로드할 파일이 없습니다: {video_path}")
|
||||
file_size = os.path.getsize(video_path)
|
||||
body = {
|
||||
"snippet": {
|
||||
"title": title[:100] or "썰박스",
|
||||
"description": (description or "").replace("<", "").replace(">", ""),
|
||||
"tags": tags or ["썰박스", "쇼츠", "홍보"],
|
||||
"categoryId": "22",
|
||||
},
|
||||
"status": {"privacyStatus": privacy, "selfDeclaredMadeForKids": False},
|
||||
}
|
||||
init_headers = {
|
||||
"Authorization": f"Bearer {access_token}",
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"X-Upload-Content-Type": "video/*",
|
||||
"X-Upload-Content-Length": str(file_size),
|
||||
}
|
||||
async with aiohttp.ClientSession() as s:
|
||||
# 1) resumable 세션 시작
|
||||
async with s.post(UPLOAD_URL, params={"uploadType": "resumable", "part": "snippet,status"},
|
||||
headers=init_headers, json=body) as r:
|
||||
if r.status != 200:
|
||||
err = await r.json()
|
||||
raise HTTPException(502, f"유튜브 업로드 세션 실패: {err.get('error', {}).get('message', r.status)}")
|
||||
upload_url = r.headers.get("Location")
|
||||
if not upload_url:
|
||||
raise HTTPException(502, "유튜브 업로드 URL을 받지 못했습니다.")
|
||||
# 2) 파일 업로드(단일 PUT — 쇼츠는 소용량)
|
||||
with open(video_path, "rb") as f:
|
||||
content = f.read()
|
||||
put_headers = {
|
||||
"Authorization": f"Bearer {access_token}",
|
||||
"Content-Type": "video/*",
|
||||
"Content-Length": str(file_size),
|
||||
}
|
||||
async with s.put(upload_url, headers=put_headers, data=content) as r:
|
||||
res = await r.json()
|
||||
vid = res.get("id")
|
||||
if not vid:
|
||||
raise HTTPException(502, f"유튜브 업로드 실패: {res.get('error', {}).get('message', '알 수 없는 오류')}")
|
||||
return {"video_id": vid, "url": f"https://www.youtube.com/watch?v={vid}"}
|
||||
Reference in new issue
Block a user