feat: 피드를 시간대별 카드로 다시 짜고 하늘 배경·내 캐릭터 추가, 다른 시안 정리
- 피드: 그날 카드 12장을 03:00에 한 번에 만들고, 시간대(아침·낮·저녁·밤, 저녁은 일몰 2시간 전부터)마다 순서를 바꾸고 조건이 맞는 카드만 켠다. 새 카드 우산·특보, 내일 미리보기, 한 문장·시(예시 seed). 흐린 날 노을은 한 줄 카드.
- 캐시를 feed:{구}:{시간대}로 나누고 시간대 경계·일몰·예보 갱신 때 만료해 새 카드가 늦게 보이던 문제를 고친다.
- 히어로는 오늘 1위 각만 보여 준다.
- 각 점수·노을 점수를 7일 지나면 지운다.
- 화면 전체 하늘 배경(시간대별 색, 느린 일렁임, 밤 별)과 화면 끝까지 이어지는 위·아래 바.
- 상단바 로그인 버튼, 내 정보 창(캐릭터 6종·배경색 6종·오늘 기분 8종·닉네임·로그아웃), PATCH /v1/auth/me, 댓글·상단바에 캐릭터·배경색·기분 표시. users.character·color·mood 칸 추가.
- 카드 슬라이드와 가로 줄을 Embla 카로셀로 바꿔 PC에서도 마우스로 끌어 넘기고 화살표로 넘긴다.
- 좋아요·저장을 받아 둔 피드 데이터에도 반영해 다른 탭에 다녀와도 유지되게 고치고, 좋아요 때 하트가 터지는 애니메이션을 넣는다.
- 보내기에서 게시물을 인스타 스토리 크기(1080×1920) 이미지로 공유하거나 내려받는다 (modern-screenshot).
- 창이 열려 있는 동안 뒤 페이지 스크롤을 잠근다.
- 시안 B 확정: 시안 A 아이콘(public/a)과 쓰지 않는 전역 스타일·글꼴 삭제.
- 문서: 데이터 흐름 지도(backend/docs/data-flow-map.html), 확정 시안(docs/시안B_확정.html), 피드 기획 v2, 호출량·DB 크기 추정, data-pipeline 갱신. 보고 폴더와 예전 시안 html 삭제.
This commit is contained in:
1 parent
f8b47f064a
commit
a9ddbaab3c
93 files changed
+2322
-2751
No files matched your search
@@ -14,6 +14,9 @@ from crud.user_crud import UserCRUD
|
||||
LOGIN_ID = re.compile(r"^[a-z0-9_]{4,20}$")
|
||||
PASSWORD_MIN = 8
|
||||
NICKNAME = re.compile(r"^\S.{0,10}\S$")
|
||||
CHARACTERS = ("rabbit", "bear", "dog", "sun", "moon", "cloud")
|
||||
COLORS = ("orange", "blue", "green", "purple", "pink", "brown")
|
||||
MOODS = ("clear", "partly", "cloudy", "rain", "thunder", "snow", "fog", "rainbow")
|
||||
|
||||
|
||||
class AuthService:
|
||||
@@ -49,6 +52,33 @@ class AuthService:
|
||||
return ErrorType.AUTH_TOKEN_INVALID, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def update_me(self, user: User, nickname: Optional[str], character: Optional[str], color: Optional[str] = None, mood: Optional[str] = None) -> tuple[ErrorType, Optional[User]]:
|
||||
"""닉네임·캐릭터·배경색·기분 중 보낸 것만 바꾼다. 기분을 빈 문자열로 보내면 지운다."""
|
||||
values: dict = {}
|
||||
if nickname is not None:
|
||||
nickname = nickname.strip()
|
||||
if not NICKNAME.match(nickname):
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
values["nickname"] = nickname
|
||||
if character is not None:
|
||||
if character not in CHARACTERS:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
values["character"] = character
|
||||
if color is not None:
|
||||
if color not in COLORS:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
values["color"] = color
|
||||
if mood is not None:
|
||||
if mood and mood not in MOODS:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
values["mood"] = mood or None
|
||||
if not values:
|
||||
return ErrorType.SUCCESS, user
|
||||
err, updated = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.update(s, user.user_id, values))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return (ErrorType.SUCCESS, updated) if updated is not None else (ErrorType.NOT_FOUND, None)
|
||||
|
||||
@staticmethod
|
||||
def tokens(user: User) -> tuple[str, str]:
|
||||
return issue_tokens(user)
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import Optional
|
||||
|
||||
@@ -8,11 +9,11 @@ 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, Post, Region
|
||||
from common.database.model.models import Article, Post, Region, WeatherHourly
|
||||
from common.enums import ArticleCategory, ErrorType, PostType, RefType, SkyGrade
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, next_vilage_available, now_kst
|
||||
from common.utils.text import ieyo, month_day
|
||||
from common.utils.text import hour_label, ieyo, month_day
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
@@ -30,19 +31,35 @@ from services.sky_service import SkyService, SkyView
|
||||
from services.weather_service import TodayWeather, WeatherService
|
||||
from services.week_service import DayPlan, EventItem, WeekService
|
||||
|
||||
# 그날 피드의 칸: (순서, 종류, 공개 시각, 참조, 지수 순위). 목~일에만 주말 추천을 넣는다.
|
||||
# 그날 피드 카드: (번호, 종류, 참조, 지수 순위). 03:00 에 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정한다 (docs/피드기획_v2.html).
|
||||
LINEUP = [
|
||||
(1, PostType.WEATHER, 3, RefType.NONE, None),
|
||||
(2, PostType.GAK, 6, RefType.NONE, 1),
|
||||
(3, PostType.SEASON, 9, RefType.ARTICLE, None),
|
||||
(4, PostType.EVENT, 10, RefType.NONE, None),
|
||||
(5, PostType.GAK, 12, RefType.NONE, 2),
|
||||
(6, PostType.SUNSET, 13, RefType.NONE, None),
|
||||
(7, PostType.TIP, 15, RefType.ARTICLE, None),
|
||||
(8, PostType.WEEK, 18, RefType.NONE, None),
|
||||
(1, PostType.WEATHER, RefType.NONE, None),
|
||||
(2, PostType.ALERT, RefType.NONE, None),
|
||||
(3, PostType.GAK, RefType.NONE, 1),
|
||||
(4, PostType.GAK, RefType.NONE, 2),
|
||||
(5, PostType.GAK, RefType.NONE, 3),
|
||||
(6, PostType.SUNSET, RefType.NONE, None),
|
||||
(7, PostType.TOMORROW, RefType.NONE, None),
|
||||
(8, PostType.WEEK, RefType.NONE, None),
|
||||
(9, PostType.EVENT, RefType.NONE, None),
|
||||
(10, PostType.SEASON, RefType.ARTICLE, None),
|
||||
(11, PostType.TIP, RefType.ARTICLE, None),
|
||||
(12, PostType.QUOTE, RefType.NONE, None),
|
||||
]
|
||||
_CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리"}
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다.
|
||||
ORDER = {
|
||||
"morning": [PostType.ALERT, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.EVENT, PostType.QUOTE],
|
||||
"day": [PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.EVENT, PostType.WEEK, PostType.SEASON, PostType.TIP, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.TOMORROW, PostType.WEEK, PostType.EVENT, PostType.SEASON, PostType.TIP, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.EVENT, 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: "한 문장"}
|
||||
_FEED_TTL_MAX = 3600
|
||||
_RAIN_PROB = 40
|
||||
_SUNSET_FULL = 60
|
||||
_FEED_DAY_START = 3 # 03:00 에 그날 카드가 바뀐다
|
||||
_COMMUTE_HOURS = (("내일 출근 8시", 8), ("내일 퇴근 7시", 19))
|
||||
|
||||
|
||||
def _pick(articles: list[Article], day: date) -> Optional[Article]:
|
||||
@@ -54,15 +71,71 @@ def _discomfort_label(v: int) -> str:
|
||||
return "쾌적" if v < 68 else "보통" if v < 75 else "불쾌" if v < 80 else "매우 불쾌"
|
||||
|
||||
|
||||
def _sky_mode(region: Region, now: datetime) -> str:
|
||||
st = sun_times(now.date(), float(region.lat), float(region.lon))
|
||||
if now < st.dawn_start_at or now > st.dusk_end_at:
|
||||
return "night"
|
||||
if abs((now - st.sunset_at).total_seconds()) <= 3600:
|
||||
return "sunset"
|
||||
if now < st.sunrise_at + timedelta(hours=1):
|
||||
def feed_day(now: datetime) -> date:
|
||||
return (now - timedelta(hours=_FEED_DAY_START)).date()
|
||||
|
||||
|
||||
def slot_of(now: datetime, sunset_at: datetime) -> str:
|
||||
"""아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–21 · 밤 21–05."""
|
||||
h = now.hour
|
||||
if 5 <= h < 11:
|
||||
return "morning"
|
||||
return "day"
|
||||
if 11 <= h < 21:
|
||||
return "day" if now < sunset_at - timedelta(hours=2) else "evening"
|
||||
return "night"
|
||||
|
||||
|
||||
def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int:
|
||||
"""다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·미세먼지 갱신 중 가장 빠른 쪽."""
|
||||
day = now.date()
|
||||
at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731
|
||||
sunset = sunset_at.astimezone(KST)
|
||||
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, at(day, 21),
|
||||
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now)]
|
||||
air = now.replace(minute=20, second=0, microsecond=0)
|
||||
changes.append(air if air > now else air + timedelta(hours=1))
|
||||
nxt = min(c for c in changes if c > now)
|
||||
return max(60, min(_FEED_TTL_MAX, int((nxt - now).total_seconds())))
|
||||
|
||||
|
||||
def _gak_key(item: IndexItem, hour: int) -> tuple[int, int, int]:
|
||||
"""하기 좋은 시간이 가까운 각을 앞에, 오늘 시간이 지난 각을 뒤에."""
|
||||
ahead = [w for w in item.definition.windows or [] if w["to"] > hour]
|
||||
if not ahead:
|
||||
return 1, 0, item.rank
|
||||
return 0, min(max(0, w["from"] - hour) for w in ahead), item.rank
|
||||
|
||||
|
||||
def _spread(cards: list[PostData]) -> list[PostData]:
|
||||
"""같은 종류가 붙으면 뒤에서 다른 종류를 당겨 끼운다."""
|
||||
out = list(cards)
|
||||
for i in range(1, len(out)):
|
||||
if out[i].post_type is out[i - 1].post_type:
|
||||
j = next((k for k in range(i + 1, len(out)) if out[k].post_type is not out[i - 1].post_type), None)
|
||||
if j is not None:
|
||||
out.insert(i, out.pop(j))
|
||||
return out
|
||||
|
||||
|
||||
def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime, has_warning: bool) -> list[PostData]:
|
||||
"""켜진 카드만 그 시간대 순서로 놓는다."""
|
||||
order = list(ORDER[slot])
|
||||
if slot == "evening" and now.weekday() == 4:
|
||||
order.remove(PostType.WEEK)
|
||||
order.insert(1, PostType.WEEK)
|
||||
if slot == "evening" and now >= sunset_at:
|
||||
order.remove(PostType.SUNSET)
|
||||
order.insert(2, PostType.SUNSET)
|
||||
pool: dict[PostType, list[PostData]] = {}
|
||||
for c in cards:
|
||||
pool.setdefault(c.post_type, []).append(c)
|
||||
# 특보는 히어로 바로 아래, 그다음 오늘 하루 날씨
|
||||
head_types = [PostType.ALERT, PostType.WEATHER] if has_warning else [PostType.WEATHER]
|
||||
head = [pool[t].pop(0) for t in head_types if pool.get(t)]
|
||||
rest = _spread([pool[t].pop(0) for t in order if t not in head_types and pool.get(t)])
|
||||
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]
|
||||
return head + rest
|
||||
|
||||
|
||||
def _top(i: IndexItem) -> TopIndex:
|
||||
@@ -71,16 +144,17 @@ def _top(i: IndexItem) -> TopIndex:
|
||||
|
||||
|
||||
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) -> ErrorType:
|
||||
"""그날 전국 공통 피드의 칸을 넣는다. 이미 있으면 그대로 둔다."""
|
||||
"""그날 피드 카드를 넣는다. 이미 있으면 그대로 둔다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
|
||||
err, exists = await DB_SESSION_MNG.execute_lambda(lambda s: crud.has_day(s, day))
|
||||
if err is not ErrorType.SUCCESS or exists:
|
||||
return err
|
||||
_, season = await DB_SESSION_MNG.execute_lambda(lambda s: season_crud.articles(s, day, ArticleCategory.SEASON.value))
|
||||
_, tips = await DB_SESSION_MNG.execute_lambda(lambda s: season_crud.articles(s, day, ArticleCategory.TIP.value))
|
||||
refs = {PostType.SEASON: _pick(season or [], day), PostType.TIP: _pick(tips or [], day)}
|
||||
end = kst_midnight(day + timedelta(days=1)) + timedelta(hours=3)
|
||||
start = kst_midnight(day) + timedelta(hours=_FEED_DAY_START)
|
||||
end = start + timedelta(days=1)
|
||||
rows = []
|
||||
for position, post_type, hour, ref_type, rank in LINEUP:
|
||||
for position, post_type, ref_type, rank in LINEUP:
|
||||
if post_type is PostType.WEEK and day.weekday() < 3:
|
||||
continue
|
||||
ref = refs.get(post_type)
|
||||
@@ -89,7 +163,7 @@ async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) ->
|
||||
rows.append({
|
||||
"feed_date": day, "position": position, "post_type": post_type.value, "ref_type": ref_type.value,
|
||||
"ref_id": ref.article_id if ref is not None else None, "index_rank": rank,
|
||||
"published_at": datetime.combine(day, time(hour), tzinfo=KST), "end_at": end,
|
||||
"published_at": start, "end_at": end,
|
||||
})
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: crud.insert_day(s, rows)])
|
||||
LOG.info(f"[feed] build {day} posts {len(rows)}: {err.name}")
|
||||
@@ -128,7 +202,10 @@ class FeedService:
|
||||
return err, None
|
||||
if region is None:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
key = f"feed:{region.code}"
|
||||
now = now_kst()
|
||||
sunset_at = sun_times(now.date(), float(region.lat), float(region.lon)).sunset_at
|
||||
slot = slot_of(now, sunset_at)
|
||||
key = f"feed:{region.code}:{slot}"
|
||||
try:
|
||||
cached = await REDIS.conn.get(key)
|
||||
if cached:
|
||||
@@ -136,18 +213,17 @@ class FeedService:
|
||||
except RedisError as e:
|
||||
LOG.error(f"[feed] cache get: {e}")
|
||||
|
||||
now = now_kst()
|
||||
day = feed_day(now)
|
||||
async with redis_lock("lock:feed:build", ttl_sec=20):
|
||||
await build_feed_day(now.date(), self.crud, self.season_crud)
|
||||
res = await self._assemble(region, now)
|
||||
await build_feed_day(day, self.crud, self.season_crud)
|
||||
res = await self._assemble(region, now, day, slot, sunset_at)
|
||||
try:
|
||||
ttl = min(_FEED_TTL_MAX, int((next_vilage_available(now) - now).total_seconds()))
|
||||
await REDIS.conn.set(key, res.model_dump_json(), ex=max(ttl, 60))
|
||||
await REDIS.conn.set(key, res.model_dump_json(), ex=feed_ttl_sec(now, sunset_at))
|
||||
except RedisError as e:
|
||||
LOG.error(f"[feed] cache set: {e}")
|
||||
return ErrorType.SUCCESS, res
|
||||
|
||||
async def _assemble(self, region: Region, now: datetime) -> Res_Feed:
|
||||
async def _assemble(self, region: Region, now: datetime, day: date, slot: str, sunset_at: datetime) -> Res_Feed:
|
||||
(err_t, today), (err_n, now_w), (err_s, sky), (err_i, board), (err_w, days), (err_e, events) = await asyncio.gather(
|
||||
self.weather.today(region.code), self.now_service.now(region.code), self.sky.view(region.code),
|
||||
self.index.board(region.code), self.week.week(region.code), self.week.events(region.code, None),
|
||||
@@ -158,19 +234,34 @@ class FeedService:
|
||||
board = board if err_i is ErrorType.SUCCESS else None
|
||||
days = days if err_w is ErrorType.SUCCESS else []
|
||||
events = events if err_e is ErrorType.SUCCESS else []
|
||||
_, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.visible(s, now))
|
||||
hour = now.replace(minute=0, second=0, microsecond=0)
|
||||
_, hourly = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: self.weather_crud.hourly_between(s, region.code, hour, kst_midnight(now.date() + timedelta(days=2)))
|
||||
)
|
||||
_, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.day(s, day))
|
||||
_, articles = await DB_SESSION_MNG.execute_lambda(lambda s: self.season_crud.articles(s, now.date(), None))
|
||||
by_article = {a.article_id: a for a in articles or []}
|
||||
quotes = [a for a in articles or [] if a.category == ArticleCategory.QUOTE.value]
|
||||
ctx = _Ctx(region=region, now=now, slot=slot, sunset_at=sunset_at, today=today, now_w=now_w, sky=sky, board=board,
|
||||
days=days, events=events, hourly=hourly or [], articles=by_article, quotes=quotes)
|
||||
|
||||
rendered = []
|
||||
gak = sorted(board.items[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
cards = []
|
||||
for p in posts or []:
|
||||
data = self._render(p, region, today, now_w, sky, board, days, events, by_article)
|
||||
if PostType(p.post_type) is PostType.GAK:
|
||||
continue
|
||||
data = self._render(p, ctx)
|
||||
if data is not None:
|
||||
rendered.append(data)
|
||||
cards.append(data)
|
||||
gak_posts = sorted((p for p in posts or [] if PostType(p.post_type) is PostType.GAK), key=lambda p: p.index_rank or 0)
|
||||
for p, item in zip(gak_posts, gak):
|
||||
cards.append(self._gak(p, item))
|
||||
has_warning = bool(now_w and now_w.warnings)
|
||||
items = board.items if board else []
|
||||
return Res_Feed(
|
||||
region_code=region.code, region_name=region.name, hero=await self._hero(region, now, now_w, board),
|
||||
stories=[_top(i) for i in items], posts=rendered,
|
||||
region_code=region.code, region_name=region.name, slot=slot,
|
||||
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board),
|
||||
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning),
|
||||
bands=Bands(
|
||||
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon) for e in events[:4]],
|
||||
top5=[_top(i) for i in items[:5]],
|
||||
@@ -181,84 +272,169 @@ class FeedService:
|
||||
),
|
||||
)
|
||||
|
||||
async def _hero(self, region: Region, now: datetime, now_w: Optional[NowWeather], board: Optional[IndexBoard]) -> Hero:
|
||||
hour = now.replace(minute=0, second=0, microsecond=0)
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.hourly_between(s, region.code, hour, hour + timedelta(hours=1)))
|
||||
cur = rows[0] if rows else None
|
||||
top = board.items[:3] if board else []
|
||||
def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard]) -> Hero:
|
||||
top = board.items[0] if board and board.items else None
|
||||
bubble = None
|
||||
if top:
|
||||
bubble = f"오늘은 {top[0].definition.name}!" if top[0].score.score >= 70 else "오늘은 쉬어 가요"
|
||||
if top is not None:
|
||||
bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요"
|
||||
return Hero(
|
||||
now_at=now, sky_mode=_sky_mode(region, now),
|
||||
now_at=now, sky_mode=_SKY_MODE[slot],
|
||||
temp_c=float(cur.temp_c) if cur else None, feels_c=float(cur.feels_c) if cur else None,
|
||||
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, top3=[_top(i) for i in top], bubble=bubble,
|
||||
weather_score=board.weather_score if board else None, top1=_top(top) if top else None, bubble=bubble,
|
||||
)
|
||||
|
||||
def _render(
|
||||
self, p: Post, region: Region, today: Optional[TodayWeather], now_w: Optional[NowWeather], sky: Optional[SkyView],
|
||||
board: Optional[IndexBoard], days: list[DayPlan], events: list[EventItem], articles: dict[int, Article],
|
||||
) -> Optional[PostData]:
|
||||
"""칸 하나를 그 구 데이터로 채운다. 채울 데이터가 없으면 그 구 피드에서는 건너뛴다."""
|
||||
base = dict(post_id=p.post_id, post_type=PostType(p.post_type), like_count=p.like_count, comment_count=p.comment_count, published_at=p.published_at.astimezone(KST))
|
||||
@staticmethod
|
||||
def _base(p: Post) -> dict:
|
||||
return dict(post_id=p.post_id, post_type=PostType(p.post_type), like_count=p.like_count, comment_count=p.comment_count,
|
||||
published_at=p.published_at.astimezone(KST))
|
||||
|
||||
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=f"{i.score.summary}. 오늘의 각 {i.rank}위는 {ieyo(d.name)}.",
|
||||
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)],
|
||||
share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}이래"])
|
||||
|
||||
def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]:
|
||||
"""카드 하나를 그 구 데이터로 채운다. 켜질 조건이 안 맞거나 채울 데이터가 없으면 None."""
|
||||
base = self._base(p)
|
||||
t = PostType(p.post_type)
|
||||
if t is PostType.WEATHER and today is not None:
|
||||
slides = [HoursSlide(kind="hours", eyebrow="오늘 하루 · 3시간마다", line=today.headline, hours=[
|
||||
HourCell(label=f"{s.at.astimezone(KST).hour}시", icon=s.icon, temp_c=float(s.row.temp_c) if s.row else None, tone=s.tone) for s in today.slots
|
||||
if t is PostType.WEATHER and c.today is not None:
|
||||
slides = [HoursSlide(kind="hours", eyebrow="오늘 하루 · 3시간마다", line=c.today.headline, hours=[
|
||||
HourCell(label=f"{x.at.astimezone(KST).hour}시", icon=x.icon, temp_c=float(x.row.temp_c) if x.row else None, tone=x.tone) for x in c.today.slots
|
||||
])]
|
||||
caption = today.headline
|
||||
if now_w is not None:
|
||||
slides.append(RowsSlide(kind="rows", eyebrow="우산 챙길까", line=now_w.rain_2h_text, icon="umbrella", rows=[
|
||||
Row(label="앞으로 2시간", value="비 와요" if now_w.will_rain_2h else "비 없음"),
|
||||
*[Row(label=c.label, value=c.text) for c in now_w.commute],
|
||||
if c.now_w is not None and c.now_w.air is not None and c.now_w.air_text:
|
||||
slides.append(RowsSlide(kind="rows", eyebrow="미세먼지", line=c.now_w.air_text, icon="vent", rows=[
|
||||
Row(label="초미세먼지", value=str(c.now_w.air.pm25) if c.now_w.air.pm25 is not None else "-"),
|
||||
Row(label="미세먼지", value=str(c.now_w.air.pm10) if c.now_w.air.pm10 is not None else "-"),
|
||||
Row(label="측정소", value=c.now_w.air.station_name),
|
||||
]))
|
||||
caption = f"{today.headline}. {now_w.tomorrow_text}."
|
||||
if now_w.air is not None and now_w.air_text:
|
||||
slides.append(RowsSlide(kind="rows", eyebrow="미세먼지", line=now_w.air_text, icon="vent", rows=[
|
||||
Row(label="초미세먼지", value=str(now_w.air.pm25) if now_w.air.pm25 is not None else "-"),
|
||||
Row(label="미세먼지", value=str(now_w.air.pm10) if now_w.air.pm10 is not None else "-"),
|
||||
Row(label="측정소", value=now_w.air.station_name),
|
||||
]))
|
||||
return PostData(**base, title="오늘 하루의 날씨", icon=today.slots[4].icon, caption=caption, slides=slides,
|
||||
share_messages=[f"{region.short_name} 오늘 날씨: {today.headline}", now_w.tomorrow_text if now_w else today.headline])
|
||||
if t is PostType.GAK and board is not None and p.index_rank and len(board.items) >= p.index_rank:
|
||||
i = board.items[p.index_rank - 1]
|
||||
d = i.definition
|
||||
return PostData(**base, title=f"{d.name} {i.score.score}", icon=d.icon, caption=f"{i.score.summary}. 오늘의 각 {i.rank}위는 {ieyo(d.name)}.",
|
||||
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)],
|
||||
share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}이래"])
|
||||
if t is PostType.SUNSET and sky is not None and sky.sunset is not None:
|
||||
s = sky.sunset
|
||||
peak = next((b for b in s.best_times if b["kind"] == "peak"), s.best_times[0])
|
||||
peak_at = datetime.fromisoformat(peak["at"])
|
||||
slides = [SunsetSlide(kind="sunset", eyebrow=f"오늘 노을 · {region.name}", line=f"{peak_at:%H:%M}, 서쪽이 가장 붉어요", score=s.score,
|
||||
grade_label=GRADE_LABEL[SkyGrade(s.grade)], cuts=[Cut(**b) for b in s.best_times])]
|
||||
if sky.spots:
|
||||
slides.append(RowsSlide(kind="rows", eyebrow="가까운 노을 명소", line=f"해 지는 쪽 {sky.sunset_azimuth}°, 서쪽이 트인 곳", icon="sunset",
|
||||
rows=[Row(label=f"{n + 1} {x.spot.name}", value=f"{x.distance_km}km") for n, x in enumerate(sky.spots)]))
|
||||
return PostData(**base, title=f"오늘 노을 {s.score}", icon="sunset", caption=f"{GRADE_LABEL[SkyGrade(s.grade)]}. {peak_at:%H:%M}쯤이 가장 예뻐요.",
|
||||
slides=slides, share_messages=[f"오늘 노을 {s.score}점이래 🌇 {peak_at:%H:%M}에 같이 볼래?"])
|
||||
if t in (PostType.SEASON, PostType.TIP) and p.ref_id in articles:
|
||||
a = articles[p.ref_id]
|
||||
return PostData(**base, title="오늘 하루의 날씨", icon=c.today.slots[4].icon, caption=c.today.headline, slides=slides,
|
||||
share_messages=[f"{c.region.short_name} 오늘 날씨: {c.today.headline}"])
|
||||
if t is PostType.ALERT:
|
||||
return self._alert(base, c)
|
||||
if t is PostType.SUNSET and c.sky is not None:
|
||||
return self._sunset(base, c)
|
||||
if t is PostType.TOMORROW and c.now_w is not None:
|
||||
return self._tomorrow(base, c)
|
||||
if t in (PostType.SEASON, PostType.TIP) and p.ref_id in c.articles:
|
||||
a = c.articles[p.ref_id]
|
||||
return PostData(**base, title=a.title, icon=a.icon, caption=" ".join(a.body[1:2]) or a.body[0],
|
||||
slides=[RowsSlide(kind="rows", eyebrow=_CATEGORY_META[a.category], line=a.body[0], icon=a.icon)], share_messages=[a.title])
|
||||
if t is PostType.EVENT and events:
|
||||
e = events[0]
|
||||
if t is PostType.EVENT:
|
||||
soon = [e for e in c.events if e.event.start_date <= c.now.date() + timedelta(days=7) and e.event.end_date >= c.now.date()]
|
||||
if not soon:
|
||||
return None
|
||||
e = soon[0]
|
||||
rows = [Row(label="장소", value=e.event.place_name), Row(label="기간", value=f"{e.event.start_date:%m.%d}~{e.event.end_date:%m.%d}")]
|
||||
if e.fit:
|
||||
rows.append(Row(label="그날 날씨", value=e.fit))
|
||||
caption = f"{month_day(e.event.start_date)}부터 {month_day(e.event.end_date)}까지예요." if e.event.is_confirmed else "올해 정확한 일정은 공식 안내로 확인해 주세요."
|
||||
return PostData(**base, title=e.event.name, icon=e.event.icon, caption=caption,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"{region.name.split()[0]} 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=rows)],
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"{c.region.name.split()[0]} 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=rows)],
|
||||
share_messages=[f"{e.event.name} 같이 갈래?"])
|
||||
if t is PostType.WEEK and days:
|
||||
weekend = [d for d in days if d.day.weekday() >= 5][:2]
|
||||
if t is PostType.WEEK and c.days:
|
||||
weekend = [d for d in c.days if d.day.weekday() >= 5][:2]
|
||||
if not weekend:
|
||||
return None
|
||||
return PostData(**base, title="이번 주말 추천", icon="calendar", caption=" ".join(f"{d.weekday}요일은 {d.pick}." for d in weekend),
|
||||
slides=[WeekSlide(kind="week", eyebrow=f"이번 주말 · {region.short_name}", line=weekend[0].pick, days=[
|
||||
slides=[WeekSlide(kind="week", eyebrow=f"이번 주말 · {c.region.short_name}", line=weekend[0].pick, days=[
|
||||
WeekDay(day=d.day, weekday=d.weekday, icon=d.icon, text=d.headline) for d in weekend
|
||||
])], share_messages=["이번 주말 같이 놀자 🙌"])
|
||||
if t is PostType.QUOTE:
|
||||
return self._quote(base, c)
|
||||
return None
|
||||
|
||||
def _alert(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""오늘 남은 시간·내일 출퇴근에 비 확률 40% 이상이거나 특보가 있을 때만 켠다."""
|
||||
tomorrow = c.now.date() + timedelta(days=1)
|
||||
later = [r for r in c.hourly if r.forecast_at > c.now and r.forecast_at.astimezone(KST).date() == c.now.date() and r.rain_prob >= _RAIN_PROB]
|
||||
commute = [(label, r) for r in c.hourly for label, h in _COMMUTE_HOURS
|
||||
if r.forecast_at.astimezone(KST).date() == tomorrow and r.forecast_at.astimezone(KST).hour == h and r.rain_prob >= _RAIN_PROB]
|
||||
warnings = (c.now_w.warnings or []) if c.now_w else []
|
||||
if not (later or commute or warnings):
|
||||
return None
|
||||
rows = [Row(label="특보", value=w.text) for w in warnings]
|
||||
if later:
|
||||
rows.append(Row(label="오늘", value=f"{hour_label(later[0].forecast_at.astimezone(KST).hour)}부터 비 {later[0].rain_prob}%"))
|
||||
rows += [Row(label=label, value=f"비 {r.rain_prob}%") for label, r in commute]
|
||||
if warnings:
|
||||
title, line = warnings[0].text, "바깥 활동 전에 꼭 확인하세요"
|
||||
elif later:
|
||||
title, line = "우산 챙겨요", f"{hour_label(later[0].forecast_at.astimezone(KST).hour)}쯤 비 소식이 있어요"
|
||||
else:
|
||||
title, line = "내일 우산 챙겨요", f"{commute[0][0]}에 비 소식이 있어요"
|
||||
return PostData(**base, title=title, icon="umbrella", caption=line,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"생활 알림 · {c.region.short_name}", line=line, icon="umbrella", rows=rows)],
|
||||
share_messages=[f"{line} ☔ 우산 챙겨!"])
|
||||
|
||||
def _sunset(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""해 지기 전엔 오늘, 진 뒤엔 내일 노을. 60점 미만이면 한 줄 카드."""
|
||||
after = c.now >= c.sunset_at
|
||||
target = next((x for x in c.sky.days if x.score_date > c.now.date()), None) if after else c.sky.sunset
|
||||
if target is None:
|
||||
return None
|
||||
when = "내일" if after else "오늘"
|
||||
grade = GRADE_LABEL[SkyGrade(target.grade)]
|
||||
if target.score < _SUNSET_FULL:
|
||||
nxt = None if after else next((x for x in c.sky.days if x.score_date > c.now.date()), None)
|
||||
caption = "구름에 가려요." + (f" 내일 노을 {nxt.score}점이에요." if nxt is not None else "")
|
||||
return PostData(**base, size="line", title=f"{when} 노을은 쉬어요", icon="sunset", caption=caption, slides=[],
|
||||
share_messages=[f"{when} 노을은 구름에 가려요"])
|
||||
peak = next((b for b in target.best_times if b["kind"] == "peak"), target.best_times[0])
|
||||
peak_at = datetime.fromisoformat(peak["at"]).astimezone(KST)
|
||||
slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} 노을 · {c.region.name}", line=f"{peak_at:%H:%M}, 서쪽이 가장 붉어요", score=target.score,
|
||||
grade_label=grade, cuts=[Cut(**b) for b in target.best_times])]
|
||||
if c.sky.spots:
|
||||
slides.append(RowsSlide(kind="rows", eyebrow="가까운 노을 명소", line=f"해 지는 쪽 {c.sky.sunset_azimuth}°, 서쪽이 트인 곳", icon="sunset",
|
||||
rows=[Row(label=f"{n + 1} {x.spot.name}", value=f"{x.distance_km}km") for n, x in enumerate(c.sky.spots)]))
|
||||
return PostData(**base, title=f"{when} 노을 {target.score}", icon="sunset", caption=f"{grade}. {peak_at:%H:%M}쯤이 가장 예뻐요.",
|
||||
slides=slides, share_messages=[f"{when} 노을 {target.score}점이래 🌇 {peak_at:%H:%M}에 같이 볼래?"])
|
||||
|
||||
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 s.score > best[1].score):
|
||||
best = (i, s)
|
||||
caption = c.now_w.tomorrow_text + "."
|
||||
if best is not None:
|
||||
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}"))
|
||||
caption += f" 내일 1위는 {ieyo(best[0].definition.name)}."
|
||||
icon = c.now_w.commute[0].icon if c.now_w.commute else "sun"
|
||||
return PostData(**base, title="내일 미리보기", icon=icon, caption=caption,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"내일 · {c.region.short_name}", line=c.now_w.tomorrow_text, icon=icon, rows=rows)],
|
||||
share_messages=[c.now_w.tomorrow_text])
|
||||
|
||||
def _quote(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""오늘 날씨에 맞는 문장. 코드 앞머리(quote-rain-·quote-cloud-·quote-clear-·quote-night-·quote-any-)로 고른다."""
|
||||
icons = [x.icon for x in c.today.slots] if c.today else []
|
||||
weather = "rain" if any(i in ("rain", "snow") for i in icons) else "cloud" if icons.count("cloud") * 2 >= len(icons or [0]) else "clear"
|
||||
prefixes = [f"quote-{weather}-", "quote-any-"] + (["quote-night-"] if c.slot == "night" else [])
|
||||
pool = [a for a in c.quotes if a.code.startswith(tuple(prefixes))]
|
||||
a = _pick(pool, c.now.date())
|
||||
if a is None:
|
||||
return None
|
||||
rows = [Row(label="출처", value=a.body[1])] if len(a.body) > 1 else []
|
||||
return PostData(**base, title=a.title, icon=a.icon, caption=a.body[0],
|
||||
slides=[RowsSlide(kind="rows", eyebrow="오늘의 한 문장", line=a.body[0], icon=a.icon, rows=rows)], share_messages=[a.body[0]])
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Ctx:
|
||||
region: Region
|
||||
now: datetime
|
||||
slot: str
|
||||
sunset_at: datetime
|
||||
today: Optional[TodayWeather]
|
||||
now_w: Optional[NowWeather]
|
||||
sky: Optional[SkyView]
|
||||
board: Optional[IndexBoard]
|
||||
days: list[DayPlan]
|
||||
events: list[EventItem]
|
||||
hourly: list[WeatherHourly]
|
||||
articles: dict[int, Article]
|
||||
quotes: list[Article]
|
||||
@@ -18,6 +18,9 @@ PAGE = 20
|
||||
class CommentView:
|
||||
comment: Comment
|
||||
nickname: str
|
||||
character: str
|
||||
color: str
|
||||
mood: Optional[str]
|
||||
liked: bool
|
||||
mine: bool
|
||||
|
||||
@@ -74,10 +77,10 @@ class ReactionService:
|
||||
return err, []
|
||||
liked: set[int] = set()
|
||||
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]))
|
||||
_, 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, liked=c.comment_id in (liked or set()), mine=user is not None and c.user_id == user.user_id)
|
||||
for c, n in rows
|
||||
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
|
||||
]
|
||||
|
||||
async def add_comment(self, post_id: int, user: User, body: str) -> tuple[ErrorType, Optional[CommentView]]:
|
||||
@@ -88,7 +91,7 @@ class ReactionService:
|
||||
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, liked=False, mine=True) if c else None)
|
||||
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)
|
||||
|
||||
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))
|
||||
|
||||
@@ -61,7 +61,10 @@ class SeasonService:
|
||||
|
||||
async def articles(self, category: Optional[ArticleCategory]) -> tuple[ErrorType, list[Article]]:
|
||||
today = now_kst().date()
|
||||
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.articles(s, today, category.value if category else None))
|
||||
err, items = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.articles(s, today, category.value if category else None))
|
||||
if category is None:
|
||||
items = [a for a in items or [] if a.category != ArticleCategory.QUOTE.value]
|
||||
return err, items
|
||||
|
||||
async def article(self, article_id: int) -> tuple[ErrorType, Optional[Article]]:
|
||||
err, a = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.article(s, article_id))
|
||||
|
||||
Reference in new issue
Block a user