Compare commits

..
4 changed files with 76 additions and 31 deletions

No files matched your search

+35 -13
View File
@@ -1,5 +1,5 @@
import re import re
from datetime import datetime from datetime import datetime, timedelta
from html import escape from html import escape
from typing import Optional from typing import Optional
@@ -7,11 +7,13 @@ import httpx
from fastapi import Depends from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import ErrorType from common.database.model.models import WeatherHourly
from common.enums import ErrorType, RainType, Sky
from common.logger import LOG from common.logger import LOG
from common.utils.kma_time import KST, now_kst from common.utils.kma_time import KST, kst_midnight, now_kst
from config.settings import settings from config.settings import settings
from crud.region_crud import RegionCRUD from crud.region_crud import RegionCRUD
from crud.weather_crud import WeatherCRUD
from router.v1.feed.protocol import Res_Feed from router.v1.feed.protocol import Res_Feed
from services.calc.day_slot import SLOT_LABEL from services.calc.day_slot import SLOT_LABEL
from services.calc.sun import sun_times from services.calc.sun import sun_times
@@ -19,7 +21,7 @@ from services.feed_service import FeedService
_CODE = re.compile(r'<meta name="region-code" content="(\d+)"') _CODE = re.compile(r'<meta name="region-code" content="(\d+)"')
_DESC = re.compile(r'(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"') _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>)") _H1 = re.compile(r"(<main><h1>[^<]*</h1>)")
@@ -29,9 +31,24 @@ def _clock(at: datetime) -> str:
return f"{'오전' if at.hour < 12 else '오후'} {h}시" + (f" {at.minute}분" if at.minute else "") return f"{'오전' if at.hour < 12 else '오후'} {h}시" + (f" {at.minute}분" if at.minute else "")
def today_line(feed: Res_Feed, sunset_at: Optional[datetime]) -> str: _SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
"""검색 결과 요약에 보일 오늘 한 줄: 지금 기온·상태, 구간별 1위 각, 해 지는 시각.""" _RAIN_WORD = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
parts = []
def day_summary(rows: list[WeatherHourly]) -> str:
"""오늘 하루 예보 요약: 최저·최고, 강수확률, 하늘 (비·눈이 있으면 그것)."""
if not rows:
return ""
temps = [float(r.temp_c) for r in rows]
wet = next((RainType(r.rain_type) for r in rows if r.rain_type != RainType.NONE.value), None)
day = [r for r in rows if 9 <= r.forecast_at.astimezone(KST).hour <= 18] or rows
sky = _RAIN_WORD[wet] if wet else _SKY_WORD[Sky(max({r.sky for r in day}, key=[r.sky for r in day].count))]
return f"최저 {round(min(temps))}°·최고 {round(max(temps))}°, 강수확률 {max(r.rain_prob for r in rows)}%, {sky}."
def today_line(feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
"""검색 결과 요약에 보일 오늘 한 줄: 하루 예보, 지금 기온·상태, 구간별 1위 각, 해 지는 시각."""
parts = [day_summary(rows)] if rows else []
h = feed.hero h = feed.hero
if h and h.temp_c is not None: if h and h.temp_c is not None:
status = "·".join(f"{s.label} {s.value}" for s in h.status) status = "·".join(f"{s.label} {s.value}" for s in h.status)
@@ -44,9 +61,9 @@ def today_line(feed: Res_Feed, sunset_at: Optional[datetime]) -> str:
return " ".join(parts) return " ".join(parts)
def fill(template: str, feed: Res_Feed, name: str, sunset_at: Optional[datetime]) -> str: def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위.""" """정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
line = today_line(feed, sunset_at) line = today_line(feed, rows, sunset_at)
if not line: if not line:
return template return template
top = feed.bands.top5 if feed.bands else [] top = feed.bands.top5 if feed.bands else []
@@ -56,8 +73,10 @@ def fill(template: str, feed: Res_Feed, name: str, sunset_at: Optional[datetime]
class SeoService: class SeoService:
def __init__(self, feed: FeedService = Depends(FeedService), regions: RegionCRUD = Depends(RegionCRUD)) -> None: def __init__(
self.feed, self.regions = feed, regions self, feed: FeedService = Depends(FeedService), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)
) -> None:
self.feed, self.regions, self.weather = feed, regions, weather
async def template(self, path: str) -> Optional[str]: async def template(self, path: str) -> Optional[str]:
"""프론트가 빌드한 정적 지역 페이지 (today/gyeonggi/seongnam.html).""" """프론트가 빌드한 정적 지역 페이지 (today/gyeonggi/seongnam.html)."""
@@ -79,6 +98,9 @@ class SeoService:
LOG.error(f"[seo] feed {code}: {err}") LOG.error(f"[seo] feed {code}: {err}")
return ErrorType.SUCCESS, template return ErrorType.SUCCESS, template
_, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code)) _, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code))
sunset_at = sun_times(now_kst().date(), float(region.lat), float(region.lon)).sunset_at if region else None 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)
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, code, start, start + timedelta(days=1)))
name = _NAME.search(template) name = _NAME.search(template)
return ErrorType.SUCCESS, fill(template, feed, name.group(1) if name else (feed.region_name or ""), sunset_at) return ErrorType.SUCCESS, fill(template, feed, rows or [], name.group(1) if name else (feed.region_name or ""), sunset_at)
+20 -9
View File
@@ -4,14 +4,15 @@ import pytest
from httpx import ASGITransport, AsyncClient from httpx import ASGITransport, AsyncClient
from common.utils.kma_time import KST from common.utils.kma_time import KST
from common.database.model.models import WeatherHourly
from router.router import app from router.router import app
from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex
from services.seo_service import SeoService, fill, today_line from services.seo_service import SeoService, day_summary, fill, today_line
REGION = "1114000000" REGION = "1114000000"
TEMPLATE = ( TEMPLATE = (
'<html><head><meta name="description" content="소개" /><meta property="og:description" content="소개" />' '<html><head><meta name="description" content="소개" /><meta property="og:description" content="소개" />'
f'<meta name="region-code" content="{REGION}" />\n </head><body><main><h1>오늘 서울 중구 날씨, 뭐 할까?</h1><p>소개 글</p></main></body></html>' f'<meta name="region-code" content="{REGION}" />\n </head><body><main><h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>소개 글</p></main></body></html>'
) )
@@ -26,20 +27,30 @@ def _feed() -> Res_Feed:
return Res_Feed(hero=hero, stories=stories, bands=Bands(top5=stories[:2])) return Res_Feed(hero=hero, stories=stories, bands=Bands(top5=stories[:2]))
def test_today_line_has_temp_status_slot_firsts_and_sunset(): def _hour(h: int, temp: float, sky: int = 1, rain: int = 1, prob: int = 0) -> WeatherHourly:
line = today_line(_feed(), datetime(2026, 10, 14, 17, 52, tzinfo=KST)) return WeatherHourly(forecast_at=datetime(2026, 10, 14, h, tzinfo=KST), temp_c=temp, sky=sky, rain_type=rain, rain_prob=prob)
assert line == "지금 13°, 습도 보통·미세먼지 좋음. 아침은 러닝각, 낮은 빨래각, 밤은 별보기각. 해 지는 시각 오후 5시 52분."
def test_day_summary_min_max_prob_and_daytime_sky():
rows = [_hour(3, 8.6, sky=4), _hour(9, 12, sky=3), _hour(12, 19.5, sky=1, prob=10), _hour(15, 20.2, sky=1), _hour(21, 14)]
assert day_summary(rows) == "최저 9°·최고 20°, 강수확률 10%, 맑음."
assert day_summary([_hour(12, 15, rain=2, prob=70)]) == "최저 15°·최고 15°, 강수확률 70%, 비."
def test_today_line_has_day_now_slot_firsts_and_sunset():
line = today_line(_feed(), [_hour(12, 19.5, prob=10)], datetime(2026, 10, 14, 17, 52, tzinfo=KST))
assert line == "최저 20°·최고 20°, 강수확률 10%, 맑음. 지금 13°, 습도 보통·미세먼지 좋음. 아침은 러닝각, 낮은 빨래각, 밤은 별보기각. 해 지는 시각 오후 5시 52분."
def test_fill_puts_today_into_description_and_body(): def test_fill_puts_today_into_description_and_body():
html = fill(TEMPLATE, _feed(), "서울 중구", None) html = fill(TEMPLATE, _feed(), [], "서울 중구", None)
assert html.count('content="지금 13°, 습도 보통·미세먼지 좋음.') == 2 assert html.count('content="지금 13°, 습도 보통·미세먼지 좋음.') == 2
assert "<h1>오늘 서울 중구 날씨, 뭐 할까?</h1><p>지금 13°" in html assert "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>지금 13°" in html
assert "<li>러닝각 80점</li><li>빨래각 77점</li>" in html assert "<li>러닝각 80점</li><li>빨래각 77점</li>" in html
def test_fill_keeps_template_when_no_weather(): def test_fill_keeps_template_when_no_weather():
assert fill(TEMPLATE, Res_Feed(), "서울 중구", None) == TEMPLATE assert fill(TEMPLATE, Res_Feed(), [], "서울 중구", None) == TEMPLATE
@pytest.mark.anyio @pytest.mark.anyio
@@ -51,6 +62,6 @@ async def test_today_page_fills_real_feed(offline, monkeypatch):
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
page = await client.get("/v1/seo/today/seoul/jung") page = await client.get("/v1/seo/today/seoul/jung")
missing = await client.get("/v1/seo/today/seoul/nowhere") missing = await client.get("/v1/seo/today/seoul/nowhere")
assert page.status_code == 200 and "<h1>오늘 서울 중구 날씨, 뭐 할까?</h1><p>지금 20°" in page.text assert page.status_code == 200 and "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>최저 " in page.text and "지금 20°" in page.text
assert "해 지는 시각 오후" in page.text and "<ol><li>" in page.text assert "해 지는 시각 오후" in page.text and "<ol><li>" in page.text
assert missing.status_code == 404 assert missing.status_code == 404
+7 -6
View File
@@ -15,14 +15,14 @@
<link rel="apple-touch-icon" href="/apple-touch-icon.png" /> <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no, viewport-fit=cover" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
<meta name="theme-color" content="#d6ebff" /> <meta name="theme-color" content="#d6ebff" />
<meta name="description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." /> <meta name="description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
<meta name="keywords" content="날씨각, 오늘 날씨, 날씨 지수, 세차하기 좋은 날, 빨래하기 좋은 날, 러닝하기 좋은 날씨, 오늘 노을, 노을 시간, 일몰 시간, 노을 명소, 주말 날씨, 주말 나들이, 이번 주말 축제, 미세먼지, 오늘 밤 달" /> <meta name="keywords" content="날씨각, 오늘 날씨, 날씨 지수, 세차하기 좋은 날, 빨래하기 좋은 날, 러닝하기 좋은 날씨, 오늘 노을, 노을 시간, 일몰 시간, 노을 명소, 주말 날씨, 주말 나들이, 이번 주말 축제, 미세먼지, 오늘 밤 달" />
<title>날씨각 · 오늘 날씨 지수, 노을, 주말 행사</title> <title>날씨각 · 오늘 날씨 지수, 노을, 주말 행사</title>
<link rel="manifest" href="/manifest.webmanifest" /> <link rel="manifest" href="/manifest.webmanifest" />
<meta property="og:type" content="website" /> <meta property="og:type" content="website" />
<meta property="og:site_name" content="날씨각" /> <meta property="og:site_name" content="날씨각" />
<meta property="og:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" /> <meta property="og:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
<meta property="og:description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." /> <meta property="og:description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
<meta property="og:url" content="%VITE_SITE_URL%/" /> <meta property="og:url" content="%VITE_SITE_URL%/" />
<link rel="canonical" href="%VITE_SITE_URL%/" /> <link rel="canonical" href="%VITE_SITE_URL%/" />
<meta property="og:image" content="%VITE_SITE_URL%/og.png" /> <meta property="og:image" content="%VITE_SITE_URL%/og.png" />
@@ -31,7 +31,7 @@
<meta property="og:image:alt" content="날씨각, 오늘 날씨에 맞는 일을 점수로 알려 주는 서비스" /> <meta property="og:image:alt" content="날씨각, 오늘 날씨에 맞는 일을 점수로 알려 주는 서비스" />
<meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" /> <meta name="twitter:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
<meta name="twitter:description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." /> <meta name="twitter:description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
<meta name="twitter:image" content="%VITE_SITE_URL%/og.png" /> <meta name="twitter:image" content="%VITE_SITE_URL%/og.png" />
<meta property="og:locale" content="ko_KR" /> <meta property="og:locale" content="ko_KR" />
<meta name="google-site-verification" content="ageFc5cYyqCTlRxsQTu4d3uetA4WG7y7yUPR1f7muVk" /> <meta name="google-site-verification" content="ageFc5cYyqCTlRxsQTu4d3uetA4WG7y7yUPR1f7muVk" />
@@ -60,7 +60,7 @@
"@type": "WebApplication", "@type": "WebApplication",
"name": "날씨각", "name": "날씨각",
"url": "%VITE_SITE_URL%/", "url": "%VITE_SITE_URL%/",
"description": "세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요.", "description": "날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요.",
"applicationCategory": "WeatherApplication", "applicationCategory": "WeatherApplication",
"operatingSystem": "All", "operatingSystem": "All",
"inLanguage": "ko-KR", "inLanguage": "ko-KR",
@@ -98,11 +98,12 @@
</head> </head>
<body> <body>
<!-- 앱이 뜨기 전 첫 화면: 정적 소개 글이 잠깐 보이지 않게 덮는다. 앱이 뜨면 지운다 --> <!-- 앱이 뜨기 전 첫 화면: 정적 소개 글이 잠깐 보이지 않게 덮는다. 앱이 뜨면 지운다 -->
<div id="boot" role="status" style="position:fixed;inset:0;z-index:60;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;background:#d6ebff;color:#28304a;font:19px Jua,sans-serif"> <div id="boot" data-nosnippet role="status" style="position:fixed;inset:0;z-index:60;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;background:#d6ebff;color:#28304a;font:19px Jua,sans-serif">
<img src="/icons/rabbit.png" alt="" width="88" height="88" /> <img src="/icons/rabbit.png" alt="" width="88" height="88" />
<p style="margin:0">날씨 불러오는 중…</p> <p style="margin:0">날씨 불러오는 중…</p>
</div> </div>
<div id="root"> <!-- 검색 결과 요약은 화면 글 대신 description 을 쓰게 한다 (지역 페이지는 서버가 오늘 날씨로 채움) -->
<div id="root" data-nosnippet>
<main> <main>
<h1>날씨각</h1> <h1>날씨각</h1>
<p>오늘 하고 싶은 일이 날씨에 맞는지 점수로 알려 드려요. 세차, 빨래, 러닝, 피크닉처럼 일상의 일을 우리 동네 날씨로 바로 확인하세요.</p> <p>오늘 하고 싶은 일이 날씨에 맞는지 점수로 알려 드려요. 세차, 빨래, 러닝, 피크닉처럼 일상의 일을 우리 동네 날씨로 바로 확인하세요.</p>
+14 -3
View File
@@ -12,7 +12,7 @@ const gakList = `<ul>${gaks.map((g) => `<li><b>${g.name}</b>: ${g.description}</
const regionPages: RegionPage[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/region.json'), 'utf8')) const regionPages: RegionPage[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/region.json'), 'utf8'))
/** 검색 로봇이 처음 받는 페이지별 HTML. 바뀌지 않는 소개 글만 넣고, 날씨 값은 앱이 뜬 뒤 불러온다 */ /** 검색 로봇이 처음 받는 페이지별 HTML. 바뀌지 않는 소개 글만 넣고, 날씨 값은 앱이 뜬 뒤 불러온다 */
const PAGES: { path: string; title: string; description: string; body: string; code?: string }[] = [ const PAGES: { path: string; title: string; description: string; body: string; code?: string; keywords?: string }[] = [
{ {
path: 'gak', path: 'gak',
title: '오늘의 각 · 세차각·빨래각·러닝각 점수 | 날씨각', title: '오늘의 각 · 세차각·빨래각·러닝각 점수 | 날씨각',
@@ -39,17 +39,27 @@ const PAGES: { path: string; title: string; description: string; body: string; c
}, },
] ]
/** 제목 앞자리: 검색어처럼 시군구 이름부터 (경기 성남시 → 성남시) */
const headName = (name: string) => name.split(' ').at(-1)!
/** 검색어로 많이 치는 꼴: 성남시 → 성남. 중구처럼 두 글자는 그대로 */
const bareName = (name: string) => (name.length > 2 ? name.slice(0, -1) : name)
/** 지역마다 한 장: /today/gyeonggi/seongnam. 같은 시도의 다른 지역으로 이어 검색 로봇이 모두 찾게 한다 */ /** 지역마다 한 장: /today/gyeonggi/seongnam. 같은 시도의 다른 지역으로 이어 검색 로봇이 모두 찾게 한다 */
for (const r of regionPages) { for (const r of regionPages) {
const sido = r.path.split('/')[0] const sido = r.path.split('/')[0]
const near = regionPages.filter((o) => o !== r && o.path.startsWith(`${sido}/`)) const near = regionPages.filter((o) => o !== r && o.path.startsWith(`${sido}/`))
const parts = r.regions.length > 1 ? `<p>${r.name}는 ${r.regions.map((g) => g.name.split(' ').at(-1)).join(', ')}별로 따로 계산해요.</p>` : '' const parts = r.regions.length > 1 ? `<p>${r.name}는 ${r.regions.map((g) => g.name.split(' ').at(-1)).join(', ')}별로 따로 계산해요.</p>` : ''
const head = headName(r.name)
const bare = bareName(head)
const guNames = r.regions.length > 1 ? r.regions.map((g) => g.name.split(' ').at(-1)!) : []
const keywords = [...new Set([`${bare} 날씨`, `${head} 날씨`, `${bare} 오늘 날씨`, `${r.name} 날씨`, ...guNames.flatMap((g) => [`${g} 날씨`, `${bareName(g)} 날씨`]), '날씨각'])].join(', ')
PAGES.push({ PAGES.push({
path: `today/${r.path}`, path: `today/${r.path}`,
code: r.main, code: r.main,
title: `오늘 ${r.name} 날씨, 뭐 할까? | 날씨각`, keywords,
title: `${headName(r.name)} 오늘 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[0]}` : ''} | 날씨각`,
description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`, description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`,
body: `<h1>오늘 ${r.name} 날씨, 뭐 할까?</h1><p>${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.</p>${parts}<p>세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.</p>${near.length ? `<h2>${r.name.split(' ')[0]} 다른 지역 날씨</h2><ul>${near.map((o) => `<li><a href="/today/${o.path}">${o.name}</a></li>`).join('')}</ul>` : ''}`, body: `<h1>${r.name} 오늘 날씨, 뭐 할까?</h1><p>${bare} 날씨, 오늘 ${head}에서는 뭐 하기 좋을까요? ${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.</p>${parts}<p>세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.</p>${near.length ? `<h2>${r.name.split(' ')[0]} 다른 지역 날씨</h2><ul>${near.map((o) => `<li><a href="/today/${o.path}">${o.name}</a></li>`).join('')}</ul>` : ''}`,
}) })
} }
@@ -72,6 +82,7 @@ function seoPages(): Plugin {
.replace(/<title>[^<]*<\/title>/, `<title>${p.title}</title>`) .replace(/<title>[^<]*<\/title>/, `<title>${p.title}</title>`)
.replace(/(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"/g, `$1${attr(p.description)}"`) .replace(/(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"/g, `$1${attr(p.description)}"`)
.replace(/(<meta (?:property|name)="(?:og:title|twitter:title)" content=")[^"]*"/g, `$1${attr(p.title)}"`) .replace(/(<meta (?:property|name)="(?:og:title|twitter:title)" content=")[^"]*"/g, `$1${attr(p.title)}"`)
.replace(/(<meta name="keywords" content=")[^"]*"/, (m, head) => (p.keywords ? `${head}${attr(p.keywords)}"` : m))
.replace(/(<meta property="og:url" content=")[^"]*"/, `$1${url}"`) .replace(/(<meta property="og:url" content=")[^"]*"/, `$1${url}"`)
.replace(/(<link rel="canonical" href=")[^"]*"/, `$1${url}"`) .replace(/(<link rel="canonical" href=")[^"]*"/, `$1${url}"`)
.replace(/<main>[\s\S]*<\/main>/, `<main>${p.body}<p><a href="/">날씨각 처음으로</a></p></main>`) .replace(/<main>[\s\S]*<\/main>/, `<main>${p.body}<p><a href="/">날씨각 처음으로</a></p></main>`)