chore: main 병합 — 지금 날씨 점수 보정을 바꾸기 표로 통일

- index_service.py 충돌: main 의 오늘·내일 날씨 점수 계산은 그대로 쓰고, 보정만 strict_weather 에서 구간별 바꾸기 표(weather_slot_scores)로 바꿈
- weather_slot_scores 는 main 의 weather_why 가 쓰는 점수 근거(factors)를 그대로 둔 Result 를 돌려줌
- strict_weather 와 그 테스트(test_weather_score_is_strict_near_top) 삭제 (바꾸기 표로 통일하기로 정함)
- test_board_activates_gak_outside_its_time_window 의 ensure 스텁을 main 의 {날짜: {구간: Result}} 모양으로 맞춤
This commit is contained in:
skkim committed 2026-10-22 13:58:36 +09:00
commit 621a0cf90d
133 files changed
+8963 -489

No files matched your search

+78 -1
View File
@@ -336,6 +336,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"
@@ -349,7 +357,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)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
@@ -362,3 +372,70 @@ 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)
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())
class UserBlock(Base):
__tablename__ = "user_block"
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
blocked_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())
+11
View File
@@ -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
@@ -113,6 +115,13 @@ class IndexCategory(CodeEnum):
LIFE = 4
class TalkReport(CodeEnum):
ABUSE = 1 # 욕설·비하
SPAM = 2 # 광고·도배
PRIVACY = 3 # 개인정보 노출
ETC = 4
class ArticleCategory(CodeEnum):
SEASON = 1
TIP = 2
@@ -136,6 +145,8 @@ class PostType(CodeEnum):
DAY_TRIP = 13 # 당일치기: 1~2시간 거리 후보 도시 중 주말 날씨 1위 + 그곳 행사
MOON = 14 # 오늘 밤 달 (보름·삭이면 그 이야기)
UV = 15 # 오늘 낮 자외선 (아침·낮, '보통' 이상인 날만)
HERO = 16 # 히어로(오늘 날씨)의 좋아요·댓글 자리. 피드 목록엔 안 나온다
TODAY_GAK = 17 # 오늘의 각 카드의 좋아요·댓글 자리. 피드 목록엔 안 나온다
class EventKind(CodeEnum):
+43
View File
@@ -0,0 +1,43 @@
import time
from typing import Optional
import httpx
from jose import JWTError, jwt
from common.logger import LOG
from config.settings import settings
CERTS_URL = "https://www.googleapis.com/oauth2/v3/certs"
ISSUERS = ("accounts.google.com", "https://accounts.google.com")
_CERTS_TTL = 3600
_certs: dict = {"keys": [], "at": 0.0}
async def _keys(force: bool = False) -> list[dict]:
"""구글 서명 공개키. 한 시간 캐시하고, 모르는 키가 오면 한 번 다시 받는다."""
if force or not _certs["keys"] or time.monotonic() - _certs["at"] > _CERTS_TTL:
async with httpx.AsyncClient(timeout=5) as c:
res = await c.get(CERTS_URL)
res.raise_for_status()
_certs["keys"], _certs["at"] = res.json()["keys"], time.monotonic()
return _certs["keys"]
async def verify(credential: str) -> Optional[str]:
"""구글 로그인 버튼이 준 ID 토큰을 확인하고 구글 사용자 고유 번호(sub)를 돌려준다. 서명·발급처·우리 클라이언트 ID·만료가 하나라도 안 맞으면 None."""
if not settings.google_client_id:
LOG.error("[google] GOOGLE_CLIENT_ID is empty")
return None
try:
kid = jwt.get_unverified_header(credential).get("kid")
keys = await _keys()
key = next((k for k in keys if k.get("kid") == kid), None) or next((k for k in await _keys(force=True) if k.get("kid") == kid), None)
if key is None:
return None
claims = jwt.decode(credential, key, algorithms=["RS256"], audience=settings.google_client_id, options={"verify_at_hash": False})
except (JWTError, httpx.HTTPError, KeyError, ValueError) as e:
LOG.warning("[google] id token rejected: %s", type(e).__name__)
return None
if claims.get("iss") not in ISSUERS or not claims.get("sub"):
return None
return str(claims["sub"])
+38
View File
@@ -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)))
+6
View File
@@ -34,6 +34,12 @@ class Settings(BaseSettings):
# 지역 검색 페이지의 정적 HTML 을 받아 올 프론트 주소 (같은 docker 망 안)
frontend_internal_url: str = "http://frontend"
# 사람 글 사진을 저장할 폴더 (compose 볼륨)
upload_dir: str = "uploads"
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
google_client_id: str = ""
jwt_access_secret: str = ""
jwt_refresh_secret: str = ""
jwt_access_minutes: int = 60
+24
View File
@@ -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
+37 -20
View File
@@ -1,21 +1,30 @@
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import delete, select, update
from sqlalchemy import delete, func, select, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Comment, CommentLike, Post, PostLike, PostSave, User
from common.database.model.models import Comment, CommentLike, CommentLikeAnon, Post, PostLike, PostLikeAnon, PostSave, User
from common.liker import Liker
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))
@@ -34,14 +43,18 @@ 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, 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(Comment.post_id == post_id, Comment.deleted.is_(False))
async def comments(self, s: AsyncSession, post_id: int, 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))
if cursor is not None:
stmt = stmt.where(Comment.comment_id > cursor)
return list((await s.execute(stmt.order_by(Comment.comment_id).limit(limit))).all())
@@ -50,16 +63,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)
)
post_id = res.scalar()
@@ -68,14 +89,10 @@ class ReactionCRUD:
await s.execute(update(Post).where(Post.post_id == 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)))
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))
+79
View File
@@ -0,0 +1,79 @@
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
) -> 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 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 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) -> Talk:
t = Talk(user_id=user_id, region_code=region_code, body=body, weather=weather, image=image)
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())
+6
View File
@@ -22,6 +22,12 @@ class UserCRUD:
await s.flush()
return user
async def create_google(self, s: AsyncSession, sub: str, nickname: str) -> User:
user = User(login_id=f"google_{sub}", provider_uid=sub, nickname=nickname, provider=2)
s.add(user)
await s.flush()
return user
async def update(self, s: AsyncSession, user_id: uuid.UUID, values: dict) -> Optional[User]:
user = await self.get(s, user_id)
if user is None:
+77
View File
@@ -211,6 +211,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,
@@ -229,6 +237,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.comment ADD COLUMN report_count INTEGER NOT NULL DEFAULT 0;
@@ -248,6 +261,70 @@ 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);
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)
);
-- 이 사람 글 안 보기
CREATE TABLE IF NOT EXISTS public.user_block (
user_id UUID NOT NULL,
blocked_id UUID NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, blocked_id)
);
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
-- 구 목록.
+2
View File
@@ -12,3 +12,5 @@ apscheduler>=3.10,<4
pytest
python-jose[cryptography]
bcrypt
python-multipart
Pillow
+4
View File
@@ -11,11 +11,13 @@ from router.v1.auth.account import router as auth_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,6 +44,8 @@ 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)
+13 -1
View File
@@ -4,7 +4,8 @@ from common.auth import current_user
from common.database.model.models import User
from common.enums import AuthProvider, ErrorType
from common.models.errors import error_info
from router.v1.auth.protocol import Me, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_Logout, Res_Me
from config.settings import settings
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me
from services.auth_service import AuthService
router = APIRouter(prefix="/v1/auth", tags=["auth"])
@@ -33,6 +34,17 @@ async def login(req: Req_Login, service: AuthService = Depends()) -> Res_Auth:
return _auth(err, user, service)
@router.post("/google", response_model=Res_Auth, response_model_exclude_none=True, summary="구글 로그인 (처음이면 자동 닉네임으로 가입)")
async def google_login(req: Req_Google, service: AuthService = Depends()) -> Res_Auth:
err, user = await service.google(req.credential)
return _auth(err, user, service)
@router.get("/config", response_model=Res_AuthConfig, response_model_exclude_none=True, summary="로그인 화면 설정 (구글 클라이언트 ID)")
async def auth_config() -> Res_AuthConfig:
return Res_AuthConfig(google_client_id=settings.google_client_id or None)
@router.post("/refresh", response_model=Res_Auth, response_model_exclude_none=True, summary="토큰 재발급")
async def refresh(req: Req_Refresh, service: AuthService = Depends()) -> Res_Auth:
err, user = await service.refresh(req.refresh_token)
+10
View File
@@ -1,5 +1,7 @@
from typing import Optional
from pydantic import Field
from common.enums import AuthProvider
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
@@ -15,6 +17,10 @@ class Req_Login(Req_WebPacketProtocol):
password: str
class Req_Google(Req_WebPacketProtocol):
credential: str = Field(min_length=20, max_length=4096, description="구글 로그인 버튼이 준 ID 토큰")
class Req_Refresh(Req_WebPacketProtocol):
refresh_token: str
@@ -47,3 +53,7 @@ class Res_Logout(Res_WebPacketProtocol):
class Res_Me(Res_WebPacketProtocol):
me: Optional[Me] = None
class Res_AuthConfig(Res_WebPacketProtocol):
google_client_id: Optional[str] = Field(None, description="구글 로그인 버튼에 쓸 OAuth 클라이언트 ID. 없으면 구글 로그인을 숨긴다")
+11 -2
View File
@@ -5,6 +5,7 @@ from fastapi import APIRouter, Depends, Path, Query
from common.auth import optional_user
from common.database.model.models import User
from common.enums import ErrorType
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
@@ -15,19 +16,27 @@ router = APIRouter(prefix="/v1/feed", tags=["feed"])
@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),
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]
pinned = [x for x in (feed.hero_post, feed.gak_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
+29
View File
@@ -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):
@@ -134,6 +136,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
@@ -154,6 +164,21 @@ class HeroStat(WebPacketProtocol):
tone: Literal["normal", "warn", "rain"] = Field(description="normal=기본, warn=조심(노랑), rain=비(파랑)")
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):
now_at: datetime
sky_mode: Literal["morning", "day", "sunset", "night"]
@@ -166,12 +191,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 +232,8 @@ 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
bands: Optional[Bands] = None
Whitespace-only changes.
+55
View File
@@ -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)))
+73
View File
@@ -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] = []
+3
View File
@@ -1,6 +1,8 @@
from datetime import date, datetime
from typing import Optional
from pydantic import Field
from common.enums import PostType
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
@@ -46,6 +48,7 @@ class Res_CommentList(Res_WebPacketProtocol):
class Req_Comment(Req_WebPacketProtocol):
body: str
region: Optional[str] = Field(None, description="로그인 없이 쓸 때 보고 있는 동네 코드. 이름이 '마포구 익명'으로 보인다")
class Res_Comment(Res_WebPacketProtocol):
+26 -22
View File
@@ -5,6 +5,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
@@ -21,19 +22,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="저장")
@@ -59,35 +60,38 @@ 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자)")
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개)")
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)
+16
View File
@@ -23,3 +23,19 @@ async def get_today_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = P
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"})
View File
Whitespace-only changes.
+51
View File
@@ -0,0 +1,51 @@
from datetime import datetime
from typing import Optional
from pydantic import Field
from common.enums import TalkReport
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="올린 사진 주소")
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 결과)")
class Req_TalkReport(Req_WebPacketProtocol):
reason: TalkReport
class Res_TalkList(Res_WebPacketProtocol):
talks: list[TalkData] = []
next_cursor: Optional[str] = Field(None, description="다음 페이지를 받을 때 그대로 cursor 로 보낸다")
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="글에 붙일 사진 주소")
+102
View File
@@ -0,0 +1,102 @@
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
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_TalkImage, Res_TalkLike, Res_TalkList, TalkData
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, like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
)
@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="보는 사람의 구 행정코드"),
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)
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)
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)))
+1
View File
@@ -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
+11 -5
View File
@@ -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(
+6 -2
View File
@@ -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 PRIORITY_WEIGHT, _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)]
File diff suppressed because it is too large. Load diff
+31
View File
@@ -1,4 +1,5 @@
import re
import secrets
import uuid
from typing import Optional
@@ -6,6 +7,7 @@ from fastapi import Depends
from common.auth import PASSWORD_MAX_BYTES, decode, hash_password, issue_tokens, verify_password
from common.database.db_session_manager import DB_SESSION_MNG
from common.google_id import verify as verify_google
from common.database.model.models import User
from common.enums import ErrorType
from config.settings import settings
@@ -19,6 +21,15 @@ COLORS = ("orange", "blue", "green", "purple", "pink", "brown")
MOODS = ("clear", "partly", "cloudy", "rain", "thunder", "snow", "fog", "rainbow")
_NICK_WORDS = ("맑은", "포근한", "산들", "반짝", "느긋한", "보슬", "선선한", "따끈한")
_NICK_ANIMALS = {"rabbit": "토끼", "bear": "곰", "dog": "강아지", "sun": "해님", "moon": "달님", "cloud": "구름"}
def auto_nickname() -> str:
"""구글로 처음 들어온 사람의 이름: 맑은토끼 482. 내 정보에서 바꿀 수 있다."""
return f"{secrets.choice(_NICK_WORDS)}{secrets.choice(list(_NICK_ANIMALS.values()))} {secrets.randbelow(900) + 100}"
class AuthService:
def __init__(self, crud: UserCRUD = Depends(UserCRUD)) -> None:
self.crud = crud
@@ -47,6 +58,26 @@ class AuthService:
return ErrorType.AUTH_FAILED, None
return ErrorType.SUCCESS, user
async def google(self, credential: str) -> tuple[ErrorType, Optional[User]]:
"""구글 ID 토큰으로 로그인. 처음이면 자동 닉네임으로 계정을 만든다. 구글 이름·이메일은 저장하지 않는다."""
sub = await verify_google(credential)
if sub is None:
return ErrorType.AUTH_FAILED, None
login_id = f"google_{sub}"
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
if err is not ErrorType.SUCCESS:
return err, None
if user is None:
err, user = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.create_google(s, sub, auto_nickname()))
if err is not ErrorType.SUCCESS:
# 같은 계정이 동시에 처음 들어온 경우엔 먼저 만들어진 쪽을 쓴다
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
if err is not ErrorType.SUCCESS or user is None:
return ErrorType.DB_ERROR, None
if user.status != 1:
return ErrorType.AUTH_FAILED, None
return ErrorType.SUCCESS, user
async def refresh(self, refresh_token: str) -> tuple[ErrorType, Optional[User]]:
claims = decode(refresh_token, settings.jwt_refresh_secret, "refresh")
if claims is None:
+118
View File
@@ -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
+72 -21
View File
@@ -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,7 +11,7 @@ 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, 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
@@ -20,8 +21,8 @@ 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, 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,7 +63,11 @@ 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),
]
# 피드 목록 대신 히어로·오늘의 각 카드에 좋아요·댓글만 붙는 자리
_PINNED = {PostType.HERO: "hero_post", PostType.TODAY_GAK: "gak_post"}
# 좋아요·댓글 단위. 이 종류들은 전국이 같은 카드 하나, 나머지는 그 구 데이터로 채우는 카드라 시도마다 따로 만든다.
NATIONAL_SCOPE = "00"
NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON})
@@ -76,12 +81,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: "한 문장"}
@@ -220,7 +226,8 @@ 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
@@ -234,6 +241,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,
@@ -366,8 +395,10 @@ class FeedService:
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 +412,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 +471,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)],
tomorrow=_hero_tomorrow(now.date() + timedelta(days=1), board) if board else None,
)
@staticmethod
@@ -454,7 +487,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]:
@@ -685,13 +718,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 +749,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 +783,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]:
+2 -3
View File
@@ -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
@@ -67,11 +66,11 @@ 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:
if x.discomfort is not None:
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal"))
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"))
+69 -9
View File
@@ -44,6 +44,21 @@ WEATHER_SCORE_DEF = SimpleNamespace(
# 가장 낮은 요소로 깎지 않는다: 밤엔 해 난 비율이 늘 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"]
@@ -90,6 +105,9 @@ 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]:
@@ -193,7 +211,7 @@ 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}
@@ -204,9 +222,9 @@ def calibrated_weather(slot: str, score: int) -> int:
return WEATHER_SCORE_TABLE[shown_slot(slot)][score]
def weather_slot_scores(results: dict[str, Result]) -> dict[str, int]:
"""구간별 날씨 점수 결과를 표시 점수로."""
return {k: calibrated_weather(k, r.score) for k, r in results.items()}
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]:
@@ -326,10 +344,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))
@@ -369,11 +389,45 @@ class IndexService:
trend=[by_key[(d.index_id, day)] 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),
@@ -403,7 +457,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 = weather_slot_scores(slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now))
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
+83
View File
@@ -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)
+58 -17
View File
@@ -7,10 +7,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
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
@@ -32,8 +39,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))
@@ -41,11 +48,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)
@@ -60,6 +67,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:
@@ -71,36 +84,64 @@ 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, 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
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)
+24 -9
View File
@@ -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)
+45
View File
@@ -0,0 +1,45 @@
import io
import os
import re
import uuid
from typing import Optional
from PIL import Image, ImageOps, UnidentifiedImageError
from config.settings import settings
from common.enums import ErrorType
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 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]]:
"""사진을 다시 그려 저장한다. 다시 그리면 찍은 위치(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"
img.save(os.path.join(folder(), name), "WEBP", quality=82)
return ErrorType.SUCCESS, URL_PREFIX + name
+173
View File
@@ -0,0 +1,173 @@
import re
from dataclasses import dataclass
from datetime import 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
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 file_of
BODY_MAX = 100
DAILY_MAX = 5
# 로그인한 서로 다른 사람의 신고가 이만큼 쌓이면 운영자 확인 전까지 숨긴다
HIDE_AT = 3
PAGE = 20
# 보는 사람과 같은 시도에서 쓴 글은 이만큼 늦게 쓴 글처럼 앞에 둔다
LOCAL_BOOST = timedelta(hours=12)
# 링크(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 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 page(self, user: Optional[User], ip_hash: str, region_code: Optional[str], cursor: Optional[str]) -> 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))
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) -> 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 file_of(image) is None:
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))
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
+1 -1
View File
@@ -43,7 +43,7 @@ def anyio_backend():
_VOLATILE = (
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
"sky_score", "index_score", "post", "post_like", "post_save", "comment", "comment_like", "holiday", "solar_term", "users",
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "holiday", "solar_term", "users",
)
+149
View File
@@ -0,0 +1,149 @@
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()
return {"Authorization": f"Bearer {body['access_token']}"}
@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"]
+3 -2
View File
@@ -50,11 +50,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}"}
+41 -4
View File
@@ -156,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
@@ -367,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시예요."
@@ -394,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%"
+80
View File
@@ -0,0 +1,80 @@
import time
import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from httpx import ASGITransport, AsyncClient
from jose import jwk, jwt
import common.google_id as google_id
import services.auth_service as auth_service
from config.settings import settings
from router.router import app
CLIENT_ID = "test-client.apps.googleusercontent.com"
def client():
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
@pytest.fixture
def google_keys(monkeypatch):
"""가짜 구글 서명키. 공개키는 _keys 대신 돌려준다."""
monkeypatch.setattr(settings, "google_client_id", CLIENT_ID)
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
public = jwk.construct(key.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo), "RS256").to_dict()
public["kid"] = "k1"
async def keys(force: bool = False):
return [public]
monkeypatch.setattr(google_id, "_keys", keys)
def sign(**over):
claims = {"iss": "https://accounts.google.com", "aud": CLIENT_ID, "sub": "1234567890", "exp": int(time.time()) + 600, "iat": int(time.time()), "name": "홍길동", "email": "a@example.com"}
claims.update(over)
return jwt.encode(claims, pem, algorithm="RS256", headers={"kid": "k1"})
return sign
@pytest.mark.anyio
async def test_verify_accepts_only_our_valid_tokens(google_keys):
assert await google_id.verify(google_keys()) == "1234567890"
assert await google_id.verify(google_keys(aud="other.apps.googleusercontent.com")) is None
assert await google_id.verify(google_keys(iss="https://evil.example")) is None
assert await google_id.verify(google_keys(exp=int(time.time()) - 10)) is None
assert await google_id.verify(google_keys()[:-4] + "abcd") is None
@pytest.mark.anyio
async def test_google_login_creates_once_with_auto_nickname_and_no_real_name(google_keys):
async with client() as c:
first = (await c.post("/v1/auth/google", json={"credential": google_keys()})).json()
assert first["access_token"] and first["me"]["provider"] == 2
nick = first["me"]["nickname"]
assert "홍길동" not in nick and "@" not in nick
again = (await c.post("/v1/auth/google", json={"credential": google_keys()})).json()
assert again["me"]["nickname"] == nick and again["me"]["login_id"] == first["me"]["login_id"]
other = (await c.post("/v1/auth/google", json={"credential": google_keys(sub="999")})).json()
assert other["me"]["login_id"] != first["me"]["login_id"]
bad = (await c.post("/v1/auth/google", json={"credential": google_keys(aud="x")})).json()
assert bad["result"]["desc"] == "AUTH_FAILED"
me = (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {first['access_token']}"})).json()["me"]
assert me["nickname"] == nick
@pytest.mark.anyio
async def test_config_exposes_client_id_only_when_set(monkeypatch):
async with client() as c:
monkeypatch.setattr(settings, "google_client_id", "")
assert "google_client_id" not in (await c.get("/v1/auth/config")).json()
monkeypatch.setattr(settings, "google_client_id", CLIENT_ID)
assert (await c.get("/v1/auth/config")).json()["google_client_id"] == CLIENT_ID
def test_auto_nickname_fits_nickname_rule():
for _ in range(50):
assert auth_service.NICKNAME.match(auth_service.auto_nickname())
+2 -3
View File
@@ -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 -5
View File
@@ -14,9 +14,12 @@ 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"
@@ -151,7 +154,7 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
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]
# 점수가 가장 높아도 제철이 아니면 순위 밖 맨 끝. 계절 표시는 제철 달이 정해진 각에만
@@ -171,7 +174,7 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
scores = [_board_score(x, today, 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). 보이는 점수는 그대로
@@ -188,7 +191,7 @@ async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
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}
@@ -206,7 +209,7 @@ async def test_board_activates_gak_outside_its_time_window(monkeypatch, cur):
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, {cur: 50})))
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)
+33
View File
@@ -291,6 +291,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
@@ -334,3 +356,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°")
+119
View File
@@ -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"])
+23 -1
View File
@@ -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 = (
@@ -76,3 +76,25 @@ async def test_gu_page_of_city_has_its_own_address(offline, monkeypatch):
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
+145
View File
@@ -0,0 +1,145 @@
from types import SimpleNamespace
import pytest
from httpx import ASGITransport, AsyncClient
from router.router import app
from services.talk_service import DAILY_MAX, HIDE_AT, parse_cursor, 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
+59
View File
@@ -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
+8 -4
View File
@@ -1,5 +1,5 @@
from dataclasses import replace
from datetime import date
from types import SimpleNamespace
from services.calc.index_calc import Context, evaluate
from services.index_service import EARLY, WEATHER_SCORE_DEF, WEATHER_SCORE_TABLE, calibrated_weather, weather_slot_scores
@@ -48,6 +48,10 @@ def test_calibrated_uses_slot_table_and_last_night_for_early():
assert calibrated_weather(EARLY, 70) == WEATHER_SCORE_TABLE["night"][70]
def test_weather_slot_scores_shows_calibrated_values():
results = {k: SimpleNamespace(score=s) for k, s in {"morning": 40, "night": 60, EARLY: 60}.items()}
assert weather_slot_scores(results) == {"morning": WEATHER_SCORE_TABLE["morning"][40], "night": WEATHER_SCORE_TABLE["night"][60], EARLY: WEATHER_SCORE_TABLE["night"][60]}
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 # 원래 결과는 바뀌지 않는다