feat: 인스타 릴스 — 릴스 mp4 저장·공개 주소(/v1/reel)·REELS 게시 API, 관리자 relay, 소개 릴스 HyperFrames 프로젝트·배경 5장, 인스타 올리기 nginx 타임아웃 600s
This commit is contained in:
1 parent
70fe14ae39
commit
7469e58a89
64 files changed
+928
-11
No files matched your search
@@ -334,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"
|
||||
|
||||
|
||||
@@ -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))
|
||||
@@ -497,3 +497,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()
|
||||
);
|
||||
@@ -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):
|
||||
|
||||
Whitespace-only changes.
@@ -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] = []
|
||||
@@ -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"})
|
||||
+38
-9
@@ -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()
|
||||
@@ -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",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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"]
|
||||
Reference in new issue
Block a user