Merge remote-tracking branch 'origin/main' into feat/apps-in-toss

This commit is contained in:
minaChoi committed 2026-10-26 15:33:39 +09:00
commit 2627dd2685
200 files changed
+2956 -843

No files matched your search

+14
View File
@@ -323,6 +323,7 @@ class CardSet(Base):
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
ig_media_id: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
hashtags: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
class CardImage(Base):
@@ -333,6 +334,19 @@ class CardImage(Base):
data: Mapped[bytes] = mapped_column(LargeBinary)
class Reel(Base):
__tablename__ = "reel"
reel_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
title: Mapped[str] = mapped_column(String(80))
caption: Mapped[str] = mapped_column(Text, default="")
hashtags: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
video: Mapped[bytes] = mapped_column(LargeBinary)
cover: Mapped[Optional[bytes]] = mapped_column(LargeBinary, nullable=True)
ig_media_id: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class User(Base):
__tablename__ = "users"
+27
View File
@@ -0,0 +1,27 @@
from typing import Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import defer
from common.database.model.models import Reel
class ReelCRUD:
async def create(self, s: AsyncSession, reel: Reel) -> Reel:
s.add(reel)
await s.flush()
return reel
async def get(self, s: AsyncSession, reel_id: int) -> Optional[Reel]:
return await s.get(Reel, reel_id)
async def recent(self, s: AsyncSession, limit: int) -> list[Reel]:
"""만든 순서 역순. 영상·표지 바이트는 안 읽는다."""
return list((await s.scalars(select(Reel).options(defer(Reel.video), defer(Reel.cover)).order_by(Reel.reel_id.desc()).limit(limit))).all())
async def video(self, s: AsyncSession, reel_id: int) -> Optional[bytes]:
return await s.scalar(select(Reel.video).where(Reel.reel_id == reel_id))
async def cover(self, s: AsyncSession, reel_id: int) -> Optional[bytes]:
return await s.scalar(select(Reel.cover).where(Reel.reel_id == reel_id))
+13
View File
@@ -196,6 +196,7 @@ CREATE TABLE IF NOT EXISTS public.card_set (
published_at TIMESTAMPTZ NULL
);
ALTER TABLE public.card_set ADD COLUMN IF NOT EXISTS ig_media_id VARCHAR(40) NULL; -- 인스타에 올렸으면 그 미디어 id
ALTER TABLE public.card_set ADD COLUMN IF NOT EXISTS hashtags TEXT NULL; -- 인스타 캡션 뒤에만 붙는 해시태그
CREATE TABLE IF NOT EXISTS public.card_image (
card_id BIGINT NOT NULL REFERENCES public.card_set (card_id) ON DELETE CASCADE,
seq SMALLINT NOT NULL, -- 1부터, 슬라이드 순서
@@ -497,3 +498,15 @@ CREATE TABLE IF NOT EXISTS public.article (
);
ALTER TABLE public.article ADD COLUMN IF NOT EXISTS image_url VARCHAR(200) NULL;
ALTER TABLE public.article ADD COLUMN IF NOT EXISTS image_credit VARCHAR(60) NULL;
-- 인스타 릴스 (관리자가 만든 mp4를 공개 주소로 내보내 인스타 REELS API 로 올린다. 날씨각 피드에는 안 나간다)
CREATE TABLE IF NOT EXISTS public.reel (
reel_id BIGSERIAL PRIMARY KEY,
title VARCHAR(80) NOT NULL,
caption TEXT NOT NULL DEFAULT '',
hashtags TEXT NULL,
video BYTEA NOT NULL, -- mp4 (H.264, 9:16)
cover BYTEA NULL, -- 표지 JPEG
ig_media_id VARCHAR(40) NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+2
View File
@@ -9,6 +9,7 @@ from common.database.db_session_manager import DB_SESSION_MNG
from common.models.gmodel import Res_WebPacketProtocol
from router.v1.auth.account import router as auth_router
from router.v1.card.card import router as card_router
from router.v1.reel.reel import router as reel_router
from router.v1.feed.feed import router as feed_router
from router.v1.image.image import router as image_router
from router.v1.index.index import router as index_router
@@ -51,6 +52,7 @@ app.include_router(watch_router)
app.include_router(image_router)
app.include_router(seo_router)
app.include_router(card_router)
app.include_router(reel_router)
class Res_Health(Res_WebPacketProtocol):
+2 -2
View File
@@ -82,7 +82,7 @@ async def list_cards(limit: int = Query(50, ge=1, le=200)) -> Res_CardList:
@router.post("", response_model=Res_Card, response_model_exclude_none=True, summary="카드뉴스 저장 (관리자). publish 면 바로 그날 피드에 올린다", dependencies=[Depends(require_admin)])
async def create_card(req: Req_CardCreate) -> Res_Card:
images = _jpegs(req.images)
card = CardSet(template=req.template, topic=req.topic, title=req.title, caption=req.caption, copy=req.texts, status=CardStatus.WAITING.value)
card = CardSet(template=req.template, topic=req.topic, title=req.title, caption=req.caption, hashtags=req.hashtags.strip() or None, copy=req.texts, status=CardStatus.WAITING.value)
err, card = await DB_SESSION_MNG.execute_lambda_write(lambda s: _crud.create(s, card, images))
if err is not ErrorType.SUCCESS:
return Res_Card(result=error_info(err))
@@ -129,7 +129,7 @@ async def publish_instagram(card_id: int = Path(...)) -> Res_Card:
return Res_Card(card_id=card.card_id, status=CardStatus(card.status), post_id=card.post_id, ig_media_id=card.ig_media_id)
_, counts = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.image_counts(s, [card_id]))
urls = [instagram.public_image_url(image_url(card_id, i)) for i in range(1, (counts or {}).get(card_id, 0) + 1)]
caption = f"{card.title}\n\n{card.caption}".strip()
caption = "\n\n".join(part for part in (card.title, card.caption, card.hashtags) if part)
try:
media_id = await instagram.publish_carousel(urls, caption)
except instagram.InstagramError as e:
+1
View File
@@ -12,6 +12,7 @@ class Req_CardCreate(WebPacketProtocol):
topic: Optional[str] = Field(default=None, max_length=60)
title: str = Field(max_length=80, description="피드 포스트 제목")
caption: str = Field(default="", max_length=2000)
hashtags: str = Field(default="", max_length=600, description="인스타 캡션 뒤에만 붙는 해시태그. 날씨각 피드에는 안 나간다")
texts: dict = Field(default_factory=dict, description="카드 문구 (다시 그릴 때 쓴다)")
images: list[str] = Field(min_length=1, max_length=20, description="1080×1350 JPEG, base64. 슬라이드 순서대로")
publish: bool = Field(default=False, description="true 면 만들자마자 그날 피드에 올린다. false 면 승인 대기")
+13 -2
View File
@@ -1,10 +1,10 @@
from typing import Optional
from fastapi import APIRouter, Depends, Path, Query
from fastapi import APIRouter, Depends, Path, Query, Request
from common.auth import optional_user
from common.database.model.models import User
from common.enums import ErrorType
from common.enums import ErrorType, PostType
from common.liker import Liker, liker
from common.models.errors import error_info
from router.v1.feed.protocol import Res_Feed, Res_Post
@@ -13,15 +13,26 @@ from services.reaction_service import ReactionService
router = APIRouter(prefix="/v1/feed", tags=["feed"])
# 토스에 올라간 10/13 번들은 UV 까지만 알아서, 그 뒤에 생긴 글 종류(카드뉴스 등)가 오면 흰 화면이 된다
TOSS_KNOWN_MAX = PostType.UV.value
def _from_toss(request: Request) -> bool:
ref = request.headers.get("origin") or request.headers.get("referer") or ""
return "AppsInToss" in request.headers.get("user-agent", "") or ".tossmini.com" in ref
@router.get("", response_model=Res_Feed, response_model_exclude_none=True, summary="메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠")
async def get_feed(
request: Request,
region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker),
service: FeedService = Depends(), reactions: ReactionService = Depends(),
) -> Res_Feed:
err, feed = await service.feed(region)
if err is not ErrorType.SUCCESS:
return Res_Feed(result=error_info(err))
if _from_toss(request):
feed = feed.model_copy(update={"posts": [p for p in feed.posts if p.post_type.value <= TOSS_KNOWN_MAX]})
pinned = [x for x in (feed.hero_post, feed.gak_post, feed.foliage_post, feed.events_post, feed.season_post) if x is not None]
ids = [p.post_id for p in feed.posts] + [x.post_id for x in pinned]
counts = await reactions.counts(ids)
View File
Whitespace-only changes.
+34
View File
@@ -0,0 +1,34 @@
from datetime import datetime
from typing import Optional
from pydantic import Field
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
class Req_ReelCreate(WebPacketProtocol):
title: str = Field(max_length=80, description="인스타 캡션 첫 줄")
caption: str = Field(default="", max_length=2000)
hashtags: str = Field(default="", max_length=600, description="인스타 캡션 뒤에 붙는 해시태그")
video: str = Field(description="mp4(H.264, 9:16), base64, 30MB 이하")
cover: Optional[str] = Field(default=None, description="표지 JPEG, base64 (없으면 인스타가 첫 장면을 쓴다)")
class Res_Reel(Res_WebPacketProtocol):
reel_id: Optional[int] = None
video_url: Optional[str] = None
cover_url: Optional[str] = None
ig_media_id: Optional[str] = None
class ReelItem(WebPacketProtocol):
reel_id: int
title: str
created_at: datetime
video_url: str
cover_url: Optional[str] = None
ig_media_id: Optional[str] = None
class Res_ReelList(Res_WebPacketProtocol):
items: list[ReelItem] = []
+135
View File
@@ -0,0 +1,135 @@
import base64
import binascii
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Path, Query, Request
from fastapi.responses import Response
from common.auth import require_admin
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Reel
from common.enums import ErrorType
from common.logger import LOG
from common.models.errors import error_info
from common.utils.kma_time import KST
from crud.reel_crud import ReelCRUD
from router.v1.reel.protocol import ReelItem, Req_ReelCreate, Res_Reel, Res_ReelList
from services.external import instagram
router = APIRouter(prefix="/v1/reel", tags=["reel"])
_MAX_VIDEO_BYTES = 30 * 1024 * 1024
_MAX_COVER_BYTES = 5 * 1024 * 1024
_crud = ReelCRUD()
def video_url(reel_id: int) -> str:
return f"/v1/reel/{reel_id}.mp4"
def cover_url(reel_id: int) -> str:
return f"/v1/reel/{reel_id}/cover.jpg"
def _decode(b64: str, what: str) -> bytes:
try:
return base64.b64decode(b64.split(",", 1)[-1], validate=True)
except (binascii.Error, ValueError) as e:
raise HTTPException(status_code=400, detail=f"{what}: base64 아님") from e
def _video(b64: str) -> bytes:
data = _decode(b64, "video")
# mp4 는 4바이트 크기 뒤에 'ftyp' 상자로 시작한다
if data[4:8] != b"ftyp" or len(data) > _MAX_VIDEO_BYTES:
raise HTTPException(status_code=400, detail="video: 30MB 이하 mp4 만")
return data
def _cover(b64: Optional[str]) -> Optional[bytes]:
if not b64:
return None
data = _decode(b64, "cover")
if not data.startswith(b"\xff\xd8") or len(data) > _MAX_COVER_BYTES:
raise HTTPException(status_code=400, detail="cover: 5MB 이하 JPEG 만")
return data
def _res(reel: Reel) -> Res_Reel:
return Res_Reel(reel_id=reel.reel_id, video_url=video_url(reel.reel_id), cover_url=cover_url(reel.reel_id) if reel.cover is not None else None, ig_media_id=reel.ig_media_id)
@router.get("", response_model=Res_ReelList, response_model_exclude_none=True, summary="릴스 목록 (관리자)", dependencies=[Depends(require_admin)])
async def list_reels(limit: int = Query(50, ge=1, le=200)) -> Res_ReelList:
err, reels = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.recent(s, limit))
if err is not ErrorType.SUCCESS:
return Res_ReelList(result=error_info(err))
return Res_ReelList(items=[ReelItem(reel_id=r.reel_id, title=r.title, created_at=r.created_at.astimezone(KST), video_url=video_url(r.reel_id), cover_url=cover_url(r.reel_id), ig_media_id=r.ig_media_id) for r in reels or []])
@router.post("", response_model=Res_Reel, response_model_exclude_none=True, summary="릴스 mp4 저장 (관리자). 공개 주소가 생기고, 인스타엔 따로 올린다", dependencies=[Depends(require_admin)])
async def create_reel(req: Req_ReelCreate) -> Res_Reel:
reel = Reel(title=req.title, caption=req.caption, hashtags=req.hashtags.strip() or None, video=_video(req.video), cover=_cover(req.cover))
err, reel = await DB_SESSION_MNG.execute_lambda_write(lambda s: _crud.create(s, reel))
if err is not ErrorType.SUCCESS:
return Res_Reel(result=error_info(err))
LOG.info(f"[reel] saved {reel.reel_id} ({len(reel.video)} bytes)")
return _res(reel)
@router.post("/{reel_id}/instagram", response_model=Res_Reel, response_model_exclude_none=True, summary="릴스를 인스타그램에 올리기 (관리자). 같은 릴스는 한 번만", dependencies=[Depends(require_admin)])
async def publish_instagram(reel_id: int = Path(...)) -> Res_Reel:
if not instagram.configured():
return Res_Reel(result=error_info(ErrorType.INVALID_INPUT), msg="INSTAGRAM_ACCESS_TOKEN / INSTAGRAM_USER_ID 가 설정되지 않았어요")
err, reel = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.get(s, reel_id))
if err is not ErrorType.SUCCESS:
return Res_Reel(result=error_info(err))
if reel is None:
return Res_Reel(result=error_info(ErrorType.NOT_FOUND))
if reel.ig_media_id:
return _res(reel)
caption = "\n\n".join(part for part in (reel.title, reel.caption, reel.hashtags) if part)
cover = instagram.public_image_url(cover_url(reel_id)) if reel.cover is not None else None
try:
media_id = await instagram.publish_reel(instagram.public_image_url(video_url(reel_id)), caption, cover_url=cover)
except instagram.InstagramError as e:
LOG.error(f"[reel] instagram {reel_id}: {e}")
return Res_Reel(result=error_info(ErrorType.EXTERNAL_API_ERROR), msg=str(e), reel_id=reel_id)
async def save(s):
r = await _crud.get(s, reel_id)
if r is not None:
r.ig_media_id = media_id
return r
err, saved = await DB_SESSION_MNG.execute_lambda_write(save)
if err is not ErrorType.SUCCESS or saved is None:
return Res_Reel(result=error_info(err if err is not ErrorType.SUCCESS else ErrorType.NOT_FOUND), msg=f"인스타엔 올라갔지만({media_id}) 저장 실패")
return _res(saved)
# 영상·표지는 바이트 자체를 돌려주므로 실패는 HTTP 상태 코드로 알린다
@router.get("/{reel_id}.mp4", summary="릴스 영상 (인스타가 받아 가는 공개 주소, Range 지원)", responses={200: {"content": {"video/mp4": {}}}, 206: {}, 404: {}})
async def get_reel_video(request: Request, reel_id: int = Path(...)) -> Response:
err, data = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.video(s, reel_id))
if err is not ErrorType.SUCCESS or data is None:
raise HTTPException(status_code=404, detail="not found")
headers = {"Accept-Ranges": "bytes", "Cache-Control": "public, max-age=31536000, immutable", "X-Content-Type-Options": "nosniff"}
rng = request.headers.get("range", "")
if rng.startswith("bytes="):
start_s, _, end_s = rng[6:].partition("-")
start = int(start_s or 0)
end = min(int(end_s) if end_s else len(data) - 1, len(data) - 1)
if start > end:
raise HTTPException(status_code=416, detail="range")
chunk = data[start : end + 1]
return Response(content=chunk, status_code=206, media_type="video/mp4", headers={**headers, "Content-Range": f"bytes {start}-{end}/{len(data)}"})
return Response(content=data, media_type="video/mp4", headers=headers)
@router.get("/{reel_id}/cover.jpg", summary="릴스 표지", responses={200: {"content": {"image/jpeg": {}}}, 404: {}})
async def get_reel_cover(reel_id: int = Path(...)) -> Response:
err, data = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.cover(s, reel_id))
if err is not ErrorType.SUCCESS or data is None:
raise HTTPException(status_code=404, detail="not found")
return Response(content=data, media_type="image/jpeg", headers={"Cache-Control": "public, max-age=31536000, immutable", "X-Content-Type-Options": "nosniff"})
+4 -4
View File
@@ -14,7 +14,7 @@ async def get_today_page(sido: str = Path(..., pattern=_SLUG), place: str = Path
err, html = await service.page(f"today/{sido}/{place}")
if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
@router.get("/today/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)")
@@ -22,7 +22,7 @@ async def get_today_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = P
err, html = await service.page(f"today/{sido}/{place}/{gu}")
if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
@router.get("/tomorrow/{sido}/{place}", response_class=HTMLResponse, summary="지역 내일 날씨 페이지: 정적 HTML 에 내일 예보를 채운다 (nginx 가 /tomorrow/... 를 넘김)")
@@ -30,7 +30,7 @@ async def get_tomorrow_page(sido: str = Path(..., pattern=_SLUG), place: str = P
err, html = await service.page(f"tomorrow/{sido}/{place}")
if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
@router.get("/tomorrow/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 내일 날씨 페이지")
@@ -38,4 +38,4 @@ async def get_tomorrow_gu_page(sido: str = Path(..., pattern=_SLUG), place: str
err, html = await service.page(f"tomorrow/{sido}/{place}/{gu}")
if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
+38 -9
View File
@@ -17,6 +17,9 @@ MAX_ITEMS = 20
# 캐러셀 컨테이너가 FINISHED 가 될 때까지 (문서: 1분에 한 번, 5분까지)
STATUS_TRIES = 10
STATUS_WAIT_SEC = 6.0
# 릴스는 인스타가 영상을 변환하느라 더 오래 걸린다 (5초 간격 5분)
VIDEO_STATUS_TRIES = 60
VIDEO_STATUS_WAIT_SEC = 5.0
class InstagramError(Exception):
@@ -65,15 +68,7 @@ async def publish_carousel(image_urls: list[str], caption: str, client: Optional
container = (await _post(client, f"{user}/media", {"image_url": image_urls[0], "caption": caption}))["id"]
else:
container = (await _post(client, f"{user}/media", {"media_type": "CAROUSEL", "children": ",".join(children), "caption": caption}))["id"]
for _ in range(STATUS_TRIES):
status = await _status(client, container)
if status == "FINISHED":
break
if status in ("ERROR", "EXPIRED"):
raise InstagramError(f"컨테이너 상태 {status}")
await asyncio.sleep(wait_sec)
else:
raise InstagramError("컨테이너가 제때 준비되지 않았다")
await _wait_finished(client, container, STATUS_TRIES, wait_sec)
media_id = (await _post(client, f"{user}/media_publish", {"creation_id": container}))["id"]
LOG.info(f"[instagram] published media {media_id} ({len(image_urls)} images)")
return media_id
@@ -82,3 +77,37 @@ async def publish_carousel(image_urls: list[str], caption: str, client: Optional
finally:
if own:
await client.aclose()
async def _wait_finished(client: httpx.AsyncClient, container: str, tries: int, wait_sec: float) -> None:
for _ in range(tries):
status = await _status(client, container)
if status == "FINISHED":
return
if status in ("ERROR", "EXPIRED"):
raise InstagramError(f"컨테이너 상태 {status}")
await asyncio.sleep(wait_sec)
raise InstagramError("컨테이너가 제때 준비되지 않았다")
async def publish_reel(video_url: str, caption: str, cover_url: Optional[str] = None, client: Optional[httpx.AsyncClient] = None, wait_sec: float = VIDEO_STATUS_WAIT_SEC) -> str:
"""공개 mp4 주소를 릴스로 올리고(피드에도 보이게) 인스타 미디어 id 를 돌려준다."""
if not configured():
raise InstagramError("INSTAGRAM_ACCESS_TOKEN / INSTAGRAM_USER_ID 가 비어 있다")
user = settings.instagram_user_id.strip()
own = client is None
client = client or httpx.AsyncClient(timeout=TIMEOUT_SEC)
try:
data = {"media_type": "REELS", "video_url": video_url, "caption": caption, "share_to_feed": "true"}
if cover_url:
data["cover_url"] = cover_url
container = (await _post(client, f"{user}/media", data))["id"]
await _wait_finished(client, container, VIDEO_STATUS_TRIES, wait_sec)
media_id = (await _post(client, f"{user}/media_publish", {"creation_id": container}))["id"]
LOG.info(f"[instagram] published reel {media_id}")
return media_id
except httpx.HTTPError as e:
raise InstagramError(f"{type(e).__name__}") from e
finally:
if own:
await client.aclose()
+1 -1
View File
@@ -43,7 +43,7 @@ def anyio_backend():
_VOLATILE = (
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "holiday", "solar_term", "users", "card_set", "card_image",
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "holiday", "solar_term", "users", "card_set", "card_image", "reel",
)
+2 -2
View File
@@ -112,7 +112,7 @@ async def test_instagram_publish_carousel_and_store_media_id(offline, admin_key,
assert data["access_token"] == "tok"
if request.url.path.endswith("/1789/media"):
if data.get("media_type") == "CAROUSEL":
assert data["children"] == "c1,c2,c3" and data["caption"].startswith("오늘의 썸 타로")
assert data["children"] == "c1,c2,c3" and data["caption"] == "오늘의 썸 타로\n\n한 장 골라 보세요\n\n#날씨각 #날씨타로"
return httpx.Response(200, json={"id": "car"})
assert data["image_url"].startswith("https://weather.example/v1/card/") and data["is_carousel_item"] == "true"
return httpx.Response(200, json={"id": f"c{len([c for c in calls if 'is_carousel_item' in c[1]])}"})
@@ -126,7 +126,7 @@ async def test_instagram_publish_carousel_and_store_media_id(offline, admin_key,
real = httpx.AsyncClient
monkeypatch.setattr(instagram.httpx, "AsyncClient", lambda **kw: real(transport=httpx.MockTransport(handler)))
async with client() as c:
made = (await c.post("/v1/card", json=body(publish=True), headers=admin_key)).json()
made = (await c.post("/v1/card", json=body(publish=True, hashtags="#날씨각 #날씨타로"), headers=admin_key)).json()
res = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json()
again = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json()
listed = (await c.get("/v1/card", headers=admin_key)).json()["items"][0]
+18
View File
@@ -0,0 +1,18 @@
from starlette.requests import Request
from common.enums import PostType
from router.v1.feed.feed import TOSS_KNOWN_MAX, _from_toss
def _req(headers: dict) -> Request:
return Request({"type": "http", "headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()]})
def test_from_toss_by_referer_or_user_agent():
assert _from_toss(_req({"referer": "https://nalssigak.apps.tossmini.com/"}))
assert _from_toss(_req({"user-agent": "Mozilla/5.0 ... AppsInToss TossApp/5.282.1"}))
assert not _from_toss(_req({"referer": "https://weather.o2o.kr/", "user-agent": "Mozilla/5.0 Safari"}))
def test_card_is_hidden_from_old_toss_bundle():
assert PostType.CARD.value > TOSS_KNOWN_MAX >= PostType.UV.value
+103
View File
@@ -0,0 +1,103 @@
import base64
import pytest
from httpx import ASGITransport, AsyncClient
from config.settings import settings
from router.router import app
KEY = "test-admin-key"
# 가장 작은 mp4 머리 (서버는 'ftyp' 상자만 본다)
MP4_BYTES = b"\x00\x00\x00\x18ftypisom" + b"0" * 200
MP4 = base64.b64encode(MP4_BYTES).decode()
JPEG = base64.b64encode(b"\xff\xd8\xff\xe0" + b"0" * 64).decode()
def client():
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
def body(**kw):
return {"title": "날씨각이 뭐예요?", "caption": "오늘 날씨에 맞는 할 일을 점수로", "hashtags": "#날씨각 #릴스", "video": MP4, **kw}
@pytest.fixture
def admin_key(monkeypatch):
monkeypatch.setattr(settings, "admin_api_key", KEY)
return {"X-Admin-Key": KEY}
@pytest.mark.anyio
async def test_reel_needs_key_and_mp4(admin_key):
async with client() as c:
assert (await c.post("/v1/reel", json=body())).status_code == 401
bad = await c.post("/v1/reel", json=body(video=JPEG), headers=admin_key)
assert bad.status_code == 400
@pytest.mark.anyio
async def test_reel_saved_and_served_with_range(admin_key):
async with client() as c:
made = (await c.post("/v1/reel", json=body(cover=JPEG), headers=admin_key)).json()
assert made["result"]["success"] and made["video_url"] == f"/v1/reel/{made['reel_id']}.mp4" and made["cover_url"].endswith("/cover.jpg")
full = await c.get(made["video_url"])
assert full.status_code == 200 and full.headers["content-type"] == "video/mp4" and full.content == MP4_BYTES
part = await c.get(made["video_url"], headers={"Range": "bytes=4-7"})
assert part.status_code == 206 and part.content == b"ftyp" and part.headers["content-range"] == f"bytes 4-7/{len(MP4_BYTES)}"
cover = await c.get(made["cover_url"])
assert cover.status_code == 200 and cover.headers["content-type"] == "image/jpeg"
listed = (await c.get("/v1/reel", headers=admin_key)).json()["items"]
assert listed[0]["reel_id"] == made["reel_id"] and "video" not in listed[0]
assert (await c.get("/v1/reel/999999.mp4")).status_code == 404
@pytest.mark.anyio
async def test_reel_instagram_publish_and_store_media_id(admin_key, monkeypatch):
import httpx
from services.external import instagram
monkeypatch.setattr(settings, "instagram_access_token", "tok")
monkeypatch.setattr(settings, "instagram_user_id", "1789")
monkeypatch.setattr(settings, "public_base_url", "https://weather.example")
monkeypatch.setattr(instagram, "VIDEO_STATUS_WAIT_SEC", 0.0)
calls: list[tuple[str, dict]] = []
polls = {"n": 0}
def handler(request: httpx.Request) -> httpx.Response:
data = dict(httpx.QueryParams(request.content.decode())) if request.method == "POST" else dict(request.url.params)
calls.append((request.url.path, data))
assert data["access_token"] == "tok"
if request.url.path.endswith("/1789/media"):
assert data["media_type"] == "REELS" and data["share_to_feed"] == "true"
assert data["video_url"].startswith("https://weather.example/v1/reel/") and data["video_url"].endswith(".mp4")
assert data["cover_url"].endswith("/cover.jpg")
assert data["caption"] == "날씨각이 뭐예요?\n\n오늘 날씨에 맞는 할 일을 점수로\n\n#날씨각 #릴스"
return httpx.Response(200, json={"id": "vid"})
if request.url.path.endswith("/vid"):
polls["n"] += 1
return httpx.Response(200, json={"status_code": "IN_PROGRESS" if polls["n"] < 3 else "FINISHED"})
if request.url.path.endswith("/media_publish"):
assert data["creation_id"] == "vid"
return httpx.Response(200, json={"id": "reel77"})
return httpx.Response(404, json={"error": {"message": "no"}})
real = httpx.AsyncClient
monkeypatch.setattr(instagram.httpx, "AsyncClient", lambda **kw: real(transport=httpx.MockTransport(handler)))
async with client() as c:
made = (await c.post("/v1/reel", json=body(cover=JPEG), headers=admin_key)).json()
res = (await c.post(f"/v1/reel/{made['reel_id']}/instagram", headers=admin_key)).json()
again = (await c.post(f"/v1/reel/{made['reel_id']}/instagram", headers=admin_key)).json()
listed = (await c.get("/v1/reel", headers=admin_key)).json()["items"][0]
assert res["result"]["success"] and res["ig_media_id"] == "reel77" and polls["n"] == 3
assert again["ig_media_id"] == "reel77" and len([p for p, _ in calls if p.endswith("/media_publish")]) == 1
assert listed["ig_media_id"] == "reel77"
@pytest.mark.anyio
async def test_reel_instagram_requires_token(admin_key, monkeypatch):
monkeypatch.setattr(settings, "instagram_access_token", "")
async with client() as c:
made = (await c.post("/v1/reel", json=body(), headers=admin_key)).json()
res = (await c.post(f"/v1/reel/{made['reel_id']}/instagram", headers=admin_key)).json()
assert res["result"]["success"] is False and "INSTAGRAM" in res["msg"]