Compare commits

...
Author SHA1 Message Date
skkim 3257360b5b feat: 위젯 카드 조회를 날씨각 umami 에 /widget-card 페이지로 기록
- 다른 사이트에서 카드를 부르면 카드 화면에 날씨각 umami 스크립트를 붙여 조회를 /widget-card(제목 '날씨 위젯 · 기본형/상세형')로 보냄. 붙인 사이트는 유입 경로로 남음. 날씨각 미리보기는 보내지 않음
- 쿠키 없음, 스크립트가 늦거나 막혀도 카드는 그대로
- 개인정보처리방침에 umami(쿠키 없는 방문 통계)와 위젯 조회 집계를 적음
- 운영 문서 4-4장: umami 에서 카드 조회 보기
2026-11-26 15:26:30 +09:00
4 changed files with 58 additions and 4 deletions

No files matched your search

+23 -3
View File
@@ -44,6 +44,13 @@ _REGION_CODE = re.compile(r"[0-9]{10}")
_PATHS: dict[str, str] = json.loads((Path(__file__).resolve().parent.parent / "seed" / "region_path.json").read_text(encoding="utf-8")) _PATHS: dict[str, str] = json.loads((Path(__file__).resolve().parent.parent / "seed" / "region_path.json").read_text(encoding="utf-8"))
_widgets = WidgetCRUD() _widgets = WidgetCRUD()
# 날씨각 umami(frontend/index.html 과 같은 사이트 ID): 카드 조회를 날씨각 통계 안의 /widget-card 페이지로 보낸다.
# 쿠키를 쓰지 않는다. 자동 수집을 끄고 주소를 바꿔 보내, 붙인 사이트는 umami '유입 경로'에 남는다(iframe 의 referrer)
UMAMI_SRC = "https://analytics.webforai.kr/script.js"
UMAMI_WEBSITE_ID = "b2244cf7-9b43-49c0-b1c0-acfaaab95ddb"
UMAMI_PATH = "/widget-card"
_KIND_LABEL = {"side": "기본형", "home": "상세형"}
_FONT = '-apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic", sans-serif' # card.css --font 의 시스템 글꼴 부분 _FONT = '-apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic", sans-serif' # card.css --font 의 시스템 글꼴 부분
# 조용한 화면 바탕: 카드(card.css)의 배경별 낮 하늘과 같은 색. 링크는 카드 is-failed 의 흰 알약과 같은 모양 # 조용한 화면 바탕: 카드(card.css)의 배경별 낮 하늘과 같은 색. 링크는 카드 is-failed 의 흰 알약과 같은 모양
# (frontend/public/embed/quiet.html 은 nginx 가 백엔드 없이 주는 같은 모양의 sky 판이다) # (frontend/public/embed/quiet.html 은 nginx 가 백엔드 없이 주는 같은 모양의 sky 판이다)
@@ -134,9 +141,20 @@ def _page(title: str, head: str, body: str, body_class: str = "") -> str:
) )
def render_card(kind: str, bg: str, data: dict, link: str) -> str: def _umami(kind: str) -> str:
"""umami 로 카드 조회 한 번(/widget-card, 제목에 모양). 스크립트가 늦거나 막혀도 카드 그리기와는 상관없다."""
title = json.dumps(f"날씨 위젯 · {_KIND_LABEL[kind]}", ensure_ascii=False)
send = f"umami.track(function(p){{p.url={json.dumps(UMAMI_PATH)};p.title={title};return p}})"
return (
f'<script defer src="{UMAMI_SRC}" data-website-id="{UMAMI_WEBSITE_ID}" data-domains="weather.o2o.kr,www.weather.o2o.kr" '
f'data-auto-track="false" onload="{escape(send, quote=True)}"></script>'
)
def render_card(kind: str, bg: str, data: dict, link: str, track: bool = False) -> str:
"""카드 화면. 상자는 군산각 카드(.wx)와 같은 구조이고, 본문 칸(data-wx-b)은 card.js 가 #wx-data 를 읽어 그린다. """카드 화면. 상자는 군산각 카드(.wx)와 같은 구조이고, 본문 칸(data-wx-b)은 card.js 가 #wx-data 를 읽어 그린다.
그리기 전에는 토끼 로딩 화면(.wx-load)이 보이고, 못 그리면(is-failed, 또는 8초 안에 스크립트가 안 돌면) 날씨각 링크(.wx-go)가 보인다.""" 그리기 전에는 토끼 로딩 화면(.wx-load)이 보이고, 못 그리면(is-failed, 또는 8초 안에 스크립트가 안 돌면) 날씨각 링크(.wx-go)가 보인다.
track 이면 umami 로 조회를 보낸다(날씨각 자신의 미리보기는 빼려고 부르는 쪽이 정한다)."""
payload = json.dumps({**data, "link": link}, ensure_ascii=False).replace("<", "\\u003c") # 값 안의 </script> 가 태그를 닫지 못하게 payload = json.dumps({**data, "link": link}, ensure_ascii=False).replace("<", "\\u003c") # 값 안의 </script> 가 태그를 닫지 못하게
# color-scheme 은 light 로 고정: light dark 면 색 선언이 없는 사이트(대부분)에서 방문자 기기가 다크 모드일 때 모서리 밖이 검게 칠해진다. # color-scheme 은 light 로 고정: light dark 면 색 선언이 없는 사이트(대부분)에서 방문자 기기가 다크 모드일 때 모서리 밖이 검게 칠해진다.
# color-scheme: dark 를 선언한 사이트에서 생기는 불투명 바탕은 붙이는 코드의 iframe border-radius 가 잘라 낸다 # color-scheme: dark 를 선언한 사이트에서 생기는 불투명 바탕은 붙이는 코드의 iframe border-radius 가 잘라 낸다
@@ -153,6 +171,8 @@ def render_card(kind: str, bg: str, data: dict, link: str) -> str:
f'<script type="application/json" id="wx-data">{payload}</script>\n' f'<script type="application/json" id="wx-data">{payload}</script>\n'
f'<script src="/embed/card.js?v={ASSET_VERSION}" defer></script>' f'<script src="/embed/card.js?v={ASSET_VERSION}" defer></script>'
) )
if track:
body += "\n" + _umami(kind)
return _page(f"{data['name']} 날씨 - 날씨각", head, body) return _page(f"{data['name']} 날씨 - 날씨각", head, body)
@@ -321,7 +341,7 @@ class EmbedService:
if data is None: if data is None:
return status, render_quiet(link, bg) return status, render_quiet(link, bg)
html = render_card(kind, bg, data, link) html = render_card(kind, bg, data, link, track=viewer is not None)
if viewer is not None: if viewer is not None:
try: try:
await self._count(viewer, kind) await self._count(viewer, kind)
+18
View File
@@ -2,6 +2,7 @@ import asyncio
import json import json
import re import re
from datetime import datetime, timedelta from datetime import datetime, timedelta
from pathlib import Path
import pytest import pytest
from httpx import ASGITransport, AsyncClient from httpx import ASGITransport, AsyncClient
@@ -205,6 +206,21 @@ def test_quiet_follows_bg():
assert f'href="{link.replace("&", "&amp;")}" target="_blank" rel="noopener">날씨각에서 날씨 보기 ›</a>' in html assert f'href="{link.replace("&", "&amp;")}" target="_blank" rel="noopener">날씨각에서 날씨 보기 ›</a>' in html
def test_card_umami_sends_widget_card_page():
data = card_data(_feed(), _today(), "군산시", NOW)
assert "analytics.webforai.kr" not in render_card("side", "sky", data, card_link(None, "preview"))
html = render_card("home", "dark", data, card_link(None, "unknown"), track=True)
tag = re.search(r'<script defer src="https://analytics\.webforai\.kr/script\.js"[^>]*></script>', html).group(0)
assert 'data-auto-track="false"' in tag and 'data-domains="weather.o2o.kr,www.weather.o2o.kr"' in tag
assert "&quot;/widget-card&quot;" in tag and "날씨 위젯 · 상세형" in tag
assert "날씨 위젯 · 기본형" in render_card("side", "sky", data, card_link(None, "unknown"), track=True)
def test_card_umami_uses_site_id_from_index_html():
index = (Path(__file__).resolve().parents[2] / "frontend" / "index.html").read_text(encoding="utf-8")
assert f'data-website-id="{embed_service.UMAMI_WEBSITE_ID}"' in index and embed_service.UMAMI_SRC in index
def test_card_markup_escapes_name(): def test_card_markup_escapes_name():
html = render_card("side", "sky", card_data(_feed(), _today(), '<b>"군산"', NOW), card_link(None, "unknown")) html = render_card("side", "sky", card_data(_feed(), _today(), '<b>"군산"', NOW), card_link(None, "unknown"))
body = html.split("<body>", 1)[1].split('<script type="application/json"', 1)[0] body = html.split("<body>", 1)[1].split('<script type="application/json"', 1)[0]
@@ -221,6 +237,7 @@ async def test_any_site_gets_card(offline):
assert header not in res.headers, header assert header not in res.headers, header
assert res.headers["cache-control"] == "no-store" assert res.headers["cache-control"] == "no-store"
assert res.headers["x-robots-tag"] == "noindex" assert res.headers["x-robots-tag"] == "noindex"
assert "analytics.webforai.kr" in res.text
assert await _views() == {"evil.example": 1} assert await _views() == {"evil.example": 1}
@@ -257,6 +274,7 @@ async def test_self_preview_not_counted(offline):
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": "http://test/widget"}) res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": "http://test/widget"})
assert res.status_code == 200 and 'id="wx-data"' in res.text assert res.status_code == 200 and 'id="wx-data"' in res.text
assert "utm_campaign=preview" in _card(res.text)["link"] assert "utm_campaign=preview" in _card(res.text)["link"]
assert "analytics.webforai.kr" not in res.text
assert await _views() == {} assert await _views() == {}
+16
View File
@@ -184,6 +184,22 @@ curl -s -H "X-Admin-Key: $ADMIN_API_KEY" https://weather.o2o.kr/v1/admin/widget/
- 보는 곳: GA4 보고서 → 획득 → 트래픽 획득. 측정기준을 '세션 소스/매체'로 두면 `widget / embed`, '세션 캠페인'으로 바꾸면 사이트별로 나옵니다. - 보는 곳: GA4 보고서 → 획득 → 트래픽 획득. 측정기준을 '세션 소스/매체'로 두면 `widget / embed`, '세션 캠페인'으로 바꾸면 사이트별로 나옵니다.
- 사용 방법 페이지의 GA 이벤트(`widget_guide_view`·`widget_option_select`·`widget_code_copy`)는 `docs/이벤트_추적.md` 이벤트 목록 표의 위젯 행에 있습니다. - 사용 방법 페이지의 GA 이벤트(`widget_guide_view`·`widget_option_select`·`widget_code_copy`)는 `docs/이벤트_추적.md` 이벤트 목록 표의 위젯 행에 있습니다.
### 4-4. umami에서 카드 조회 보기
다른 사이트에 붙은 카드가 보일 때마다, 날씨각 umami(`analytics.webforai.kr`, 날씨각 웹과 같은 사이트)에 `/widget-card` 페이지 조회로 한 번 보냅니다(`backend/services/embed_service.py` 의 `_umami`).
| umami 화면 | 보이는 것 |
|---|---|
| 페이지 | `/widget-card` = 위젯 카드 조회 수 |
| 유입 경로 | 카드를 붙인 사이트 주소 |
| 페이지 제목 | `날씨 위젯 · 기본형` / `날씨 위젯 · 상세형` |
- 날씨각 자신의 미리보기(사용 방법 페이지)는 보내지 않습니다. 서버 집계와 같은 기준입니다.
- 쿠키를 쓰지 않습니다. umami 스크립트가 늦거나 막혀도 카드는 그대로 보입니다(그 조회만 빠짐).
- 날씨각 전체 방문자·조회 수에 위젯 조회가 더해집니다. 위젯을 빼고 보려면 umami에서 페이지 `/widget-card` 를 필터로 뺍니다.
- `data-domains` 가 `weather.o2o.kr` 이라 로컬(`localhost`)에서는 보내지 않습니다.
- umami 사이트 ID 는 `frontend/index.html` 과 같아야 합니다(`tests/test_embed.py` 가 확인).
--- ---
## 5. 붙이는 쪽에 안내할 것 ## 5. 붙이는 쪽에 안내할 것
+1 -1
View File
@@ -37,7 +37,7 @@
<p>회원 정보는 회원 탈퇴 시까지 보관하며, 탈퇴 요청을 받으면 지체 없이 파기합니다. 접속 기록은 「통신비밀보호법」에 따라 3개월간 보관합니다.</p> <p>회원 정보는 회원 탈퇴 시까지 보관하며, 탈퇴 요청을 받으면 지체 없이 파기합니다. 접속 기록은 「통신비밀보호법」에 따라 3개월간 보관합니다.</p>
<h2>3. 제3자 제공 및 처리 위탁</h2> <h2>3. 제3자 제공 및 처리 위탁</h2>
<p>회사는 이용자의 개인정보를 제3자에게 제공하지 않습니다. 이용 통계 분석을 위해 Google Analytics(Google LLC)를 사용하며, 이 과정에서 쿠키와 기기 정보가 Google에 전송될 수 있습니다. 광고 게재를 위해 Google AdSense(Google LLC)를 사용하며, Google은 쿠키로 이 사이트와 다른 사이트 방문 기록을 바탕으로 광고를 보여 줄 수 있습니다. 맞춤 광고는 Google 광고 설정(https://adssettings.google.com)에서 끌 수 있습니다. 브라우저 설정에서 쿠키를 거부할 수 있습니다.</p> <p>회사는 이용자의 개인정보를 제3자에게 제공하지 않습니다. 이용 통계 분석을 위해 Google Analytics(Google LLC)를 사용하며, 이 과정에서 쿠키와 기기 정보가 Google에 전송될 수 있습니다. 이용 통계를 위해 쿠키를 쓰지 않는 방문 통계 도구 umami(analytics.webforai.kr)도 사용합니다. umami는 본 페이지 주소, 들어온 경로, 브라우저·기기 종류, 국가를 집계하며 IP 주소는 저장하지 않습니다. 다른 사이트에 붙은 날씨각 위젯(날씨 카드)이 보일 때도 그 조회와 위젯을 붙인 사이트 주소를 같은 방식으로 집계합니다. 광고 게재를 위해 Google AdSense(Google LLC)를 사용하며, Google은 쿠키로 이 사이트와 다른 사이트 방문 기록을 바탕으로 광고를 보여 줄 수 있습니다. 맞춤 광고는 Google 광고 설정(https://adssettings.google.com)에서 끌 수 있습니다. 브라우저 설정에서 쿠키를 거부할 수 있습니다.</p>
<h2>4. 파기 절차 및 방법</h2> <h2>4. 파기 절차 및 방법</h2>
<p>보유 기간이 끝나거나 목적이 달성된 개인정보는 지체 없이 복구할 수 없는 방법으로 삭제합니다.</p> <p>보유 기간이 끝나거나 목적이 달성된 개인정보는 지체 없이 복구할 수 없는 방법으로 삭제합니다.</p>