chore: main 병합 — 로그인 없이 댓글·좋아요, 구글 로그인만, 동네 이야기·카드뉴스 등 (차단 표 user_block 하나로 합침, 익명 댓글도 신고 가능)
This commit is contained in:
commit
dba34675c8
408 files changed
+36377
-725
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import hmac
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
@@ -75,3 +76,9 @@ async def current_user(user: Optional[User] = Depends(optional_user)) -> User:
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail=ErrorType.AUTH_REQUIRED.name)
|
||||
return user
|
||||
|
||||
|
||||
async def require_admin(x_admin_key: Optional[str] = Header(None)) -> None:
|
||||
"""관리자 도구(admin/) 전용 API. ADMIN_API_KEY 가 비어 있으면 아무도 못 부른다."""
|
||||
if not settings.admin_api_key or not x_admin_key or not hmac.compare_digest(x_admin_key, settings.admin_api_key):
|
||||
raise HTTPException(status_code=401, detail=ErrorType.AUTH_FAILED.name)
|
||||
@@ -3,7 +3,7 @@ from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import BigInteger, Boolean, Date, DateTime, Integer, Numeric, SmallInteger, String, func
|
||||
from sqlalchemy import BigInteger, Boolean, Date, DateTime, ForeignKey, Integer, LargeBinary, Numeric, SmallInteger, String, Text, func
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
@@ -309,6 +309,44 @@ class Post(Base):
|
||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class CardSet(Base):
|
||||
__tablename__ = "card_set"
|
||||
|
||||
card_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
template: Mapped[str] = mapped_column(String(20))
|
||||
topic: Mapped[Optional[str]] = mapped_column(String(60), nullable=True)
|
||||
title: Mapped[str] = mapped_column(String(80))
|
||||
caption: Mapped[str] = mapped_column(Text, default="")
|
||||
copy: Mapped[dict] = mapped_column(JSONB, default=dict)
|
||||
status: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
post_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||
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):
|
||||
__tablename__ = "card_image"
|
||||
|
||||
card_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("card_set.card_id", ondelete="CASCADE"), primary_key=True)
|
||||
seq: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
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"
|
||||
|
||||
@@ -337,6 +375,14 @@ class PostLike(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class PostLikeAnon(Base):
|
||||
__tablename__ = "post_like_anon"
|
||||
|
||||
post_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
ip_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class PostSave(Base):
|
||||
__tablename__ = "post_save"
|
||||
|
||||
@@ -350,7 +396,9 @@ class Comment(Base):
|
||||
|
||||
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
post_id: Mapped[int] = mapped_column(BigInteger)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
|
||||
user_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), nullable=True)
|
||||
ip_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||
body: Mapped[str] = mapped_column(String(60))
|
||||
like_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
report_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
@@ -382,3 +430,65 @@ class CommentLike(Base):
|
||||
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class CommentLikeAnon(Base):
|
||||
__tablename__ = "comment_like_anon"
|
||||
|
||||
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
ip_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class MyGak(Base):
|
||||
__tablename__ = "my_gak"
|
||||
|
||||
my_gak_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
|
||||
name: Mapped[str] = mapped_column(String(12))
|
||||
rule: Mapped[dict] = mapped_column(JSONB)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class Talk(Base):
|
||||
__tablename__ = "talk"
|
||||
|
||||
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
|
||||
region_code: Mapped[str] = mapped_column(String(10))
|
||||
body: Mapped[str] = mapped_column(String(100))
|
||||
weather: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)
|
||||
image: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
topic: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
like_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
report_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
hidden: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class TalkLike(Base):
|
||||
__tablename__ = "talk_like"
|
||||
|
||||
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class TalkLikeAnon(Base):
|
||||
__tablename__ = "talk_like_anon"
|
||||
|
||||
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
ip_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class TalkReport(Base):
|
||||
__tablename__ = "talk_report"
|
||||
|
||||
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
reason: Mapped[int] = mapped_column(SmallInteger)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ class ErrorType(Enum):
|
||||
EXTERNAL_API_ERROR = 2001
|
||||
NOT_FOUND = 3001
|
||||
INVALID_INPUT = 3002
|
||||
DAILY_LIMIT = 3003 # 하루에 쓸 수 있는 수를 넘음
|
||||
LINK_NOT_ALLOWED = 3004 # 글에 링크·전화번호
|
||||
AUTH_REQUIRED = 4001
|
||||
AUTH_FAILED = 4002
|
||||
AUTH_DUPLICATE_ID = 4003
|
||||
@@ -114,6 +116,23 @@ class IndexCategory(CodeEnum):
|
||||
LIFE = 4
|
||||
|
||||
|
||||
class TalkTopic(CodeEnum):
|
||||
"""사람 글 주제. 안 고르면 동네 이야기. 피드에서 같은 주제 포스트 옆에 묶어 보여 준다"""
|
||||
|
||||
LOCAL = 1 # 동네 이야기
|
||||
SKY = 2 # 하늘·노을
|
||||
RAIN = 3 # 비·눈
|
||||
FOLIAGE = 4 # 단풍·꽃
|
||||
OUTFIT = 5 # 오늘 옷차림
|
||||
|
||||
|
||||
class TalkReport(CodeEnum):
|
||||
ABUSE = 1 # 욕설·비하
|
||||
SPAM = 2 # 광고·도배
|
||||
PRIVACY = 3 # 개인정보 노출
|
||||
ETC = 4
|
||||
|
||||
|
||||
class ArticleCategory(CodeEnum):
|
||||
SEASON = 1
|
||||
TIP = 2
|
||||
@@ -137,6 +156,12 @@ class PostType(CodeEnum):
|
||||
DAY_TRIP = 13 # 당일치기: 1~2시간 거리 후보 도시 중 주말 날씨 1위 + 그곳 행사
|
||||
MOON = 14 # 오늘 밤 달 (보름·삭이면 그 이야기)
|
||||
UV = 15 # 오늘 낮 자외선 (아침·낮, '보통' 이상인 날만)
|
||||
HERO = 16 # 히어로(오늘 날씨)의 좋아요·댓글 자리. 피드 목록엔 안 나온다
|
||||
TODAY_GAK = 17 # 오늘의 각 카드의 좋아요·댓글 자리. 피드 목록엔 안 나온다
|
||||
FOLIAGE = 18 # 단풍 지도 카드의 좋아요·댓글 자리. 피드 목록엔 안 나온다
|
||||
EVENTS_BAND = 19 # 이번 주 가까운 행사 띠의 좋아요·댓글 자리
|
||||
SEASON_BAND = 20 # 이번 주 계절 이야기 띠의 좋아요·댓글 자리
|
||||
CARD = 21 # 카드뉴스: 관리자(admin/)가 만든 이미지 묶음을 그날 전국 피드에 올린다
|
||||
|
||||
|
||||
class EventKind(CodeEnum):
|
||||
@@ -155,6 +180,13 @@ class RefType(CodeEnum):
|
||||
INDEX = 2
|
||||
ARTICLE = 3
|
||||
EVENT = 4
|
||||
CARD = 5
|
||||
|
||||
|
||||
class CardStatus(CodeEnum):
|
||||
WAITING = 1 # 승인 대기
|
||||
PUBLISHED = 2
|
||||
REJECTED = 3
|
||||
|
||||
|
||||
class AuthProvider(CodeEnum):
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, Request
|
||||
|
||||
from common.auth import optional_user
|
||||
from common.database.model.models import User
|
||||
from config.settings import settings
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Liker:
|
||||
"""좋아요를 누른 사람. 로그인했으면 user_id, 아니면 IP 해시로 한 번만 센다."""
|
||||
user_id: Optional[uuid.UUID]
|
||||
ip_hash: str
|
||||
|
||||
|
||||
def client_ip(request: Request) -> str:
|
||||
"""nginx 가 X-Forwarded-For 맨 끝에 붙인 접속 주소만 믿는다. 앞쪽은 클라이언트가 마음대로 넣을 수 있다."""
|
||||
xff = request.headers.get("x-forwarded-for", "")
|
||||
last = xff.rsplit(",", 1)[-1].strip()
|
||||
if last:
|
||||
return last
|
||||
return request.client.host if request.client else ""
|
||||
|
||||
|
||||
def ip_hash(ip: str) -> str:
|
||||
"""IP 원문은 저장하지 않는다. 서버 비밀값으로 HMAC 한 값만 남긴다."""
|
||||
if not settings.jwt_refresh_secret:
|
||||
raise RuntimeError("JWT_REFRESH_SECRET is empty")
|
||||
return hmac.new(settings.jwt_refresh_secret.encode(), f"like-ip:{ip}".encode(), hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
async def liker(request: Request, user: Optional[User] = Depends(optional_user)) -> Liker:
|
||||
return Liker(user_id=user.user_id if user else None, ip_hash=ip_hash(client_ip(request)))
|
||||
@@ -28,12 +28,29 @@ class Settings(BaseSettings):
|
||||
|
||||
data_go_kr_service_key: str = ""
|
||||
teams_webhook_url: str = ""
|
||||
# 관리자 도구(admin/)가 카드뉴스를 올릴 때 X-Admin-Key 로 보내는 값. 비어 있으면 관리자 API 는 막힌다
|
||||
admin_api_key: str = ""
|
||||
# 인스타그램 올리기 (Instagram API with Instagram Login). 비어 있으면 '인스타에 올리기'가 막힌다
|
||||
instagram_access_token: str = ""
|
||||
instagram_user_id: str = ""
|
||||
# 인스타가 카드 이미지를 받아 갈 공개 주소 (프론트 nginx 가 /v1 을 백엔드로 넘긴다)
|
||||
public_base_url: str = "https://weather.o2o.kr"
|
||||
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
|
||||
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr"
|
||||
|
||||
# 지역 검색 페이지의 정적 HTML 을 받아 올 프론트 주소 (같은 docker 망 안)
|
||||
frontend_internal_url: str = "http://frontend"
|
||||
|
||||
# 사람 글 사진을 저장할 폴더 (compose 볼륨)
|
||||
upload_dir: str = "uploads"
|
||||
# 사람 글 사진을 올릴 Azure Blob. 접속 문자열이 비면 위 폴더에 저장한다
|
||||
azure_storage_connection_string: str = ""
|
||||
azure_storage_container: str = ""
|
||||
azure_storage_prefix: str = "nalssigak"
|
||||
# 접속 문자열 대신 컨테이너 주소 + SAS 토큰으로도 올릴 수 있다
|
||||
azure_blob_base_url: str = ""
|
||||
azure_blob_sas_token: str = ""
|
||||
|
||||
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
|
||||
google_client_id: str = ""
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import CardImage, CardSet, Post
|
||||
from common.enums import CardStatus, PostType, RefType
|
||||
|
||||
# 카드뉴스 포스트 번호. 03:00 에 만드는 카드(LINEUP 1~20)와 겹치지 않게 101부터
|
||||
CARD_POSITION_START = 101
|
||||
NATIONAL_SCOPE = "00"
|
||||
|
||||
|
||||
class CardCRUD:
|
||||
async def create(self, s: AsyncSession, card: CardSet, images: list[bytes]) -> CardSet:
|
||||
s.add(card)
|
||||
await s.flush()
|
||||
s.add_all(CardImage(card_id=card.card_id, seq=i + 1, data=data) for i, data in enumerate(images))
|
||||
return card
|
||||
|
||||
async def get(self, s: AsyncSession, card_id: int) -> Optional[CardSet]:
|
||||
return await s.get(CardSet, card_id)
|
||||
|
||||
async def recent(self, s: AsyncSession, limit: int) -> list[CardSet]:
|
||||
"""만든 순서 역순. 올린 것·승인 대기·반려 모두."""
|
||||
return list((await s.scalars(select(CardSet).order_by(CardSet.card_id.desc()).limit(limit))).all())
|
||||
|
||||
async def many(self, s: AsyncSession, card_ids: list[int]) -> list[CardSet]:
|
||||
if not card_ids:
|
||||
return []
|
||||
return list((await s.scalars(select(CardSet).where(CardSet.card_id.in_(card_ids)))).all())
|
||||
|
||||
async def image_counts(self, s: AsyncSession, card_ids: list[int]) -> dict[int, int]:
|
||||
if not card_ids:
|
||||
return {}
|
||||
rows = await s.execute(select(CardImage.card_id, func.count()).where(CardImage.card_id.in_(card_ids)).group_by(CardImage.card_id))
|
||||
return {card_id: n for card_id, n in rows.all()}
|
||||
|
||||
async def image(self, s: AsyncSession, card_id: int, seq: int) -> Optional[bytes]:
|
||||
row = await s.get(CardImage, (card_id, seq))
|
||||
return row.data if row is not None else None
|
||||
|
||||
async def publish(self, s: AsyncSession, card: CardSet, day: date, now: datetime, end: datetime) -> Post:
|
||||
"""그날 전국 피드에 포스트 하나로 올린다. 같은 날 여러 개면 번호를 하나씩 늘린다."""
|
||||
last = await s.scalar(select(func.max(Post.position)).where(Post.feed_date == day, Post.scope == NATIONAL_SCOPE, Post.position >= CARD_POSITION_START))
|
||||
post = Post(feed_date=day, position=(last or CARD_POSITION_START - 1) + 1, scope=NATIONAL_SCOPE, post_type=PostType.CARD.value,
|
||||
ref_type=RefType.CARD.value, ref_id=card.card_id, published_at=now, end_at=end)
|
||||
s.add(post)
|
||||
await s.flush()
|
||||
card.status, card.post_id, card.published_at = CardStatus.PUBLISHED.value, post.post_id, now
|
||||
return post
|
||||
@@ -35,9 +35,10 @@ class IndexCRUD:
|
||||
return await s.scalar(stmt)
|
||||
|
||||
async def has_unslotted(self, s: AsyncSession, region_code: str, day: date) -> bool:
|
||||
"""그날 행 중 구간 점수가 비어 있는 행(구간 계산 전 행)이 있는지."""
|
||||
"""현재 방식으로 모든 구간을 계산하지 않은 행이 있는지."""
|
||||
stmt = select(IndexScore.index_id).where(
|
||||
IndexScore.region_code == region_code, IndexScore.score_date == day, text("index_score.slots = '{}'::jsonb")
|
||||
IndexScore.region_code == region_code, IndexScore.score_date == day,
|
||||
text("NOT (index_score.slots ?& ARRAY['morning', 'day', 'evening', 'night', 'early'])")
|
||||
).limit(1)
|
||||
return (await s.scalar(stmt)) is not None
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import MyGak
|
||||
|
||||
|
||||
class MyGakCRUD:
|
||||
async def of_user(self, s: AsyncSession, user_id: uuid.UUID) -> list[MyGak]:
|
||||
return list((await s.scalars(select(MyGak).where(MyGak.user_id == user_id).order_by(MyGak.my_gak_id))).all())
|
||||
|
||||
async def count(self, s: AsyncSession, user_id: uuid.UUID) -> int:
|
||||
return await s.scalar(select(func.count()).select_from(MyGak).where(MyGak.user_id == user_id))
|
||||
|
||||
async def add(self, s: AsyncSession, user_id: uuid.UUID, name: str, rule: dict) -> MyGak:
|
||||
row = MyGak(user_id=user_id, name=name, rule=rule)
|
||||
s.add(row)
|
||||
await s.flush()
|
||||
return row
|
||||
|
||||
async def delete(self, s: AsyncSession, user_id: uuid.UUID, my_gak_id: int) -> bool:
|
||||
res = await s.execute(delete(MyGak).where(MyGak.my_gak_id == my_gak_id, MyGak.user_id == user_id).returning(MyGak.my_gak_id))
|
||||
return res.first() is not None
|
||||
@@ -1,23 +1,32 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import delete, select, update
|
||||
from sqlalchemy import delete, func, or_, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import Comment, CommentLike, CommentReport, Post, PostLike, PostSave, User, UserBlock
|
||||
from common.database.model.models import Comment, CommentLike, CommentLikeAnon, CommentReport, Post, PostLike, PostLikeAnon, PostSave, User, UserBlock
|
||||
from common.liker import Liker
|
||||
|
||||
HIDE_AT = 3 # 신고가 이만큼 쌓이면 모두에게서 숨긴다
|
||||
|
||||
|
||||
async def toggle_like_row(s: AsyncSession, who: Liker, member: type, anon: type, id_name: str, id_value: int, on: bool) -> bool:
|
||||
"""로그인했으면 member 표에 user_id 로, 아니면 anon 표에 ip_hash 로 넣거나 지운다. 실제로 바뀌었으면 True."""
|
||||
model, keys = (member, {id_name: id_value, "user_id": who.user_id}) if who.user_id is not None else (anon, {id_name: id_value, "ip_hash": who.ip_hash})
|
||||
id_col = getattr(model, id_name)
|
||||
if on:
|
||||
res = await s.execute(insert(model).values(**keys).on_conflict_do_nothing().returning(id_col))
|
||||
else:
|
||||
res = await s.execute(delete(model).where(*(getattr(model, k) == v for k, v in keys.items())).returning(id_col))
|
||||
return res.first() is not None
|
||||
|
||||
|
||||
class ReactionCRUD:
|
||||
async def toggle_post_like(self, s: AsyncSession, post_id: int, user_id: uuid.UUID, on: bool) -> int:
|
||||
async def toggle_post_like(self, s: AsyncSession, post_id: int, who: Liker, on: bool) -> int:
|
||||
"""좋아요를 켜거나 끄고, 실제로 바뀌었을 때만 수를 고친다. 바뀐 뒤 좋아요 수를 돌려준다."""
|
||||
if on:
|
||||
res = await s.execute(insert(PostLike).values(post_id=post_id, user_id=user_id).on_conflict_do_nothing().returning(PostLike.post_id))
|
||||
else:
|
||||
res = await s.execute(delete(PostLike).where(PostLike.post_id == post_id, PostLike.user_id == user_id).returning(PostLike.post_id))
|
||||
if res.first() is not None:
|
||||
if await toggle_like_row(s, who, PostLike, PostLikeAnon, "post_id", post_id, on):
|
||||
await s.execute(update(Post).where(Post.post_id == post_id).values(like_count=Post.like_count + (1 if on else -1)))
|
||||
return await s.scalar(select(Post.like_count).where(Post.post_id == post_id))
|
||||
|
||||
@@ -36,21 +45,24 @@ class ReactionCRUD:
|
||||
saved = set((await s.scalars(select(PostSave.post_id).where(PostSave.user_id == user_id, PostSave.post_id.in_(post_ids)))).all())
|
||||
return liked, saved
|
||||
|
||||
async def anon_liked_posts(self, s: AsyncSession, ip_hash: str, post_ids: list[int]) -> set[int]:
|
||||
return set((await s.scalars(select(PostLikeAnon.post_id).where(PostLikeAnon.ip_hash == ip_hash, PostLikeAnon.post_id.in_(post_ids)))).all())
|
||||
|
||||
async def saved_posts(self, s: AsyncSession, user_id: uuid.UUID, cursor: Optional[int], limit: int) -> list[tuple[Post, PostSave]]:
|
||||
stmt = select(Post, PostSave).join(PostSave, PostSave.post_id == Post.post_id).where(PostSave.user_id == user_id, Post.deleted.is_(False))
|
||||
if cursor is not None:
|
||||
stmt = stmt.where(Post.post_id < cursor)
|
||||
return list((await s.execute(stmt.order_by(Post.post_id.desc()).limit(limit))).all())
|
||||
|
||||
async def comments(self, s: AsyncSession, post_id: int, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Comment, str, str, str, Optional[str]]]:
|
||||
"""숨긴 댓글은 빼고, 보는 사람이 신고한 댓글·차단한 사람의 댓글도 뺀다."""
|
||||
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).join(User, User.user_id == Comment.user_id).where(
|
||||
async def comments(self, s: AsyncSession, post_id: int, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Comment, Optional[str], Optional[str], Optional[str], Optional[str]]]:
|
||||
"""로그인 없이 쓴 댓글은 User 칸이 모두 None 이다. 숨긴 댓글은 빼고, 보는 사람이 신고한 댓글·차단한 사람의 댓글도 뺀다."""
|
||||
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).outerjoin(User, User.user_id == Comment.user_id).where(
|
||||
Comment.post_id == post_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)
|
||||
)
|
||||
if viewer is not None:
|
||||
stmt = stmt.where(
|
||||
Comment.comment_id.not_in(select(CommentReport.comment_id).where(CommentReport.user_id == viewer)),
|
||||
Comment.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer)),
|
||||
or_(Comment.user_id.is_(None), Comment.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer))),
|
||||
)
|
||||
if cursor is not None:
|
||||
stmt = stmt.where(Comment.comment_id > cursor)
|
||||
@@ -60,16 +72,24 @@ class ReactionCRUD:
|
||||
stmt = select(CommentLike.comment_id).where(CommentLike.user_id == user_id, CommentLike.comment_id.in_(comment_ids))
|
||||
return set((await s.scalars(stmt)).all())
|
||||
|
||||
async def add_comment(self, s: AsyncSession, post_id: int, user_id: uuid.UUID, body: str) -> Comment:
|
||||
c = Comment(post_id=post_id, user_id=user_id, body=body)
|
||||
async def anon_liked_comments(self, s: AsyncSession, ip_hash: str, comment_ids: list[int]) -> set[int]:
|
||||
stmt = select(CommentLikeAnon.comment_id).where(CommentLikeAnon.ip_hash == ip_hash, CommentLikeAnon.comment_id.in_(comment_ids))
|
||||
return set((await s.scalars(stmt)).all())
|
||||
|
||||
async def add_comment(self, s: AsyncSession, post_id: int, who: Liker, body: str, region_name: Optional[str]) -> Comment:
|
||||
c = Comment(post_id=post_id, user_id=who.user_id, body=body) if who.user_id is not None else Comment(post_id=post_id, ip_hash=who.ip_hash, region_name=region_name, body=body)
|
||||
s.add(c)
|
||||
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count + 1))
|
||||
await s.flush()
|
||||
return c
|
||||
|
||||
async def delete_comment(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID) -> bool:
|
||||
async def anon_comments_since(self, s: AsyncSession, ip_hash: str, since: datetime) -> int:
|
||||
return await s.scalar(select(func.count()).select_from(Comment).where(Comment.user_id.is_(None), Comment.ip_hash == ip_hash, Comment.created_at >= since))
|
||||
|
||||
async def delete_comment(self, s: AsyncSession, comment_id: int, who: Liker) -> bool:
|
||||
owner = Comment.user_id == who.user_id if who.user_id is not None else (Comment.user_id.is_(None) & (Comment.ip_hash == who.ip_hash))
|
||||
res = await s.execute(
|
||||
update(Comment).where(Comment.comment_id == comment_id, Comment.user_id == user_id, Comment.deleted.is_(False))
|
||||
update(Comment).where(Comment.comment_id == comment_id, owner, Comment.deleted.is_(False))
|
||||
.values(deleted=True).returning(Comment.post_id, Comment.is_hidden)
|
||||
)
|
||||
row = res.first()
|
||||
@@ -80,20 +100,17 @@ class ReactionCRUD:
|
||||
await s.execute(update(Post).where(Post.post_id == row.post_id).values(comment_count=Post.comment_count - 1))
|
||||
return True
|
||||
|
||||
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID, on: bool) -> Optional[int]:
|
||||
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, who: Liker, on: bool) -> Optional[int]:
|
||||
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)))
|
||||
if exists is None:
|
||||
return None
|
||||
if on:
|
||||
res = await s.execute(insert(CommentLike).values(comment_id=comment_id, user_id=user_id).on_conflict_do_nothing().returning(CommentLike.comment_id))
|
||||
else:
|
||||
res = await s.execute(delete(CommentLike).where(CommentLike.comment_id == comment_id, CommentLike.user_id == user_id).returning(CommentLike.comment_id))
|
||||
if res.first() is not None:
|
||||
if await toggle_like_row(s, who, CommentLike, CommentLikeAnon, "comment_id", comment_id, on):
|
||||
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(like_count=Comment.like_count + (1 if on else -1)))
|
||||
return await s.scalar(select(Comment.like_count).where(Comment.comment_id == comment_id))
|
||||
|
||||
async def comment_author(self, s: AsyncSession, comment_id: int) -> Optional[uuid.UUID]:
|
||||
return await s.scalar(select(Comment.user_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)))
|
||||
async def comment_author(self, s: AsyncSession, comment_id: int):
|
||||
"""지금 보이는 댓글이면 (comment_id, user_id) 행, 없으면 None. 로그인 없이 쓴 댓글은 user_id 가 None."""
|
||||
return (await s.execute(select(Comment.comment_id, Comment.user_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)))).first()
|
||||
|
||||
async def report_comment(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID, reason: int) -> None:
|
||||
"""같은 사람이 두 번 신고해도 한 번만 센다. HIDE_AT 건이 되면 숨기고 댓글 수에서 뺀다."""
|
||||
|
||||
@@ -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))
|
||||
@@ -0,0 +1,96 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import BigInteger, case, cast, delete, func, select, tuple_, update
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import Region, Talk, TalkLike, TalkLikeAnon, TalkReport, User, UserBlock
|
||||
from common.liker import Liker
|
||||
from crud.reaction_crud import toggle_like_row
|
||||
|
||||
|
||||
class TalkCRUD:
|
||||
async def page(
|
||||
self, s: AsyncSession, viewer: Optional[uuid.UUID], sido: Optional[str], boost_sec: int, cursor: Optional[tuple[int, int]], limit: int,
|
||||
topic: Optional[int] = None,
|
||||
) -> list[tuple[Talk, User, Optional[str], int]]:
|
||||
"""최신 글부터. 보는 사람과 같은 시도 글은 boost_sec 만큼 늦게 쓴 것처럼 앞에 둔다. 숨김·지운 글과 내가 안 보기로 한 사람의 글은 뺀다.
|
||||
cursor 는 앞 페이지 마지막 글의 (정렬 키, talk_id)."""
|
||||
key = cast(func.floor(func.extract("epoch", Talk.created_at)), BigInteger)
|
||||
if sido:
|
||||
key = key + case((func.left(Talk.region_code, 2) == sido, boost_sec), else_=0)
|
||||
stmt = (
|
||||
select(Talk, User, Region.short_name, key)
|
||||
.join(User, User.user_id == Talk.user_id)
|
||||
.outerjoin(Region, Region.code == Talk.region_code)
|
||||
.where(Talk.deleted.is_(False), Talk.hidden.is_(False), User.deleted.is_(False))
|
||||
)
|
||||
if viewer is not None:
|
||||
stmt = stmt.where(Talk.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer)))
|
||||
if topic is not None:
|
||||
stmt = stmt.where(Talk.topic == topic)
|
||||
if cursor is not None:
|
||||
stmt = stmt.where(tuple_(key, Talk.talk_id) < tuple_(*cursor))
|
||||
return list((await s.execute(stmt.order_by(key.desc(), Talk.talk_id.desc()).limit(limit))).all())
|
||||
|
||||
async def recent(self, s: AsyncSession, viewer: Optional[uuid.UUID], since: datetime, limit: int) -> list[tuple[Talk, User, Optional[str]]]:
|
||||
"""since 뒤에 쓴 글 최신순 (숨김·지운 글, 내가 안 보기로 한 사람 글 빼고). 피드 묶음을 고를 재료"""
|
||||
stmt = (
|
||||
select(Talk, User, Region.short_name)
|
||||
.join(User, User.user_id == Talk.user_id)
|
||||
.outerjoin(Region, Region.code == Talk.region_code)
|
||||
.where(Talk.deleted.is_(False), Talk.hidden.is_(False), User.deleted.is_(False), Talk.created_at >= since)
|
||||
)
|
||||
if viewer is not None:
|
||||
stmt = stmt.where(Talk.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer)))
|
||||
return list((await s.execute(stmt.order_by(Talk.created_at.desc()).limit(limit))).all())
|
||||
|
||||
async def mine(self, s: AsyncSession, user_id: uuid.UUID, cursor: Optional[int], limit: int) -> list[tuple[Talk, Optional[str]]]:
|
||||
"""내가 쓴 글, 최신부터. 신고로 숨겨진 글도 쓴 사람에겐 보인다."""
|
||||
stmt = select(Talk, Region.short_name).outerjoin(Region, Region.code == Talk.region_code).where(Talk.user_id == user_id, Talk.deleted.is_(False))
|
||||
if cursor is not None:
|
||||
stmt = stmt.where(Talk.talk_id < cursor)
|
||||
return list((await s.execute(stmt.order_by(Talk.talk_id.desc()).limit(limit))).all())
|
||||
|
||||
async def liked(self, s: AsyncSession, user_id: uuid.UUID, talk_ids: list[int]) -> set[int]:
|
||||
return set((await s.scalars(select(TalkLike.talk_id).where(TalkLike.user_id == user_id, TalkLike.talk_id.in_(talk_ids)))).all())
|
||||
|
||||
async def anon_liked(self, s: AsyncSession, ip_hash: str, talk_ids: list[int]) -> set[int]:
|
||||
return set((await s.scalars(select(TalkLikeAnon.talk_id).where(TalkLikeAnon.ip_hash == ip_hash, TalkLikeAnon.talk_id.in_(talk_ids)))).all())
|
||||
|
||||
async def count_since(self, s: AsyncSession, user_id: uuid.UUID, since: datetime) -> int:
|
||||
return await s.scalar(select(func.count()).select_from(Talk).where(Talk.user_id == user_id, Talk.created_at >= since))
|
||||
|
||||
async def add(
|
||||
self, s: AsyncSession, user_id: uuid.UUID, region_code: str, body: str, weather: Optional[str], image: Optional[str] = None, topic: int = 1
|
||||
) -> Talk:
|
||||
t = Talk(user_id=user_id, region_code=region_code, body=body, weather=weather, image=image, topic=topic)
|
||||
s.add(t)
|
||||
await s.flush()
|
||||
await s.refresh(t)
|
||||
return t
|
||||
|
||||
async def get(self, s: AsyncSession, talk_id: int) -> Optional[Talk]:
|
||||
return await s.scalar(select(Talk).where(Talk.talk_id == talk_id, Talk.deleted.is_(False)))
|
||||
|
||||
async def delete(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID) -> bool:
|
||||
res = await s.execute(update(Talk).where(Talk.talk_id == talk_id, Talk.user_id == user_id, Talk.deleted.is_(False)).values(deleted=True).returning(Talk.talk_id))
|
||||
return res.first() is not None
|
||||
|
||||
async def toggle_like(self, s: AsyncSession, talk_id: int, who: Liker, on: bool) -> int:
|
||||
"""좋아요를 켜거나 끄고, 실제로 바뀌었을 때만 수를 고친다. 바뀐 뒤 좋아요 수를 돌려준다."""
|
||||
if await toggle_like_row(s, who, TalkLike, TalkLikeAnon, "talk_id", talk_id, on):
|
||||
await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(like_count=Talk.like_count + (1 if on else -1)))
|
||||
return await s.scalar(select(Talk.like_count).where(Talk.talk_id == talk_id))
|
||||
|
||||
async def report(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID, reason: int, hide_at: int) -> None:
|
||||
"""한 사람은 한 번만 센다. hide_at 건이 되면 숨긴다."""
|
||||
res = await s.execute(insert(TalkReport).values(talk_id=talk_id, user_id=user_id, reason=reason).on_conflict_do_nothing().returning(TalkReport.talk_id))
|
||||
if res.first() is None:
|
||||
return
|
||||
await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(report_count=Talk.report_count + 1, hidden=Talk.report_count + 1 >= hide_at))
|
||||
|
||||
async def block(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> None:
|
||||
await s.execute(insert(UserBlock).values(user_id=user_id, blocked_id=blocked_id).on_conflict_do_nothing())
|
||||
@@ -168,8 +168,8 @@ CREATE TABLE IF NOT EXISTS public.post (
|
||||
post_id BIGSERIAL PRIMARY KEY,
|
||||
feed_date DATE NOT NULL,
|
||||
position SMALLINT NOT NULL, -- 그날 카드 번호 (1부터). 화면 순서는 시간대마다 따로 정한다
|
||||
post_type SMALLINT NOT NULL, -- PostType: 1=오늘날씨 2=지수 3=노을 4=계절소식 5=행사 6=상식 7=주말예보 8=우산·특보 9=내일미리보기 10=한문장 11=주말플랜 12=미세먼지
|
||||
ref_type SMALLINT NOT NULL DEFAULT 1, -- RefType: 1=없음(그 구 데이터로 채움) 2=index_definition 3=article 4=event
|
||||
post_type SMALLINT NOT NULL, -- PostType: 1=오늘날씨 2=지수 3=노을 4=계절소식 5=행사 6=상식 7=주말예보 8=우산·특보 9=내일미리보기 10=한문장 11=주말플랜 12=미세먼지 13=당일치기 14=달 15=자외선 16~20=히어로·오늘의각·단풍·행사띠·계절띠 반응 자리 21=카드뉴스
|
||||
ref_type SMALLINT NOT NULL DEFAULT 1, -- RefType: 1=없음(그 구 데이터로 채움) 2=index_definition 3=article 4=event 5=card_set
|
||||
ref_id BIGINT NULL, -- ref_type 이 가리키는 테이블의 id
|
||||
index_rank SMALLINT NULL, -- 지수 포스트가 "그 구의 N위 지수"일 때 N
|
||||
like_count INTEGER NOT NULL DEFAULT 0,
|
||||
@@ -182,6 +182,28 @@ ALTER TABLE public.post ADD COLUMN IF NOT EXISTS scope VARCHAR(2) NOT NULL DEFAU
|
||||
DROP INDEX IF EXISTS public.uq_post_feed;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_post_feed_scope ON public.post (feed_date, position, scope) WHERE deleted = FALSE;
|
||||
|
||||
-- 카드뉴스: 관리자(admin/)가 만든 1080×1350 JPEG 묶음. 승인하면 그날 전국 피드에 post(post_type 16, ref_type 5) 로 올라간다
|
||||
CREATE TABLE IF NOT EXISTS public.card_set (
|
||||
card_id BIGSERIAL PRIMARY KEY,
|
||||
template VARCHAR(20) NOT NULL, -- admin 템플릿 id (tarot, ootd)
|
||||
topic VARCHAR(60) NULL,
|
||||
title VARCHAR(80) NOT NULL, -- 피드 포스트 제목
|
||||
caption TEXT NOT NULL DEFAULT '',
|
||||
copy JSONB NOT NULL DEFAULT '{}', -- 카드 문구 (다시 그릴 때 쓴다)
|
||||
status SMALLINT NOT NULL DEFAULT 1, -- CardStatus: 1=승인 대기 2=게시 3=반려
|
||||
post_id BIGINT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
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부터, 슬라이드 순서
|
||||
data BYTEA NOT NULL, -- JPEG
|
||||
PRIMARY KEY (card_id, seq)
|
||||
);
|
||||
|
||||
-- 사람·반응 (좋아요·저장·댓글은 로그인 필요, 보내기는 누구나)
|
||||
|
||||
-- 사용자. 일반(아이디·비밀번호) 또는 구글 로그인. 이름·전화번호는 받지 않는다.
|
||||
@@ -212,6 +234,14 @@ CREATE TABLE IF NOT EXISTS public.post_like (
|
||||
PRIMARY KEY (post_id, user_id)
|
||||
);
|
||||
|
||||
-- 로그인 없이 누른 좋아요. IP 원문 대신 HMAC-SHA256 해시로 한 IP 에 한 번만 센다. like_count 는 post_like 와 이 표를 합한 수
|
||||
CREATE TABLE IF NOT EXISTS public.post_like_anon (
|
||||
post_id BIGINT NOT NULL,
|
||||
ip_hash CHAR(64) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (post_id, ip_hash)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.post_save (
|
||||
post_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
@@ -230,6 +260,11 @@ CREATE TABLE IF NOT EXISTS public.comment (
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_comment_post ON public.comment (post_id, created_at) WHERE deleted = FALSE;
|
||||
-- 로그인 없이 쓴 댓글은 user_id 가 비고 IP 해시와 쓸 때의 동네 이름('마포구 익명'으로 보임)을 남긴다
|
||||
ALTER TABLE public.comment ALTER COLUMN user_id DROP NOT NULL;
|
||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS ip_hash VARCHAR(64) NULL;
|
||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS region_name VARCHAR(20) NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_comment_ip ON public.comment (ip_hash, created_at) WHERE user_id IS NULL;
|
||||
|
||||
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS terms_agreed_at TIMESTAMPTZ NULL;
|
||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS report_count INTEGER NOT NULL DEFAULT 0;
|
||||
@@ -245,7 +280,7 @@ CREATE TABLE IF NOT EXISTS public.comment_report (
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_comment_report_user ON public.comment_report (user_id);
|
||||
|
||||
-- 사용자 차단. 차단한 사람의 댓글이 내게 안 보인다
|
||||
-- 사용자 차단. 차단한 사람의 댓글·동네 이야기 글이 내게 안 보인다
|
||||
CREATE TABLE IF NOT EXISTS public.user_block (
|
||||
user_id UUID NOT NULL, -- 차단한 사람
|
||||
blocked_id UUID NOT NULL, -- 차단당한 사람
|
||||
@@ -261,6 +296,65 @@ CREATE TABLE IF NOT EXISTS public.comment_like (
|
||||
PRIMARY KEY (comment_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.comment_like_anon (
|
||||
comment_id BIGINT NOT NULL,
|
||||
ip_hash CHAR(64) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (comment_id, ip_hash)
|
||||
);
|
||||
|
||||
-- 나만의 각: 사용자가 이름과 날씨 조건(수치)을 정해 저장. 점수는 저장하지 않고 볼 때 그 동네 예보로 계산한다
|
||||
CREATE TABLE IF NOT EXISTS public.my_gak (
|
||||
my_gak_id BIGSERIAL PRIMARY KEY,
|
||||
user_id UUID NOT NULL,
|
||||
name VARCHAR(12) NOT NULL, -- 사용자가 지은 이름 (소맥각)
|
||||
rule JSONB NOT NULL, -- 조건: temp [lo,hi]·rain·wind_max·air·humidity [lo,hi]·slots
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_my_gak_user ON public.my_gak (user_id);
|
||||
|
||||
-- 동네 이야기: 사용자가 쓴 짧은 글(전국에 보임). 쓸 때의 동네 날씨를 함께 남긴다
|
||||
CREATE TABLE IF NOT EXISTS public.talk (
|
||||
talk_id BIGSERIAL PRIMARY KEY,
|
||||
user_id UUID NOT NULL,
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
body VARCHAR(100) NOT NULL,
|
||||
weather VARCHAR(30), -- 쓸 때 날씨 한 줄 (예: 18° 맑음)
|
||||
image VARCHAR(200), -- 올린 사진 경로 (위치 정보를 지운 사본)
|
||||
like_count INTEGER NOT NULL DEFAULT 0,
|
||||
report_count INTEGER NOT NULL DEFAULT 0, -- 로그인한 사람의 신고만 센다
|
||||
hidden BOOLEAN NOT NULL DEFAULT FALSE, -- 신고가 쌓이면 자동으로 숨김
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_talk_list ON public.talk (talk_id DESC) WHERE deleted = FALSE AND hidden = FALSE;
|
||||
CREATE INDEX IF NOT EXISTS idx_talk_user_day ON public.talk (user_id, created_at);
|
||||
-- 글 주제 (TalkTopic: 1 동네 이야기, 2 하늘·노을, 3 비·눈, 4 단풍·꽃, 5 오늘 옷차림)
|
||||
ALTER TABLE public.talk ADD COLUMN IF NOT EXISTS topic SMALLINT NOT NULL DEFAULT 1;
|
||||
CREATE INDEX IF NOT EXISTS idx_talk_recent ON public.talk (created_at DESC) WHERE deleted = FALSE AND hidden = FALSE;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.talk_like (
|
||||
talk_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (talk_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.talk_like_anon (
|
||||
talk_id BIGINT NOT NULL,
|
||||
ip_hash CHAR(64) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (talk_id, ip_hash)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.talk_report (
|
||||
talk_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
reason SMALLINT NOT NULL, -- TalkReport: 1=욕설·비하 2=광고·도배 3=개인정보 노출 4=기타
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (talk_id, user_id)
|
||||
);
|
||||
|
||||
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
|
||||
|
||||
-- 구 목록.
|
||||
@@ -408,3 +502,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()
|
||||
);
|
||||
@@ -12,3 +12,6 @@ apscheduler>=3.10,<4
|
||||
pytest
|
||||
python-jose[cryptography]
|
||||
bcrypt
|
||||
python-multipart
|
||||
Pillow
|
||||
azure-storage-blob
|
||||
@@ -8,14 +8,18 @@ from common.cache.redis_client import REDIS
|
||||
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
|
||||
from router.v1.my_gak.my_gak import router as my_gak_router
|
||||
from router.v1.reaction.reaction import router as reaction_router
|
||||
from router.v1.region.region import router as region_router
|
||||
from router.v1.season.season import router as season_router
|
||||
from router.v1.seo.seo import router as seo_router
|
||||
from router.v1.sky.sky import router as sky_router
|
||||
from router.v1.talk.talk import router as talk_router
|
||||
from router.v1.watch.watch import router as watch_router
|
||||
from router.v1.weather.weather import router as weather_router
|
||||
from router.v1.week.week import router as week_router
|
||||
@@ -42,9 +46,13 @@ app.include_router(season_router)
|
||||
app.include_router(feed_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(reaction_router)
|
||||
app.include_router(my_gak_router)
|
||||
app.include_router(talk_router)
|
||||
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,157 @@
|
||||
import base64
|
||||
import binascii
|
||||
from datetime import timedelta
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Path, Query
|
||||
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 CardSet
|
||||
from common.enums import CardStatus, ErrorType
|
||||
from common.logger import LOG
|
||||
from common.models.errors import error_info
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from crud.card_crud import CardCRUD
|
||||
from router.v1.card.protocol import CardItem, Req_CardCreate, Res_Card, Res_CardList
|
||||
from services.external import instagram
|
||||
from services.feed_service import _FEED_DAY_START, clear_feed_cache, feed_day
|
||||
|
||||
router = APIRouter(prefix="/v1/card", tags=["card"])
|
||||
|
||||
_MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
||||
_crud = CardCRUD()
|
||||
|
||||
|
||||
def image_url(card_id: int, seq: int) -> str:
|
||||
return f"/v1/card/{card_id}/{seq}.jpg"
|
||||
|
||||
|
||||
def _jpegs(images: list[str]) -> list[bytes]:
|
||||
out = []
|
||||
for i, b64 in enumerate(images, 1):
|
||||
try:
|
||||
data = base64.b64decode(b64.split(",", 1)[-1], validate=True)
|
||||
except (binascii.Error, ValueError) as e:
|
||||
raise HTTPException(status_code=400, detail=f"image {i}: base64 아님") from e
|
||||
if not data.startswith(b"\xff\xd8") or len(data) > _MAX_IMAGE_BYTES:
|
||||
raise HTTPException(status_code=400, detail=f"image {i}: 5MB 이하 JPEG 만")
|
||||
out.append(data)
|
||||
return out
|
||||
|
||||
|
||||
async def _publish(card_id: int) -> tuple[ErrorType, Res_Card]:
|
||||
"""그날(03:00 기준) 전국 피드에 올리고 피드 캐시를 지워 바로 보이게 한다. 다음 날 03:00 에 피드에서 빠진다."""
|
||||
now = now_kst()
|
||||
day = feed_day(now)
|
||||
end = kst_midnight(day + timedelta(days=1)) + timedelta(hours=_FEED_DAY_START)
|
||||
|
||||
async def run(s):
|
||||
card = await _crud.get(s, card_id)
|
||||
if card is None:
|
||||
return None
|
||||
if card.status != CardStatus.PUBLISHED.value:
|
||||
await _crud.publish(s, card, day, now, end)
|
||||
return card
|
||||
|
||||
err, card = await DB_SESSION_MNG.execute_lambda_write(run)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, Res_Card(result=error_info(err))
|
||||
if card is None:
|
||||
return ErrorType.NOT_FOUND, Res_Card(result=error_info(ErrorType.NOT_FOUND))
|
||||
await clear_feed_cache()
|
||||
LOG.info(f"[card] publish {card_id} → post {card.post_id}")
|
||||
return ErrorType.SUCCESS, Res_Card(card_id=card.card_id, status=CardStatus(card.status), post_id=card.post_id)
|
||||
|
||||
|
||||
@router.get("", response_model=Res_CardList, response_model_exclude_none=True, summary="만든 카드뉴스 목록 (관리자). 다시 내려받거나 올릴 때", dependencies=[Depends(require_admin)])
|
||||
async def list_cards(limit: int = Query(50, ge=1, le=200)) -> Res_CardList:
|
||||
err, cards = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.recent(s, limit))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_CardList(result=error_info(err))
|
||||
_, counts = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.image_counts(s, [c.card_id for c in cards]))
|
||||
counts = counts or {}
|
||||
return Res_CardList(items=[
|
||||
CardItem(card_id=c.card_id, template=c.template, topic=c.topic, title=c.title, status=CardStatus(c.status), post_id=c.post_id,
|
||||
created_at=c.created_at.astimezone(KST), published_at=c.published_at.astimezone(KST) if c.published_at else None,
|
||||
image_urls=[image_url(c.card_id, i) for i in range(1, counts.get(c.card_id, 0) + 1)], ig_media_id=c.ig_media_id)
|
||||
for c in cards
|
||||
])
|
||||
|
||||
|
||||
@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, 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))
|
||||
urls = [image_url(card.card_id, i) for i in range(1, len(images) + 1)]
|
||||
if req.publish:
|
||||
_, res = await _publish(card.card_id)
|
||||
res.image_urls = urls
|
||||
return res
|
||||
return Res_Card(card_id=card.card_id, status=CardStatus.WAITING, image_urls=urls)
|
||||
|
||||
|
||||
@router.post("/{card_id}/publish", response_model=Res_Card, response_model_exclude_none=True, summary="승인 대기 카드뉴스를 그날 피드에 올리기 (관리자)", dependencies=[Depends(require_admin)])
|
||||
async def publish_card(card_id: int = Path(...)) -> Res_Card:
|
||||
_, res = await _publish(card_id)
|
||||
return res
|
||||
|
||||
|
||||
@router.post("/{card_id}/reject", response_model=Res_Card, response_model_exclude_none=True, summary="승인 대기 카드뉴스 반려 (관리자)", dependencies=[Depends(require_admin)])
|
||||
async def reject_card(card_id: int = Path(...)) -> Res_Card:
|
||||
async def run(s):
|
||||
card = await _crud.get(s, card_id)
|
||||
if card is not None and card.status == CardStatus.WAITING.value:
|
||||
card.status = CardStatus.REJECTED.value
|
||||
return card
|
||||
|
||||
err, card = await DB_SESSION_MNG.execute_lambda_write(run)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Card(result=error_info(err))
|
||||
if card is None:
|
||||
return Res_Card(result=error_info(ErrorType.NOT_FOUND))
|
||||
return Res_Card(card_id=card.card_id, status=CardStatus(card.status), post_id=card.post_id)
|
||||
|
||||
|
||||
@router.post("/{card_id}/instagram", response_model=Res_Card, response_model_exclude_none=True, summary="카드뉴스를 인스타그램에 캐러셀로 올리기 (관리자). 같은 카드는 한 번만", dependencies=[Depends(require_admin)])
|
||||
async def publish_instagram(card_id: int = Path(...)) -> Res_Card:
|
||||
if not instagram.configured():
|
||||
return Res_Card(result=error_info(ErrorType.INVALID_INPUT), msg="INSTAGRAM_ACCESS_TOKEN / INSTAGRAM_USER_ID 가 설정되지 않았어요")
|
||||
err, card = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.get(s, card_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Card(result=error_info(err))
|
||||
if card is None:
|
||||
return Res_Card(result=error_info(ErrorType.NOT_FOUND))
|
||||
if card.ig_media_id:
|
||||
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 = "\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:
|
||||
LOG.error(f"[card] instagram {card_id}: {e}")
|
||||
return Res_Card(result=error_info(ErrorType.EXTERNAL_API_ERROR), msg=str(e), card_id=card_id)
|
||||
|
||||
async def save(s):
|
||||
c = await _crud.get(s, card_id)
|
||||
if c is not None:
|
||||
c.ig_media_id = media_id
|
||||
return c
|
||||
|
||||
err, saved = await DB_SESSION_MNG.execute_lambda_write(save)
|
||||
if err is not ErrorType.SUCCESS or saved is None:
|
||||
return Res_Card(result=error_info(err if err is not ErrorType.SUCCESS else ErrorType.NOT_FOUND), msg=f"인스타엔 올라갔지만({media_id}) 저장 실패")
|
||||
return Res_Card(card_id=card_id, status=CardStatus(saved.status), post_id=saved.post_id, ig_media_id=media_id)
|
||||
|
||||
|
||||
# 이미지 자체를 돌려주므로 실패는 HTTP 상태 코드로 알린다
|
||||
@router.get("/{card_id}/{seq}.jpg", summary="카드뉴스 이미지", responses={200: {"content": {"image/jpeg": {}}}, 404: {}})
|
||||
async def get_card_image(card_id: int = Path(...), seq: int = Path(..., ge=1, le=20)) -> Response:
|
||||
err, data = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.image(s, card_id, seq))
|
||||
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"})
|
||||
@@ -0,0 +1,43 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import CardStatus
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class Req_CardCreate(WebPacketProtocol):
|
||||
template: str = Field(max_length=20)
|
||||
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 면 승인 대기")
|
||||
|
||||
|
||||
class Res_Card(Res_WebPacketProtocol):
|
||||
card_id: Optional[int] = None
|
||||
status: Optional[CardStatus] = None
|
||||
post_id: Optional[int] = None
|
||||
image_urls: list[str] = []
|
||||
ig_media_id: Optional[str] = None
|
||||
|
||||
|
||||
class CardItem(WebPacketProtocol):
|
||||
card_id: int
|
||||
template: str
|
||||
topic: Optional[str] = None
|
||||
title: str
|
||||
status: CardStatus
|
||||
post_id: Optional[int] = None
|
||||
created_at: datetime
|
||||
published_at: Optional[datetime] = None
|
||||
image_urls: list[str] = []
|
||||
ig_media_id: Optional[str] = None
|
||||
|
||||
|
||||
class Res_CardList(Res_WebPacketProtocol):
|
||||
items: list[CardItem] = []
|
||||
@@ -1,10 +1,11 @@
|
||||
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
|
||||
from services.feed_service import FeedService
|
||||
@@ -12,22 +13,41 @@ 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(
|
||||
region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user),
|
||||
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))
|
||||
ids = [p.post_id for p in feed.posts]
|
||||
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)
|
||||
liked, saved = await reactions.marks(user, ids)
|
||||
# 캐시된 피드는 모두에게 같으니, 로그인 안 한 사람의 좋아요 표시는 캐시 밖에서 IP 해시로 덧붙인다
|
||||
anon_liked = await reactions.anon_liked(who.ip_hash, ids) if user is None else set()
|
||||
for x in pinned:
|
||||
x.like_count, x.comment_count = counts.get(x.post_id, (x.like_count, x.comment_count))
|
||||
x.liked = x.post_id in (liked if user is not None else anon_liked)
|
||||
for p in feed.posts:
|
||||
p.like_count, p.comment_count = counts.get(p.post_id, (p.like_count, p.comment_count))
|
||||
if user is not None:
|
||||
p.liked, p.saved = p.post_id in liked, p.post_id in saved
|
||||
else:
|
||||
p.liked = p.post_id in anon_liked
|
||||
return feed
|
||||
|
||||
|
||||
|
||||
@@ -49,6 +49,8 @@ class GakSlide(WebPacketProtocol):
|
||||
score: int
|
||||
line: str
|
||||
summary: str
|
||||
rows: list[Row] = Field(default=[], description="점수 근거: 비중 큰 날씨 조건부터 네 개와 지금 값 (기온 · 체감 18°)")
|
||||
say: Optional[str] = Field(default=None, description="점수 구간 설명 문장 (seed sentences)")
|
||||
|
||||
|
||||
class Cut(WebPacketProtocol):
|
||||
@@ -84,7 +86,7 @@ class WeekDay(WebPacketProtocol):
|
||||
temp_min_c: Optional[float] = None
|
||||
temp_max_c: Optional[float] = None
|
||||
rain_prob: Optional[int] = None
|
||||
gaks: list[WeekGak] = Field(default_factory=list, description="그날 대표 각 (점수 × 중요도 순 3개). 각 점수가 아직 없는 날은 비어 있음")
|
||||
gaks: list[WeekGak] = Field(default_factory=list, description="그날 대표 각 (중요도 배율을 반영한 최종 표시 점수 내림차순 3개, 동점이면 중요도 순). 각 점수가 아직 없는 날은 비어 있음")
|
||||
|
||||
|
||||
class WeekSlide(WebPacketProtocol):
|
||||
@@ -115,7 +117,15 @@ class PlanSlide(WebPacketProtocol):
|
||||
steps: list[PlanStep]
|
||||
|
||||
|
||||
Slide = Annotated[Union[HoursSlide, RowsSlide, GakSlide, SunsetSlide, WeekSlide, PlanSlide], Field(discriminator="kind")]
|
||||
class ImageSlide(WebPacketProtocol):
|
||||
"""카드뉴스 한 장 (1080×1350 JPEG). url 은 같은 서버의 /v1/card/... 경로."""
|
||||
|
||||
kind: Literal["image"]
|
||||
url: str
|
||||
alt: str = ""
|
||||
|
||||
|
||||
Slide = Annotated[Union[HoursSlide, RowsSlide, GakSlide, SunsetSlide, WeekSlide, PlanSlide, ImageSlide], Field(discriminator="kind")]
|
||||
|
||||
|
||||
class PostData(WebPacketProtocol):
|
||||
@@ -134,6 +144,14 @@ class PostData(WebPacketProtocol):
|
||||
saved: Optional[bool] = None
|
||||
|
||||
|
||||
class PostReaction(WebPacketProtocol):
|
||||
"""포스트 틀이 아닌 카드(히어로·오늘의 각·단풍 지도·띠)에 붙는 좋아요·댓글."""
|
||||
post_id: int
|
||||
like_count: int
|
||||
comment_count: int
|
||||
liked: Optional[bool] = None
|
||||
|
||||
|
||||
class TopIndex(WebPacketProtocol):
|
||||
index_id: int
|
||||
code: str
|
||||
@@ -144,7 +162,7 @@ class TopIndex(WebPacketProtocol):
|
||||
summary: Optional[str] = None
|
||||
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
|
||||
slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음")
|
||||
slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음")
|
||||
slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (중요도 배율을 반영한 최종 표시 점수 내림차순, 동점이면 중요도 순)")
|
||||
|
||||
|
||||
class HeroStat(WebPacketProtocol):
|
||||
@@ -152,6 +170,22 @@ class HeroStat(WebPacketProtocol):
|
||||
label: str
|
||||
value: str
|
||||
tone: Literal["normal", "warn", "rain"] = Field(description="normal=기본, warn=조심(노랑), rain=비(파랑)")
|
||||
detail: Optional[str] = Field(default=None, description="단계 이름 밑의 실제 값 (예: 68%, 72, 2, 초미세먼지 15㎍/㎥). 상태 줄에만")
|
||||
|
||||
|
||||
class WeatherWhy(WebPacketProtocol):
|
||||
label: str
|
||||
weight: int = Field(description="비중 % (합 100)")
|
||||
score: int = Field(description="이 조건 점수 0~100")
|
||||
note: str = Field(description="지금 값 (예: 체감 19°, 편한 범위 18~24° 안)")
|
||||
|
||||
|
||||
class HeroTomorrow(WebPacketProtocol):
|
||||
"""히어로 '내일' 스위치. 3시간 칸 날씨는 /v1/weather/today?day=tomorrow 로 따로 받는다."""
|
||||
day: date
|
||||
weather_slots: dict[str, int] = Field(default_factory=dict, description="내일 구간별 날씨 점수 {morning·day·evening·night: 점수}")
|
||||
weather_why: dict[str, list[WeatherWhy]] = Field(default_factory=dict, description="내일 구간별 날씨 점수 근거")
|
||||
top1: Optional[TopIndex] = Field(default=None, description="내일 하루 점수로 1위인 각. score·summary 는 내일 값")
|
||||
|
||||
|
||||
class Hero(WebPacketProtocol):
|
||||
@@ -166,12 +200,14 @@ class Hero(WebPacketProtocol):
|
||||
will_rain_2h: Optional[bool] = None
|
||||
weather_score: Optional[int] = None
|
||||
weather_slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 날씨 점수 {morning·day·evening·night: 점수}")
|
||||
weather_why: dict[str, list[WeatherWhy]] = Field(default_factory=dict, description="구간별 날씨 점수 근거(조건·비중·조건 점수·지금 값). 키는 weather_slots 와 같다")
|
||||
top1: Optional[TopIndex] = None
|
||||
bubble: Optional[str] = None
|
||||
moon_name: Optional[str] = Field(default=None, description="오늘 밤 달 모양: 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달")
|
||||
moon_pct: Optional[int] = Field(default=None, description="달에서 빛나는 면의 비율 0~100 (모양 그림용, 밝기 아님)")
|
||||
stats: list[HeroStat] = Field(default_factory=list, description="히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저")
|
||||
status: list[HeroStat] = Field(default_factory=list, description="히어로 상태 한 줄: 습도·불쾌지수·자외선(밤 구간 빼고)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)")
|
||||
tomorrow: Optional[HeroTomorrow] = None
|
||||
|
||||
|
||||
class BandEvent(WebPacketProtocol):
|
||||
@@ -205,6 +241,11 @@ class Res_Feed(Res_WebPacketProtocol):
|
||||
hero: Optional[Hero] = None
|
||||
stories: list[TopIndex] = []
|
||||
posts: list[PostData] = []
|
||||
hero_post: Optional[PostReaction] = None
|
||||
gak_post: Optional[PostReaction] = None
|
||||
foliage_post: Optional[PostReaction] = None
|
||||
events_post: Optional[PostReaction] = None
|
||||
season_post: Optional[PostReaction] = None
|
||||
bands: Optional[Bands] = None
|
||||
|
||||
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,55 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Path
|
||||
|
||||
from common.auth import current_user, optional_user
|
||||
from common.database.model.models import MyGak, User
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from router.v1.my_gak.protocol import MyGakData, MyGakPreset, MyGakRule, MyGakScore, Req_MyGak, Req_MyGakScore, Res_MyGak, Res_MyGakList, Res_MyGakPresets, Res_MyGakScore
|
||||
from services.my_gak_service import MyGakService
|
||||
|
||||
router = APIRouter(prefix="/v1/my-gak", tags=["my-gak"])
|
||||
|
||||
|
||||
def _data(g: MyGak) -> MyGakData:
|
||||
return MyGakData(my_gak_id=g.my_gak_id, name=g.name, rule=MyGakRule(**g.rule))
|
||||
|
||||
|
||||
@router.get("", response_model=Res_MyGakList, response_model_exclude_none=True, summary="내 각 목록 (로그인하지 않았으면 빈 목록)")
|
||||
async def list_my_gak(user: Optional[User] = Depends(optional_user), service: MyGakService = Depends()) -> Res_MyGakList:
|
||||
if user is None:
|
||||
return Res_MyGakList()
|
||||
err, rows = await service.mine(user)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_MyGakList(result=error_info(err))
|
||||
return Res_MyGakList(items=[_data(g) for g in rows])
|
||||
|
||||
|
||||
@router.post("", response_model=Res_MyGak, response_model_exclude_none=True, summary="이름과 날씨 조건으로 내 각 만들기")
|
||||
async def add_my_gak(req: Req_MyGak, user: User = Depends(current_user), service: MyGakService = Depends()) -> Res_MyGak:
|
||||
err, g = await service.add(user, req.name, req.rule.model_dump(exclude_none=True))
|
||||
return Res_MyGak(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_MyGak(item=_data(g))
|
||||
|
||||
|
||||
@router.get("/presets", response_model=Res_MyGakPresets, response_model_exclude_none=True, summary="공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기)")
|
||||
async def list_presets(service: MyGakService = Depends()) -> Res_MyGakPresets:
|
||||
err, items = await service.presets()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_MyGakPresets(result=error_info(err))
|
||||
return Res_MyGakPresets(items=[MyGakPreset(**x) for x in items])
|
||||
|
||||
|
||||
@router.post("/score", response_model=Res_MyGakScore, response_model_exclude_none=True, summary="조건들의 그 동네 오늘 점수 (로그인 없이, 받은 링크의 각도)")
|
||||
async def score_my_gak(req: Req_MyGakScore, service: MyGakService = Depends()) -> Res_MyGakScore:
|
||||
err, got = await service.score(req.region_code, [r.model_dump(exclude_none=True) for r in req.rules])
|
||||
if err is not ErrorType.SUCCESS or got is None:
|
||||
return Res_MyGakScore(result=error_info(err))
|
||||
now_slot, scores = got
|
||||
return Res_MyGakScore(now_slot=now_slot, scores=[MyGakScore(**x) for x in scores])
|
||||
|
||||
|
||||
@router.delete("/{my_gak_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 각 지우기")
|
||||
async def delete_my_gak(my_gak_id: int = Path(...), user: User = Depends(current_user), service: MyGakService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.delete(user, my_gak_id)))
|
||||
@@ -0,0 +1,73 @@
|
||||
from typing import Literal, Optional
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
Slot = Literal["morning", "day", "evening", "night"]
|
||||
|
||||
|
||||
class MyGakRule(WebPacketProtocol):
|
||||
temp: Optional[list[float]] = Field(None, min_length=2, max_length=2, description="체감온도 범위 [최저, 최고]° (-20~40)")
|
||||
rain: Optional[Literal["dry", "wet"]] = Field(None, description="dry: 비 안 와야 / wet: 비 와야 / 없으면 상관없음")
|
||||
wind_max: Optional[float] = Field(None, ge=1, le=20, description="바람 상한 m/s")
|
||||
air: Optional[Literal["good", "normal"]] = Field(None, description="미세먼지 허용 단계: good 좋음까지 / normal 보통까지")
|
||||
humidity: Optional[list[int]] = Field(None, min_length=2, max_length=2, description="습도 범위 [최저, 최고]%")
|
||||
slots: list[Slot] = Field(default=["morning", "day", "evening", "night"], min_length=1, max_length=4, description="볼 시간대")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check(self) -> "MyGakRule":
|
||||
if self.temp and not (-20 <= self.temp[0] < self.temp[1] <= 40):
|
||||
raise ValueError("temp 는 -20~40 안에서 최저 < 최고")
|
||||
if self.humidity and not (0 <= self.humidity[0] < self.humidity[1] <= 100):
|
||||
raise ValueError("humidity 는 0~100 안에서 최저 < 최고")
|
||||
if not (self.temp or self.rain or self.wind_max is not None or self.air or self.humidity):
|
||||
raise ValueError("조건을 하나 이상 정해야 함")
|
||||
return self
|
||||
|
||||
|
||||
class MyGakData(WebPacketProtocol):
|
||||
my_gak_id: int
|
||||
name: str
|
||||
rule: MyGakRule
|
||||
|
||||
|
||||
class Req_MyGak(Req_WebPacketProtocol):
|
||||
name: str = Field(min_length=1, max_length=12, description="내 각 이름 (끝에 '각'이 없으면 붙인다)")
|
||||
rule: MyGakRule
|
||||
|
||||
|
||||
class MyGakPreset(WebPacketProtocol):
|
||||
code: str
|
||||
name: str
|
||||
icon: str
|
||||
rule: MyGakRule = Field(description="공식 각을 내 각 조건으로 비슷하게 옮긴 값. 점수는 공식 각과 다를 수 있음")
|
||||
|
||||
|
||||
class Res_MyGakPresets(Res_WebPacketProtocol):
|
||||
items: list[MyGakPreset] = []
|
||||
|
||||
|
||||
class Res_MyGakList(Res_WebPacketProtocol):
|
||||
items: list[MyGakData] = Field(default=[], description="내 각. 로그인하지 않았으면 비어 있음")
|
||||
|
||||
|
||||
class Res_MyGak(Res_WebPacketProtocol):
|
||||
item: Optional[MyGakData] = None
|
||||
|
||||
|
||||
class Req_MyGakScore(Req_WebPacketProtocol):
|
||||
region_code: str = Field(min_length=10, max_length=10)
|
||||
rules: list[MyGakRule] = Field(min_length=1, max_length=21)
|
||||
|
||||
|
||||
class MyGakScore(WebPacketProtocol):
|
||||
score: Optional[int] = Field(None, description="지금 시간대 점수. 지금이 고른 시간대가 아니면 고른 시간대 중 가장 좋은 점수. 예보가 없으면 null")
|
||||
slot: Optional[Slot] = Field(None, description="score 가 어느 시간대 점수인지")
|
||||
slots: dict[str, int] = Field(default={}, description="고른 시간대별 점수 (아침·낮·저녁·밤 순)")
|
||||
reasons: list[str] = Field(default=[], description="score 근거: 조건마다 그 시간대 실제 값")
|
||||
|
||||
|
||||
class Res_MyGakScore(Res_WebPacketProtocol):
|
||||
now_slot: Optional[Slot] = None
|
||||
scores: list[MyGakScore] = []
|
||||
@@ -2,6 +2,8 @@ import uuid
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import PostType, ReportReason
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
@@ -47,6 +49,7 @@ class Res_CommentList(Res_WebPacketProtocol):
|
||||
|
||||
class Req_Comment(Req_WebPacketProtocol):
|
||||
body: str
|
||||
region: Optional[str] = Field(None, description="로그인 없이 쓸 때 보고 있는 동네 코드. 이름이 '마포구 익명'으로 보인다")
|
||||
|
||||
|
||||
class Res_Comment(Res_WebPacketProtocol):
|
||||
|
||||
@@ -6,6 +6,7 @@ from fastapi import APIRouter, Depends, Path, Query
|
||||
from common.auth import current_user, optional_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType, PostType
|
||||
from common.liker import Liker, liker
|
||||
from common.models.errors import error_info
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from common.utils.kma_time import KST
|
||||
@@ -23,19 +24,19 @@ def _comment(v: CommentView) -> CommentData:
|
||||
return CommentData(comment_id=c.comment_id, nickname=v.nickname, character=v.character, color=v.color, mood=v.mood, body=c.body, like_count=c.like_count, liked=v.liked, mine=v.mine, created_at=c.created_at.astimezone(KST))
|
||||
|
||||
|
||||
async def _like(post_id: int, user: User, on: bool, service: ReactionService) -> Res_PostLike:
|
||||
err, count = await service.like_post(post_id, user, on)
|
||||
async def _like(post_id: int, who: Liker, on: bool, service: ReactionService) -> Res_PostLike:
|
||||
err, count = await service.like_post(post_id, who, on)
|
||||
return Res_PostLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_PostLike(liked=on, like_count=count)
|
||||
|
||||
|
||||
@router.post("/post/{post_id}/like", response_model=Res_PostLike, response_model_exclude_none=True, summary="좋아요")
|
||||
async def like_post(post_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_PostLike:
|
||||
return await _like(post_id, user, True, service)
|
||||
@router.post("/post/{post_id}/like", response_model=Res_PostLike, response_model_exclude_none=True, summary="좋아요 (로그인 없으면 IP 당 한 번)")
|
||||
async def like_post(post_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_PostLike:
|
||||
return await _like(post_id, who, True, service)
|
||||
|
||||
|
||||
@router.delete("/post/{post_id}/like", response_model=Res_PostLike, response_model_exclude_none=True, summary="좋아요 취소")
|
||||
async def unlike_post(post_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_PostLike:
|
||||
return await _like(post_id, user, False, service)
|
||||
async def unlike_post(post_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_PostLike:
|
||||
return await _like(post_id, who, False, service)
|
||||
|
||||
|
||||
@router.post("/post/{post_id}/save", response_model=Res_PostSave, response_model_exclude_none=True, summary="저장")
|
||||
@@ -61,38 +62,41 @@ async def list_saved(cursor: Optional[int] = Query(None), user: User = Depends(c
|
||||
|
||||
@router.get("/post/{post_id}/comment/list", response_model=Res_CommentList, response_model_exclude_none=True, summary="댓글 목록 (로그인 없이 보기)")
|
||||
async def list_comments(
|
||||
post_id: int = Path(...), cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), service: ReactionService = Depends()
|
||||
post_id: int = Path(...), cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker),
|
||||
service: ReactionService = Depends(),
|
||||
) -> Res_CommentList:
|
||||
err, items = await service.comments(post_id, user, cursor)
|
||||
err, items = await service.comments(post_id, user, who.ip_hash, cursor)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_CommentList(result=error_info(err))
|
||||
return Res_CommentList(comments=[_comment(v) for v in items], next_cursor=items[-1].comment.comment_id if len(items) == PAGE else None)
|
||||
|
||||
|
||||
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자, 이용약관 동의 전이면 TERMS_REQUIRED)")
|
||||
async def add_comment(post_id: int = Path(...), req: Req_Comment = ..., user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_Comment:
|
||||
err, v = await service.add_comment(post_id, user, req.body)
|
||||
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개, 로그인했는데 이용약관 동의 전이면 TERMS_REQUIRED)")
|
||||
async def add_comment(
|
||||
post_id: int = Path(...), req: Req_Comment = ..., user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: ReactionService = Depends(),
|
||||
) -> Res_Comment:
|
||||
err, v = await service.add_comment(post_id, user, who, req.body, req.region)
|
||||
return Res_Comment(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_Comment(comment=_comment(v))
|
||||
|
||||
|
||||
@router.delete("/comment/{comment_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 댓글 지우기")
|
||||
async def delete_comment(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.delete_comment(comment_id, user)))
|
||||
@router.delete("/comment/{comment_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 댓글 지우기 (로그인 없이 쓴 댓글은 같은 IP 에서)")
|
||||
async def delete_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.delete_comment(comment_id, who)))
|
||||
|
||||
|
||||
async def _clike(comment_id: int, user: User, on: bool, service: ReactionService) -> Res_CommentLike:
|
||||
err, count = await service.like_comment(comment_id, user, on)
|
||||
async def _clike(comment_id: int, who: Liker, on: bool, service: ReactionService) -> Res_CommentLike:
|
||||
err, count = await service.like_comment(comment_id, who, on)
|
||||
return Res_CommentLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_CommentLike(liked=on, like_count=count)
|
||||
|
||||
|
||||
@router.post("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요")
|
||||
async def like_comment(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_CommentLike:
|
||||
return await _clike(comment_id, user, True, service)
|
||||
@router.post("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요 (로그인 없으면 IP 당 한 번)")
|
||||
async def like_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_CommentLike:
|
||||
return await _clike(comment_id, who, True, service)
|
||||
|
||||
|
||||
@router.delete("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요 취소")
|
||||
async def unlike_comment(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_CommentLike:
|
||||
return await _clike(comment_id, user, False, service)
|
||||
async def unlike_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_CommentLike:
|
||||
return await _clike(comment_id, who, False, service)
|
||||
|
||||
|
||||
@router.post("/comment/{comment_id}/report", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="남의 댓글 신고 (신고한 사람에겐 바로 안 보이고, 3건이면 모두에게 숨김)")
|
||||
|
||||
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"})
|
||||
@@ -15,3 +15,27 @@ async def get_today_page(sido: str = Path(..., pattern=_SLUG), place: str = Path
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
|
||||
|
||||
@router.get("/today/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)")
|
||||
async def get_today_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), gu: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
|
||||
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"})
|
||||
|
||||
|
||||
@router.get("/tomorrow/{sido}/{place}", response_class=HTMLResponse, summary="지역 내일 날씨 페이지: 정적 HTML 에 내일 예보를 채운다 (nginx 가 /tomorrow/... 를 넘김)")
|
||||
async def get_tomorrow_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
|
||||
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"})
|
||||
|
||||
|
||||
@router.get("/tomorrow/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 내일 날씨 페이지")
|
||||
async def get_tomorrow_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), gu: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
|
||||
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"})
|
||||
Whitespace-only changes.
@@ -0,0 +1,62 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import TalkReport, TalkTopic
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class TalkData(WebPacketProtocol):
|
||||
talk_id: int
|
||||
nickname: str
|
||||
character: str
|
||||
color: str
|
||||
mood: Optional[str] = None
|
||||
region_name: Optional[str] = Field(None, description="쓴 사람이 고른 동네 (성남시 분당구)")
|
||||
weather: Optional[str] = Field(None, description="쓸 때 그 동네 날씨 (18° 맑음)")
|
||||
body: str
|
||||
image: Optional[str] = Field(None, description="올린 사진 주소")
|
||||
topic: TalkTopic = TalkTopic.LOCAL
|
||||
like_count: int
|
||||
liked: bool
|
||||
mine: bool
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class Req_Talk(Req_WebPacketProtocol):
|
||||
region_code: str = Field(min_length=10, max_length=10)
|
||||
body: str = Field(min_length=1, max_length=200, description="공백을 줄인 뒤 100자까지")
|
||||
image: Optional[str] = Field(None, max_length=200, description="먼저 올린 사진 주소 (POST /v1/talk/image 결과)")
|
||||
topic: TalkTopic = Field(TalkTopic.LOCAL, description="글 주제. 안 고르면 동네 이야기")
|
||||
|
||||
|
||||
class Req_TalkReport(Req_WebPacketProtocol):
|
||||
reason: TalkReport
|
||||
|
||||
|
||||
class Res_TalkList(Res_WebPacketProtocol):
|
||||
talks: list[TalkData] = []
|
||||
next_cursor: Optional[str] = Field(None, description="다음 페이지를 받을 때 그대로 cursor 로 보낸다")
|
||||
|
||||
|
||||
class TalkGroup(WebPacketProtocol):
|
||||
topic: int = Field(description="0 이면 '동네 사람들'(모든 주제), 아니면 TalkTopic")
|
||||
talks: list[TalkData] = []
|
||||
|
||||
|
||||
class Res_TalkGroups(Res_WebPacketProtocol):
|
||||
groups: list[TalkGroup] = Field([], description="동네 사람들 묶음은 늘 있고(비어 있을 수 있음), 주제 묶음은 3장 이상일 때만")
|
||||
|
||||
|
||||
class Res_Talk(Res_WebPacketProtocol):
|
||||
talk: Optional[TalkData] = None
|
||||
|
||||
|
||||
class Res_TalkLike(Res_WebPacketProtocol):
|
||||
liked: Optional[bool] = None
|
||||
like_count: Optional[int] = None
|
||||
|
||||
|
||||
class Res_TalkImage(Res_WebPacketProtocol):
|
||||
image: Optional[str] = Field(None, description="글에 붙일 사진 주소")
|
||||
@@ -0,0 +1,116 @@
|
||||
from typing import Optional
|
||||
|
||||
import asyncio
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Path, Query, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from common.auth import current_user, optional_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType, TalkTopic
|
||||
from common.liker import Liker, liker
|
||||
from common.models.errors import error_info
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from common.utils.kma_time import KST
|
||||
from router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkGroups, Res_TalkImage, Res_TalkLike, Res_TalkList, TalkData, TalkGroup
|
||||
from services.talk_image import MAX_BYTES, URL_PREFIX, file_of, save
|
||||
from services.talk_service import TalkService, TalkView
|
||||
|
||||
router = APIRouter(prefix="/v1/talk", tags=["talk"])
|
||||
|
||||
|
||||
def _data(v: TalkView) -> TalkData:
|
||||
t, u = v.talk, v.author
|
||||
return TalkData(
|
||||
talk_id=t.talk_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, region_name=v.region_name, weather=t.weather,
|
||||
body=t.body, image=t.image, topic=TalkTopic(t.topic), like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/groups", response_model=Res_TalkGroups, response_model_exclude_none=True, summary="오늘 피드 묶음 (동네 사람들 + 주제별, 가까운 동네·덜 지난 글 먼저, 한 사람 한 장)")
|
||||
async def talk_groups(
|
||||
region: Optional[str] = Query(None, min_length=10, max_length=10, description="보는 사람의 구 행정코드"),
|
||||
user: Optional[User] = Depends(optional_user),
|
||||
who: Liker = Depends(liker),
|
||||
service: TalkService = Depends(),
|
||||
) -> Res_TalkGroups:
|
||||
err, groups = await service.groups(user, who.ip_hash, region)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_TalkGroups(result=error_info(err))
|
||||
return Res_TalkGroups(groups=[TalkGroup(topic=k, talks=[_data(v) for v in vs]) for k, vs in groups.items()])
|
||||
|
||||
|
||||
@router.get("/list", response_model=Res_TalkList, response_model_exclude_none=True, summary="동네 이야기 (전국 최신순, 보는 동네와 같은 시도 글은 앞으로, 같은 사람 글은 띄움, 로그인 없이 보기)")
|
||||
async def list_talks(
|
||||
region: Optional[str] = Query(None, min_length=10, max_length=10, description="보는 사람의 구 행정코드"),
|
||||
topic: Optional[TalkTopic] = Query(None, description="이 주제 글만. 없으면 전체"),
|
||||
cursor: Optional[str] = Query(None, max_length=40),
|
||||
user: Optional[User] = Depends(optional_user),
|
||||
who: Liker = Depends(liker),
|
||||
service: TalkService = Depends(),
|
||||
) -> Res_TalkList:
|
||||
err, views, nxt = await service.page(user, who.ip_hash, region, cursor, topic.value if topic else None)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_TalkList(result=error_info(err))
|
||||
return Res_TalkList(talks=[_data(v) for v in views], next_cursor=nxt)
|
||||
|
||||
|
||||
@router.get("/mine", response_model=Res_TalkList, response_model_exclude_none=True, summary="내가 쓴 글 (최신순)")
|
||||
async def list_my_talks(cursor: Optional[str] = Query(None, max_length=20), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_TalkList:
|
||||
if cursor is not None and not cursor.isdigit():
|
||||
return Res_TalkList(result=error_info(ErrorType.INVALID_INPUT))
|
||||
err, views, nxt = await service.mine(user, int(cursor) if cursor else None)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_TalkList(result=error_info(err))
|
||||
return Res_TalkList(talks=[_data(v) for v in views], next_cursor=str(nxt) if nxt else None)
|
||||
|
||||
|
||||
@router.post("", response_model=Res_Talk, response_model_exclude_none=True, summary="동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)")
|
||||
async def add_talk(req: Req_Talk, user: User = Depends(current_user), service: TalkService = Depends()) -> Res_Talk:
|
||||
err, v = await service.add(user, req.region_code, req.body, req.image, req.topic)
|
||||
return Res_Talk(result=error_info(err)) if err is not ErrorType.SUCCESS or v is None else Res_Talk(talk=_data(v))
|
||||
|
||||
|
||||
@router.post("/image", response_model=Res_TalkImage, response_model_exclude_none=True, summary="글에 붙일 사진 올리기 (10MB까지, 위치 정보를 지우고 1080px로 줄여 저장)")
|
||||
async def upload_talk_image(file: UploadFile = File(...), user: User = Depends(current_user)) -> Res_TalkImage:
|
||||
data = await file.read(MAX_BYTES + 1)
|
||||
err, url = await asyncio.to_thread(save, data)
|
||||
return Res_TalkImage(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_TalkImage(image=url)
|
||||
|
||||
|
||||
@router.get("/image/{name}", summary="올린 사진", response_class=FileResponse)
|
||||
async def get_talk_image(name: str = Path(..., max_length=40)) -> FileResponse:
|
||||
path = file_of(URL_PREFIX + name)
|
||||
if path is None:
|
||||
raise HTTPException(status_code=404)
|
||||
return FileResponse(path, media_type="image/webp", headers={"Cache-Control": "public, max-age=31536000, immutable"})
|
||||
|
||||
|
||||
@router.delete("/{talk_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 이야기 지우기")
|
||||
async def delete_talk(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.delete(user, talk_id)))
|
||||
|
||||
|
||||
async def _like(talk_id: int, who: Liker, on: bool, service: TalkService) -> Res_TalkLike:
|
||||
err, count = await service.like(who, talk_id, on)
|
||||
return Res_TalkLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_TalkLike(liked=on, like_count=count)
|
||||
|
||||
|
||||
@router.post("/{talk_id}/like", response_model=Res_TalkLike, response_model_exclude_none=True, summary="이야기 좋아요 (로그인 없으면 IP 당 한 번)")
|
||||
async def like_talk(talk_id: int = Path(...), who: Liker = Depends(liker), service: TalkService = Depends()) -> Res_TalkLike:
|
||||
return await _like(talk_id, who, True, service)
|
||||
|
||||
|
||||
@router.delete("/{talk_id}/like", response_model=Res_TalkLike, response_model_exclude_none=True, summary="이야기 좋아요 취소")
|
||||
async def unlike_talk(talk_id: int = Path(...), who: Liker = Depends(liker), service: TalkService = Depends()) -> Res_TalkLike:
|
||||
return await _like(talk_id, who, False, service)
|
||||
|
||||
|
||||
@router.post("/{talk_id}/report", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이야기 신고 (서로 다른 3명이면 숨김)")
|
||||
async def report_talk(req: Req_TalkReport, talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.report(user, talk_id, req.reason)))
|
||||
|
||||
|
||||
@router.post("/{talk_id}/block", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이 글 쓴 사람의 글 안 보기")
|
||||
async def block_talk_author(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.block_author(user, talk_id)))
|
||||
@@ -13,6 +13,7 @@ class WeatherSlot(WebPacketProtocol):
|
||||
sky: Optional[Sky] = None
|
||||
rain_type: Optional[RainType] = None
|
||||
rain_prob: Optional[int] = None
|
||||
humidity: Optional[int] = None
|
||||
icon: str
|
||||
tone: SlotTone
|
||||
note: str
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
from datetime import timedelta
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.enums import AirGrade, ErrorType, RainType, Sky
|
||||
from common.models.errors import error_info
|
||||
from common.utils.kma_time import KST
|
||||
from common.utils.kma_time import KST, now_kst
|
||||
from router.v1.weather.protocol import (
|
||||
AirData,
|
||||
CommuteData,
|
||||
@@ -24,13 +27,16 @@ def _to_slot(s: Slot) -> WeatherSlot:
|
||||
data = WeatherSlot(at=s.at, label=f"{s.at.astimezone(KST).hour}시", icon=s.icon, tone=s.tone, note=s.note)
|
||||
if s.row is not None:
|
||||
data.temp_c, data.feels_c = float(s.row.temp_c), float(s.row.feels_c)
|
||||
data.sky, data.rain_type, data.rain_prob = Sky(s.row.sky), RainType(s.row.rain_type), s.row.rain_prob
|
||||
data.sky, data.rain_type, data.rain_prob, data.humidity = Sky(s.row.sky), RainType(s.row.rain_type), s.row.rain_prob, s.row.humidity
|
||||
return data
|
||||
|
||||
|
||||
@router.get("/today", response_model=Res_WeatherToday, response_model_exclude_none=True, summary="오늘 3시간 칸 날씨")
|
||||
async def get_weather_today(region: str = Query(..., description="구 행정코드"), service: WeatherService = Depends()) -> Res_WeatherToday:
|
||||
err, today = await service.today(region)
|
||||
@router.get("/today", response_model=Res_WeatherToday, response_model_exclude_none=True, summary="오늘(또는 내일) 3시간 칸 날씨")
|
||||
async def get_weather_today(
|
||||
region: str = Query(..., description="구 행정코드"), day: Literal["today", "tomorrow"] = Query("today", description="tomorrow 면 내일 칸"),
|
||||
service: WeatherService = Depends(),
|
||||
) -> Res_WeatherToday:
|
||||
err, today = await service.today(region, now_kst().date() + timedelta(days=1) if day == "tomorrow" else None)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_WeatherToday(result=error_info(err))
|
||||
return Res_WeatherToday(
|
||||
|
||||
@@ -5,7 +5,7 @@ import sys
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
from services.calc.index_calc import PRIORITY_WEIGHT # noqa: E402
|
||||
from services.calc.index_calc import _cond # noqa: E402
|
||||
|
||||
SEED = os.path.join(ROOT, "seed", "index_definition.json")
|
||||
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
|
||||
@@ -64,12 +64,16 @@ def tim(r):
|
||||
return "달이 어두울수록 좋음 (보름 20점 → 그믐 100점)"
|
||||
if t == "sunset_score":
|
||||
return "그날 노을 점수를 그대로 씀"
|
||||
if t == "sunrise_score":
|
||||
return "그날 일출 하늘 점수를 그대로 씀"
|
||||
return f"고정 {r['value']}점"
|
||||
|
||||
|
||||
def zero(z):
|
||||
if z["field"] == "warning":
|
||||
return f"{z['value']} 특보가 있으면"
|
||||
if z["field"] not in FIELD:
|
||||
return _cond(z)[2] + (f" 최대 {z['cap']}점" if "cap" in z else " 0점")
|
||||
name, unit = FIELD[z["field"]]
|
||||
op = "이상" if z["op"] == ">=" else "미만"
|
||||
s = f"{name} {z['value']}{unit} {op}이면"
|
||||
@@ -83,7 +87,7 @@ def air(r):
|
||||
|
||||
|
||||
AX = [("temp", "기온", temp), ("rain", "비", rain), ("wind", "바람", wind), ("humidity", "습도", hum), ("air", "미세먼지", air),
|
||||
("uv", "자외선", lambda r: f"자외선 {r['full']} 이하면 만점, {r['zero']} 이상이면 0점 (Open-Meteo)"),
|
||||
("uv", "자외선", lambda r: f"자외선 {r['full']} {'이상이면' if r['full'] > r['zero'] else '이하면'} 만점, {r['zero']} {'이하면' if r['full'] > r['zero'] else '이상이면'} 0점 (Open-Meteo)"),
|
||||
("sun", "햇빛", lambda r: f"해 난 비율 {round(r['full'] * 100)}% 이상이면 만점, {round(r['zero'] * 100)}% 이하면 0점 (Open-Meteo)"),
|
||||
("view", "가시거리", lambda r: f"{r['full']}km 이상이면 만점, {r['zero']}km 이하면 0점 (Open-Meteo)"),
|
||||
("time", "시간·요일", tim)]
|
||||
@@ -105,7 +109,7 @@ def main() -> None:
|
||||
P("- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.")
|
||||
P("- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.")
|
||||
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.")
|
||||
P("- 순위는 점수 × 중요도 가중치(" + " · ".join(f"{PRIO[k]} {v}" for k, v in PRIORITY_WEIGHT.items()) + ")로 정합니다. 화면에 보이는 점수는 그대로입니다.\n")
|
||||
P("- 최종 점수는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시 모두 이 최종 점수를 사용합니다.\n")
|
||||
P("## 한눈에 보기\n")
|
||||
P("| 순서 | 각 | 코드 | 분류 | 중요도 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |")
|
||||
P("|---:|---|---|---|:---:|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""나들이 점수 바꾸기 표(services/calc/outing_score_table.json)를 다시 만든다.
|
||||
|
||||
나들이 점수(index_calc.outing: 낮 10~17시, 기온·비·하늘·바람)의 원래 점수를 1년 치 분포의 순위로 보고,
|
||||
평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾼다 (지금 날씨 점수와 같은 방식, scripts/gen_weather_score_table.py).
|
||||
1년 치 날씨는 Open-Meteo 과거 예보로, region.csv 에서 8개마다 1곳(32곳)을 쓴다. 하늘은 구름양 40%·80% 이상을 구름 많음·흐림으로 본다.
|
||||
|
||||
나들이 점수 규칙(OUTING_*)이 바뀌면 실행: cd backend && python scripts/gen_outing_score_table.py
|
||||
"""
|
||||
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from common.enums import RainType, Sky # noqa: E402
|
||||
from common.logger import LOG # noqa: E402
|
||||
from scripts.gen_weather_score_table import _WEATHER, DAYS, EVERY, MEAN, SIGMA, fetch, straighten_top, table # noqa: E402
|
||||
from services.calc.index_calc import OUTING_HOURS, Hour, outing # noqa: E402
|
||||
|
||||
BACKEND = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
REGIONS = os.path.join(BACKEND, "seed", "region.csv")
|
||||
OUT = os.path.join(BACKEND, "services", "calc", "outing_score_table.json")
|
||||
_HOURLY = "apparent_temperature,precipitation,precipitation_probability,wind_speed_10m,cloud_cover"
|
||||
|
||||
|
||||
def region_scores(lat: float, lon: float, start: date, end: date) -> list[int]:
|
||||
"""한 지점의 날마다 나들이 점수(원래 점수). 10~17시가 모두 있는 날만."""
|
||||
base = dict(latitude=lat, longitude=lon, start_date=start.isoformat(), end_date=end.isoformat(), timezone="Asia/Seoul")
|
||||
w = fetch(_WEATHER, base | dict(hourly=_HOURLY, wind_speed_unit="ms"))["hourly"]
|
||||
at_index = {t: i for i, t in enumerate(w["time"])}
|
||||
out = []
|
||||
day = start
|
||||
while day <= end:
|
||||
hours = []
|
||||
for h in range(*OUTING_HOURS):
|
||||
i = at_index.get(f"{day.isoformat()}T{h:02d}:00")
|
||||
if i is None or w["apparent_temperature"][i] is None:
|
||||
break
|
||||
cloud = w["cloud_cover"][i] or 0
|
||||
hours.append(Hour(
|
||||
hour=h, feels_c=w["apparent_temperature"][i], rain_type=RainType.RAIN if (w["precipitation"][i] or 0) >= 0.1 else RainType.NONE,
|
||||
rain_prob=int(w["precipitation_probability"][i] or 0), wind_ms=w["wind_speed_10m"][i], humidity=50,
|
||||
sky=Sky.CLOUDY if cloud >= 80 else Sky.PARTLY if cloud >= 40 else Sky.CLEAR,
|
||||
))
|
||||
result = outing(hours) if len(hours) == OUTING_HOURS[1] - OUTING_HOURS[0] else None
|
||||
if result is not None:
|
||||
out.append(result.score)
|
||||
day += timedelta(days=1)
|
||||
return out
|
||||
|
||||
|
||||
def main() -> None:
|
||||
end = date.today() - timedelta(days=2)
|
||||
start = end - timedelta(days=DAYS)
|
||||
regions = list(csv.DictReader(open(REGIONS, encoding="utf-8")))[::EVERY]
|
||||
scores: list[int] = []
|
||||
for r in regions:
|
||||
scores += region_scores(float(r["lat"]), float(r["lon"]), start, end)
|
||||
LOG.info(f"[outing-table] {r['name']} 완료")
|
||||
time.sleep(1)
|
||||
doc = {
|
||||
"about": f"나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 {MEAN}·표준편차 {SIGMA}. scripts/gen_outing_score_table.py 가 만든다",
|
||||
"period": [start.isoformat(), end.isoformat()], "regions": len(regions), "samples": len(scores),
|
||||
"table": straighten_top(table(scores)), # 100점은 원래 점수 100(완벽한 날)일 때만
|
||||
}
|
||||
with open(OUT, "w", encoding="utf-8") as f:
|
||||
json.dump(doc, f, ensure_ascii=False, indent=1)
|
||||
print(len(regions), "regions", len(scores), "samples")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,60 @@
|
||||
"""/faq 지역 질문에 넣을 지역별 장소를 시드로 다시 만든다. 시도마다 한 파일: frontend/seo/region_faq/seoul.json
|
||||
|
||||
region.json 이나 place*.csv, sunset_spot.csv 가 바뀌면 실행: python backend/scripts/gen_region_faq.py
|
||||
앱 번들에 들어가는 region.json 을 키우지 않으려고 따로 둔다. vite 빌드가 /faq 를 만들 때만 읽는다.
|
||||
"""
|
||||
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
SEED = os.path.join(ROOT, "backend", "seed")
|
||||
PAGES = os.path.join(ROOT, "frontend", "seo", "region.json")
|
||||
OUT = os.path.join(ROOT, "frontend", "seo", "region_faq")
|
||||
|
||||
OUTDOOR, INDOOR, SUNSET = 3, 2, 2
|
||||
|
||||
|
||||
def rows(name: str) -> list[dict]:
|
||||
return list(csv.DictReader(open(os.path.join(SEED, name), encoding="utf-8")))
|
||||
|
||||
|
||||
# 손으로 고른 장소를 관광공사 장소보다 먼저
|
||||
places = rows("place.csv") + rows("place_tourapi.csv")
|
||||
sunsets = rows("sunset_spot.csv")
|
||||
|
||||
|
||||
def pick(found: list[dict], n: int) -> list[str]:
|
||||
"""아이콘(산책·피크닉·사진…)이 겹치지 않게 먼저 고르고, 모자라면 순서대로 채운다."""
|
||||
out, icons = [], set()
|
||||
for p in found:
|
||||
if p["icon"] not in icons and p["name"] not in out:
|
||||
out.append(p["name"])
|
||||
icons.add(p["icon"])
|
||||
for p in found:
|
||||
if p["name"] not in out:
|
||||
out.append(p["name"])
|
||||
return out[:n]
|
||||
|
||||
|
||||
result = {}
|
||||
for page in json.load(open(PAGES, encoding="utf-8")):
|
||||
names = {r["name"] for r in page["regions"]}
|
||||
mine = [p for p in places if p["region_name"] in names]
|
||||
result[page["path"]] = dict(
|
||||
outdoor=pick([p for p in mine if p["is_outdoor"] == "1"], OUTDOOR),
|
||||
indoor=pick([p for p in mine if p["is_outdoor"] == "0"], INDOOR),
|
||||
sunset=list(dict.fromkeys(s["name"] for s in sunsets if s["region_name"] in names))[:SUNSET],
|
||||
)
|
||||
# 시도마다 한 파일 (seoul.json). 지난번에 만든 시도 파일은 지우고 다시 쓴다
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
for f in os.listdir(OUT):
|
||||
if f.endswith(".json"):
|
||||
os.remove(os.path.join(OUT, f))
|
||||
by_sido = {}
|
||||
for path, spots in result.items():
|
||||
by_sido.setdefault(path.split("/")[0], {})[path] = spots
|
||||
for sido, part in by_sido.items():
|
||||
json.dump(part, open(os.path.join(OUT, f"{sido}.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
|
||||
print(len(result), "pages", sum(any(v.values()) for v in result.values()), "with places", len(by_sido), "files")
|
||||
@@ -24,6 +24,9 @@ R = '''종로 jongno 중 jung 용산 yongsan 성동 seongdong 광진 gwangjin
|
||||
춘천 chuncheon 원주 wonju 강릉 gangneung 동해 donghae 태백 taebaek 속초 sokcho 삼척 samcheok 홍천 hongcheon 횡성 hoengseong 영월 yeongwol 평창 pyeongchang 정선 jeongseon 철원 cheorwon 화천 hwacheon 양구 yanggu 인제 inje 양양 yangyang
|
||||
전주 jeonju 군산 gunsan 익산 iksan 정읍 jeongeup 남원 namwon 김제 gimje 완주 wanju 진안 jinan 무주 muju 장수 jangsu 임실 imsil 순창 sunchang 고창 gochang 부안 buan'''.split()
|
||||
ROMAN = dict(zip(R[::2], R[1::2]))
|
||||
G = '''장안 jangan 권선 gwonseon 팔달 paldal 영통 yeongtong 수정 sujeong 중원 jungwon 분당 bundang 만안 manan 동안 dongan 원미 wonmi 소사 sosa 오정 ojeong 상록 sangnok 단원 danwon 덕양 deogyang 일산동 ilsandong 일산서 ilsanseo 처인 cheoin 기흥 giheung 수지 suji
|
||||
만세 manse 효행 hyohaeng 병점 byeongjeom 동탄 dongtan 상당 sangdang 서원 seowon 흥덕 heungdeok 청원 cheongwon 동남 dongnam 서북 seobuk 남 nam 북 buk 의창 uichang 성산 seongsan 마산합포 masanhappo 마산회원 masanhoewon 진해 jinhae 완산 wansan 덕진 deokjin'''.split()
|
||||
GU = dict(zip(G[::2], G[1::2]))
|
||||
# 구로 나뉜 시는 시청이 있는 구를 먼저 보여 준다
|
||||
CITY_MAIN = {'수원시': '팔달구', '성남시': '중원구', '안양시': '동안구', '부천시': '원미구', '안산시': '단원구', '고양시': '덕양구', '용인시': '처인구', '화성시': '만세구', '청주시': '상당구', '천안시': '서북구', '포항시': '남구', '창원시': '의창구', '전주시': '완산구'}
|
||||
pages = {}
|
||||
@@ -36,8 +39,12 @@ for row in csv.DictReader(open(SRC, encoding='utf-8')):
|
||||
p['regions'].append(r)
|
||||
if len(rest) == 1 or CITY_MAIN[place] == rest[1]:
|
||||
p['main'] = r['code']
|
||||
# 구로 나뉜 시의 구도 자기 주소를 갖는다: /today/gyeonggi/seongnam/bundang
|
||||
if len(rest) == 2:
|
||||
gu = f"{path}/{GU[rest[1][:-1]]}"
|
||||
pages[gu] = dict(path=gu, name=row['name'], main=r['code'], regions=[r])
|
||||
out = list(pages.values())
|
||||
assert all(p['main'] for p in out), [p['path'] for p in out if not p['main']]
|
||||
assert sum(len(p['regions']) for p in out) == 256
|
||||
assert sum(len(p['regions']) for p in out if p['path'].count('/') == 1) == 256
|
||||
json.dump(out, open(OUT, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
|
||||
print(len(out), 'pages', sum(len(p['regions']) > 1 for p in out), 'cities')
|
||||
@@ -0,0 +1,148 @@
|
||||
"""지금 날씨 점수 바꾸기 표(services/calc/weather_score_table.json)를 다시 만든다.
|
||||
|
||||
지금 날씨 점수 공식(WEATHER_SCORE_DEF)으로 나온 원래 점수를 구간(아침·낮·저녁·밤)마다 1년 치 분포의 순위로 바꾼 뒤,
|
||||
평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾼다. 90점 이상은 구간마다 약 2.5%가 나온다. 맨 위는 straighten_top 으로 100점이 가장 좋은 원래 점수에서만 나오게 한다.
|
||||
1년 치 날씨는 Open-Meteo 과거 예보(강수확률 포함)와 대기질(초미세먼지)로, region.csv 에서 8개마다 1곳(32곳)을 쓴다.
|
||||
|
||||
WEATHER_SCORE_DEF 가 바뀌면 실행: cd backend && python scripts/gen_weather_score_table.py
|
||||
"""
|
||||
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import date, datetime, timedelta
|
||||
from statistics import NormalDist
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from common.enums import RainType, Sky # noqa: E402
|
||||
from common.logger import LOG # noqa: E402
|
||||
from services.calc.day_slot import SLOTS, slot_hours # noqa: E402
|
||||
from services.calc.index_calc import Context, Hour, evaluate # noqa: E402
|
||||
from services.calc.sun import sun_times # noqa: E402
|
||||
from services.index_service import WEATHER_SCORE_DEF # noqa: E402
|
||||
|
||||
BACKEND = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
REGIONS = os.path.join(BACKEND, "seed", "region.csv")
|
||||
OUT = os.path.join(BACKEND, "services", "calc", "weather_score_table.json")
|
||||
|
||||
MEAN, SIGMA = 60, 15
|
||||
DAYS = 364
|
||||
EVERY = 8
|
||||
_WEATHER = "https://historical-forecast-api.open-meteo.com/v1/forecast"
|
||||
_AIR = "https://air-quality-api.open-meteo.com/v1/air-quality"
|
||||
_HOURLY = "apparent_temperature,precipitation,snowfall,precipitation_probability,wind_speed_10m,relative_humidity_2m,sunshine_duration,cloud_cover"
|
||||
|
||||
|
||||
def fetch(url: str, params: dict) -> dict:
|
||||
"""잠깐 막히면 쉬었다가 다시 부른다. 네 번 모두 안 되면 멈춘다."""
|
||||
query = urllib.parse.urlencode(params)
|
||||
for attempt in range(4):
|
||||
try:
|
||||
with urllib.request.urlopen(f"{url}?{query}", timeout=60) as r:
|
||||
return json.load(r)
|
||||
except OSError as e:
|
||||
LOG.error(f"[weather-table] {url} 실패 {attempt + 1}회: {e}")
|
||||
time.sleep(10 * (attempt + 1))
|
||||
raise RuntimeError(f"{url} 를 받지 못함")
|
||||
|
||||
|
||||
def region_scores(lat: float, lon: float, start: date, end: date) -> dict[str, list[int]]:
|
||||
"""한 지점의 날마다 구간별 원래 점수. 앱과 같은 입력으로 맞춘다 (일조는 그 시각을 덮는 3시간 합 ÷ 3시간, 미세먼지는 구간 평균)."""
|
||||
base = dict(latitude=lat, longitude=lon, start_date=start.isoformat(), end_date=(end + timedelta(days=1)).isoformat(), timezone="Asia/Seoul")
|
||||
w = fetch(_WEATHER, base | dict(hourly=_HOURLY, wind_speed_unit="ms"))["hourly"]
|
||||
air = fetch(_AIR, base | dict(hourly="pm2_5"))["hourly"]
|
||||
pm = dict(zip(air["time"], air["pm2_5"]))
|
||||
at_index = {t: i for i, t in enumerate(w["time"])}
|
||||
|
||||
def key(at: datetime) -> str:
|
||||
return at.strftime("%Y-%m-%dT%H:%M")
|
||||
|
||||
def hour_at(at: datetime, h: int) -> tuple[Hour | None, float | None]:
|
||||
i = at_index.get(key(at))
|
||||
if i is None or w["apparent_temperature"][i] is None:
|
||||
return None, None
|
||||
end_at = datetime.combine(at.date(), datetime.min.time()) + timedelta(hours=(at.hour + 3) // 3 * 3)
|
||||
sun = [w["sunshine_duration"][j] for j in (at_index.get(key(end_at - timedelta(hours=k))) for k in (3, 2, 1)) if j is not None and w["sunshine_duration"][j] is not None]
|
||||
wet = (w["precipitation"][i] or 0) >= 0.1
|
||||
cloud = w["cloud_cover"][i] or 0
|
||||
return Hour(
|
||||
hour=h, feels_c=w["apparent_temperature"][i],
|
||||
rain_type=(RainType.SNOW if (w["snowfall"][i] or 0) > 0 else RainType.RAIN) if wet else RainType.NONE,
|
||||
rain_prob=int(w["precipitation_probability"][i] or 0), wind_ms=w["wind_speed_10m"][i], humidity=int(w["relative_humidity_2m"][i]),
|
||||
sky=Sky.CLOUDY if cloud >= 80 else Sky.PARTLY if cloud >= 40 else Sky.CLEAR,
|
||||
sunshine_ratio=min(sum(sun) / 10800, 1.0) if len(sun) == 3 else None,
|
||||
), pm.get(key(at))
|
||||
|
||||
out: dict[str, list[int]] = {s: [] for s in SLOTS}
|
||||
day = start
|
||||
while day <= end:
|
||||
midnight = datetime.combine(day, datetime.min.time())
|
||||
for slot, hours in slot_hours(day, sun_times(day, lat, lon).sunset_at).items():
|
||||
got = [hour_at(midnight + timedelta(hours=h), h) for h in sorted(hours)]
|
||||
if any(x is None for x, _ in got):
|
||||
continue
|
||||
pms = [p for _, p in got if p is not None]
|
||||
ctx = Context(day=day, is_holiday=False, pm25=round(sum(pms) / len(pms)) if pms else None, air_label=None, moon=0, sunset_score=None,
|
||||
wind_warning=False, lookahead_rain_prob=0)
|
||||
r = evaluate(WEATHER_SCORE_DEF, [[x for x, _ in got]], ctx)
|
||||
if r is not None:
|
||||
out[slot].append(r.score)
|
||||
day += timedelta(days=1)
|
||||
return out
|
||||
|
||||
|
||||
def table(scores: list[int]) -> list[int]:
|
||||
"""원래 점수 0~100 각각을 '분포에서의 가운데 순위'로 정규분포 점수에 맞춘다. 순서는 그대로 (줄어들지 않게)."""
|
||||
n = len(scores)
|
||||
out = []
|
||||
for v in range(101):
|
||||
below = sum(1 for s in scores if s < v)
|
||||
same = sum(1 for s in scores if s == v)
|
||||
out.append(max(0, min(100, round(MEAN + SIGMA * NormalDist().inv_cdf((below + same / 2 + 0.5) / (n + 1))))))
|
||||
for i in range(1, 101):
|
||||
out[i] = max(out[i], out[i - 1])
|
||||
return out
|
||||
|
||||
|
||||
ANCHOR_SCORE = 83 # 위쪽 끝을 직선으로 잇기 시작하는 표시 점수
|
||||
|
||||
|
||||
def straighten_top(t: list[int], top: int = 100) -> list[int]:
|
||||
"""표 맨 위가 100으로 잘려 비슷한 원래 점수(96·97·99)가 모두 100점이 되던 것을 막는다.
|
||||
표시 점수가 ANCHOR_SCORE 이하인 마지막 원래 점수에서 top(그 구간에서 나올 수 있는 가장 높은 원래 점수)의 100점까지 직선으로 잇는다.
|
||||
100점은 원래 점수가 top 이상일 때만 나온다. 그 아래 점수는 바뀌지 않는다."""
|
||||
anchor = max(i for i, v in enumerate(t[: top + 1]) if v <= ANCHOR_SCORE)
|
||||
out = list(t)
|
||||
for raw in range(anchor + 1, 101):
|
||||
out[raw] = 100 if raw >= top else min(99, round(t[anchor] + (100 - t[anchor]) * (raw - anchor) / (top - anchor)))
|
||||
return out
|
||||
|
||||
|
||||
def main() -> None:
|
||||
end = date.today() - timedelta(days=2)
|
||||
start = end - timedelta(days=DAYS)
|
||||
regions = list(csv.DictReader(open(REGIONS, encoding="utf-8")))[::EVERY]
|
||||
scores: dict[str, list[int]] = {s: [] for s in SLOTS}
|
||||
for r in regions:
|
||||
for slot, got in region_scores(float(r["lat"]), float(r["lon"]), start, end).items():
|
||||
scores[slot] += got
|
||||
LOG.info(f"[weather-table] {r['name']} 완료")
|
||||
time.sleep(1)
|
||||
doc = {
|
||||
"about": f"지금 날씨 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 {MEAN}·표준편차 {SIGMA}. scripts/gen_weather_score_table.py 가 만든다",
|
||||
"period": [start.isoformat(), end.isoformat()], "regions": len(regions), "samples": {s: len(v) for s, v in scores.items()},
|
||||
# 밤은 해 난 비율이 늘 0점이라 원래 점수가 100 - 그 비중까지만 나온다
|
||||
"slots": {s: straighten_top(table(v), 100 - WEATHER_SCORE_DEF.weight_sun if s == "night" else 100) for s, v in scores.items()},
|
||||
}
|
||||
with open(OUT, "w", encoding="utf-8") as f:
|
||||
json.dump(doc, f, ensure_ascii=False, indent=1)
|
||||
print(len(regions), "regions", doc["samples"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -18,13 +18,17 @@ _FALL_FLOOR = exp(-0.5)
|
||||
# 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p)
|
||||
_TEMP_PLATEAU = 2
|
||||
_HUMIDITY_PLATEAU = 5
|
||||
# 각 중요도(index_definition.priority)별 순위 가중치: 1=상 2=중 3=하. 순위만 바꾸고 보이는 점수는 그대로 둔다.
|
||||
PRIORITY_WEIGHT = {1: 1.0, 2: 0.85, 3: 0.7}
|
||||
|
||||
|
||||
def rank_score(score: int, priority: int) -> float:
|
||||
"""각 순위를 정하는 값 = 점수 × 중요도 가중치."""
|
||||
return score * PRIORITY_WEIGHT[priority]
|
||||
def priority_score(score: int, priority: int) -> int:
|
||||
"""중요도 배율을 한 번 적용하고 정수로 반올림한 표시·순위 공통 점수."""
|
||||
return round(score * PRIORITY_WEIGHT[priority])
|
||||
|
||||
|
||||
def rank_score(score: int, priority: int) -> tuple[int, int]:
|
||||
"""중요도 반영이 끝난 표시 점수 내림차순. 동점이면 중요도 순."""
|
||||
return score, -priority
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -57,6 +61,7 @@ class Context:
|
||||
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
|
||||
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
|
||||
rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지'
|
||||
time_matches: bool = True # 평가하는 시간대가 각의 활동 시간대에 해당하는지
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -209,7 +214,7 @@ def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
|
||||
return (ctx.sunrise_score if ctx.sunrise_score is not None else _UNKNOWN), (
|
||||
f"일출 하늘 점수 {ctx.sunrise_score}" if ctx.sunrise_score is not None else f"일출 하늘 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
|
||||
)
|
||||
return _clamp(rule["value"]), f"날짜와 상관없이 이 시간대 기본 점수 {_clamp(rule['value'])}점"
|
||||
return (100, "활동 시간대에 해당해요") if ctx.time_matches else (0, "활동 시간대가 아니에요")
|
||||
|
||||
|
||||
_TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"}
|
||||
@@ -296,9 +301,14 @@ def _summary(hours: list[Hour]) -> str:
|
||||
return f"{hour_label(mid.hour % 24)} {round(mid.feels_c)}°, {tag}"
|
||||
|
||||
|
||||
def _weighted(factors: dict[str, int], weights: dict[str, int]) -> int:
|
||||
worst = min((factors[a] for a in AXES if weights[a]), default=100)
|
||||
return round(sum(factors[a] * weights[a] for a in AXES) / 100 * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
|
||||
def _weighted(factors: dict[str, int], weights: dict[str, int], worst_pull: bool = True, time_is_binary: bool = False) -> int:
|
||||
"""비중대로 섞고, worst_pull 이면 가장 낮은 요소로 최대 25% 깎는다 (지금 날씨 점수는 깎지 않는다)."""
|
||||
mixed = sum(factors[a] * weights[a] for a in AXES) / 100
|
||||
if not worst_pull:
|
||||
return round(mixed)
|
||||
# 시간대 불일치는 해당 가중치만 잃으며, 최저 요소에 따른 추가 감점에는 넣지 않는다.
|
||||
worst = min((factors[a] for a in AXES if weights[a] and not (time_is_binary and a == "time")), default=100)
|
||||
return round(mixed * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
|
||||
|
||||
|
||||
def _until(definition) -> str:
|
||||
@@ -338,7 +348,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
}
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
notes = {a: n for a, (_, n) in scored.items()}
|
||||
score = _weighted(factors, weights)
|
||||
score = _weighted(factors, weights, getattr(definition, "worst_pull", True), rules["time"]["type"] == "fixed")
|
||||
agg = {
|
||||
"rain_prob": max_prob, "wind_ms": max(winds) if winds else None, "pm25": ctx.pm25,
|
||||
"feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)),
|
||||
@@ -395,7 +405,7 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
|
||||
}
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
notes = {a: n for a, (_, n) in scored.items()}
|
||||
score = _weighted(factors, weights)
|
||||
score = _weighted(factors, weights, getattr(definition, "worst_pull", True), rules["time"]["type"] == "fixed")
|
||||
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
|
||||
# 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다
|
||||
known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"}
|
||||
@@ -413,7 +423,8 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
|
||||
# 나들이 날씨 점수: 낮 10~17시에 바깥에서 놀기 좋은 정도. 주말 전국 순위·당일치기 추천에 쓴다.
|
||||
OUTING_HOURS = (10, 18)
|
||||
_OUTING_WEIGHTS = {"temp": 35, "rain": 40, "sky": 15, "wind": 10}
|
||||
_OUTING_RULES = {"temp": {"type": "range", "lo": 17, "hi": 24, "best": 21}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 4, "limit": 12}}
|
||||
# 만점 조건을 엄격하게: 기온은 최적 21° ±0.5°, 바람은 초속 1m 이하(ok/2)여야 100점 — 같은 예보를 받는 여러 지역이 한꺼번에 100점이 되던 것을 줄인다
|
||||
_OUTING_RULES = {"temp": {"type": "range", "lo": 17, "hi": 24, "best": 21, "plateau": 0.5}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 2, "limit": 12}}
|
||||
_OUTING_SKY = {Sky.CLEAR: 100, Sky.PARTLY: 80, Sky.CLOUDY: 50}
|
||||
_OUTING_RAIN_PROB, _OUTING_RAIN_CAP = 60, 30
|
||||
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
from dataclasses import dataclass
|
||||
from types import SimpleNamespace
|
||||
from typing import Literal, Optional
|
||||
|
||||
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS
|
||||
|
||||
Rain = Literal["dry", "wet"]
|
||||
Air = Literal["good", "normal"]
|
||||
|
||||
# 미세먼지 허용 단계 → 초미세먼지(㎍/㎥) 점수 규칙. 단계 경계(좋음 15·보통 35)까지 100, 넘으면 깎는다
|
||||
_AIR = {"good": {"zero": 35, "full": 15}, "normal": {"zero": 75, "full": 35}}
|
||||
_WIND_LIMIT_OVER = 6 # 바람 상한에서 이만큼 더 세지면 0점
|
||||
|
||||
|
||||
def _n(v: float) -> float:
|
||||
"""근거 문구에 15.0° 대신 15° 로 나오게."""
|
||||
return int(v) if float(v).is_integer() else v
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MyRule:
|
||||
"""사용자가 정한 내 각 조건. None 인 항목은 보지 않는다."""
|
||||
|
||||
temp: Optional[tuple[float, float]] = None # 체감온도 범위(°)
|
||||
rain: Optional[Rain] = None # dry: 안 와야, wet: 와야
|
||||
wind_max: Optional[float] = None # 바람 상한(m/s)
|
||||
air: Optional[Air] = None # 미세먼지 허용 단계
|
||||
humidity: Optional[tuple[int, int]] = None # 습도 범위(%)
|
||||
slots: tuple[str, ...] = SLOTS # 볼 시간대
|
||||
|
||||
|
||||
def axes(rule: MyRule) -> list[str]:
|
||||
return [a for a, on in (("temp", rule.temp), ("rain", rule.rain), ("wind", rule.wind_max is not None), ("air", rule.air), ("humidity", rule.humidity)) if on]
|
||||
|
||||
|
||||
def definition(rule: MyRule) -> SimpleNamespace:
|
||||
"""공식 각과 같은 계산(evaluate)에 넣을 정의. 고른 조건끼리 가중치를 똑같이 나눈다."""
|
||||
used = axes(rule)
|
||||
share = {a: 100 // len(used) + (1 if i < 100 % len(used) else 0) for i, a in enumerate(used)} if used else {}
|
||||
return SimpleNamespace(
|
||||
**{f"weight_{a}": share.get(a, 0) for a in ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")},
|
||||
factor_rules={
|
||||
"temp": {"type": "range", "lo": _n(rule.temp[0]), "hi": _n(rule.temp[1])} if rule.temp else {"type": "range", "lo": -50, "hi": 60},
|
||||
"rain": {"dir": rule.rain or "dry"},
|
||||
"wind": {"type": "calm", "ok": _n(rule.wind_max), "limit": rule.wind_max + _WIND_LIMIT_OVER} if rule.wind_max is not None else {"type": "ignore"},
|
||||
"humidity": {"type": "range", "lo": rule.humidity[0], "hi": rule.humidity[1]} if rule.humidity else {"type": "ignore"},
|
||||
"air": _AIR[rule.air] if rule.air else None,
|
||||
"time": {"type": "fixed", "value": 100},
|
||||
},
|
||||
zero_rules=[{"field": "rain", "op": "==", "value": "yes", "cap": 20}] if rule.rain == "dry" else [],
|
||||
windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
|
||||
)
|
||||
|
||||
|
||||
# 공식 각을 내 각 조건으로 옮길 때 쓰는 대표 시각(해 뜨고 지는 시각은 계절마다 달라 가운데 값으로)
|
||||
_SUNRISE_HOUR, _SUNSET_HOUR = 6, 18
|
||||
_TEMP_MIN, _TEMP_MAX = -20, 40
|
||||
|
||||
|
||||
def _slot_of_hour(h: int) -> str:
|
||||
h %= 24
|
||||
if NIGHT_END_HOUR <= h < 11:
|
||||
return "morning"
|
||||
if 11 <= h < _SUNSET_HOUR - 2:
|
||||
return "day"
|
||||
if _SUNSET_HOUR - 2 <= h < _SUNSET_HOUR + 1:
|
||||
return "evening"
|
||||
return "night"
|
||||
|
||||
|
||||
def _window_slots(windows: list[dict]) -> list[str]:
|
||||
hours: set[int] = set()
|
||||
for w in windows:
|
||||
if "around" in w:
|
||||
mid = _SUNRISE_HOUR if w["around"] == "sunrise" else _SUNSET_HOUR
|
||||
hours.update(range(mid - w["hours"], mid + w["hours"]))
|
||||
else:
|
||||
hours.update(range(w["from"], w["to"]))
|
||||
got = {_slot_of_hour(h) for h in hours}
|
||||
return [s for s in SLOTS if s in got]
|
||||
|
||||
|
||||
def _preset_temp(r: dict) -> Optional[list[float]]:
|
||||
off = r.get("offset", 0)
|
||||
t = r["type"]
|
||||
if t == "range":
|
||||
lo, hi = r["lo"] - off, r["hi"] - off
|
||||
elif t == "higher":
|
||||
lo, hi = r["full"] - off, _TEMP_MAX
|
||||
elif t == "lower":
|
||||
lo, hi = _TEMP_MIN, r["full"] - off
|
||||
else:
|
||||
return None # 범위에서 멀수록 좋은 규칙은 범위 하나로 옮길 수 없다
|
||||
lo, hi = max(_TEMP_MIN, lo), min(_TEMP_MAX, hi)
|
||||
return [_n(lo), _n(hi)] if lo < hi else None
|
||||
|
||||
|
||||
_PRESET_HUMIDITY = {"higher": [60, 100], "lower": [0, 60]}
|
||||
|
||||
|
||||
def preset(defn) -> dict:
|
||||
"""공식 각을 내 각 조건(MyGakRule 모양)으로 비슷하게 옮긴다. 비중 0인 요소와 옮길 수 없는 규칙은 뺀다."""
|
||||
r = defn.factor_rules
|
||||
out: dict = {"slots": _window_slots(defn.windows) or list(SLOTS)}
|
||||
if defn.weight_temp and (temp := _preset_temp(r["temp"])):
|
||||
out["temp"] = temp
|
||||
if defn.weight_rain:
|
||||
out["rain"] = r["rain"]["dir"]
|
||||
wind = r.get("wind", {})
|
||||
if defn.weight_wind and wind.get("type") in ("calm", "moderate"):
|
||||
out["wind_max"] = _n(max(1, wind["ok"])) if wind["type"] == "calm" else 5
|
||||
air = r.get("air")
|
||||
if defn.weight_air and not (air and air["full"] > air["zero"]):
|
||||
out["air"] = "normal"
|
||||
hum = r.get("humidity", {})
|
||||
if defn.weight_humidity and hum.get("type") in ("range", "higher", "lower"):
|
||||
out["humidity"] = [hum["lo"], hum["hi"]] if hum["type"] == "range" else _PRESET_HUMIDITY[hum["type"]]
|
||||
return out
|
||||
@@ -0,0 +1,112 @@
|
||||
{
|
||||
"about": "나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 60·표준편차 15. scripts/gen_outing_score_table.py 가 만든다",
|
||||
"period": [
|
||||
"2025-10-22",
|
||||
"2026-10-21"
|
||||
],
|
||||
"regions": 32,
|
||||
"samples": 11680,
|
||||
"table": [
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
8,
|
||||
13,
|
||||
17,
|
||||
22,
|
||||
25,
|
||||
28,
|
||||
30,
|
||||
32,
|
||||
34,
|
||||
36,
|
||||
37,
|
||||
37,
|
||||
38,
|
||||
38,
|
||||
39,
|
||||
39,
|
||||
40,
|
||||
41,
|
||||
41,
|
||||
42,
|
||||
42,
|
||||
47,
|
||||
50,
|
||||
50,
|
||||
50,
|
||||
50,
|
||||
50,
|
||||
50,
|
||||
50,
|
||||
50,
|
||||
50,
|
||||
50,
|
||||
51,
|
||||
51,
|
||||
51,
|
||||
51,
|
||||
52,
|
||||
54,
|
||||
57,
|
||||
61,
|
||||
62,
|
||||
62,
|
||||
62,
|
||||
63,
|
||||
63,
|
||||
63,
|
||||
63,
|
||||
63,
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
65,
|
||||
65,
|
||||
65,
|
||||
65,
|
||||
66,
|
||||
66,
|
||||
66,
|
||||
66,
|
||||
67,
|
||||
67,
|
||||
67,
|
||||
68,
|
||||
68,
|
||||
68,
|
||||
69,
|
||||
69,
|
||||
70,
|
||||
70,
|
||||
71,
|
||||
72,
|
||||
73,
|
||||
74,
|
||||
75,
|
||||
76,
|
||||
78,
|
||||
79,
|
||||
81,
|
||||
83,
|
||||
85,
|
||||
86,
|
||||
88,
|
||||
90,
|
||||
92,
|
||||
93,
|
||||
95,
|
||||
97,
|
||||
98,
|
||||
100
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
{
|
||||
"about": "지금 날씨 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 60·표준편차 15. scripts/gen_weather_score_table.py 가 만든다",
|
||||
"period": [
|
||||
"2025-10-22",
|
||||
"2026-10-21"
|
||||
],
|
||||
"regions": 32,
|
||||
"samples": {
|
||||
"morning": 11680,
|
||||
"day": 11680,
|
||||
"evening": 11680,
|
||||
"night": 11680
|
||||
},
|
||||
"slots": {
|
||||
"morning": [
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
4,
|
||||
5,
|
||||
5,
|
||||
9,
|
||||
11,
|
||||
14,
|
||||
16,
|
||||
17,
|
||||
18,
|
||||
20,
|
||||
21,
|
||||
23,
|
||||
25,
|
||||
26,
|
||||
28,
|
||||
29,
|
||||
31,
|
||||
31,
|
||||
32,
|
||||
33,
|
||||
33,
|
||||
34,
|
||||
34,
|
||||
35,
|
||||
35,
|
||||
35,
|
||||
36,
|
||||
37,
|
||||
37,
|
||||
38,
|
||||
38,
|
||||
39,
|
||||
40,
|
||||
41,
|
||||
42,
|
||||
43,
|
||||
44,
|
||||
45,
|
||||
46,
|
||||
47,
|
||||
47,
|
||||
48,
|
||||
49,
|
||||
50,
|
||||
52,
|
||||
53,
|
||||
54,
|
||||
55,
|
||||
57,
|
||||
59,
|
||||
61,
|
||||
62,
|
||||
63,
|
||||
64,
|
||||
64,
|
||||
65,
|
||||
65,
|
||||
66,
|
||||
66,
|
||||
67,
|
||||
67,
|
||||
68,
|
||||
68,
|
||||
69,
|
||||
69,
|
||||
70,
|
||||
71,
|
||||
71,
|
||||
72,
|
||||
73,
|
||||
73,
|
||||
74,
|
||||
74,
|
||||
75,
|
||||
76,
|
||||
77,
|
||||
78,
|
||||
79,
|
||||
80,
|
||||
82,
|
||||
83,
|
||||
84,
|
||||
86,
|
||||
87,
|
||||
88,
|
||||
90,
|
||||
91,
|
||||
92,
|
||||
93,
|
||||
95,
|
||||
96,
|
||||
97,
|
||||
99,
|
||||
100
|
||||
],
|
||||
"day": [
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
4,
|
||||
6,
|
||||
9,
|
||||
12,
|
||||
15,
|
||||
19,
|
||||
22,
|
||||
24,
|
||||
26,
|
||||
27,
|
||||
28,
|
||||
29,
|
||||
30,
|
||||
31,
|
||||
31,
|
||||
32,
|
||||
32,
|
||||
33,
|
||||
33,
|
||||
34,
|
||||
35,
|
||||
36,
|
||||
37,
|
||||
37,
|
||||
38,
|
||||
39,
|
||||
40,
|
||||
41,
|
||||
41,
|
||||
42,
|
||||
42,
|
||||
43,
|
||||
43,
|
||||
44,
|
||||
44,
|
||||
45,
|
||||
45,
|
||||
46,
|
||||
46,
|
||||
47,
|
||||
47,
|
||||
47,
|
||||
48,
|
||||
48,
|
||||
48,
|
||||
49,
|
||||
49,
|
||||
50,
|
||||
50,
|
||||
51,
|
||||
52,
|
||||
54,
|
||||
56,
|
||||
59,
|
||||
61,
|
||||
62,
|
||||
63,
|
||||
63,
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
65,
|
||||
65,
|
||||
66,
|
||||
66,
|
||||
66,
|
||||
67,
|
||||
67,
|
||||
68,
|
||||
68,
|
||||
69,
|
||||
70,
|
||||
71,
|
||||
72,
|
||||
73,
|
||||
74,
|
||||
76,
|
||||
77,
|
||||
79,
|
||||
81,
|
||||
83,
|
||||
86,
|
||||
89,
|
||||
92,
|
||||
94,
|
||||
97,
|
||||
100
|
||||
],
|
||||
"evening": [
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
7,
|
||||
11,
|
||||
14,
|
||||
17,
|
||||
20,
|
||||
23,
|
||||
25,
|
||||
27,
|
||||
28,
|
||||
29,
|
||||
30,
|
||||
31,
|
||||
32,
|
||||
32,
|
||||
33,
|
||||
34,
|
||||
34,
|
||||
35,
|
||||
36,
|
||||
37,
|
||||
38,
|
||||
38,
|
||||
39,
|
||||
39,
|
||||
40,
|
||||
40,
|
||||
41,
|
||||
41,
|
||||
42,
|
||||
42,
|
||||
43,
|
||||
43,
|
||||
44,
|
||||
45,
|
||||
45,
|
||||
46,
|
||||
46,
|
||||
47,
|
||||
47,
|
||||
48,
|
||||
48,
|
||||
48,
|
||||
49,
|
||||
50,
|
||||
50,
|
||||
51,
|
||||
52,
|
||||
53,
|
||||
55,
|
||||
56,
|
||||
59,
|
||||
60,
|
||||
62,
|
||||
63,
|
||||
63,
|
||||
64,
|
||||
64,
|
||||
65,
|
||||
65,
|
||||
66,
|
||||
66,
|
||||
67,
|
||||
67,
|
||||
68,
|
||||
69,
|
||||
69,
|
||||
70,
|
||||
71,
|
||||
71,
|
||||
72,
|
||||
74,
|
||||
75,
|
||||
76,
|
||||
78,
|
||||
79,
|
||||
81,
|
||||
83,
|
||||
85,
|
||||
87,
|
||||
89,
|
||||
92,
|
||||
94,
|
||||
96,
|
||||
98,
|
||||
100
|
||||
],
|
||||
"night": [
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
4,
|
||||
7,
|
||||
10,
|
||||
11,
|
||||
13,
|
||||
15,
|
||||
17,
|
||||
20,
|
||||
22,
|
||||
26,
|
||||
28,
|
||||
30,
|
||||
32,
|
||||
33,
|
||||
34,
|
||||
34,
|
||||
35,
|
||||
35,
|
||||
35,
|
||||
36,
|
||||
36,
|
||||
37,
|
||||
38,
|
||||
38,
|
||||
39,
|
||||
40,
|
||||
41,
|
||||
41,
|
||||
42,
|
||||
43,
|
||||
44,
|
||||
45,
|
||||
46,
|
||||
48,
|
||||
49,
|
||||
50,
|
||||
52,
|
||||
53,
|
||||
55,
|
||||
57,
|
||||
60,
|
||||
62,
|
||||
63,
|
||||
65,
|
||||
65,
|
||||
66,
|
||||
66,
|
||||
66,
|
||||
67,
|
||||
68,
|
||||
68,
|
||||
69,
|
||||
69,
|
||||
70,
|
||||
70,
|
||||
71,
|
||||
71,
|
||||
72,
|
||||
73,
|
||||
74,
|
||||
74,
|
||||
75,
|
||||
77,
|
||||
78,
|
||||
80,
|
||||
82,
|
||||
84,
|
||||
86,
|
||||
88,
|
||||
90,
|
||||
92,
|
||||
94,
|
||||
96,
|
||||
98,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100
|
||||
]
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
"""인스타그램 캐러셀 올리기 (Instagram API with Instagram Login, graph.instagram.com).
|
||||
|
||||
이미지는 인스타가 받아 갈 수 있는 공개 주소여야 한다 (우리 /v1/card/<id>/<n>.jpg 를 PUBLIC_BASE_URL 뒤에 붙인다).
|
||||
순서: 장마다 컨테이너 → 캐러셀 컨테이너 → 상태 FINISHED 확인 → 게시. 문서: developers.facebook.com/docs/instagram-platform/instagram-api-with-instagram-login/content-publishing
|
||||
"""
|
||||
import asyncio
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from common.logger import LOG
|
||||
from config.settings import settings
|
||||
|
||||
GRAPH = "https://graph.instagram.com/v24.0"
|
||||
TIMEOUT_SEC = 30.0
|
||||
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):
|
||||
pass
|
||||
|
||||
|
||||
def configured() -> bool:
|
||||
return bool(settings.instagram_access_token.strip() and settings.instagram_user_id.strip())
|
||||
|
||||
|
||||
def public_image_url(path: str) -> str:
|
||||
return f"{settings.public_base_url.rstrip('/')}{path}"
|
||||
|
||||
|
||||
async def _post(client: httpx.AsyncClient, path: str, data: dict) -> dict:
|
||||
res = await client.post(f"{GRAPH}/{path}", data={**data, "access_token": settings.instagram_access_token})
|
||||
body = res.json() if res.content else {}
|
||||
if res.status_code >= 400 or "error" in body:
|
||||
msg = (body.get("error") or {}).get("message") or f"HTTP {res.status_code}"
|
||||
raise InstagramError(msg)
|
||||
return body
|
||||
|
||||
|
||||
async def _status(client: httpx.AsyncClient, container_id: str) -> str:
|
||||
res = await client.get(f"{GRAPH}/{container_id}", params={"fields": "status_code", "access_token": settings.instagram_access_token})
|
||||
body = res.json() if res.content else {}
|
||||
if res.status_code >= 400 or "error" in body:
|
||||
raise InstagramError((body.get("error") or {}).get("message") or f"HTTP {res.status_code}")
|
||||
return body.get("status_code", "")
|
||||
|
||||
|
||||
async def publish_carousel(image_urls: list[str], caption: str, client: Optional[httpx.AsyncClient] = None, wait_sec: float = STATUS_WAIT_SEC) -> str:
|
||||
"""공개 이미지 주소들을 캐러셀 한 개로 올리고 인스타 미디어 id 를 돌려준다."""
|
||||
if not configured():
|
||||
raise InstagramError("INSTAGRAM_ACCESS_TOKEN / INSTAGRAM_USER_ID 가 비어 있다")
|
||||
if not 1 <= len(image_urls) <= MAX_ITEMS:
|
||||
raise InstagramError(f"이미지는 1~{MAX_ITEMS}장")
|
||||
user = settings.instagram_user_id.strip()
|
||||
own = client is None
|
||||
client = client or httpx.AsyncClient(timeout=TIMEOUT_SEC)
|
||||
try:
|
||||
children = []
|
||||
for url in image_urls:
|
||||
children.append((await _post(client, f"{user}/media", {"image_url": url, "is_carousel_item": "true"}))["id"])
|
||||
if len(children) == 1:
|
||||
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"]
|
||||
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
|
||||
except httpx.HTTPError as e:
|
||||
raise InstagramError(f"{type(e).__name__}") from e
|
||||
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,5 +1,6 @@
|
||||
import asyncio
|
||||
import random
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import Optional
|
||||
@@ -10,18 +11,19 @@ from redis.exceptions import RedisError
|
||||
from common.cache.lock import redis_lock
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Article, OpenMeteoHourly, Post, Region, WeatherHourly
|
||||
from common.database.model.models import Article, CardSet, IndexScore, OpenMeteoHourly, Post, Region, WeatherHourly
|
||||
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, SkyType, WarningType
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, ULTRA_DELAY, kst_midnight, latest_ultra_base, next_vilage_available, now_kst
|
||||
from common.utils.text import compass, day_range, hour_label, short_day
|
||||
from crud.card_crud import CardCRUD
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.v1.feed.protocol import (
|
||||
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide,
|
||||
PlanSlide, PlanStep, TopIndex, WeekDay, WeekGak, WeekSlide,
|
||||
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HeroTomorrow, HourCell, HoursSlide, ImageSlide, PostData, PostReaction, Res_Feed, Row, RowsSlide, SunsetSlide,
|
||||
PlanSlide, PlanStep, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide,
|
||||
)
|
||||
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
|
||||
from services.air_service import pm10_grade, pm25_grade
|
||||
@@ -62,10 +64,20 @@ LINEUP = [
|
||||
(18, PostType.DAY_TRIP, RefType.NONE, None),
|
||||
(19, PostType.MOON, RefType.NONE, None),
|
||||
(20, PostType.UV, RefType.NONE, None),
|
||||
(21, PostType.HERO, RefType.NONE, None),
|
||||
(22, PostType.TODAY_GAK, RefType.NONE, None),
|
||||
(23, PostType.FOLIAGE, RefType.NONE, None),
|
||||
(24, PostType.EVENTS_BAND, RefType.NONE, None),
|
||||
(25, PostType.SEASON_BAND, RefType.NONE, None),
|
||||
]
|
||||
# 피드 목록 대신 히어로·오늘의 각·단풍 지도·띠에 좋아요·댓글만 붙는 자리
|
||||
_PINNED = {
|
||||
PostType.HERO: "hero_post", PostType.TODAY_GAK: "gak_post", PostType.FOLIAGE: "foliage_post",
|
||||
PostType.EVENTS_BAND: "events_post", PostType.SEASON_BAND: "season_post",
|
||||
}
|
||||
# 좋아요·댓글 단위. 이 종류들은 전국이 같은 카드 하나, 나머지는 그 구 데이터로 채우는 카드라 시도마다 따로 만든다.
|
||||
NATIONAL_SCOPE = "00"
|
||||
NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON})
|
||||
NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON, PostType.FOLIAGE, PostType.SEASON_BAND})
|
||||
|
||||
|
||||
def sido_of(region_code: str) -> str:
|
||||
@@ -76,12 +88,13 @@ def sido_of(region_code: str) -> str:
|
||||
def post_scope(post_type: PostType, region_code: str) -> str:
|
||||
return NATIONAL_SCOPE if post_type in NATIONAL_TYPES else sido_of(region_code)
|
||||
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 앞쪽 절반 사이사이 무작위.
|
||||
# 알림은 비·특보가 있을 때만 켜지니 맨 앞, 주말·노을처럼 공유할 만한 카드를 그다음, 공기·자외선·상식 같은 평이한 정보는 뒤로.
|
||||
ORDER = {
|
||||
"morning": [PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
|
||||
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.GAK, PostType.MOON, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.AIR, PostType.TOMORROW, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.MOON, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.AIR, PostType.SEASON, PostType.TIP, PostType.QUOTE],
|
||||
"morning": [PostType.ALERT, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SUNSET, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.MOON, PostType.AIR, PostType.UV, PostType.TIP, PostType.QUOTE],
|
||||
"day": [PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.MOON, PostType.AIR, PostType.UV, PostType.TIP, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.ALERT, PostType.WEEK, PostType.MOON, PostType.WEEKEND_PLAN, PostType.GAK, PostType.TOMORROW, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.AIR, PostType.TIP, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.ALERT, PostType.MOON, PostType.WEEK, PostType.SUNSET, PostType.WEEKEND_PLAN, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.AIR, PostType.TIP, PostType.QUOTE],
|
||||
}
|
||||
_SKY_MODE = {"morning": "morning", "day": "day", "evening": "sunset", "night": "night"}
|
||||
_CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"}
|
||||
@@ -92,6 +105,7 @@ _RAIN_PROB = 40
|
||||
_UV_SHOW = 3 # 자외선 포스트: 오늘 가장 셀 때 '보통' 이상이면 띄운다
|
||||
_HERO_RAIN_PROB = 60 # 히어로 '오늘 비': 오늘 남은 칸 중 비 형태가 있거나 확률이 이만큼 넘는 첫 칸
|
||||
_SUNSET_FULL = 60
|
||||
_CARD_SECOND_AT = 6 # 같은 날 두 번째 카드뉴스 자리
|
||||
_FEED_DAY_START = 3 # 03:00 에 그날 카드가 바뀐다
|
||||
_COMMUTE_HOURS = (("내일 출근 8시", 8), ("내일 퇴근 7시", 19))
|
||||
_RAIN_LOOK = ("umbrella", "☔ 우산 챙겨!")
|
||||
@@ -142,6 +156,7 @@ def _hero_input(
|
||||
now=now, night=slot in ("evening", "night"), after_dark=slot == "night", rain_at=rainy[0].at if rainy else None,
|
||||
rain_later_at=later, today_known=bool(ahead),
|
||||
air=AirGrade(now_w.air.grade) if now_w and now_w.air and now_w.air.grade is not None else None, uv=uv,
|
||||
pm25=now_w.air.pm25 if now_w and now_w.air else None, pm10=now_w.air.pm10 if now_w and now_w.air else None,
|
||||
temp_min=min(temps, default=None), temp_max=max(temps, default=None),
|
||||
temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None,
|
||||
moon=moon, humidity=cur.humidity if cur else None, discomfort=cur.discomfort_index if cur else None,
|
||||
@@ -220,10 +235,15 @@ def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime
|
||||
if slot == "night":
|
||||
rest = [c for c in rest if c.post_type is not PostType.QUOTE] + [c for c in rest if c.post_type is PostType.QUOTE]
|
||||
events = pool.get(PostType.EVENT, [])
|
||||
gaps = sorted(random.Random(seed).sample(range(1, len(rest)), min(len(events), max(0, len(rest) - 1))), reverse=True)
|
||||
front = range(1, max(1, len(rest) // 2 + 1))
|
||||
gaps = sorted(random.Random(seed).sample(front, min(len(events), len(front))), reverse=True)
|
||||
for gap, e in zip(gaps, reversed(events[:len(gaps)])):
|
||||
rest.insert(gap, e)
|
||||
return head + rest
|
||||
# 카드뉴스(관리자가 올린 것)는 날씨 바로 아래, 같은 날 두 번째부터는 피드 중간쯤
|
||||
cards = pool.get(PostType.CARD, [])
|
||||
for i, card in enumerate(cards[1:]):
|
||||
rest.insert(min(len(rest), _CARD_SECOND_AT + i), card)
|
||||
return head + cards[:1] + rest
|
||||
|
||||
|
||||
def _by_position(posts: list[Post]) -> list[Post]:
|
||||
@@ -234,6 +254,28 @@ def _by_position(posts: list[Post]) -> list[Post]:
|
||||
return list(out.values())
|
||||
|
||||
|
||||
def _tomorrow_best(board: IndexBoard, day: date) -> Optional[tuple[IndexItem, IndexScore]]:
|
||||
"""내일 하루 점수로 1위인 각과 그 점수 (동점이면 중요도 순)."""
|
||||
best = None
|
||||
for i in board.items:
|
||||
s = next((x for x in i.trend if x.score_date == day), None)
|
||||
if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)):
|
||||
best = (i, s)
|
||||
return best
|
||||
|
||||
|
||||
def _hero_tomorrow(day: date, board: IndexBoard) -> HeroTomorrow:
|
||||
best = _tomorrow_best(board, day)
|
||||
top1 = None
|
||||
if best is not None:
|
||||
d, s = best[0].definition, best[1]
|
||||
top1 = TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=s.score, rank=1, summary=s.summary)
|
||||
return HeroTomorrow(
|
||||
day=day, weather_slots=board.tomorrow_slots, top1=top1,
|
||||
weather_why={k: [WeatherWhy(label=w.label, weight=w.weight, score=w.score, note=w.note) for w in ws] for k, ws in board.tomorrow_why.items()},
|
||||
)
|
||||
|
||||
|
||||
def _top(i: IndexItem) -> TopIndex:
|
||||
d = i.definition
|
||||
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary, active=i.active,
|
||||
@@ -311,7 +353,7 @@ class FeedService:
|
||||
now = now_kst()
|
||||
sunset_at = sun_times(now.date(), float(region.lat), float(region.lon)).sunset_at
|
||||
slot = slot_of(now, sunset_at)
|
||||
key = f"feed:{region.code}:{slot}"
|
||||
key = f"feed:{region.code}:priority-score-v4:{slot}"
|
||||
try:
|
||||
cached = await REDIS.conn.get(key)
|
||||
if cached:
|
||||
@@ -357,17 +399,23 @@ class FeedService:
|
||||
)
|
||||
_, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.day(s, day, [NATIONAL_SCOPE, sido_of(region.code)]))
|
||||
posts = _by_position(posts or [])
|
||||
card_ids = [p.ref_id for p in posts if PostType(p.post_type) is PostType.CARD and p.ref_id is not None]
|
||||
_, card_sets = await DB_SESSION_MNG.execute_lambda(lambda s: CardCRUD().many(s, card_ids))
|
||||
_, card_counts = await DB_SESSION_MNG.execute_lambda(lambda s: CardCRUD().image_counts(s, card_ids))
|
||||
cards = {c.card_id: (c, (card_counts or {}).get(c.card_id, 0)) for c in card_sets or []}
|
||||
_, articles = await DB_SESSION_MNG.execute_lambda(lambda s: self.season_crud.articles(s, now.date(), None))
|
||||
by_article = {a.article_id: a for a in articles or []}
|
||||
quotes = [a for a in articles or [] if a.category == ArticleCategory.QUOTE.value]
|
||||
ctx = _Ctx(region=region, now=now, slot=slot, sunset_at=sunset_at, today=today, tomorrow=tomorrow, now_w=now_w, sky=sky, board=board,
|
||||
days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip,
|
||||
uv=await self._uv_today(region.code, now))
|
||||
uv=await self._uv_today(region.code, now), cards=cards)
|
||||
|
||||
gak = sorted(board.ranked[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
cards = []
|
||||
pinned = {_PINNED[PostType(p.post_type)]: PostReaction(post_id=p.post_id, like_count=p.like_count, comment_count=p.comment_count)
|
||||
for p in posts or [] if PostType(p.post_type) in _PINNED}
|
||||
for p in posts or []:
|
||||
if PostType(p.post_type) is PostType.GAK:
|
||||
if PostType(p.post_type) is PostType.GAK or PostType(p.post_type) in _PINNED:
|
||||
continue
|
||||
data = self._render(p, ctx)
|
||||
if data is not None:
|
||||
@@ -381,7 +429,7 @@ class FeedService:
|
||||
feed = Res_Feed(
|
||||
region_code=region.code, region_name=region.name, slot=slot,
|
||||
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or [])),
|
||||
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"),
|
||||
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"), **pinned,
|
||||
bands=Bands(
|
||||
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon,
|
||||
image=e.event.image_url, image_credit=image_credit(e.event)) for e in mix_kinds(events)[:4]],
|
||||
@@ -440,10 +488,12 @@ class FeedService:
|
||||
discomfort=cur.discomfort_index if cur else None, discomfort_label=discomfort_label(cur.discomfort_index) if cur else None,
|
||||
rain_2h_text=now_w.rain_2h_text if now_w else None, will_rain_2h=now_w.will_rain_2h if now_w else None,
|
||||
weather_score=board.weather_score if board else None, weather_slots=board.weather_slots if board else {},
|
||||
weather_why={k: [WeatherWhy(label=w.label, weight=w.weight, score=w.score, note=w.note) for w in ws] for k, ws in board.weather_why.items()} if board else {},
|
||||
top1=_top(top) if top else None, bubble=bubble,
|
||||
moon_name=moon[0].name if moon else None, moon_pct=round(moon[0].lit * 100) if moon else None,
|
||||
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(x_in)],
|
||||
status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_status(x_in)],
|
||||
status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone, detail=x.detail) for x in hero_status(x_in)],
|
||||
tomorrow=_hero_tomorrow(now.date() + timedelta(days=1), board) if board else None,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -454,7 +504,7 @@ class FeedService:
|
||||
def _gak(self, p: Post, i: IndexItem) -> PostData:
|
||||
d = i.definition
|
||||
return PostData(**self._base(p), title=f"{d.name} {i.score.score}점", icon=d.icon, caption=_gak_caption(i),
|
||||
slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary)],
|
||||
slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary, rows=gak_rows(i), say=_band_sentence(d.sentences, i.score.score))],
|
||||
share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}점이래"])
|
||||
|
||||
def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]:
|
||||
@@ -517,8 +567,18 @@ class FeedService:
|
||||
return self._moon(base, c)
|
||||
if t is PostType.UV:
|
||||
return self._uv_post(base, c)
|
||||
if t is PostType.CARD and p.ref_id in c.cards:
|
||||
return self._card(base, *c.cards[p.ref_id])
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _card(base: dict, card: CardSet, count: int) -> Optional[PostData]:
|
||||
"""관리자가 올린 카드뉴스: 이미지 장마다 슬라이드 하나."""
|
||||
if count == 0:
|
||||
return None
|
||||
slides = [ImageSlide(kind="image", url=f"/v1/card/{card.card_id}/{i}.jpg", alt=f"{card.title} {i}/{count}") for i in range(1, count + 1)]
|
||||
return PostData(**base, title=card.title, icon="stars", caption=card.caption, slides=slides, share_messages=[card.title])
|
||||
|
||||
def _moon(self, base: dict, c: "_Ctx") -> PostData:
|
||||
"""오늘 밤(정오~다음 날 정오)에 보름이나 삭이 있으면 그 이야기를, 아니면 달 모양·잘 보이는지와 다음 보름. 피드 아래쪽에 둔다."""
|
||||
tonight = _tonight(c.now)
|
||||
@@ -685,13 +745,8 @@ class FeedService:
|
||||
return PostData(**base, title=plan.title, icon=icon, caption=caption, slides=slides, share_messages=[share])
|
||||
|
||||
def _tomorrow(self, base: dict, c: "_Ctx") -> PostData:
|
||||
tomorrow = c.now.date() + timedelta(days=1)
|
||||
rows = [Row(label=x.label, value=x.text) for x in c.now_w.commute]
|
||||
best = None
|
||||
for i in c.board.items if c.board else []:
|
||||
s = next((x for x in i.trend if x.score_date == tomorrow), None)
|
||||
if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)):
|
||||
best = (i, s)
|
||||
best = _tomorrow_best(c.board, c.now.date() + timedelta(days=1)) if c.board else None
|
||||
if best is not None:
|
||||
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점"))
|
||||
caption = _temp_change(c.today, c.tomorrow) or "출근 전에 한 번 더 확인해 주세요."
|
||||
@@ -721,9 +776,32 @@ def _band_sentence(sentences: Optional[dict], score: int) -> Optional[str]:
|
||||
return sentences[str(lo)] if lo is not None else None
|
||||
|
||||
|
||||
# 각 포스트에 보일 근거 줄 이름. 시간(요일·노을 점수)은 계산 방식 설명이라 뺀다
|
||||
_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "uv": "자외선", "sun": "햇볕", "view": "시야"}
|
||||
_NOTE_HEAD = {"wind": "바람 ", "humidity": "습도 ", "air": "초미세먼지 "}
|
||||
|
||||
|
||||
def gak_rows(i: IndexItem, n: int = 4) -> list[Row]:
|
||||
"""비중이 큰 조건부터 n개와 지금 값. 점수에 안 쓰는 조건도 n개가 될 때까지 지금 날씨로 채운다. 값은 계산 근거 문구의 첫 마디 (체감 18°, 확률 20%, 초속 3m)."""
|
||||
d, notes = i.definition, i.score.notes or {}
|
||||
weighted = sorted((a for a in _AXIS_NAME if getattr(d, f"weight_{a}", 0) and notes.get(a)), key=lambda a: -getattr(d, f"weight_{a}"))
|
||||
axes = weighted + [a for a in ("temp", "rain", "wind", "air", "humidity") if a not in weighted and notes.get(a)]
|
||||
rows = []
|
||||
for a in axes[:n]:
|
||||
head, _, tail = notes[a].partition(", ")
|
||||
prob = re.search(r"확률 \d+%", notes[a]) if a == "rain" else None
|
||||
if prob:
|
||||
value = prob.group(0)
|
||||
elif a == "air" and tail:
|
||||
value = tail
|
||||
else:
|
||||
value = head.removeprefix(_NOTE_HEAD.get(a, ""))
|
||||
rows.append(Row(label=_AXIS_NAME[a], value=value))
|
||||
return rows
|
||||
|
||||
|
||||
def _gak_caption(i: IndexItem) -> str:
|
||||
"""점수 구간 설명 문장 + 슬라이드에 없는 내일 점수(없으면 하기 좋은 시간)."""
|
||||
band = _band_sentence(i.definition.sentences, i.score.score)
|
||||
"""슬라이드에 없는 내일 점수(없으면 하기 좋은 시간). 점수 구간 설명 문장은 슬라이드에 있다."""
|
||||
nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None)
|
||||
if nxt is not None:
|
||||
diff = nxt.score - i.score.score
|
||||
@@ -732,7 +810,7 @@ def _gak_caption(i: IndexItem) -> str:
|
||||
else:
|
||||
spans = [_span(w) for w in i.definition.windows or []]
|
||||
tail = f"하기 좋은 때는 {spans[0][0]}~{spans[0][1]}시예요." if spans else f"오늘의 각 {i.rank}위예요."
|
||||
return f"{band} {tail}" if band else tail
|
||||
return tail
|
||||
|
||||
|
||||
def _temp_change(today: Optional[TodayWeather], tomorrow: Optional[TodayWeather]) -> Optional[str]:
|
||||
@@ -762,7 +840,7 @@ _CLOUDY = {Sky.CLEAR: 0.0, Sky.PARTLY: 0.5, Sky.CLOUDY: 1.0}
|
||||
|
||||
|
||||
def _day_gaks(board: Optional[IndexBoard], day: date, n: int = 3) -> list[WeekGak]:
|
||||
"""그날 대표 각: 각 상세의 날짜별 점수(하루 중 가장 좋은 시간대)를 점수 × 중요도 순으로."""
|
||||
"""그날 대표 각: 날짜별 표시 점수 내림차순, 동점이면 중요도 순으로."""
|
||||
scored = [(i.definition, s) for i in (board.items if board else []) for s in i.trend if s.score_date == day]
|
||||
scored.sort(key=lambda x: rank_score(x[1].score, x[0].priority), reverse=True)
|
||||
return [WeekGak(index_id=d.index_id, name=d.name, icon=d.icon, score=s.score) for d, s in scored[:n]]
|
||||
@@ -807,3 +885,4 @@ class _Ctx:
|
||||
quotes: list[Article]
|
||||
trip: Optional[tuple[TripPick, list[EventItem]]] = None
|
||||
uv: list[OpenMeteoHourly] = field(default_factory=list) # 오늘 낮 3시간 칸 자외선
|
||||
cards: dict[int, tuple[CardSet, int]] = field(default_factory=dict) # 카드뉴스 card_id → (묶음, 장 수)
|
||||
@@ -11,7 +11,6 @@ Tone = Literal["normal", "warn", "rain"]
|
||||
|
||||
UV_HIGH = 6.0
|
||||
MUGGY_DI = 75 # 불쾌지수 '불쾌'가 시작되는 값
|
||||
DISCOMFORT_MONTHS = range(6, 10) # 기상청처럼 6~9월에만. 더위 지표라 선선한 철엔 비 와도 '쾌적'으로 나온다
|
||||
HUMID_DRY, HUMID_WET = 30, 60 # 습도 % : 이 아래 건조, 이 위 습함
|
||||
TEMP_SWING_C = 10.0
|
||||
WIND_CHILL_C = 3.0
|
||||
@@ -25,6 +24,7 @@ class HeroStatItem:
|
||||
label: str
|
||||
value: str
|
||||
tone: Tone = "normal"
|
||||
detail: Optional[str] = None # 단계 이름 밑의 실제 값 (예: 68%, 72, 2, 초미세먼지 15㎍/㎥)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -35,6 +35,8 @@ class HeroInput:
|
||||
rain_later_at: Optional[datetime] = None # 그 뒤 오늘 안에 비 오는 첫 시각 (단기예보)
|
||||
today_known: bool = False # 오늘 남은 시간 예보가 있어 '오늘 비 안 와요'라고 말할 수 있는지
|
||||
air: Optional[AirGrade] = None
|
||||
pm25: Optional[int] = None
|
||||
pm10: Optional[int] = None
|
||||
uv: Optional[float] = None
|
||||
temp_min: Optional[float] = None
|
||||
temp_max: Optional[float] = None
|
||||
@@ -67,16 +69,17 @@ def humidity_label(h: int) -> str:
|
||||
|
||||
|
||||
def hero_status(x: HeroInput) -> list[HeroStatItem]:
|
||||
"""히어로 상태 한 줄: 습도·불쾌지수(6~9월)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
|
||||
"""히어로 상태 한 줄: 습도·불쾌지수(늘)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
|
||||
out: list[HeroStatItem] = []
|
||||
if x.humidity is not None:
|
||||
out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity)))
|
||||
if x.discomfort is not None and x.now.month in DISCOMFORT_MONTHS:
|
||||
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal"))
|
||||
out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity), detail=f"{x.humidity}%"))
|
||||
if x.discomfort is not None:
|
||||
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal", detail=str(x.discomfort)))
|
||||
if not x.after_dark and x.uv is not None:
|
||||
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal"))
|
||||
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal", detail=f"{x.uv:g}"))
|
||||
if x.air is not None:
|
||||
out.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn" if x.air in (AirGrade.BAD, AirGrade.VERY_BAD) else "normal"))
|
||||
pm = " · ".join(s for s in (f"초미세먼지 {x.pm25}㎍/㎥" if x.pm25 is not None else "", f"미세먼지 {x.pm10}㎍/㎥" if x.pm10 is not None else "") if s) or None
|
||||
out.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn" if x.air in (AirGrade.BAD, AirGrade.VERY_BAD) else "normal", detail=pm))
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import asyncio
|
||||
import json
|
||||
from dataclasses import dataclass, field, replace
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Optional
|
||||
|
||||
@@ -17,7 +19,7 @@ from crud.weather_crud import WeatherCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.air_service import GRADE_LABEL, AirService
|
||||
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS, slot_hours, slot_of
|
||||
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, rank_score
|
||||
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, priority_score, rank_score
|
||||
from services.calc.moon import night, up_ratio, view_line
|
||||
from services.calc.sun import sun_times
|
||||
from services.external.open_meteo import is_dark_slot
|
||||
@@ -39,7 +41,27 @@ WEATHER_SCORE_DEF = SimpleNamespace(
|
||||
"air": {"zero": 75, "full": 10}, "sun": {"zero": 0.2, "full": 0.9}, "time": {"type": "fixed", "value": 100},
|
||||
},
|
||||
zero_rules=[], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
|
||||
# 가장 낮은 요소로 깎지 않는다: 밤엔 해 난 비율이 늘 0점이라 깎기가 밤 점수를 눌렀다
|
||||
worst_pull=False,
|
||||
)
|
||||
WEATHER_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "sun": "햇볕"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class WeatherWhy:
|
||||
label: str
|
||||
weight: int
|
||||
score: int
|
||||
note: str
|
||||
|
||||
|
||||
def weather_why(r: Result) -> list[WeatherWhy]:
|
||||
"""날씨 점수를 이룬 조건들. 비중 큰 것부터."""
|
||||
axes = sorted((a for a in WEATHER_AXIS_NAME if getattr(WEATHER_SCORE_DEF, f"weight_{a}")), key=lambda a: -getattr(WEATHER_SCORE_DEF, f"weight_{a}"))
|
||||
return [WeatherWhy(label=WEATHER_AXIS_NAME[a], weight=getattr(WEATHER_SCORE_DEF, f"weight_{a}"), score=r.factors[a], note=r.notes.get(a, "")) for a in axes]
|
||||
|
||||
# 지금 날씨 점수 바꾸기 표: 구간마다 원래 점수 0~100 → 표시 점수(평균 60, 90점 이상은 드물게). scripts/gen_weather_score_table.py 가 만든다
|
||||
WEATHER_SCORE_TABLE: dict[str, list[int]] = json.loads((Path(__file__).parent / "calc" / "weather_score_table.json").read_text(encoding="utf-8"))["slots"]
|
||||
|
||||
|
||||
SEASONS = ("겨울", "봄", "여름", "가을")
|
||||
@@ -70,8 +92,8 @@ class IndexItem:
|
||||
trend: list[IndexScore]
|
||||
slot: Optional[str] = None
|
||||
slots: dict[str, int] = field(default_factory=dict)
|
||||
slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음
|
||||
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다
|
||||
slot_ranks: dict[str, int] = field(default_factory=dict) # 각 구간의 날씨·시간대 적합도로 계산한 순위
|
||||
active: bool = True # 시간대와 관계없이 활성화. 제철이 아닌 각만 제외
|
||||
season: Optional[str] = None # 지금 제철이면 계절 이름 (화면 표시)
|
||||
in_season: bool = True # 제철이 아니면 순위·피드에서 빼고 목록 맨 끝에 둔다
|
||||
|
||||
@@ -83,10 +105,13 @@ class IndexBoard:
|
||||
weather_score: Optional[int]
|
||||
items: list[IndexItem]
|
||||
weather_slots: dict[str, int] = field(default_factory=dict)
|
||||
weather_why: dict[str, list[WeatherWhy]] = field(default_factory=dict)
|
||||
tomorrow_slots: dict[str, int] = field(default_factory=dict) # 내일 아침·낮·저녁·밤 날씨 점수
|
||||
tomorrow_why: dict[str, list[WeatherWhy]] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def ranked(self) -> list[IndexItem]:
|
||||
"""지금 구간에 해당하는 각만 (순위·피드용)."""
|
||||
"""활성화된 각 (순위·피드용)."""
|
||||
return [i for i in self.items if i.active]
|
||||
|
||||
|
||||
@@ -176,7 +201,6 @@ def windows_for(
|
||||
|
||||
|
||||
EARLY = "early" # 0~5시: 전날 밤 구간
|
||||
MIN_SLOT_HOURS = 2 # 각 시간대가 구간과 이만큼은 겹쳐야 그 구간 점수를 낸다 (한 시간짜리 각은 한 시간)
|
||||
|
||||
|
||||
def current_slot(now: datetime, sunset_at: datetime) -> str:
|
||||
@@ -187,12 +211,22 @@ def shown_slot(key: str) -> str:
|
||||
return "night" if key == EARLY else key
|
||||
|
||||
|
||||
def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]:
|
||||
def _shown_parts(parts: dict, cur: str) -> dict:
|
||||
"""구간 점수를 아침·낮·저녁·밤 순으로. 0~5시면 밤은 전날 밤 구간을 쓴다."""
|
||||
shown = {shown_slot(k): v for k, v in parts.items() if k != ("night" if cur == EARLY else EARLY)}
|
||||
return {k: shown[k] for k in SLOTS if k in shown}
|
||||
|
||||
|
||||
def calibrated_weather(slot: str, score: int) -> int:
|
||||
"""지금 날씨 점수의 원래 점수를 그 구간 표로 바꾼다. 0~5시(전날 밤 구간)는 밤 표."""
|
||||
return WEATHER_SCORE_TABLE[shown_slot(slot)][score]
|
||||
|
||||
|
||||
def weather_slot_scores(results: dict[str, Result]) -> dict[str, Result]:
|
||||
"""구간별 날씨 점수 결과의 점수를 표시 점수로 바꾼다 (점수 근거 factors 는 그대로)."""
|
||||
return {k: replace(r, score=calibrated_weather(k, r.score)) for k, r in results.items()}
|
||||
|
||||
|
||||
def rain_hours(by_at: dict[datetime, WeatherHourly], day: date) -> frozenset[int]:
|
||||
"""그날 비·눈 오는 시각(0~23)."""
|
||||
start = kst_midnight(day)
|
||||
@@ -203,16 +237,21 @@ def slot_results(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
|
||||
now: Optional[datetime] = None,
|
||||
) -> dict[str, Result]:
|
||||
"""그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다. now 를 주면 지금 구간은 지금 시각부터만 본다."""
|
||||
"""각 구간의 날씨로 평가한다. 활동 시간대와 안 겹쳐도 계산하되 시간 요소는 0점. now 가 있으면 현재 구간은 남은 시각만 본다."""
|
||||
hours_by_slot = slot_hours(day, sunset_at)
|
||||
cur = _trim_passed(hours_by_slot, day, sunset_at, now) if now else None
|
||||
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in hours_by_slot.items()}
|
||||
parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR)))
|
||||
need = min(MIN_SLOT_HOURS, max((len(h) for h in window_hours(defn, day, region)), default=0))
|
||||
hours_by_slot[EARLY] = set(range(NIGHT_END_HOUR))
|
||||
if now:
|
||||
_trim_passed(hours_by_slot, day, sunset_at, now)
|
||||
activity = [{h % 24 for h in w} for w in window_hours(defn, day, region)]
|
||||
out = {}
|
||||
for key, windows in parts.items():
|
||||
k_need = min(need, len(hours_by_slot[key])) if key == cur else need
|
||||
result = evaluate(defn, [w for w in windows if len(w) >= k_need], ctx)
|
||||
for key, hours in hours_by_slot.items():
|
||||
if not hours:
|
||||
continue
|
||||
matches = any(any(h % 24 in w for h in hours) for w in activity)
|
||||
# 시간대 일치 여부와 날씨 평가를 분리해 하루 점수로 대체하지 않는다.
|
||||
window = SimpleNamespace(windows=[{"from": min(hours), "to": max(hours) + 1}])
|
||||
windows = windows_for(window, day, region, by_at, by_om, only=hours)
|
||||
result = evaluate(defn, windows, replace(ctx, time_matches=matches))
|
||||
if result is not None:
|
||||
out[key] = result
|
||||
return out
|
||||
@@ -240,6 +279,13 @@ def _with_slot(row: IndexScore, data: dict) -> IndexScore:
|
||||
return out
|
||||
|
||||
|
||||
def _with_priority(row: IndexScore, priority: int) -> IndexScore:
|
||||
"""DB의 원점수·요소 점수는 보존하고 응답용 사본의 최종 점수에만 중요도를 적용한다."""
|
||||
out = IndexScore(**{c.key: getattr(row, c.key, None) for c in IndexScore.__table__.columns})
|
||||
out.score = priority_score(row.score, priority)
|
||||
return out
|
||||
|
||||
|
||||
def day_forecast(d: WeatherDaily) -> DayForecast:
|
||||
return DayForecast(
|
||||
temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None,
|
||||
@@ -305,10 +351,12 @@ class IndexService:
|
||||
if region is None:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
now = now_kst()
|
||||
err, weather_parts = await self.ensure(region, now)
|
||||
err, weather_days = await self.ensure(region, now)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
today = now.date()
|
||||
weather_parts = weather_days[today]
|
||||
tomorrow_parts = weather_days.get(today + timedelta(days=1), {})
|
||||
cur = current_slot(now, sun_times(today, float(region.lat), float(region.lon)).sunset_at)
|
||||
slots = slot_days(today)
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
||||
@@ -319,37 +367,23 @@ class IndexService:
|
||||
month = today.month
|
||||
out_season = [d for d in defs if not in_season(d, month)]
|
||||
defs = [d for d in defs if in_season(d, month)]
|
||||
# 오늘 점수는 지금 구간 점수. 구간 점수가 없는 행(예전 계산분)은 하루 점수 그대로, 지금 구간과 안 겹치는 각은 뺀다
|
||||
# 현재 구간의 날씨와 시간 요소로 계산한 점수만 사용한다.
|
||||
now_score: dict[int, IndexScore] = {}
|
||||
for d in defs:
|
||||
row = by_key.get((d.index_id, today))
|
||||
if row is None:
|
||||
if row is None or cur not in row.slots:
|
||||
continue
|
||||
if not row.slots:
|
||||
now_score[d.index_id] = row
|
||||
elif cur in row.slots:
|
||||
now_score[d.index_id] = _with_slot(row, row.slots[cur])
|
||||
now_score[d.index_id] = _with_priority(_with_slot(row, row.slots[cur]), d.priority)
|
||||
ranked = sorted((d for d in defs if d.index_id in now_score), key=lambda d: rank_score(now_score[d.index_id].score, d.priority), reverse=True)
|
||||
items = []
|
||||
for i, d in enumerate(ranked):
|
||||
row = by_key[(d.index_id, today)]
|
||||
parts = _shown_parts({k: v["score"] for k, v in row.slots.items()}, cur)
|
||||
parts = _shown_parts({k: priority_score(v["score"], d.priority) for k, v in row.slots.items()}, cur)
|
||||
items.append(IndexItem(
|
||||
definition=d, score=now_score[d.index_id], rank=i + 1,
|
||||
trend=[now_score[d.index_id] if day == today else by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
trend=[now_score[d.index_id] if day == today else _with_priority(by_key[(d.index_id, day)], d.priority) for day in slots if (d.index_id, day) in by_key],
|
||||
slot=shown_slot(cur), slots=parts, season=season_badge(d, month),
|
||||
))
|
||||
off = sorted(
|
||||
(d for d in defs if d.index_id not in now_score and (d.index_id, today) in by_key),
|
||||
key=lambda d: rank_score(by_key[(d.index_id, today)].score, d.priority), reverse=True,
|
||||
)
|
||||
for d in off:
|
||||
row = by_key[(d.index_id, today)]
|
||||
items.append(IndexItem(
|
||||
definition=d, score=row, rank=len(items) + 1,
|
||||
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slots=_shown_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False, season=season_badge(d, month),
|
||||
))
|
||||
for k in SLOTS:
|
||||
in_slot = sorted((i for i in items if k in i.slots), key=lambda i: rank_score(i.slots[k], i.definition.priority), reverse=True)
|
||||
for n, i in enumerate(in_slot):
|
||||
@@ -358,15 +392,49 @@ class IndexService:
|
||||
for d in sorted((d for d in out_season if (d.index_id, today) in by_key), key=lambda d: d.sort_order):
|
||||
row = by_key[(d.index_id, today)]
|
||||
items.append(IndexItem(
|
||||
definition=d, score=row, rank=len(items) + 1,
|
||||
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key], active=False, in_season=False,
|
||||
definition=d, score=_with_priority(row, d.priority), rank=len(items) + 1,
|
||||
trend=[_with_priority(by_key[(d.index_id, day)], d.priority) for day in slots if (d.index_id, day) in by_key], active=False, in_season=False,
|
||||
))
|
||||
return ErrorType.SUCCESS, IndexBoard(
|
||||
region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur),
|
||||
region=region, day=today, weather_score=weather_parts[cur].score if cur in weather_parts else None, items=items,
|
||||
weather_slots=_shown_parts({k: r.score for k, r in weather_parts.items()}, cur),
|
||||
weather_why=_shown_parts({k: weather_why(r) for k, r in weather_parts.items()}, cur),
|
||||
tomorrow_slots=_shown_parts({k: r.score for k, r in tomorrow_parts.items()}, ""),
|
||||
tomorrow_why=_shown_parts({k: weather_why(r) for k, r in tomorrow_parts.items()}, ""),
|
||||
)
|
||||
|
||||
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, int]]]:
|
||||
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다."""
|
||||
async def custom(self, region_code: str, defns: list) -> tuple[ErrorType, Optional[tuple[str, list[dict[str, Result]]]]]:
|
||||
"""공식 각이 아닌 정의(내 각)들을 그 동네 오늘 아침·낮·저녁·밤으로 계산한다. (지금 구간, 정의마다 구간별 결과)"""
|
||||
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if region is None:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
now = now_kst()
|
||||
_, _, ultra = await asyncio.gather(self.weather_service.ensure_vilage(region, now), self.air_service.ensure(now), ultra_hours(region, now))
|
||||
today = now.date()
|
||||
start = kst_midnight(today)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region.code, start - timedelta(days=1), start + timedelta(days=2)))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if not rows:
|
||||
return ErrorType.EXTERNAL_API_ERROR, None
|
||||
air = await self.air_service.nearest(region)
|
||||
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
|
||||
ctx = Context(
|
||||
day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), wind_warning=False,
|
||||
pm25=air.pm25 if air else None, air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None,
|
||||
)
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
|
||||
cur = current_slot(now, sunset_at)
|
||||
out = []
|
||||
for d in defns:
|
||||
parts = slot_results(d, today, region, by_at, {}, ctx, sunset_at, now)
|
||||
out.append({shown_slot(k): r for k, r in parts.items() if k != ("night" if cur == EARLY else EARLY)})
|
||||
return ErrorType.SUCCESS, (shown_slot(cur), out)
|
||||
|
||||
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[date, dict[str, Result]]]]:
|
||||
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘·내일 구간별 날씨 점수도 같이 낸다."""
|
||||
_, _, _, warnings, ultra = await asyncio.gather(
|
||||
self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now),
|
||||
self.warning_service.for_region(region, now), ultra_hours(region, now, wait=True),
|
||||
@@ -396,7 +464,13 @@ class IndexService:
|
||||
)
|
||||
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), **base_ctx)
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
|
||||
weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()}
|
||||
tomorrow = today + timedelta(days=1)
|
||||
tomorrow_ctx = Context(day=tomorrow, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, tomorrow), **base_ctx)
|
||||
tomorrow_sunset = sun_times(tomorrow, float(region.lat), float(region.lon)).sunset_at
|
||||
weather_parts = {
|
||||
today: weather_slot_scores(slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now)),
|
||||
tomorrow: weather_slot_scores(slot_results(WEATHER_SCORE_DEF, tomorrow, region, by_at, by_om, tomorrow_ctx, tomorrow_sunset)),
|
||||
}
|
||||
|
||||
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
|
||||
inputs_at = max(issued, air.measured_at) if air else issued
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import MyGak, User
|
||||
from common.enums import ErrorType
|
||||
from crud.my_gak_crud import MyGakCRUD
|
||||
from services.calc.day_slot import SLOTS
|
||||
from services.calc.my_gak_calc import MyRule, axes, definition, preset
|
||||
from services.index_service import IndexService
|
||||
|
||||
# 한 사람이 만들 수 있는 내 각 수
|
||||
MAX_PER_USER = 20
|
||||
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b|\d{3,}", re.I)
|
||||
|
||||
|
||||
def gak_name(name: str) -> Optional[str]:
|
||||
"""앞뒤 공백을 빼고 끝에 '각'을 붙인다. 링크·긴 숫자(전화번호 등)는 받지 않는다."""
|
||||
name = " ".join(name.split())
|
||||
if not name or _LINK.search(name):
|
||||
return None
|
||||
name = name if name.endswith("각") else f"{name}각"
|
||||
return name if len(name) <= 12 else None
|
||||
|
||||
|
||||
def my_rule(rule: dict) -> MyRule:
|
||||
return MyRule(
|
||||
temp=tuple(rule["temp"]) if rule.get("temp") else None, rain=rule.get("rain"), wind_max=rule.get("wind_max"), air=rule.get("air"),
|
||||
humidity=tuple(rule["humidity"]) if rule.get("humidity") else None, slots=tuple(s for s in SLOTS if s in (rule.get("slots") or SLOTS)),
|
||||
)
|
||||
|
||||
|
||||
class MyGakService:
|
||||
def __init__(self, crud: MyGakCRUD = Depends(MyGakCRUD), index: IndexService = Depends(IndexService)) -> None:
|
||||
self.crud, self.index = crud, index
|
||||
|
||||
async def mine(self, user: User) -> tuple[ErrorType, list[MyGak]]:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.of_user(s, user.user_id))
|
||||
return err, rows or []
|
||||
|
||||
async def add(self, user: User, name: str, rule: dict) -> tuple[ErrorType, Optional[MyGak]]:
|
||||
name = gak_name(name)
|
||||
if name is None:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count(s, user.user_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if n >= MAX_PER_USER:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, name, rule))
|
||||
|
||||
async def delete(self, user: User, my_gak_id: int) -> ErrorType:
|
||||
err, found = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, user.user_id, my_gak_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
return ErrorType.SUCCESS if found else ErrorType.NOT_FOUND
|
||||
|
||||
async def presets(self) -> tuple[ErrorType, list[dict]]:
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.index.crud.definitions(s))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
return err, [{"code": d.code, "name": d.name, "icon": d.icon, "rule": preset(d)} for d in defs]
|
||||
|
||||
async def score(self, region_code: str, rules: list[dict]) -> tuple[ErrorType, Optional[tuple[str, list[dict]]]]:
|
||||
"""조건마다 그 동네 오늘 시간대별 점수. 지금 시간대를 골랐으면 그 점수, 아니면 고른 시간대 중 가장 좋은 점수."""
|
||||
mine = [my_rule(r) for r in rules]
|
||||
err, got = await self.index.custom(region_code, [definition(r) for r in mine])
|
||||
if err is not ErrorType.SUCCESS or got is None:
|
||||
return err, None
|
||||
now_slot, parts = got
|
||||
out = []
|
||||
for r, p in zip(mine, parts):
|
||||
picked = {k: v for k, v in p.items() if k in r.slots}
|
||||
key = now_slot if now_slot in picked else max(picked, key=lambda k: picked[k].score, default=None)
|
||||
res = picked.get(key) if key else None
|
||||
out.append({
|
||||
"score": res.score if res else None, "slot": key if res else None,
|
||||
"slots": {k: v.score for k, v in picked.items()},
|
||||
"reasons": [res.notes[a] for a in axes(r) if res.notes.get(a)] if res else [],
|
||||
})
|
||||
return ErrorType.SUCCESS, (now_slot, out)
|
||||
@@ -8,10 +8,17 @@ from fastapi import Depends
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Comment, Post, User
|
||||
from common.enums import ErrorType, ReportReason
|
||||
from common.liker import Liker
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.reaction_crud import ReactionCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from services.talk_service import _LINK, _PHONE
|
||||
|
||||
COMMENT_MAX = 60
|
||||
# 로그인 없이 IP 하나가 하루에 쓸 수 있는 댓글 수
|
||||
ANON_DAILY_MAX = 20
|
||||
ANON_CHARACTER, ANON_COLOR = "rabbit", "orange"
|
||||
PAGE = 20
|
||||
|
||||
|
||||
@@ -33,8 +40,8 @@ class SavedView:
|
||||
|
||||
|
||||
class ReactionService:
|
||||
def __init__(self, crud: ReactionCRUD = Depends(ReactionCRUD), feed: FeedCRUD = Depends(FeedCRUD)) -> None:
|
||||
self.crud, self.feed = crud, feed
|
||||
def __init__(self, crud: ReactionCRUD = Depends(ReactionCRUD), feed: FeedCRUD = Depends(FeedCRUD), regions: RegionCRUD = Depends(RegionCRUD)) -> None:
|
||||
self.crud, self.feed, self.regions = crud, feed, regions
|
||||
|
||||
async def _post_exists(self, post_id: int) -> ErrorType:
|
||||
err, post = await DB_SESSION_MNG.execute_lambda(lambda s: self.feed.get(s, post_id))
|
||||
@@ -42,11 +49,11 @@ class ReactionService:
|
||||
return err
|
||||
return ErrorType.SUCCESS if post is not None else ErrorType.NOT_FOUND
|
||||
|
||||
async def like_post(self, post_id: int, user: User, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
async def like_post(self, post_id: int, who: Liker, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
err = await self._post_exists(post_id)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, user.user_id, on))
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, who, on))
|
||||
|
||||
async def save_post(self, post_id: int, user: User, on: bool) -> ErrorType:
|
||||
err = await self._post_exists(post_id)
|
||||
@@ -61,6 +68,12 @@ class ReactionService:
|
||||
err, marks = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.my_marks(s, user.user_id, post_ids))
|
||||
return marks if err is ErrorType.SUCCESS else (set(), set())
|
||||
|
||||
async def anon_liked(self, ip_hash: str, post_ids: list[int]) -> set[int]:
|
||||
if not post_ids:
|
||||
return set()
|
||||
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked_posts(s, ip_hash, post_ids))
|
||||
return liked if err is ErrorType.SUCCESS else set()
|
||||
|
||||
async def counts(self, post_ids: list[int]) -> dict[int, tuple[int, int]]:
|
||||
"""피드는 캐시돼 있어서 좋아요·댓글 수는 매번 DB 에서 덮어쓴다."""
|
||||
if not post_ids:
|
||||
@@ -72,50 +85,78 @@ class ReactionService:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.saved_posts(s, user.user_id, cursor, PAGE))
|
||||
return err, [SavedView(post=p, saved_at=ps.created_at) for p, ps in rows or []]
|
||||
|
||||
async def comments(self, post_id: int, user: Optional[User], cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
|
||||
@staticmethod
|
||||
def _view(c: Comment, nickname: Optional[str], character: Optional[str], color: Optional[str], mood: Optional[str], liked: bool, who: Liker) -> CommentView:
|
||||
if c.user_id is None:
|
||||
mine = who.user_id is None and c.ip_hash == who.ip_hash
|
||||
return CommentView(comment=c, nickname=f"{c.region_name} 익명" if c.region_name else "익명", character=ANON_CHARACTER, color=ANON_COLOR, mood=None, liked=liked, mine=mine)
|
||||
return CommentView(comment=c, nickname=nickname or "", character=character or ANON_CHARACTER, color=color or ANON_COLOR, mood=mood, liked=liked, mine=c.user_id == who.user_id)
|
||||
|
||||
async def comments(self, post_id: int, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, user.user_id if user else None, cursor, PAGE))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
liked: set[int] = set()
|
||||
ids = [c.comment_id for c, *_ in rows]
|
||||
if user is not None and rows:
|
||||
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked_comments(s, user.user_id, [c.comment_id for c, *_ in rows]))
|
||||
return ErrorType.SUCCESS, [
|
||||
CommentView(comment=c, nickname=n, character=ch, color=co, mood=mo, liked=c.comment_id in (liked or set()), mine=user is not None and c.user_id == user.user_id)
|
||||
for c, n, ch, co, mo in rows
|
||||
]
|
||||
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked_comments(s, user.user_id, ids))
|
||||
elif rows:
|
||||
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked_comments(s, ip_hash, ids))
|
||||
who = Liker(user_id=user.user_id if user else None, ip_hash=ip_hash)
|
||||
return ErrorType.SUCCESS, [self._view(c, n, ch, co, mo, c.comment_id in (liked or set()), who) for c, n, ch, co, mo in rows]
|
||||
|
||||
async def add_comment(self, post_id: int, user: User, body: str) -> tuple[ErrorType, Optional[CommentView]]:
|
||||
async def add_comment(self, post_id: int, user: Optional[User], who: Liker, body: str, region_code: Optional[str] = None) -> tuple[ErrorType, Optional[CommentView]]:
|
||||
"""로그인 없이도 쓴다. 그때는 링크·전화번호를 막고 IP 하나에 하루 ANON_DAILY_MAX 개까지, 이름은 쓸 때 동네로 '마포구 익명'."""
|
||||
body = body.strip()
|
||||
if not body or len(body) > COMMENT_MAX:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
if user.terms_agreed_at is None:
|
||||
if user is not None and user.terms_agreed_at is None:
|
||||
return ErrorType.TERMS_REQUIRED, None
|
||||
err = await self._post_exists(post_id)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
err, c = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_comment(s, post_id, user.user_id, body))
|
||||
return err, (CommentView(comment=c, nickname=user.nickname, character=user.character, color=user.color, mood=user.mood, liked=False, mine=True) if c else None)
|
||||
region_name = None
|
||||
if user is None:
|
||||
if _LINK.search(body) or _PHONE.search(body):
|
||||
return ErrorType.LINK_NOT_ALLOWED, None
|
||||
today = kst_midnight(now_kst().date())
|
||||
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_comments_since(s, who.ip_hash, today))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if n >= ANON_DAILY_MAX:
|
||||
return ErrorType.DAILY_LIMIT, None
|
||||
if region_code:
|
||||
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
region_name = region.short_name if region else None
|
||||
err, c = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_comment(s, post_id, who, body, region_name))
|
||||
if c is None:
|
||||
return err, None
|
||||
if user is None:
|
||||
return err, self._view(c, None, None, None, None, False, who)
|
||||
return err, self._view(c, user.nickname, user.character, user.color, user.mood, False, who)
|
||||
|
||||
async def delete_comment(self, comment_id: int, user: User) -> ErrorType:
|
||||
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete_comment(s, comment_id, user.user_id))
|
||||
async def delete_comment(self, comment_id: int, who: Liker) -> ErrorType:
|
||||
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete_comment(s, comment_id, who))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
|
||||
|
||||
async def like_comment(self, comment_id: int, user: User, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
err, count = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_comment_like(s, comment_id, user.user_id, on))
|
||||
async def like_comment(self, comment_id: int, who: Liker, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
err, count = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_comment_like(s, comment_id, who, on))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return (ErrorType.NOT_FOUND, None) if count is None else (ErrorType.SUCCESS, count)
|
||||
|
||||
async def _others_comment(self, comment_id: int, user: User) -> tuple[ErrorType, Optional[uuid.UUID]]:
|
||||
"""남이 쓴, 지금 보이는 댓글의 작성자. 내 댓글이면 INVALID_INPUT."""
|
||||
"""남이 쓴, 지금 보이는 댓글의 작성자. 내 댓글이면 INVALID_INPUT, 로그인 없이 쓴 댓글이면 작성자는 None."""
|
||||
err, author = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comment_author(s, comment_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if author is None:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
return (ErrorType.INVALID_INPUT, None) if author == user.user_id else (ErrorType.SUCCESS, author)
|
||||
return (ErrorType.INVALID_INPUT, None) if author.user_id == user.user_id else (ErrorType.SUCCESS, author.user_id)
|
||||
|
||||
async def report_comment(self, comment_id: int, user: User, reason: ReportReason) -> ErrorType:
|
||||
err, _ = await self._others_comment(comment_id, user)
|
||||
@@ -127,6 +168,9 @@ class ReactionService:
|
||||
err, author = await self._others_comment(comment_id, user)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
# 로그인 없이 쓴 댓글은 차단할 사람이 없어 신고만 받는다
|
||||
if author is None:
|
||||
return ErrorType.INVALID_INPUT
|
||||
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.block(s, user.user_id, author)])
|
||||
|
||||
async def unblock(self, user: User, blocked_id: uuid.UUID) -> ErrorType:
|
||||
|
||||
@@ -21,7 +21,7 @@ from services.feed_service import FeedService
|
||||
|
||||
_CODE = re.compile(r'<meta name="region-code" content="(\d+)"')
|
||||
_DESC = re.compile(r'(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"')
|
||||
_NAME = re.compile(r"<h1>(.+?) 오늘 날씨")
|
||||
_NAME = re.compile(r"<h1>(.+?) (?:오늘|내일) 날씨")
|
||||
_H1 = re.compile(r"(<main><h1>[^<]*</h1>)")
|
||||
|
||||
|
||||
@@ -61,15 +61,27 @@ def today_line(feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[da
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
|
||||
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
|
||||
line = today_line(feed, rows, sunset_at)
|
||||
def tomorrow_line(rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
|
||||
"""내일 페이지 한 줄: 내일 하루 예보와 해 지는 시각."""
|
||||
parts = [day_summary(rows)] if rows else []
|
||||
if parts and sunset_at:
|
||||
parts.append(f"해 지는 시각 {_clock(sunset_at)}.")
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def _put(template: str, line: str, extra: str = "") -> str:
|
||||
"""설명 메타와 본문 h1 바로 아래에 한 줄을 넣는다."""
|
||||
if not line:
|
||||
return template
|
||||
html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template)
|
||||
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{extra}", html, count=1)
|
||||
|
||||
|
||||
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
|
||||
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
|
||||
top = feed.bands.top5 if feed.bands else []
|
||||
ranks = f"<h2>오늘 {escape(name)} 각 순위</h2><ol>{''.join(f'<li>{escape(t.name)} {t.score}점</li>' for t in top)}</ol>" if top else ""
|
||||
html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template)
|
||||
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{ranks}", html, count=1)
|
||||
return _put(template, today_line(feed, rows, sunset_at), ranks)
|
||||
|
||||
|
||||
class SeoService:
|
||||
@@ -98,9 +110,12 @@ class SeoService:
|
||||
LOG.error(f"[seo] feed {code}: {err}")
|
||||
return ErrorType.SUCCESS, template
|
||||
_, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code))
|
||||
today = now_kst().date()
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at if region else None
|
||||
start = kst_midnight(today)
|
||||
ahead = path.startswith("tomorrow/")
|
||||
day = now_kst().date() + timedelta(days=1 if ahead else 0)
|
||||
sunset_at = sun_times(day, float(region.lat), float(region.lon)).sunset_at if region else None
|
||||
start = kst_midnight(day)
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, code, start, start + timedelta(days=1)))
|
||||
if ahead:
|
||||
return ErrorType.SUCCESS, _put(template, tomorrow_line(rows or [], sunset_at))
|
||||
name = _NAME.search(template)
|
||||
return ErrorType.SUCCESS, fill(template, feed, rows or [], name.group(1) if name else (feed.region_name or ""), sunset_at)
|
||||
@@ -0,0 +1,87 @@
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from azure.core.exceptions import AzureError
|
||||
from azure.storage.blob import BlobServiceClient, ContainerClient, ContentSettings
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
from config.settings import settings
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024 # 올릴 수 있는 원본 크기
|
||||
MAX_SIDE = 1080 # 긴 변을 이만큼으로 줄인다
|
||||
URL_PREFIX = "/v1/talk/image/"
|
||||
_NAME = re.compile(r"^[0-9a-f]{32}\.webp$")
|
||||
|
||||
|
||||
def folder() -> str:
|
||||
path = os.path.join(settings.upload_dir, "talk")
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _container() -> Optional[ContainerClient]:
|
||||
"""Azure Blob 컨테이너: 접속 문자열 또는 컨테이너 주소 + SAS 토큰. 둘 다 없으면 None (서버 폴더에 저장)"""
|
||||
if settings.azure_storage_connection_string and settings.azure_storage_container:
|
||||
return BlobServiceClient.from_connection_string(settings.azure_storage_connection_string).get_container_client(settings.azure_storage_container)
|
||||
if settings.azure_blob_base_url and settings.azure_blob_sas_token:
|
||||
return ContainerClient.from_container_url(f"{settings.azure_blob_base_url.rstrip('/')}?{settings.azure_blob_sas_token.lstrip('?')}")
|
||||
return None
|
||||
|
||||
|
||||
def _public(url: str) -> str:
|
||||
"""글에 붙일 주소: SAS 토큰(쓰기 권한)을 떼어 낸 공개 주소"""
|
||||
return url.split("?", 1)[0]
|
||||
|
||||
|
||||
def _blob_name(name: str) -> str:
|
||||
return f"{settings.azure_storage_prefix.strip('/')}/talk/{name}"
|
||||
|
||||
|
||||
def is_ours(url: str) -> bool:
|
||||
"""우리가 올린 사진 주소인지: 서버 폴더에 있거나, 우리 Blob 폴더의 우리가 만든 이름"""
|
||||
if file_of(url) is not None:
|
||||
return True
|
||||
c = _container()
|
||||
if c is None:
|
||||
return False
|
||||
base = f"{_public(c.url)}/{_blob_name('')}"
|
||||
return url.startswith(base) and bool(_NAME.match(url.removeprefix(base)))
|
||||
|
||||
|
||||
def file_of(url: str) -> Optional[str]:
|
||||
"""올린 사진 주소 → 저장된 파일 경로. 우리가 만든 이름이 아니거나 파일이 없으면 None."""
|
||||
name = url.removeprefix(URL_PREFIX)
|
||||
if not url.startswith(URL_PREFIX) or not _NAME.match(name):
|
||||
return None
|
||||
path = os.path.join(folder(), name)
|
||||
return path if os.path.isfile(path) else None
|
||||
|
||||
|
||||
def save(data: bytes) -> tuple[ErrorType, Optional[str]]:
|
||||
"""사진을 다시 그려 저장한다(Azure Blob, 설정이 없으면 서버 폴더). 다시 그리면 찍은 위치(GPS)·기기 같은 메타데이터가 모두 빠진다. 돌려준 값은 글에 붙일 주소."""
|
||||
if len(data) > MAX_BYTES:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as src:
|
||||
img = ImageOps.exif_transpose(src).convert("RGB")
|
||||
except (UnidentifiedImageError, OSError, Image.DecompressionBombError):
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
img.thumbnail((MAX_SIDE, MAX_SIDE))
|
||||
name = f"{uuid.uuid4().hex}.webp"
|
||||
c = _container()
|
||||
if c is None:
|
||||
img.save(os.path.join(folder(), name), "WEBP", quality=82)
|
||||
return ErrorType.SUCCESS, URL_PREFIX + name
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, "WEBP", quality=82)
|
||||
try:
|
||||
blob = c.upload_blob(_blob_name(name), buf.getvalue(), content_settings=ContentSettings(content_type="image/webp", cache_control="public, max-age=31536000, immutable"))
|
||||
except AzureError as e:
|
||||
LOG.error(f"[talk_image] blob upload: {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR, None
|
||||
return ErrorType.SUCCESS, _public(blob.url)
|
||||
@@ -0,0 +1,229 @@
|
||||
import math
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Talk, User, WeatherHourly
|
||||
from common.enums import ErrorType, RainType, Sky, TalkReport, TalkTopic
|
||||
from common.liker import Liker
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.talk_crud import TalkCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from services.talk_image import is_ours
|
||||
|
||||
BODY_MAX = 100
|
||||
DAILY_MAX = 5
|
||||
# 로그인한 서로 다른 사람의 신고가 이만큼 쌓이면 운영자 확인 전까지 숨긴다
|
||||
HIDE_AT = 3
|
||||
PAGE = 20
|
||||
# 보는 사람과 같은 시도에서 쓴 글은 이만큼 늦게 쓴 글처럼 앞에 둔다
|
||||
LOCAL_BOOST = timedelta(hours=12)
|
||||
# 피드 묶음: 최근 이 기간 글 중에서 고른다. 한 묶음 최대 장수, 이보다 적으면 주제 묶음은 숨긴다
|
||||
GROUP_WINDOW = timedelta(days=7)
|
||||
GROUP_POOL = 300
|
||||
GROUP_MAX = 10
|
||||
GROUP_MIN = 3
|
||||
# 묶음 순서는 '덜 지난 것처럼 쳐 주는 시간'으로 매긴다: 같은 구 6시간, 같은 시도 3시간, 좋아요는 2시간 × log2(1+좋아요)
|
||||
NEAR_GU_H, NEAR_SIDO_H, LIKE_H = 6, 3, 2
|
||||
|
||||
# 링크(http, www, 도메인 꼴)와 전화번호(010-1234-5678, 01012345678, 02-123-4567)
|
||||
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b", re.I)
|
||||
_PHONE = re.compile(r"0\d{1,2}[-.\s]?\d{3,4}[-.\s]?\d{4}")
|
||||
|
||||
_SKY = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
_RAIN = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
|
||||
|
||||
|
||||
def weather_line(row: Optional[WeatherHourly]) -> Optional[str]:
|
||||
"""글에 붙일 그때 날씨: 18° 맑음 / 12° 비."""
|
||||
if row is None:
|
||||
return None
|
||||
rain = RainType(row.rain_type)
|
||||
word = _RAIN.get(rain) or _SKY.get(Sky(row.sky), "")
|
||||
return f"{round(float(row.temp_c))}° {word}".strip()
|
||||
|
||||
|
||||
def spread_authors(views: list["TalkView"]) -> list["TalkView"]:
|
||||
"""같은 사람 글이 붙으면 뒤에서 다른 사람 글을 당겨 끼운다."""
|
||||
out = list(views)
|
||||
for i in range(1, len(out)):
|
||||
if out[i].author.user_id == out[i - 1].author.user_id:
|
||||
j = next((k for k in range(i + 1, len(out)) if out[k].author.user_id != out[i - 1].author.user_id), None)
|
||||
if j is not None:
|
||||
out.insert(i, out.pop(j))
|
||||
return out
|
||||
|
||||
|
||||
def group_age(t: Talk, region_code: Optional[str], now: datetime) -> float:
|
||||
"""묶음 안 정렬 값(작을수록 앞): 지난 시간에서 가까운 동네·좋아요만큼 뺀다. 오래된 글은 좋아요가 많아도 결국 뒤로 간다"""
|
||||
age = (now - t.created_at).total_seconds() / 3600
|
||||
near = NEAR_GU_H if region_code and t.region_code == region_code else NEAR_SIDO_H if region_code and t.region_code[:2] == region_code[:2] else 0
|
||||
return age - near - LIKE_H * math.log2(1 + t.like_count)
|
||||
|
||||
|
||||
def pick_group(views: list["TalkView"], region_code: Optional[str], now: datetime) -> list["TalkView"]:
|
||||
"""한 사람 한 장, 최대 GROUP_MAX 장. 첫 장은 신고 받은 적 없는 글"""
|
||||
out: list[TalkView] = []
|
||||
seen: set = set()
|
||||
for v in sorted(views, key=lambda v: group_age(v.talk, region_code, now)):
|
||||
if v.author.user_id in seen:
|
||||
continue
|
||||
seen.add(v.author.user_id)
|
||||
out.append(v)
|
||||
if len(out) == GROUP_MAX:
|
||||
break
|
||||
clean = next((i for i, v in enumerate(out) if v.talk.report_count == 0), None)
|
||||
if clean:
|
||||
out.insert(0, out.pop(clean))
|
||||
return out
|
||||
|
||||
|
||||
def parse_cursor(cursor: str) -> Optional[tuple[int, int]]:
|
||||
key, _, talk_id = cursor.partition("_")
|
||||
return (int(key), int(talk_id)) if key.lstrip("-").isdigit() and talk_id.isdigit() else None
|
||||
|
||||
|
||||
@dataclass
|
||||
class TalkView:
|
||||
talk: Talk
|
||||
author: User
|
||||
region_name: Optional[str]
|
||||
liked: bool
|
||||
mine: bool
|
||||
|
||||
|
||||
class TalkService:
|
||||
def __init__(self, crud: TalkCRUD = Depends(TalkCRUD), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)) -> None:
|
||||
self.crud, self.regions, self.weather = crud, regions, weather
|
||||
|
||||
async def groups(self, user: Optional[User], ip_hash: str, region_code: Optional[str]) -> tuple[ErrorType, dict[int, list[TalkView]]]:
|
||||
"""피드 묶음. 0은 '동네 사람들'(모든 주제), 나머지는 주제별(GROUP_MIN 장 이상일 때만)"""
|
||||
now = now_kst()
|
||||
viewer = user.user_id if user else None
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.recent(s, viewer, now - GROUP_WINDOW, GROUP_POOL))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, {}
|
||||
err, liked = await self._liked(user, ip_hash, [t.talk_id for t, *_ in rows])
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, {}
|
||||
views = [TalkView(talk=t, author=u, region_name=name, liked=t.talk_id in liked, mine=viewer == t.user_id) for t, u, name in rows]
|
||||
out = {0: pick_group(views, region_code, now)}
|
||||
for topic in TalkTopic:
|
||||
if topic is TalkTopic.LOCAL:
|
||||
continue
|
||||
group = pick_group([v for v in views if v.talk.topic == topic.value], region_code, now)
|
||||
if len(group) >= GROUP_MIN:
|
||||
out[topic.value] = group
|
||||
return ErrorType.SUCCESS, out
|
||||
|
||||
async def page(
|
||||
self, user: Optional[User], ip_hash: str, region_code: Optional[str], cursor: Optional[str], topic: Optional[int] = None
|
||||
) -> tuple[ErrorType, list[TalkView], Optional[str]]:
|
||||
"""한 페이지와 다음 페이지 cursor. 같은 사람 글은 페이지 안에서 떨어뜨린다."""
|
||||
after = parse_cursor(cursor) if cursor else None
|
||||
if cursor and after is None:
|
||||
return ErrorType.INVALID_INPUT, [], None
|
||||
viewer = user.user_id if user else None
|
||||
sido = region_code[:2] if region_code else None
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, sido, int(LOCAL_BOOST.total_seconds()), after, PAGE, topic))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, [], None
|
||||
err, liked = await self._liked(user, ip_hash, [t.talk_id for t, *_ in rows])
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, [], None
|
||||
views = [TalkView(talk=t, author=u, region_name=name, liked=t.talk_id in liked, mine=viewer == t.user_id) for t, u, name, _ in rows]
|
||||
last = rows[-1] if len(rows) == PAGE else None
|
||||
return ErrorType.SUCCESS, spread_authors(views), f"{last[3]}_{last[0].talk_id}" if last else None
|
||||
|
||||
async def mine(self, user: User, cursor: Optional[int]) -> tuple[ErrorType, list[TalkView], Optional[int]]:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.mine(s, user.user_id, cursor, PAGE))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, [], None
|
||||
err, liked = await self._liked(user, "", [t.talk_id for t, _ in rows])
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, [], None
|
||||
views = [TalkView(talk=t, author=user, region_name=name, liked=t.talk_id in liked, mine=True) for t, name in rows]
|
||||
return ErrorType.SUCCESS, views, rows[-1][0].talk_id if len(rows) == PAGE else None
|
||||
|
||||
async def _liked(self, user: Optional[User], ip_hash: str, ids: list[int]) -> tuple[ErrorType, set[int]]:
|
||||
if not ids:
|
||||
return ErrorType.SUCCESS, set()
|
||||
if user is not None:
|
||||
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked(s, user.user_id, ids))
|
||||
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked(s, ip_hash, ids))
|
||||
|
||||
async def _weather_now(self, region_code: str) -> Optional[str]:
|
||||
"""지금 시각에 가장 가까운 예보 한 칸. 못 읽으면 날씨 없이 쓴다."""
|
||||
now = now_kst()
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region_code, now - timedelta(hours=1), now + timedelta(hours=2)))
|
||||
if err is not ErrorType.SUCCESS or not rows:
|
||||
return None
|
||||
return weather_line(min(rows, key=lambda r: abs(r.forecast_at - now)))
|
||||
|
||||
async def add(
|
||||
self, user: User, region_code: str, body: str, image: Optional[str] = None, topic: TalkTopic = TalkTopic.LOCAL
|
||||
) -> tuple[ErrorType, Optional[TalkView]]:
|
||||
body = " ".join(body.split())
|
||||
if not body or len(body) > BODY_MAX:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
if image is not None and not is_ours(image):
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
if _LINK.search(body) or _PHONE.search(body):
|
||||
return ErrorType.LINK_NOT_ALLOWED, None
|
||||
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if region is None:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
today = kst_midnight(now_kst().date())
|
||||
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count_since(s, user.user_id, today))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if n >= DAILY_MAX:
|
||||
return ErrorType.DAILY_LIMIT, None
|
||||
weather = await self._weather_now(region_code)
|
||||
err, t = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, region_code, body, weather, image, topic.value))
|
||||
if err is not ErrorType.SUCCESS or t is None:
|
||||
return err, None
|
||||
return ErrorType.SUCCESS, TalkView(talk=t, author=user, region_name=region.short_name, liked=False, mine=True)
|
||||
|
||||
async def delete(self, user: User, talk_id: int) -> ErrorType:
|
||||
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, talk_id, user.user_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
|
||||
|
||||
async def _talk(self, talk_id: int) -> tuple[ErrorType, Optional[Talk]]:
|
||||
err, t = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, talk_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return (ErrorType.SUCCESS, t) if t is not None else (ErrorType.NOT_FOUND, None)
|
||||
|
||||
async def like(self, who: Liker, talk_id: int, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
err, _ = await self._talk(talk_id)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_like(s, talk_id, who, on))
|
||||
|
||||
async def report(self, user: User, talk_id: int, reason: TalkReport) -> ErrorType:
|
||||
err, t = await self._talk(talk_id)
|
||||
if err is not ErrorType.SUCCESS or t is None:
|
||||
return err
|
||||
if t.user_id == user.user_id:
|
||||
return ErrorType.INVALID_INPUT
|
||||
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.report(s, talk_id, user.user_id, reason.value, HIDE_AT))
|
||||
return err
|
||||
|
||||
async def block_author(self, user: User, talk_id: int) -> ErrorType:
|
||||
err, t = await self._talk(talk_id)
|
||||
if err is not ErrorType.SUCCESS or t is None:
|
||||
return err
|
||||
if t.user_id == user.user_id:
|
||||
return ErrorType.INVALID_INPUT
|
||||
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.block(s, user.user_id, t.user_id))
|
||||
return err
|
||||
@@ -22,7 +22,7 @@ from crud.index_crud import IndexCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.calc.index_calc import priority_score, rank_score
|
||||
from services.external.culture_api import IMAGE_CREDIT as CULTURE_CREDIT
|
||||
from services.external.culture_api import SOURCE_PREFIX as CULTURE_PREFIX
|
||||
from services.external.culture_api import CONCERT, EXHIBITION, fetch_exhibitions, parse_exhibitions
|
||||
@@ -291,14 +291,14 @@ class WeekService:
|
||||
for d in daily:
|
||||
rows = [r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d.forecast_date]
|
||||
rain_hours = _rain_hours(rows)
|
||||
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: rank_score(x.score, priority.get(x.index_id, 2)), reverse=True)[:2]
|
||||
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: rank_score(priority_score(x.score, priority.get(x.index_id, 2)), priority.get(x.index_id, 2)), reverse=True)[:2]
|
||||
holiday = (holidays or {}).get(d.forecast_date)
|
||||
weekday = _WEEKDAY_KO[d.forecast_date.weekday()]
|
||||
word = _weather_word(d, rain_hours)
|
||||
temps = f" {round(float(d.temp_min_c))}~{round(float(d.temp_max_c))}°" if d.temp_min_c is not None and d.temp_max_c is not None else ""
|
||||
is_rainy = d.rain_type != RainType.NONE.value
|
||||
if top:
|
||||
summary = ", ".join(f"{names.get(x.index_id, '')} {x.score}점" for x in top)
|
||||
summary = ", ".join(f"{names.get(x.index_id, '')} {priority_score(x.score, priority.get(x.index_id, 2))}점" for x in top)
|
||||
pick = "비 오는 날, 실내 일정이 좋아요" if is_rainy else f"{names.get(top[0].index_id, '')} 추천"
|
||||
else:
|
||||
summary, pick = f"비 확률 {d.rain_prob}%", ("실내 일정이 좋아요" if is_rainy else "바깥 일정 잡기 좋아요")
|
||||
|
||||
@@ -22,7 +22,7 @@ from crud.region_crud import RegionCRUD
|
||||
from crud.sky_crud import SkyCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.calc.index_calc import OUTING_HOURS, outing, outing_estimate
|
||||
from services.calc.index_calc import OUTING_HOURS, Outing, outing, outing_estimate
|
||||
from services.index_service import day_forecast, windows_for
|
||||
from services.weather_service import WeatherService
|
||||
from services.week_service import _icon
|
||||
@@ -30,14 +30,29 @@ from services.week_service import _icon
|
||||
# 주말 전국 날씨 순위·당일치기 추천. 대표 지역(노을 순위 30곳)과 당일치기 후보 도시의 토·일 나들이 점수를
|
||||
# 워커가 하루 두 번(06:40·18:40) 미리 계산해 Redis 에 둔다. 없으면 순위 API 가 그 자리에서 계산한다.
|
||||
_SEED = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "trip_city.csv")
|
||||
_KEY = "weekend_rank:{:%Y%m%d}"
|
||||
_KEY = "weekend_rank:v2:{:%Y%m%d}" # v2: 점수를 바꾸기 표로 보정한 값 (옛 점수 캐시를 쓰지 않게 키를 바꿨다)
|
||||
_TTL = 13 * 3600
|
||||
_PARALLEL = 4 # 기상청 동시 호출 수
|
||||
_WAIT_STEPS, _WAIT_SEC = 60, 0.5
|
||||
_WINDOW = SimpleNamespace(windows=[{"from": OUTING_HOURS[0], "to": OUTING_HOURS[1]}])
|
||||
# 나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수(평균 60, 90점 이상은 드물게). scripts/gen_outing_score_table.py 가 만든다
|
||||
OUTING_SCORE_TABLE: list[int] = json.loads(
|
||||
open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "calc", "outing_score_table.json"), encoding="utf-8").read()
|
||||
)["table"]
|
||||
|
||||
|
||||
def calibrated_outing(score: int) -> int:
|
||||
return OUTING_SCORE_TABLE[score]
|
||||
|
||||
|
||||
def outing_day_score(result: Outing) -> int:
|
||||
"""순위·당일치기에 쓰는 하루 나들이 점수. 시간별 예보로 낸 점수와 중기예보 예상 점수 모두 같은 표를 거친다."""
|
||||
return calibrated_outing(result.score)
|
||||
|
||||
|
||||
# 당일치기: 내 지역에서 직선 이 거리 안의 후보 도시만 (1~2시간 거리), 너무 가까운 곳(같은 동네)은 뺀다.
|
||||
TRIP_MIN_KM, TRIP_MAX_KM = 20, 200
|
||||
TRIP_MIN_SCORE = 50
|
||||
TRIP_MIN_SCORE = calibrated_outing(50) # 원래 점수 50점과 같은 날씨 수준
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -205,7 +220,7 @@ class WeekendRank:
|
||||
if result is None or row is None:
|
||||
continue
|
||||
out.append(DayScore(
|
||||
region_code=region.code, day=d, score=result.score, reason=result.reason, icon=_icon(Sky(row.sky), RainType(row.rain_type)),
|
||||
region_code=region.code, day=d, score=outing_day_score(result), reason=result.reason, icon=_icon(Sky(row.sky), RainType(row.rain_type)),
|
||||
temp_min_c=float(row.temp_min_c) if row.temp_min_c is not None else None,
|
||||
temp_max_c=float(row.temp_max_c) if row.temp_max_c is not None else None,
|
||||
rain_prob=row.rain_prob, estimated=result.estimated,
|
||||
|
||||
@@ -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_save", "comment", "comment_like", "comment_report", "user_block", "holiday", "solar_term", "users",
|
||||
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "comment_report", "user_block", "holiday", "solar_term", "users", "card_set", "card_image", "reel",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from router.router import app
|
||||
|
||||
REGION = "1144000000"
|
||||
IP_A = {"X-Forwarded-For": "203.0.113.10"}
|
||||
IP_B = {"X-Forwarded-For": "203.0.113.20"}
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||
h = {"Authorization": f"Bearer {body['access_token']}"}
|
||||
await c.post("/v1/auth/terms", headers=h) # 로그인한 사람은 약관에 동의해야 댓글을 쓴다
|
||||
return h
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_post_like_counts_once_per_ip(offline):
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
url = f"/v1/reaction/post/{post_id}/like"
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_B)).json()["like_count"] == 2
|
||||
h = await _login(c, "anon_like_01")
|
||||
assert (await c.post(url, headers={**h, **IP_A})).json()["like_count"] == 3
|
||||
|
||||
feed_a = (await c.get("/v1/feed", params={"region": REGION}, headers=IP_A)).json()
|
||||
p = next(x for x in feed_a["posts"] if x["post_id"] == post_id)
|
||||
assert p["liked"] is True and p["like_count"] == 3 and "saved" not in p
|
||||
other = (await c.get("/v1/feed", params={"region": REGION}, headers={"X-Forwarded-For": "203.0.113.30"})).json()
|
||||
assert next(x for x in other["posts"] if x["post_id"] == post_id)["liked"] is False
|
||||
|
||||
assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2
|
||||
assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_only_last_forwarded_ip_counts(offline):
|
||||
"""클라이언트가 X-Forwarded-For 앞쪽을 바꿔도 nginx 가 붙인 마지막 주소가 같으면 같은 사람이다."""
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
url = f"/v1/reaction/post/{post_id}/like"
|
||||
assert (await c.post(url, headers={"X-Forwarded-For": "1.1.1.1, 203.0.113.10"})).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers={"X-Forwarded-For": "2.2.2.2, 203.0.113.10"})).json()["like_count"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_comment_like(offline):
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
h = await _login(c, "anon_like_02")
|
||||
comment_id = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": "맑아요"})).json()["comment"]["comment_id"]
|
||||
url = f"/v1/reaction/comment/{comment_id}/like"
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_B)).json()["like_count"] == 2
|
||||
assert (await c.post(url, headers=h)).json()["like_count"] == 3
|
||||
|
||||
listed = (await c.get(f"/v1/reaction/post/{post_id}/comment/list", headers=IP_A)).json()["comments"]
|
||||
assert listed[0]["liked"] is True
|
||||
listed = (await c.get(f"/v1/reaction/post/{post_id}/comment/list", headers={"X-Forwarded-For": "203.0.113.30"})).json()["comments"]
|
||||
assert listed[0]["liked"] is False
|
||||
|
||||
assert (await c.delete(url, headers=IP_B)).json()["like_count"] == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_talk_like():
|
||||
async with client() as c:
|
||||
h = await _login(c, "anon_like_03")
|
||||
talk_id = (await c.post("/v1/talk", json={"region_code": REGION, "body": "바람 불어요"}, headers=h)).json()["talk"]["talk_id"]
|
||||
url = f"/v1/talk/{talk_id}/like"
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_B)).json()["like_count"] == 2
|
||||
assert (await c.post(url, headers=h)).json()["like_count"] == 3
|
||||
|
||||
talks = (await c.get("/v1/talk/list", headers=IP_A)).json()["talks"]
|
||||
assert next(x for x in talks if x["talk_id"] == talk_id)["liked"] is True
|
||||
talks = (await c.get("/v1/talk/list", headers={"X-Forwarded-For": "203.0.113.30"})).json()["talks"]
|
||||
assert next(x for x in talks if x["talk_id"] == talk_id)["liked"] is False
|
||||
|
||||
assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_comment_shows_region_and_only_same_ip_deletes(offline):
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
url = f"/v1/reaction/post/{post_id}/comment"
|
||||
made = (await c.post(url, headers=IP_A, json={"body": " 우산 챙겨요 ", "region": REGION})).json()["comment"]
|
||||
assert made["body"] == "우산 챙겨요" and made["nickname"] == "마포구 익명" and made["mine"] is True
|
||||
assert (await c.post(url, headers=IP_A, json={"body": "www.example.com 보세요"})).json()["result"]["desc"] == "LINK_NOT_ALLOWED"
|
||||
no_region = (await c.post(url, headers=IP_A, json={"body": "안녕"})).json()["comment"]
|
||||
assert no_region["nickname"] == "익명"
|
||||
|
||||
listed = (await c.get(f"{url}/list", headers=IP_B)).json()["comments"]
|
||||
assert [(x["nickname"], x["mine"]) for x in listed] == [("마포구 익명", False), ("익명", False)]
|
||||
assert next(x for x in (await c.get(f"{url}/list", headers=IP_A)).json()["comments"] if x["comment_id"] == made["comment_id"])["mine"] is True
|
||||
|
||||
h = await _login(c, "anon_cmt_01")
|
||||
delete = f"/v1/reaction/comment/{made['comment_id']}"
|
||||
assert (await c.delete(delete, headers=IP_B)).json()["result"]["desc"] == "NOT_FOUND"
|
||||
assert (await c.delete(delete, headers={**h, **IP_A})).json()["result"]["desc"] == "NOT_FOUND"
|
||||
assert (await c.delete(delete, headers=IP_A)).json()["result"]["success"] is True
|
||||
feed = (await c.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert next(x for x in feed["posts"] if x["post_id"] == post_id)["comment_count"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_comment_daily_limit_per_ip(offline):
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
url = f"/v1/reaction/post/{post_id}/comment"
|
||||
ip = {"X-Forwarded-For": "203.0.113.40"}
|
||||
for i in range(20):
|
||||
assert (await c.post(url, headers=ip, json={"body": f"댓글{i}"})).json()["result"]["success"] is True
|
||||
assert (await c.post(url, headers=ip, json={"body": "하나 더"})).json()["result"]["desc"] == "DAILY_LIMIT"
|
||||
assert (await c.post(url, headers=IP_B, json={"body": "다른 사람"})).json()["result"]["success"] is True
|
||||
h = await _login(c, "anon_cmt_02")
|
||||
assert (await c.post(url, headers={**h, **ip}, json={"body": "로그인하면 따로"})).json()["result"]["success"] is True
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_hero_and_today_gak_take_likes_and_comments(offline):
|
||||
async with client() as c:
|
||||
feed = (await c.get("/v1/feed", params={"region": REGION})).json()
|
||||
hero, gak = feed["hero_post"]["post_id"], feed["gak_post"]["post_id"]
|
||||
assert hero != gak and {hero, gak}.isdisjoint(p["post_id"] for p in feed["posts"])
|
||||
assert (await c.post(f"/v1/reaction/post/{hero}/like", headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(f"/v1/reaction/post/{gak}/comment", headers=IP_A, json={"body": "좋다"})).json()["result"]["success"] is True
|
||||
|
||||
mine = (await c.get("/v1/feed", params={"region": REGION}, headers=IP_A)).json()
|
||||
assert mine["hero_post"] == {"post_id": hero, "like_count": 1, "comment_count": 0, "liked": True}
|
||||
assert mine["gak_post"] == {"post_id": gak, "like_count": 0, "comment_count": 1, "liked": False}
|
||||
assert (await c.get("/v1/feed", params={"region": REGION}, headers=IP_B)).json()["hero_post"]["liked"] is False
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_hero_tomorrow_and_tomorrow_slots(offline):
|
||||
async with client() as c:
|
||||
hero = (await c.get("/v1/feed", params={"region": REGION})).json()["hero"]
|
||||
assert set(hero["tomorrow"]["weather_slots"]) <= {"morning", "day", "evening", "night"}
|
||||
res = (await c.get("/v1/weather/today", params={"region": REGION, "day": "tomorrow"})).json()
|
||||
assert res["day"] == hero["tomorrow"]["day"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_comment_can_be_reported_not_blocked(offline):
|
||||
"""로그인 없이 쓴 댓글도 신고는 되고(신고한 사람에겐 숨김), 차단할 사람이 없어 차단은 안 된다. 다른 사람을 차단해도 익명 댓글은 그대로 보인다."""
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
url = f"/v1/reaction/post/{post_id}/comment"
|
||||
listing = f"{url}/list"
|
||||
anon_id = (await c.post(url, headers=IP_A, json={"body": "익명 댓글"})).json()["comment"]["comment_id"]
|
||||
writer = await _login(c, "anon_mod_01")
|
||||
writer_id = (await c.post(url, headers=writer, json={"body": "회원 댓글"})).json()["comment"]["comment_id"]
|
||||
viewer = await _login(c, "anon_mod_02")
|
||||
|
||||
blocked = (await c.post(f"/v1/reaction/comment/{writer_id}/block", headers=viewer)).json()
|
||||
assert blocked["result"]["success"] is True
|
||||
ids = [x["comment_id"] for x in (await c.get(listing, headers=viewer)).json()["comments"]]
|
||||
assert anon_id in ids and writer_id not in ids
|
||||
|
||||
assert (await c.post(f"/v1/reaction/comment/{anon_id}/block", headers=viewer)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.post(f"/v1/reaction/comment/{anon_id}/report", headers=viewer, json={"reason": 1})).json()["result"]["success"] is True
|
||||
assert anon_id not in [x["comment_id"] for x in (await c.get(listing, headers=viewer)).json()["comments"]]
|
||||
assert anon_id in [x["comment_id"] for x in (await c.get(listing, headers=IP_B)).json()["comments"]]
|
||||
@@ -54,11 +54,12 @@ async def test_signup_rejects_bad_input():
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_reactions_require_login_and_update_feed(offline):
|
||||
async def test_comment_without_login_is_anonymous_and_reactions_update_feed(offline):
|
||||
async with client() as c:
|
||||
feed = (await c.get("/v1/feed", params={"region": REGION})).json()
|
||||
post_id = feed["posts"][0]["post_id"]
|
||||
assert (await c.post(f"/v1/reaction/post/{post_id}/like")).status_code == 401
|
||||
anon = (await c.post(f"/v1/reaction/post/{feed['posts'][1]['post_id']}/comment", json={"body": "안녕"})).json()
|
||||
assert anon["result"]["success"] is True and anon["comment"]["nickname"] == "익명"
|
||||
|
||||
token = (await _signup(c))["access_token"]
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from common.enums import CardStatus, PostType
|
||||
from config.settings import settings
|
||||
from router.router import app
|
||||
|
||||
SEOUL, BUSAN = "1111000000", "2611000000"
|
||||
KEY = "test-admin-key"
|
||||
# 가장 작은 JPEG 머리 (서버는 JPEG 시작 바이트만 본다)
|
||||
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 {"template": "tarot", "topic": "연애 썸", "title": "오늘의 썸 타로", "caption": "한 장 골라 보세요", "texts": {"n1": "컵 2"}, "images": [JPEG, JPEG, JPEG], **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_admin_api_needs_key(monkeypatch):
|
||||
async with client() as c:
|
||||
monkeypatch.setattr(settings, "admin_api_key", "")
|
||||
assert (await c.post("/v1/card", json=body(), headers={"X-Admin-Key": ""})).status_code == 401
|
||||
monkeypatch.setattr(settings, "admin_api_key", KEY)
|
||||
assert (await c.post("/v1/card", json=body())).status_code == 401
|
||||
assert (await c.post("/v1/card", json=body(), headers={"X-Admin-Key": "wrong"})).status_code == 401
|
||||
assert (await c.post("/v1/card/1/publish", headers={"X-Admin-Key": "wrong"})).status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rejects_non_jpeg(admin_key):
|
||||
async with client() as c:
|
||||
res = await c.post("/v1/card", json=body(images=[base64.b64encode(b"not a jpeg").decode()]), headers=admin_key)
|
||||
assert res.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_waiting_card_not_in_feed_until_published(offline, admin_key):
|
||||
async with client() as c:
|
||||
made = (await c.post("/v1/card", json=body(), headers=admin_key)).json()
|
||||
assert made["status"] == CardStatus.WAITING.value and len(made["image_urls"]) == 3
|
||||
feed = (await c.get("/v1/feed", params={"region": SEOUL})).json()
|
||||
assert not [p for p in feed["posts"] if p["post_type"] == PostType.CARD.value]
|
||||
|
||||
published = (await c.post(f"/v1/card/{made['card_id']}/publish", headers=admin_key)).json()
|
||||
assert published["status"] == CardStatus.PUBLISHED.value and published["post_id"]
|
||||
# 게시하면 피드 캐시를 지워 바로 보인다. 전국 카드라 다른 시도에서도 같은 포스트
|
||||
seoul, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL, BUSAN)]
|
||||
image = await c.get(made["image_urls"][0])
|
||||
for feed in (seoul, busan):
|
||||
card = next(p for p in feed["posts"] if p["post_type"] == PostType.CARD.value)
|
||||
assert card["post_id"] == published["post_id"] and card["title"] == "오늘의 썸 타로"
|
||||
assert [s["kind"] for s in card["slides"]] == ["image"] * 3 and card["slides"][0]["url"] == made["image_urls"][0]
|
||||
# 날씨 바로 아래
|
||||
types = [p["post_type"] for p in seoul["posts"]]
|
||||
assert types.index(PostType.CARD.value) <= 2
|
||||
assert image.status_code == 200 and image.headers["content-type"] == "image/jpeg" and image.content.startswith(b"\xff\xd8")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_publish_twice_keeps_one_post_and_reject(offline, admin_key):
|
||||
async with client() as c:
|
||||
made = (await c.post("/v1/card", json=body(publish=True), headers=admin_key)).json()
|
||||
again = (await c.post(f"/v1/card/{made['card_id']}/publish", headers=admin_key)).json()
|
||||
assert made["status"] == CardStatus.PUBLISHED.value and again["post_id"] == made["post_id"]
|
||||
second = (await c.post("/v1/card", json=body(title="두 번째"), headers=admin_key)).json()
|
||||
rejected = (await c.post(f"/v1/card/{second['card_id']}/reject", headers=admin_key)).json()
|
||||
assert rejected["status"] == CardStatus.REJECTED.value
|
||||
missing = await c.get("/v1/card/999999/1.jpg")
|
||||
assert missing.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_cards_newest_first_with_image_urls(offline, admin_key):
|
||||
async with client() as c:
|
||||
a = (await c.post("/v1/card", json=body(title="첫 카드"), headers=admin_key)).json()
|
||||
b = (await c.post("/v1/card", json=body(title="둘째 카드", publish=True), headers=admin_key)).json()
|
||||
assert (await c.get("/v1/card")).status_code == 401
|
||||
res = (await c.get("/v1/card", headers=admin_key)).json()
|
||||
ids = [x["card_id"] for x in res["items"]]
|
||||
assert ids[:2] == [b["card_id"], a["card_id"]]
|
||||
first = res["items"][0]
|
||||
assert first["title"] == "둘째 카드" and first["status"] == CardStatus.PUBLISHED.value and first["post_id"] and len(first["image_urls"]) == 3
|
||||
assert res["items"][1]["status"] == CardStatus.WAITING.value and res["items"][1].get("published_at") is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_instagram_publish_carousel_and_store_media_id(offline, 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")
|
||||
calls: list[tuple[str, dict]] = []
|
||||
|
||||
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"):
|
||||
if data.get("media_type") == "CAROUSEL":
|
||||
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]])}"})
|
||||
if request.url.path.endswith("/car"):
|
||||
return httpx.Response(200, json={"status_code": "FINISHED"})
|
||||
if request.url.path.endswith("/media_publish"):
|
||||
assert data["creation_id"] == "car"
|
||||
return httpx.Response(200, json={"id": "media99"})
|
||||
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/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]
|
||||
assert res["result"]["success"] and res["ig_media_id"] == "media99"
|
||||
assert again["ig_media_id"] == "media99" and len([p for p, _ in calls if p.endswith("/media_publish")]) == 1
|
||||
assert listed["ig_media_id"] == "media99"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_instagram_requires_token(offline, admin_key, monkeypatch):
|
||||
monkeypatch.setattr(settings, "instagram_access_token", "")
|
||||
async with client() as c:
|
||||
made = (await c.post("/v1/card", json=body(), headers=admin_key)).json()
|
||||
res = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json()
|
||||
assert res["result"]["success"] is False and "INSTAGRAM" in res["msg"]
|
||||
@@ -48,11 +48,10 @@ def test_current_slot_before_5_is_previous_night():
|
||||
assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening"
|
||||
|
||||
|
||||
def test_gak_hidden_in_slots_outside_its_window():
|
||||
def test_gak_scores_every_slot_and_time_match_is_binary():
|
||||
parts = slot_results(_defn([{"from": 17, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert set(parts) == {"evening", "night"}
|
||||
# 18시 한 시간만 저녁 구간(16~18시)과 겹치면 저녁 점수는 내지 않는다
|
||||
assert set(slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)) == {"night"}
|
||||
assert set(parts) == {"morning", "day", "evening", "night", EARLY}
|
||||
assert {k: r.factors["time"] for k, r in parts.items()} == {"morning": 0, "day": 0, "evening": 100, "night": 100, EARLY: 0}
|
||||
|
||||
|
||||
def test_rain_in_evening_lowers_only_later_slots():
|
||||
@@ -102,12 +101,25 @@ def test_ultra_rain_lowers_slot_score():
|
||||
assert wet < dry
|
||||
|
||||
|
||||
def test_slot_needs_two_overlapping_hours():
|
||||
"""10~17시 각은 아침 구간(5~11시)과 10시 한 시간만 겹쳐서 아침 점수를 내지 않는다. 한 시간짜리 각은 한 시간이면 된다."""
|
||||
def test_time_match_includes_one_overlapping_hour():
|
||||
by_at = _rows()
|
||||
assert "morning" not in slot_results(_defn([{"from": 10, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
assert "morning" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
assert "morning" in slot_results(_defn([{"from": 10, "to": 11}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
for start, end in ((10, 17), (9, 17), (10, 11)):
|
||||
assert slot_results(_defn([{"from": start, "to": end}]), DAY, REGION, by_at, {}, CTX, SUNSET)["morning"].factors["time"] == 100
|
||||
|
||||
|
||||
def test_outside_window_uses_current_weather_instead_of_daily_weather():
|
||||
parts = slot_results(_defn([{"from": 7, "to": 11}]), DAY, REGION, _rows(rain_from=16), {}, CTX, SUNSET)
|
||||
assert parts["morning"].score == 100
|
||||
assert parts["night"].score < parts["morning"].score
|
||||
assert parts["night"].factors["rain"] == 0 and parts["night"].factors["time"] == 0
|
||||
|
||||
|
||||
def test_early_hours_match_windows_crossing_midnight():
|
||||
parts = slot_results(_defn([{"from": 21, "to": 26}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert parts[EARLY].factors["time"] == 100
|
||||
now = datetime(2026, 10, 8, 2, 0, tzinfo=KST)
|
||||
parts = slot_results(_defn([{"from": 21, "to": 26}]), DAY, REGION, _rows(), {}, CTX, SUNSET, now)
|
||||
assert parts[EARLY].factors["time"] == 0
|
||||
|
||||
|
||||
def test_current_slot_skips_passed_hours():
|
||||
|
||||
@@ -8,10 +8,12 @@ from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.index_crud import IndexCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from router.router import app
|
||||
from services.feed_service import build_feed_day
|
||||
from services.index_service import in_season
|
||||
from services.week_service import collect_events
|
||||
|
||||
REGION = "1114000000"
|
||||
@@ -61,7 +63,10 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"]
|
||||
assert len(body["stories"]) == 40
|
||||
_, definitions = await DB_SESSION_MNG.execute_lambda(lambda s: IndexCRUD().definitions(s))
|
||||
expected = {d.code for d in definitions if in_season(d, now_kst().month)}
|
||||
assert {g["code"] for g in body["stories"]} == expected
|
||||
assert all(g["active"] for g in body["stories"])
|
||||
assert body["hero"]["weather_score"] == body["hero"]["weather_slots"][body["slot"]]
|
||||
assert all(g["slots"][body["slot"]] == g["score"] and g["slot_ranks"][body["slot"]] == g["rank"] for g in body["stories"] if g["active"])
|
||||
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
@@ -151,6 +156,27 @@ def test_arrange_orders_by_slot_and_keeps_same_types_apart():
|
||||
assert night[:3] == [PostType.ALERT, PostType.WEATHER, PostType.TOMORROW] and night[-1] is PostType.QUOTE
|
||||
|
||||
|
||||
def test_arrange_puts_shareable_cards_before_plain_info():
|
||||
"""주말·노을·행사는 앞쪽 절반, 공기·자외선·상식은 각 뒤로."""
|
||||
from datetime import datetime
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from services.feed_service import arrange
|
||||
|
||||
sunset = datetime(2026, 10, 1, 18, 10, tzinfo=KST)
|
||||
cards = [_card(t, n) for n, t in enumerate([
|
||||
PostType.WEATHER, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.TOMORROW, PostType.WEEK,
|
||||
PostType.EVENT, PostType.EVENT, PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.WEEKEND_PLAN, PostType.AIR, PostType.UV, PostType.MOON,
|
||||
])]
|
||||
for slot, h in (("morning", 8), ("day", 13), ("evening", 17), ("evening", 19), ("night", 22)):
|
||||
out = [c.post_type for c in arrange(cards, slot, datetime(2026, 10, 1, h, tzinfo=KST), sunset, False, "2026-10-01:1114000000")]
|
||||
half = len(out) // 2
|
||||
assert PostType.SUNSET in out[:half] and PostType.WEEK in out[:half], (slot, out)
|
||||
assert all(i < half + 2 for i, t in enumerate(out) if t is PostType.EVENT), (slot, out)
|
||||
first_gak = out.index(PostType.GAK)
|
||||
assert all(out.index(t) > first_gak for t in (PostType.AIR, PostType.TIP) if t in out), (slot, out)
|
||||
|
||||
|
||||
def test_arrange_scatters_up_to_three_events_same_spot_all_day():
|
||||
from datetime import datetime
|
||||
|
||||
@@ -362,14 +388,14 @@ async def test_feed_has_day_trip_card_with_city_event(offline, monkeypatch):
|
||||
assert event["line"] == "강릉 커피축제" and event["image"] == "https://tong.visitkorea.or.kr/c.jpg"
|
||||
|
||||
|
||||
def test_gak_caption_starts_with_score_band_sentence():
|
||||
def test_gak_band_sentence_moves_to_slide_and_caption_keeps_hours():
|
||||
"""점수 구간 설명 문장은 슬라이드(say)에 두고, 글 설명엔 내일 점수나 하기 좋은 때만."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.feed_service import _gak_caption
|
||||
from services.feed_service import _band_sentence, _gak_caption
|
||||
d = SimpleNamespace(sentences={"0": "쉬어요", "30": "애매", "60": "괜찮아요", "80": "딱 좋아요!"}, windows=[{"from": 18, "to": 24}])
|
||||
item = SimpleNamespace(definition=d, score=SimpleNamespace(score=83, score_date=date(2026, 10, 7)), trend=[], rank=1)
|
||||
assert _gak_caption(item) == "딱 좋아요! 하기 좋은 때는 18~24시예요."
|
||||
item.definition.sentences = {}
|
||||
assert _band_sentence(d.sentences, 83) == "딱 좋아요!"
|
||||
assert _gak_caption(item) == "하기 좋은 때는 18~24시예요."
|
||||
|
||||
|
||||
@@ -389,3 +415,19 @@ def test_uv_post_only_when_moderate_or_higher():
|
||||
assert FeedService._uv_post(None, base, ctx([(12, 2.0), (15, 3.4)])).slides[0].line == "오늘 자외선 지수 보통\n오후 3시 무렵 나가면 선크림·모자 챙겨요"
|
||||
assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None
|
||||
assert FeedService._uv_post(None, base, ctx([])) is None
|
||||
|
||||
|
||||
def test_gak_rows_shows_heaviest_conditions_with_short_values():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.feed_service import gak_rows
|
||||
|
||||
d = SimpleNamespace(weight_temp=30, weight_rain=25, weight_wind=10, weight_humidity=0, weight_air=15, weight_uv=0, weight_sun=0, weight_view=0, weight_time=20)
|
||||
notes = {"temp": "체감 18°, 편한 범위 15~25° 안", "rain": "비 확률 20%", "wind": "바람 초속 3.1m", "air": "초미세먼지 16㎍/㎥, 좋음", "time": "수요일"}
|
||||
item = SimpleNamespace(definition=d, score=SimpleNamespace(notes=notes))
|
||||
assert [(r.label, r.value) for r in gak_rows(item, 3)] == [("기온", "체감 18°"), ("비", "확률 20%"), ("미세먼지", "좋음")]
|
||||
# 점수에 안 쓰는 조건은 뒤에 지금 날씨로 채운다
|
||||
d.weight_wind = 0
|
||||
assert [r.label for r in gak_rows(item)] == ["기온", "비", "미세먼지", "바람"]
|
||||
item.score.notes = {**notes, "rain": "비 소식, 내일까지 비 확률 70%"}
|
||||
assert gak_rows(item)[1].value == "확률 70%"
|
||||
@@ -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
|
||||
@@ -60,10 +60,9 @@ def test_status_line_has_four_by_day_and_warns_only_caution():
|
||||
assert _status(x) == [("습도", "습함", "normal"), ("불쾌지수", "쾌적", "normal"), ("자외선", "높음", "warn"), ("미세먼지", "나쁨", "warn")]
|
||||
|
||||
|
||||
def test_status_line_shows_discomfort_only_june_to_september():
|
||||
"""불쾌지수는 더위 지표라 10월 비 오는 날에도 '쾌적'이 나온다. 기상청처럼 6~9월에만."""
|
||||
def test_status_line_shows_discomfort_all_year():
|
||||
x = HeroInput(now=NOW, night=False, humidity=95, discomfort=66, uv=1.0, air=AirGrade.GOOD)
|
||||
assert [s.label for s in hero_status(x)] == ["습도", "자외선", "미세먼지"]
|
||||
assert [s.label for s in hero_status(x)] == ["습도", "불쾌지수", "자외선", "미세먼지"]
|
||||
|
||||
|
||||
def test_status_line_drops_uv_at_night_and_missing_values():
|
||||
|
||||
@@ -8,15 +8,18 @@ import services.air_service as air_service
|
||||
import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import OpenMeteoHourly, WeatherHourly
|
||||
from common.database.model.models import IndexScore, OpenMeteoHourly, WeatherHourly
|
||||
from common.enums import ErrorType
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.calc.index_calc import AXES, Result, rank_score
|
||||
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, season_of, slot_days, slot_label, windows_for
|
||||
|
||||
_RESULT_50 = Result(score=50, factors={a: 50 for a in AXES}, notes={}, zero_reason=None, summary="")
|
||||
_WEATHER_50 = {k: _RESULT_50 for k in ("morning", "day", "evening", "night", "early")}
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
|
||||
@@ -24,6 +27,14 @@ async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
def _board_score(index_id, day, score, slot_score=None):
|
||||
value = score if slot_score is None else slot_score
|
||||
return IndexScore(index_id=index_id, score_date=day, score=score, slots={
|
||||
k: {"score": value, "summary": "", "factors": {}, "zero_reason": None, "notes": {}}
|
||||
for k in ("morning", "day", "evening", "night", "early")
|
||||
})
|
||||
|
||||
|
||||
def _vilage(*_):
|
||||
start = kst_midnight(now_kst().date())
|
||||
items = []
|
||||
@@ -61,14 +72,17 @@ async def test_index_list_ranks_every_gak_with_today_tomorrow_weekend_trend(fake
|
||||
assert body["result"]["success"] is True
|
||||
assert len(body["items"]) == len(_seed()) and len(body["top3"]) == 3
|
||||
priority = {d["code"]: d["priority"] for d in _seed()}
|
||||
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤, 제철 아닌 각은 맨 끝. 앞 두 묶음 안에서는 점수 × 중요도 순
|
||||
# 시간대와 관계없이 제철인 각은 모두 활성화하고, 제철 아닌 각은 맨 끝.
|
||||
assert all(i["active"] for i in body["items"] if i["in_season"])
|
||||
actives = [i["active"] for i in body["items"]]
|
||||
assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"])
|
||||
seasons = [i["in_season"] for i in body["items"]]
|
||||
assert seasons == sorted(seasons, reverse=True) and all(i["active"] is False for i in body["items"] if not i["in_season"])
|
||||
for group in (True, False):
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]]
|
||||
assert weighted == sorted(weighted, reverse=True)
|
||||
scores = [i["score"] for i in body["items"] if i["active"] is group and i["in_season"]]
|
||||
assert scores == sorted(scores, reverse=True)
|
||||
order = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]]
|
||||
assert order == sorted(order, reverse=True)
|
||||
today = now_kst().date()
|
||||
for i in body["items"]:
|
||||
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
|
||||
@@ -139,10 +153,10 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
|
||||
SimpleNamespace(index_id=2, code="now", priority=2, months=[today.month], sort_order=2),
|
||||
SimpleNamespace(index_id=3, code="off", priority=1, months=other[:3], sort_order=3),
|
||||
]
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 50), (2, 60), (3, 99))]
|
||||
scores = [_board_score(x, today, v) for x, v in ((1, 50), (2, 60), (3, 99))]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {now_kst().date(): _WEATHER_50})))
|
||||
_, board = await service.board(REGION)
|
||||
view = [(i.definition.code, i.active, i.in_season, i.season) for i in board.items]
|
||||
# 점수가 가장 높아도 제철이 아니면 순위 밖 맨 끝. 계절 표시는 제철 달이 정해진 각에만
|
||||
@@ -152,41 +166,71 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
async def test_board_displays_and_ranks_by_priority_adjusted_score(monkeypatch):
|
||||
today = now_kst().date()
|
||||
defs = [
|
||||
SimpleNamespace(index_id=1, code="low", priority=3),
|
||||
SimpleNamespace(index_id=2, code="mid", priority=2),
|
||||
SimpleNamespace(index_id=3, code="high", priority=1),
|
||||
]
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))]
|
||||
scores = [_board_score(x, today, v) for x, v in ((1, 90), (2, 80), (3, 70))]
|
||||
scores += [_board_score(x, today + timedelta(days=1), v) for x, v in ((1, 90), (2, 80), (3, 70))]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {now_kst().date(): _WEATHER_50})))
|
||||
err, board = await service.board(REGION)
|
||||
assert err is ErrorType.SUCCESS
|
||||
# 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로
|
||||
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 80, 2), ("low", 90, 3)]
|
||||
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 68, 2), ("low", 63, 3)]
|
||||
for item in board.items:
|
||||
assert item.trend[0].score == item.score.score
|
||||
assert item.trend[1].score == item.score.score
|
||||
assert all(value == item.score.score for value in item.slots.values())
|
||||
# 응답용 보정은 DB에서 읽은 원점수를 바꾸지 않으며, 같은 요청을 다시 해도 중복 적용하지 않는다.
|
||||
assert [row.score for row in scores] == [90, 80, 70, 90, 80, 70]
|
||||
_, again = await service.board(REGION)
|
||||
assert [i.score.score for i in again.items] == [70, 68, 63]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
|
||||
async def test_board_ranks_each_slot_by_displayed_score(monkeypatch):
|
||||
today = now_kst().date()
|
||||
defs = [SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=2, code="high", priority=1)]
|
||||
every = ("morning", "day", "evening", "night", "early")
|
||||
slots = {1: {k: {"score": 90, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every},
|
||||
2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every if k not in ("night", "early")}}
|
||||
2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every}}
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=80, slots=slots[x]) for x in (1, 2)]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {k: 50 for k in every})))
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {now_kst().date(): {k: _RESULT_50 for k in every}})))
|
||||
monkeypatch.setattr("services.index_service._with_slot", lambda row, data: SimpleNamespace(score=data["score"]))
|
||||
_, board = await service.board(REGION)
|
||||
ranks = {i.definition.code: i.slot_ranks for i in board.items}
|
||||
# 아침: 하 90(63) > 상 20(20). 낮: 상 70(70) > 하 90(63). 상은 밤 구간이 없어 밤 순위도 없다
|
||||
# 하 90점은 표시 63점, 상 70점은 표시 70점으로 순위와 화면 숫자가 일치한다.
|
||||
assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2
|
||||
assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2
|
||||
assert "night" not in ranks["high"]
|
||||
assert ranks["high"]["night"] == 1 and ranks["low"]["night"] == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("cur", ["morning", "day", "evening", "night", "early"])
|
||||
async def test_board_activates_gak_outside_its_time_window(monkeypatch, cur):
|
||||
today = now_kst().date()
|
||||
defs = [SimpleNamespace(index_id=1, code="outside", priority=1)]
|
||||
row = _board_score(1, today, 85, slot_score=65)
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async([row]))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {today: {cur: _RESULT_50}})))
|
||||
monkeypatch.setattr("services.index_service.current_slot", lambda *a: cur)
|
||||
|
||||
err, board = await service.board(REGION)
|
||||
|
||||
assert err is ErrorType.SUCCESS
|
||||
assert len(board.ranked) == 1
|
||||
item = board.ranked[0]
|
||||
assert item.active and item.score.score == 65 and item.rank == 1
|
||||
assert item.trend == [item.score] and item.slot == ("night" if cur == "early" else cur)
|
||||
assert item.slots == {k: 65 for k in ("morning", "day", "evening", "night")}
|
||||
assert item.slot_ranks == {k: 1 for k in item.slots}
|
||||
|
||||
|
||||
def _om_row(at, **over):
|
||||
|
||||
@@ -9,7 +9,7 @@ import pytest
|
||||
from common.enums import RainType, Sky
|
||||
from services.calc.index_calc import (
|
||||
OUTING_HOURS, Context, DayForecast, Hour, air_score, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
|
||||
uv_score, view_score, zero_rules_text,
|
||||
priority_score, rank_score, uv_score, view_score, zero_rules_text,
|
||||
)
|
||||
from services.calc.moon import illumination
|
||||
|
||||
@@ -38,6 +38,36 @@ def test_perfect_evening_scores_100():
|
||||
assert r.notes["temp"] == "체감 21°, 편한 범위 18~24° 안"
|
||||
|
||||
|
||||
def test_rank_and_display_share_priority_adjusted_screenshot_scores():
|
||||
items = [(83, 1), (82, 1), (80, 1), (91, 2), (77, 1), (77, 1), (76, 1), (89, 2), (87, 2)]
|
||||
shown = [(priority_score(score, priority), priority) for score, priority in items]
|
||||
ranked = sorted(shown, key=lambda item: rank_score(*item), reverse=True)
|
||||
assert [score for score, _ in ranked] == [83, 82, 80, 77, 77, 77, 76, 76, 74]
|
||||
assert priority_score(91, 2) == 77
|
||||
assert priority_score(89, 2) == 76
|
||||
|
||||
|
||||
def test_rank_uses_priority_only_to_break_ties():
|
||||
items = [(80, 3), (80, 1), (81, 3), (80, 2)]
|
||||
assert sorted(items, key=lambda item: rank_score(*item), reverse=True) == [(81, 3), (80, 1), (80, 2), (80, 3)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("weight", [5, 10, 20])
|
||||
def test_time_match_adds_only_its_weight_without_extra_penalty(weight):
|
||||
rules = _defn().factor_rules | {"time": {"type": "fixed", "value": 55}}
|
||||
defn = _defn(weight_temp=100 - weight, weight_rain=0, weight_wind=0, weight_humidity=0, weight_air=0,
|
||||
weight_time=weight, factor_rules=rules)
|
||||
hours = [[_h(12)]]
|
||||
matched = evaluate(defn, hours, replace(CTX, time_matches=True))
|
||||
unmatched = evaluate(defn, hours, replace(CTX, time_matches=False))
|
||||
assert matched.factors["time"] == 100 and unmatched.factors["time"] == 0
|
||||
assert matched.score == 100 and unmatched.score == 100 - weight
|
||||
|
||||
|
||||
def test_time_matching_does_not_replace_weekday_score():
|
||||
assert evaluate(_defn(), [[_h(12)]], replace(CTX, time_matches=False)).factors["time"] == 100
|
||||
|
||||
|
||||
def test_good_but_not_perfect_stays_below_100():
|
||||
assert evaluate(_defn(), [[_h(19, feels=23, hum=58, wind=1.8)]], CTX).score < 95
|
||||
|
||||
@@ -275,6 +305,28 @@ def test_seasonal_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code, good, bad", [
|
||||
("hangang", dict(feels=20.0, wind=1.5, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
|
||||
("themepark", dict(day=_WED, feels=20.0, wind=2.0), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
|
||||
("date", dict(feels=20.0, wind=1.5), dict(feels=5.0, prob=90, rain=RainType.RAIN, pm25=60)),
|
||||
("frizz", dict(feels=28.0, prob=90, rain=RainType.RAIN, hum=90), dict(feels=12.0, hum=35)),
|
||||
("boiler", dict(feels=2.0, hum=85, prob=60), dict(feels=22.0, hum=40)),
|
||||
("sunscreen", dict(feels=26.0, uv=8.0), dict(feels=8.0, uv=0.5)),
|
||||
("mosquito", dict(feels=27.0, hum=85, wind=0.5), dict(feels=15.0, hum=40, wind=6.0)),
|
||||
("tennis", dict(feels=18.0, wind=1.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
|
||||
("hyodo", dict(feels=20.0, wind=1.5), dict(feels=20.0, prob=80, rain=RainType.RAIN)),
|
||||
("thanks", dict(feels=0.0, prob=90, rain=RainType.RAIN), dict(feels=20.0)),
|
||||
("gift", dict(feels=17.0, wind=1.5), dict(feels=17.0, prob=80, rain=RainType.RAIN)),
|
||||
("party", dict(feels=3.0, prob=90, rain=RainType.RAIN), dict(day=_WED, feels=20.0)),
|
||||
("game", dict(feels=3.0, prob=90, rain=RainType.RAIN, pm25=70), dict(day=_WED, feels=20.0)),
|
||||
("selfie", dict(wind=1.0, hum=35, sunshine_ratio=0.8), dict(prob=90, rain=RainType.RAIN, hum=90, wind=8.0, sunshine_ratio=0.0)),
|
||||
("sentimental", dict(feels=13.0, prob=90, rain=RainType.RAIN, wind=3.0, hum=85), dict(feels=28.0, hum=40, wind=0.5)),
|
||||
])
|
||||
def test_trend_and_mood_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert _seed_score(code, **good) >= 80
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
def test_new_gak_100_only_when_every_factor_is_perfect():
|
||||
perfect = dict(feels=19.5, wind=1.0, hum=35)
|
||||
assert _seed_score("golf", **perfect) == 100
|
||||
@@ -318,3 +370,14 @@ def test_umbrella_lost_needs_rain_that_stopped():
|
||||
assert evaluate(defn, [[_h(13), _h(14)]], after_rain).score >= 80
|
||||
assert evaluate(defn, [[_h(13), _h(14)]], CTX).zero_reason == "앞서 내린 비가 없어 0점"
|
||||
assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0
|
||||
|
||||
|
||||
def test_weather_why_lists_every_condition_heaviest_first():
|
||||
from services.index_service import WEATHER_SCORE_DEF, weather_why
|
||||
|
||||
ctx = Context(day=date(2026, 10, 2), is_holiday=False, pm25=12, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
r = evaluate(WEATHER_SCORE_DEF, [[_h(h, feels=19.0, prob=0, wind=2.0, hum=55, sunshine_ratio=0.9) for h in range(9, 22)]], ctx)
|
||||
why = weather_why(r)
|
||||
assert [w.label for w in why] == ["기온", "비", "햇볕", "바람", "습도", "미세먼지"]
|
||||
assert sum(w.weight for w in why) == 100
|
||||
assert why[0].note.startswith("체감 19°")
|
||||
@@ -0,0 +1,119 @@
|
||||
import json
|
||||
import os
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from router.router import app
|
||||
from router.v1.my_gak.protocol import MyGakRule
|
||||
from services.calc.index_calc import Context, Hour, evaluate
|
||||
from services.calc.my_gak_calc import MyRule, axes, definition, preset
|
||||
from services.my_gak_service import MAX_PER_USER, gak_name
|
||||
|
||||
RULE = {"temp": [15, 25], "rain": "dry", "slots": ["evening", "night"]}
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": "조건토끼"})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
def _hours(feels: float, rain: RainType = RainType.NONE, prob: int = 0, wind: float = 1.0, humidity: int = 50) -> list[Hour]:
|
||||
return [Hour(hour=h, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=humidity, sky=Sky.CLEAR) for h in (19, 20, 21)]
|
||||
|
||||
|
||||
def _score(rule: MyRule, hours: list[Hour], pm25: int | None = 10) -> int:
|
||||
ctx = Context(day=date(2026, 10, 20), is_holiday=False, pm25=pm25, air_label=None, moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
return evaluate(definition(rule), [hours], ctx).score
|
||||
|
||||
|
||||
def test_name_gets_gak_suffix_and_rejects_links_and_numbers():
|
||||
assert gak_name(" 소맥 ") == "소맥각"
|
||||
assert gak_name("야독각") == "야독각"
|
||||
assert gak_name("naver.com") is None
|
||||
assert gak_name("01012345678") is None
|
||||
assert gak_name("가" * 12) is None
|
||||
|
||||
|
||||
def test_only_chosen_conditions_count_and_score_falls_with_distance():
|
||||
rule = MyRule(temp=(15, 25), rain="dry")
|
||||
assert axes(rule) == ["temp", "rain"]
|
||||
inside = _score(rule, _hours(20))
|
||||
near = _score(rule, _hours(27))
|
||||
far = _score(rule, _hours(33))
|
||||
assert inside >= 90 and inside > near > far
|
||||
# 고르지 않은 바람·습도는 아무리 나빠도 점수에 안 들어간다
|
||||
assert _score(rule, _hours(20, wind=15, humidity=95)) == inside
|
||||
|
||||
|
||||
def test_dry_rule_caps_when_raining_and_wet_rule_likes_rain():
|
||||
assert _score(MyRule(rain="dry"), _hours(20, RainType.RAIN, 90)) <= 20
|
||||
assert _score(MyRule(rain="wet"), _hours(20, RainType.RAIN, 90)) >= 90
|
||||
|
||||
|
||||
def test_wind_and_air_limits():
|
||||
assert _score(MyRule(wind_max=4), _hours(20, wind=2)) > _score(MyRule(wind_max=4), _hours(20, wind=9))
|
||||
assert _score(MyRule(air="good"), _hours(20), pm25=10) > _score(MyRule(air="good"), _hours(20), pm25=40)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_add_list_delete_and_limits():
|
||||
async with client() as c:
|
||||
assert (await c.post("/v1/my-gak", json={"name": "소맥", "rule": RULE})).status_code == 401
|
||||
h = await _login(c, "rule_01")
|
||||
assert (await c.get("/v1/my-gak")).json()["items"] == []
|
||||
item = (await c.post("/v1/my-gak", json={"name": "소맥", "rule": RULE}, headers=h)).json()["item"]
|
||||
assert item["name"] == "소맥각" and item["rule"]["temp"] == [15, 25] and item["rule"]["slots"] == ["evening", "night"]
|
||||
assert [g["my_gak_id"] for g in (await c.get("/v1/my-gak", headers=h)).json()["items"]] == [item["my_gak_id"]]
|
||||
assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["success"] is True
|
||||
assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["desc"] == "NOT_FOUND"
|
||||
for i in range(MAX_PER_USER):
|
||||
assert (await c.post("/v1/my-gak", json={"name": f"각{chr(0xAC00 + i)}", "rule": RULE}, headers=h)).json()["item"]
|
||||
assert (await c.post("/v1/my-gak", json={"name": "하나더", "rule": RULE}, headers=h)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rejects_bad_rules():
|
||||
async with client() as c:
|
||||
h = await _login(c, "rule_02")
|
||||
bad = lambda rule: c.post("/v1/my-gak", json={"name": "야독", "rule": rule}, headers=h) # noqa: E731
|
||||
assert (await bad({})).status_code == 422
|
||||
assert (await bad({"temp": [25, 15]})).status_code == 422
|
||||
assert (await bad({"temp": [15, 25], "slots": []})).status_code == 422
|
||||
assert (await bad({"humidity": [10, 120]})).status_code == 422
|
||||
|
||||
|
||||
def _defn(rules: dict, windows: list[dict], **weights) -> SimpleNamespace:
|
||||
w = {"temp": 30, "rain": 30, "wind": 0, "humidity": 0, "air": 0} | weights
|
||||
return SimpleNamespace(factor_rules=rules, windows=windows, **{f"weight_{k}": v for k, v in w.items()})
|
||||
|
||||
|
||||
def test_preset_copies_rules_that_fit_and_drops_the_rest():
|
||||
base = {"rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 3, "limit": 10}, "humidity": {"type": "range", "lo": 30, "hi": 60}}
|
||||
p = preset(_defn(base | {"temp": {"type": "range", "lo": 18, "hi": 24}}, [{"from": 18, "to": 24}], wind=15, humidity=10, air=10))
|
||||
assert p == {"slots": ["evening", "night"], "temp": [18, 24], "rain": "dry", "wind_max": 3, "air": "normal", "humidity": [30, 60]}
|
||||
# 더울수록·추울수록은 만점 기온부터 끝까지, 산 정상 보정은 되돌린다
|
||||
assert preset(_defn(base | {"temp": {"type": "higher", "zero": 16, "full": 27}}, [{"from": 9, "to": 11}]))["temp"] == [27, 40]
|
||||
assert preset(_defn(base | {"temp": {"type": "lower", "zero": 10, "full": -5}}, [{"from": 9, "to": 11}]))["temp"] == [-20, -5]
|
||||
assert preset(_defn(base | {"temp": {"type": "range", "lo": 10, "hi": 20, "offset": -4}}, [{"from": 9, "to": 11}]))["temp"] == [14, 24]
|
||||
# 범위에서 멀수록 좋은 기온, 탁할수록 좋은 미세먼지, 비중 0인 바람은 옮기지 않는다
|
||||
p = preset(_defn(base | {"temp": {"type": "away", "lo": 15, "hi": 24}, "air": {"zero": 15, "full": 75}}, [{"around": "sunset", "hours": 1}], air=20))
|
||||
assert p == {"slots": ["evening"], "rain": "dry"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_presets_cover_every_gak_with_valid_rules():
|
||||
async with client() as c:
|
||||
body = (await c.get("/v1/my-gak/presets")).json()
|
||||
with open(os.path.join(os.path.dirname(os.path.dirname(__file__)), "seed", "index_definition.json"), encoding="utf-8") as f:
|
||||
seed = json.load(f)
|
||||
assert [x["code"] for x in body["items"]] == [x["code"] for x in sorted(seed, key=lambda x: x["sort_order"])]
|
||||
for x in body["items"]:
|
||||
MyGakRule(**x["rule"])
|
||||
@@ -0,0 +1,58 @@
|
||||
from common.enums import RainType, Sky
|
||||
from services.calc.index_calc import Hour, Outing, outing
|
||||
from services.weekend_rank import OUTING_SCORE_TABLE, TRIP_MIN_SCORE, calibrated_outing, outing_day_score
|
||||
|
||||
|
||||
def test_table_is_a_monotonic_0_to_100_lookup():
|
||||
assert len(OUTING_SCORE_TABLE) == 101
|
||||
assert all(0 <= v <= 100 for v in OUTING_SCORE_TABLE)
|
||||
assert all(a <= b for a, b in zip(OUTING_SCORE_TABLE, OUTING_SCORE_TABLE[1:]))
|
||||
assert OUTING_SCORE_TABLE[0] < OUTING_SCORE_TABLE[100] == 100
|
||||
|
||||
|
||||
def test_table_makes_top_scores_rare_and_centers_60():
|
||||
"""원래 점수가 높을수록 표시 점수가 오르되, 90점 이상으로 가는 원래 점수는 위쪽 일부뿐."""
|
||||
assert any(55 <= v <= 65 for v in OUTING_SCORE_TABLE)
|
||||
assert sum(v >= 90 for v in OUTING_SCORE_TABLE) <= 15
|
||||
# 맑고 알맞은 날(원래 100)과 조금 못 미치는 날(원래 97)이 모두 100점으로 몰리지 않는다
|
||||
assert calibrated_outing(95) < 100
|
||||
|
||||
|
||||
def test_calibrated_outing_reads_the_table():
|
||||
assert calibrated_outing(70) == OUTING_SCORE_TABLE[70]
|
||||
assert calibrated_outing(0) == OUTING_SCORE_TABLE[0]
|
||||
|
||||
|
||||
def test_day_score_uses_calibrated_value_for_hourly_and_estimated_results():
|
||||
for estimated in (False, True):
|
||||
r = Outing(score=80, factors={}, notes={}, reason="비 0% · 체감 21° · 맑음", capped=False, estimated=estimated)
|
||||
assert outing_day_score(r) == OUTING_SCORE_TABLE[80]
|
||||
|
||||
|
||||
def test_trip_min_score_keeps_the_same_weather_quality():
|
||||
"""당일치기 최소 기준은 원래 점수 50과 같은 날씨 수준을 표시 점수로 옮긴 값."""
|
||||
assert TRIP_MIN_SCORE == calibrated_outing(50)
|
||||
# 표는 가까운 원래 점수끼리 같은 값이 될 수 있어, 눈에 띄게 낮은 날은 빠지고 높은 날은 들어가는지만 본다
|
||||
assert calibrated_outing(45) < TRIP_MIN_SCORE <= calibrated_outing(55)
|
||||
|
||||
|
||||
def _day(feels: float = 21.0, wind: float = 0.5, prob: int = 0, sky: Sky = Sky.CLEAR) -> list[Hour]:
|
||||
return [Hour(hour=h, feels_c=feels, rain_type=RainType.NONE, rain_prob=prob, wind_ms=wind, humidity=50, sky=sky) for h in range(10, 18)]
|
||||
|
||||
|
||||
def test_outing_100_needs_exact_temperature_and_very_calm_wind():
|
||||
"""맑고 비 없는 날도 체감 21° 근처(±0.5°)·바람 초속 1m 이하여야 100점. 그래야 같은 예보의 여러 지역이 한꺼번에 100점이 되지 않는다."""
|
||||
assert outing(_day()).score == 100
|
||||
assert outing(_day(feels=21.4)).factors["temp"] == 100
|
||||
assert outing(_day(feels=22.3)).factors["temp"] < 100
|
||||
assert outing(_day(wind=1.0)).factors["wind"] == 100
|
||||
assert outing(_day(wind=1.8)).factors["wind"] < 95
|
||||
assert outing(_day(wind=1.2)).score > outing(_day(wind=1.8)).score > outing(_day(wind=2.0)).score
|
||||
|
||||
|
||||
def test_100_only_for_a_perfect_original_score_and_top_scores_stay_distinct():
|
||||
"""맨 위가 100으로 잘려 원래 96·97·99가 모두 100점이 되던 것을 막는다: 100점은 원래 100뿐, 그 아래는 서로 다른 점수."""
|
||||
assert OUTING_SCORE_TABLE[100] == 100
|
||||
assert OUTING_SCORE_TABLE[99] < 100
|
||||
top = OUTING_SCORE_TABLE[90:]
|
||||
assert all(a < b for a, b in zip(top, top[1:]))
|
||||
@@ -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"]
|
||||
@@ -7,7 +7,7 @@ from common.utils.kma_time import KST
|
||||
from common.database.model.models import WeatherHourly
|
||||
from router.router import app
|
||||
from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex
|
||||
from services.seo_service import SeoService, day_summary, fill, today_line
|
||||
from services.seo_service import SeoService, day_summary, fill, today_line, tomorrow_line
|
||||
|
||||
REGION = "1114000000"
|
||||
TEMPLATE = (
|
||||
@@ -65,3 +65,36 @@ async def test_today_page_fills_real_feed(offline, monkeypatch):
|
||||
assert page.status_code == 200 and "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>최저 " in page.text and "지금 20°" in page.text
|
||||
assert "해 지는 시각 오후" in page.text and "<ol><li>" in page.text
|
||||
assert missing.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gu_page_of_city_has_its_own_address(offline, monkeypatch):
|
||||
async def template(self, path):
|
||||
return TEMPLATE if path == "today/gyeonggi/seongnam/bundang" else None
|
||||
|
||||
monkeypatch.setattr(SeoService, "template", template)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
page = await client.get("/v1/seo/today/gyeonggi/seongnam/bundang")
|
||||
assert page.status_code == 200 and "지금 20°" in page.text
|
||||
|
||||
|
||||
def test_tomorrow_line_has_day_and_sunset():
|
||||
line = tomorrow_line([_hour(12, 19.5, prob=10)], datetime(2026, 10, 15, 17, 51, tzinfo=KST))
|
||||
assert line == "최저 20°·최고 20°, 강수확률 10%, 맑음. 해 지는 시각 오후 5시 51분."
|
||||
assert tomorrow_line([], datetime(2026, 10, 15, 17, 51, tzinfo=KST)) == ""
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_tomorrow_page_fills_tomorrow_forecast(offline, monkeypatch):
|
||||
tmpl = TEMPLATE.replace("오늘 날씨", "내일 날씨")
|
||||
|
||||
async def template(self, path):
|
||||
return tmpl if path == "tomorrow/gyeonggi/seongnam/bundang" else None
|
||||
|
||||
monkeypatch.setattr(SeoService, "template", template)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
page = await client.get("/v1/seo/tomorrow/gyeonggi/seongnam/bundang")
|
||||
missing = await client.get("/v1/seo/tomorrow/seoul/nowhere")
|
||||
assert page.status_code == 200 and "<h1>서울 중구 내일 날씨, 뭐 할까?</h1><p>최저 " in page.text
|
||||
assert "지금 " not in page.text and "<ol>" not in page.text
|
||||
assert missing.status_code == 404
|
||||
@@ -0,0 +1,193 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from router.router import app
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from services.talk_service import DAILY_MAX, GROUP_MAX, HIDE_AT, parse_cursor, pick_group, spread_authors, weather_line
|
||||
|
||||
REGION = "1144000000"
|
||||
BUSAN = "2611000000"
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
async def _write(c, h, body="망원동 하늘 진짜 맑아요", region=REGION):
|
||||
return (await c.post("/v1/talk", json={"region_code": region, "body": body}, headers=h)).json()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_write_list_like_delete():
|
||||
async with client() as c:
|
||||
assert (await c.post("/v1/talk", json={"region_code": REGION, "body": "안녕"})).status_code == 401
|
||||
h = await _login(c, "talk_01")
|
||||
t = (await _write(c, h, " 바람 많이 불어요 "))["talk"]
|
||||
assert t["body"] == "바람 많이 불어요" and t["mine"] is True and t["region_name"]
|
||||
|
||||
anon = (await c.get("/v1/talk/list")).json()["talks"]
|
||||
mine = next(x for x in anon if x["talk_id"] == t["talk_id"])
|
||||
assert mine["mine"] is False and mine["nickname"] == "talk_01"
|
||||
|
||||
liked = (await c.post(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()
|
||||
assert liked["liked"] is True and liked["like_count"] == 1
|
||||
assert (await c.post(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()["like_count"] == 1
|
||||
assert (await c.delete(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()["like_count"] == 0
|
||||
|
||||
other = await _login(c, "talk_02")
|
||||
assert (await c.delete(f"/v1/talk/{t['talk_id']}", headers=other)).json()["result"]["desc"] == "NOT_FOUND"
|
||||
assert (await c.delete(f"/v1/talk/{t['talk_id']}", headers=h)).json()["result"]["success"] is True
|
||||
assert t["talk_id"] not in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rejects_links_phone_long_and_daily_limit():
|
||||
async with client() as c:
|
||||
h = await _login(c, "talk_03")
|
||||
assert (await _write(c, h, "여기 보세요 https://spam.example"))["result"]["desc"] == "LINK_NOT_ALLOWED"
|
||||
assert (await _write(c, h, "연락 주세요 010-1234-5678"))["result"]["desc"] == "LINK_NOT_ALLOWED"
|
||||
assert (await _write(c, h, "가" * 101))["result"]["desc"] == "INVALID_INPUT"
|
||||
bad_region = (await c.post("/v1/talk", json={"region_code": "0000000000", "body": "안녕"}, headers=h)).json()
|
||||
assert bad_region["result"]["desc"] == "INVALID_INPUT"
|
||||
for i in range(DAILY_MAX):
|
||||
assert (await _write(c, h, f"오늘 {i}번째"))["talk"]
|
||||
assert (await _write(c, h))["result"]["desc"] == "DAILY_LIMIT"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_reports_hide_and_block_hides_author():
|
||||
async with client() as c:
|
||||
author = await _login(c, "talk_04")
|
||||
t = (await _write(c, author))["talk"]
|
||||
assert (await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 1}, headers=author)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
|
||||
viewer = await _login(c, "talk_05")
|
||||
assert (await c.post(f"/v1/talk/{t['talk_id']}/block", headers=viewer)).json()["result"]["success"] is True
|
||||
seen = [x["talk_id"] for x in (await c.get("/v1/talk/list", headers=viewer)).json()["talks"]]
|
||||
assert t["talk_id"] not in seen
|
||||
assert t["talk_id"] in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
|
||||
|
||||
for i in range(HIDE_AT):
|
||||
h = await _login(c, f"talk_r{i}")
|
||||
await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 2}, headers=h)
|
||||
await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 2}, headers=h)
|
||||
assert t["talk_id"] not in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
|
||||
|
||||
|
||||
def test_weather_line():
|
||||
class Row:
|
||||
temp_c, sky, rain_type = 18.4, 1, 1
|
||||
|
||||
class Wet:
|
||||
temp_c, sky, rain_type = 11.6, 3, 2
|
||||
|
||||
assert weather_line(Row()) == "18° 맑음"
|
||||
assert weather_line(Wet()) == "12° 비"
|
||||
assert weather_line(None) is None
|
||||
|
||||
|
||||
def _ids(body: dict) -> list[int]:
|
||||
return [x["talk_id"] for x in body["talks"]]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_same_sido_talks_come_first_for_that_viewer():
|
||||
async with client() as c:
|
||||
busan = (await _write(c, await _login(c, "talk_bs1"), "광안리 바람 시원해요", BUSAN))["talk"]["talk_id"]
|
||||
seoul = (await _write(c, await _login(c, "talk_se1"), "망원동 비 그쳤어요"))["talk"]["talk_id"]
|
||||
nation = _ids((await c.get("/v1/talk/list")).json())
|
||||
local = _ids((await c.get("/v1/talk/list", params={"region": BUSAN})).json())
|
||||
assert nation.index(seoul) < nation.index(busan)
|
||||
assert local.index(busan) < local.index(seoul)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_pages_follow_cursor_without_repeats():
|
||||
async with client() as c:
|
||||
mine = []
|
||||
for i in range(5):
|
||||
h = await _login(c, f"talk_pg{i}")
|
||||
for j in range(DAILY_MAX):
|
||||
mine.append((await _write(c, h, f"페이지 글 {i}-{j}", BUSAN if j % 2 else REGION))["talk"]["talk_id"])
|
||||
seen, cursor = [], None
|
||||
while True:
|
||||
body = (await c.get("/v1/talk/list", params={"region": BUSAN} | ({"cursor": cursor} if cursor else {}))).json()
|
||||
seen += _ids(body)
|
||||
cursor = body.get("next_cursor")
|
||||
if not cursor:
|
||||
break
|
||||
assert (await c.get("/v1/talk/list", params={"cursor": "abc"})).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert len(seen) == len(set(seen)) and set(mine) <= set(seen)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mine_lists_only_my_talks_newest_first():
|
||||
async with client() as c:
|
||||
assert (await c.get("/v1/talk/mine")).status_code == 401
|
||||
h = await _login(c, "talk_mine")
|
||||
ids = [(await _write(c, h, f"내 글 {i}"))["talk"]["talk_id"] for i in range(3)]
|
||||
await _write(c, await _login(c, "talk_notmine"), "남의 글")
|
||||
await c.delete(f"/v1/talk/{ids[0]}", headers=h)
|
||||
body = (await c.get("/v1/talk/mine", headers=h)).json()
|
||||
assert _ids(body) == [ids[2], ids[1]] and all(x["mine"] for x in body["talks"])
|
||||
|
||||
|
||||
def test_spread_authors_and_cursor():
|
||||
v = lambda who: SimpleNamespace(author=SimpleNamespace(user_id=who)) # noqa: E731
|
||||
assert [x.author.user_id for x in spread_authors([v("a"), v("a"), v("a"), v("b"), v("c")])] == ["a", "b", "a", "c", "a"]
|
||||
assert parse_cursor("1760000000_42") == (1760000000, 42)
|
||||
assert parse_cursor("12") is None and parse_cursor("x_1") is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_topic_is_saved_and_filters_list():
|
||||
async with client() as c:
|
||||
h = await _login(c, "talk_tp1")
|
||||
sky = (await c.post("/v1/talk", json={"region_code": REGION, "body": "노을 분홍빛", "topic": 2}, headers=h)).json()["talk"]
|
||||
plain = (await _write(c, h, "그냥 동네 이야기"))["talk"]
|
||||
assert sky["topic"] == 2 and plain["topic"] == 1
|
||||
only_sky = _ids((await c.get("/v1/talk/list", params={"topic": 2})).json())
|
||||
only_foliage = _ids((await c.get("/v1/talk/list", params={"topic": 4})).json())
|
||||
assert sky["talk_id"] in only_sky and plain["talk_id"] not in only_sky
|
||||
assert sky["talk_id"] not in only_foliage
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_groups_have_near_group_and_topic_group_from_three_people():
|
||||
async with client() as c:
|
||||
for i in range(3):
|
||||
h = await _login(c, f"talk_gr{i}")
|
||||
for j in range(2):
|
||||
await c.post("/v1/talk", json={"region_code": REGION, "body": f"단풍 물들었어요 {i}-{j}", "topic": 4}, headers=h)
|
||||
groups = {g["topic"]: g["talks"] for g in (await c.get("/v1/talk/groups", params={"region": REGION})).json()["groups"]}
|
||||
assert 0 in groups and 4 in groups
|
||||
assert all(t["topic"] == 4 for t in groups[4])
|
||||
for talks in groups.values():
|
||||
names = [t["nickname"] for t in talks]
|
||||
assert len(names) == len(set(names)) and len(talks) <= GROUP_MAX
|
||||
|
||||
|
||||
def _view(talk_id, user, region, hours_ago, likes=0, reports=0):
|
||||
now = datetime(2026, 10, 23, 12, tzinfo=timezone.utc)
|
||||
talk = SimpleNamespace(talk_id=talk_id, region_code=region, created_at=now - timedelta(hours=hours_ago), like_count=likes, report_count=reports)
|
||||
return SimpleNamespace(talk=talk, author=SimpleNamespace(user_id=user))
|
||||
|
||||
|
||||
def test_pick_group_orders_near_fresh_first_one_per_person_clean_first():
|
||||
now = datetime(2026, 10, 23, 12, tzinfo=timezone.utc)
|
||||
far = _view(1, "a", BUSAN, 1)
|
||||
same_sido = _view(2, "b", "1111000000", 1)
|
||||
same_gu = _view(3, "c", REGION, 1)
|
||||
old_popular = _view(4, "d", REGION, 30, likes=50)
|
||||
again = _view(5, "c", REGION, 0)
|
||||
assert [v.talk.talk_id for v in pick_group([far, same_sido, same_gu, old_popular, again], REGION, now)] == [5, 2, 1, 4]
|
||||
reported = _view(6, "e", REGION, 0, reports=1)
|
||||
assert pick_group([reported, far], REGION, now)[0].talk.talk_id == 1
|
||||
@@ -0,0 +1,59 @@
|
||||
import io
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from PIL import Image
|
||||
|
||||
from router.router import app
|
||||
|
||||
REGION = "1144000000"
|
||||
GPS_IFD = 0x8825
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
def _jpeg_with_gps(w: int = 2400, h: int = 1600) -> bytes:
|
||||
exif = Image.Exif()
|
||||
exif[0x010F] = "PhoneMaker"
|
||||
exif[GPS_IFD] = {1: "N", 2: (37.0, 33.0, 0.0), 3: "E", 4: (126.0, 58.0, 0.0)}
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (w, h), (120, 180, 230)).save(buf, "JPEG", exif=exif)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_upload_strips_location_resizes_and_attaches_to_talk():
|
||||
src = _jpeg_with_gps()
|
||||
assert Image.open(io.BytesIO(src)).getexif().get_ifd(GPS_IFD)
|
||||
async with client() as c:
|
||||
assert (await c.post("/v1/talk/image", files={"file": ("a.jpg", src, "image/jpeg")})).status_code == 401
|
||||
h = await _login(c, "photo_01")
|
||||
url = (await c.post("/v1/talk/image", files={"file": ("a.jpg", src, "image/jpeg")}, headers=h)).json()["image"]
|
||||
got = await c.get(url)
|
||||
assert got.status_code == 200 and got.headers["content-type"] == "image/webp"
|
||||
img = Image.open(io.BytesIO(got.content))
|
||||
assert max(img.size) == 1080
|
||||
assert not img.getexif()
|
||||
talk = (await c.post("/v1/talk", json={"region_code": REGION, "body": "하늘 사진", "image": url}, headers=h)).json()["talk"]
|
||||
assert talk["image"] == url
|
||||
listed = (await c.get("/v1/talk/list")).json()["talks"][0]
|
||||
assert listed["image"] == url
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rejects_non_images_and_foreign_paths():
|
||||
async with client() as c:
|
||||
h = await _login(c, "photo_02")
|
||||
bad = (await c.post("/v1/talk/image", files={"file": ("a.txt", b"not an image", "text/plain")}, headers=h)).json()
|
||||
assert bad["result"]["desc"] == "INVALID_INPUT"
|
||||
for image in ("https://evil.example/a.webp", "/v1/talk/image/../../etc/passwd", "/v1/talk/image/" + "0" * 32 + ".webp"):
|
||||
res = (await c.post("/v1/talk", json={"region_code": REGION, "body": "안녕", "image": image}, headers=h)).json()
|
||||
assert res["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.get("/v1/talk/image/" + "0" * 32 + ".webp")).status_code == 404
|
||||
@@ -0,0 +1,74 @@
|
||||
from dataclasses import replace
|
||||
from datetime import date
|
||||
|
||||
from services.calc.index_calc import Context, evaluate
|
||||
from scripts.gen_weather_score_table import straighten_top
|
||||
from services.index_service import EARLY, WEATHER_SCORE_DEF, WEATHER_SCORE_TABLE, calibrated_weather, weather_slot_scores
|
||||
from tests.test_index_calc import _defn, _h
|
||||
|
||||
PERFECT = Context(day=date(2026, 10, 2), is_holiday=False, pm25=8, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
SLOTS = ("morning", "day", "evening", "night")
|
||||
|
||||
|
||||
def test_weather_score_has_no_worst_factor_pull():
|
||||
"""해 난 비율만 0점(밤)이어도 나머지가 만점이면 비중대로 85점. 가장 낮은 요소로 25% 더 깎지 않는다."""
|
||||
hours = [_h(h, feels=21.0, prob=0, wind=0.8, hum=50, sunshine_ratio=0.0) for h in range(19, 23)]
|
||||
r = evaluate(WEATHER_SCORE_DEF, [hours], PERFECT)
|
||||
assert r.factors["sun"] == 0
|
||||
assert r.score == 85
|
||||
|
||||
|
||||
def test_gak_scores_keep_worst_factor_pull():
|
||||
"""각 점수는 그대로: 한 요소가 0점이면 섞은 점수에서 25% 깎인다."""
|
||||
defn = _defn(zero_rules=[])
|
||||
r = evaluate(defn, [[_h(19, wind=12.0)]], PERFECT)
|
||||
assert r.factors["wind"] == 0
|
||||
plain = round(sum(r.factors[a] * getattr(defn, f"weight_{a}", 0) for a in r.factors) / 100)
|
||||
assert r.score == round(plain * 0.75)
|
||||
|
||||
|
||||
def test_table_covers_every_slot_and_never_goes_down():
|
||||
for slot in SLOTS:
|
||||
table = WEATHER_SCORE_TABLE[slot]
|
||||
assert len(table) == 101
|
||||
assert all(0 <= v <= 100 for v in table)
|
||||
assert all(a <= b for a, b in zip(table, table[1:]))
|
||||
assert table[100] == 100
|
||||
|
||||
|
||||
def test_table_makes_90_rare_and_centers_60():
|
||||
"""구간마다 원래 점수 중앙값 근처가 60점 근처로, 90점 이상은 원래 점수 상위 몇 칸뿐."""
|
||||
for slot in SLOTS:
|
||||
table = WEATHER_SCORE_TABLE[slot]
|
||||
assert any(55 <= v <= 65 for v in table)
|
||||
assert sum(v >= 90 for v in table) < sum(v < 90 for v in table)
|
||||
|
||||
|
||||
def test_calibrated_uses_slot_table_and_last_night_for_early():
|
||||
assert calibrated_weather("day", 70) == WEATHER_SCORE_TABLE["day"][70]
|
||||
assert calibrated_weather(EARLY, 70) == WEATHER_SCORE_TABLE["night"][70]
|
||||
|
||||
|
||||
def test_weather_slot_scores_keeps_results_with_calibrated_scores():
|
||||
"""점수 근거(factors)는 그대로 두고 점수만 표시 점수로 바꾼 결과를 돌려준다."""
|
||||
results = {k: replace(evaluate(WEATHER_SCORE_DEF, [[_h(12)]], PERFECT), score=s) for k, s in {"morning": 40, "night": 60, EARLY: 60}.items()}
|
||||
shown = weather_slot_scores(results)
|
||||
assert {k: r.score for k, r in shown.items()} == {"morning": WEATHER_SCORE_TABLE["morning"][40], "night": WEATHER_SCORE_TABLE["night"][60], EARLY: WEATHER_SCORE_TABLE["night"][60]}
|
||||
assert all(shown[k].factors == results[k].factors for k in results)
|
||||
assert results["morning"].score == 40 # 원래 결과는 바뀌지 않는다
|
||||
|
||||
|
||||
def test_straighten_top_makes_100_only_at_the_top_and_keeps_the_rest():
|
||||
clamped = list(range(0, 80)) + [85, 90, 95] + [100] * 18 # 맨 위가 100으로 잘린 표 (원래 80~82 → 85·90·95, 83 이상은 모두 100)
|
||||
fixed = straighten_top(clamped, top=100)
|
||||
assert fixed[:80] == clamped[:80] # 아래쪽은 그대로
|
||||
assert fixed[100] == 100 and max(fixed[:100]) < 100
|
||||
above = fixed[80:]
|
||||
assert all(a < b for a, b in zip(above, above[1:])) or above[-1] == 100 # 위쪽은 구별되는 점수로 오른다
|
||||
assert straighten_top(clamped, top=90)[90] == 100 # 완벽한 점수가 100보다 낮은 구간(밤)은 거기서 100
|
||||
|
||||
|
||||
def test_weather_table_gives_100_only_at_the_best_reachable_original_score():
|
||||
assert WEATHER_SCORE_TABLE["day"][99] < 100 == WEATHER_SCORE_TABLE["day"][100]
|
||||
night_top = 100 - WEATHER_SCORE_DEF.weight_sun # 밤은 해 난 비율이 늘 0점이라 원래 점수가 85까지만 나온다
|
||||
assert WEATHER_SCORE_TABLE["night"][night_top - 1] < 100 == WEATHER_SCORE_TABLE["night"][night_top]
|
||||
Reference in new issue
Block a user