Merge branch 'feat/embed-widget' — 위젯 카드 조회를 umami /widget-card 로 기록, umami 스크립트를 날씨각에 복사해 두고 씀, 개인정보처리방침에 umami 추가
This commit is contained in:
commit
639ca83553
7 files changed
+76
-6
No files matched your search
@@ -44,6 +44,15 @@ _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"))
|
||||
_widgets = WidgetCRUD()
|
||||
|
||||
# 날씨각 umami(frontend/index.html 과 같은 사이트 ID): 카드 조회를 날씨각 통계 안의 /widget-card 페이지로 보낸다.
|
||||
# 쿠키를 쓰지 않는다. 자동 수집을 끄고 주소를 바꿔 보내, 붙인 사이트는 umami '유입 경로'에 남는다(iframe 의 referrer).
|
||||
# 스크립트는 날씨각에 복사해 둔 것(frontend/public/embed/umami.js)을 쓰고 기록만 umami 서버(UMAMI_HOST)로 보낸다 — 외부 스크립트를 직접 실행하지 않게
|
||||
UMAMI_SRC = "/embed/umami.js"
|
||||
UMAMI_HOST = "https://analytics.webforai.kr"
|
||||
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 의 시스템 글꼴 부분
|
||||
# 조용한 화면 바탕: 카드(card.css)의 배경별 낮 하늘과 같은 색. 링크는 카드 is-failed 의 흰 알약과 같은 모양
|
||||
# (frontend/public/embed/quiet.html 은 nginx 가 백엔드 없이 주는 같은 모양의 sky 판이다)
|
||||
@@ -134,9 +143,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-host-url="{UMAMI_HOST}" 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-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> 가 태그를 닫지 못하게
|
||||
# color-scheme 은 light 로 고정: light dark 면 색 선언이 없는 사이트(대부분)에서 방문자 기기가 다크 모드일 때 모서리 밖이 검게 칠해진다.
|
||||
# color-scheme: dark 를 선언한 사이트에서 생기는 불투명 바탕은 붙이는 코드의 iframe border-radius 가 잘라 낸다
|
||||
@@ -153,6 +173,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 src="/embed/card.js?v={ASSET_VERSION}" defer></script>'
|
||||
)
|
||||
if track:
|
||||
body += "\n" + _umami(kind)
|
||||
return _page(f"{data['name']} 날씨 - 날씨각", head, body)
|
||||
|
||||
|
||||
@@ -321,7 +343,7 @@ class EmbedService:
|
||||
if data is None:
|
||||
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:
|
||||
try:
|
||||
await self._count(viewer, kind)
|
||||
|
||||
@@ -2,6 +2,7 @@ import asyncio
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
@@ -205,6 +206,27 @@ def test_quiet_follows_bg():
|
||||
assert f'href="{link.replace("&", "&")}" target="_blank" rel="noopener">날씨각에서 날씨 보기 ›</a>' in html
|
||||
|
||||
|
||||
def test_card_umami_sends_widget_card_page():
|
||||
data = card_data(_feed(), _today(), "군산시", NOW)
|
||||
assert "/embed/umami.js" not in render_card("side", "sky", data, card_link(None, "preview"))
|
||||
html = render_card("home", "dark", data, card_link(None, "unknown"), track=True)
|
||||
# 외부 스크립트를 직접 실행하지 않는다: 날씨각에 복사해 둔 스크립트를 쓰고 기록만 umami 서버로 보낸다
|
||||
tag = re.search(r'<script defer src="/embed/umami\.js"[^>]*></script>', html).group(0)
|
||||
assert 'data-host-url="https://analytics.webforai.kr"' in tag
|
||||
assert 'data-auto-track="false"' in tag and 'data-domains="weather.o2o.kr,www.weather.o2o.kr"' in tag
|
||||
assert ""/widget-card"" in tag and "날씨 위젯 · 상세형" in tag
|
||||
assert 'src="https://analytics.webforai.kr' not in html
|
||||
assert "날씨 위젯 · 기본형" in render_card("side", "sky", data, card_link(None, "unknown"), track=True)
|
||||
|
||||
|
||||
def test_card_umami_matches_index_html():
|
||||
frontend = Path(__file__).resolve().parents[2] / "frontend"
|
||||
index = (frontend / "index.html").read_text(encoding="utf-8")
|
||||
assert f'data-website-id="{embed_service.UMAMI_WEBSITE_ID}"' in index
|
||||
assert f'src="{embed_service.UMAMI_SRC}"' in index and f'data-host-url="{embed_service.UMAMI_HOST}"' in index
|
||||
assert (frontend / "public" / embed_service.UMAMI_SRC.lstrip("/")).is_file()
|
||||
|
||||
|
||||
def test_card_markup_escapes_name():
|
||||
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]
|
||||
@@ -221,6 +243,7 @@ async def test_any_site_gets_card(offline):
|
||||
assert header not in res.headers, header
|
||||
assert res.headers["cache-control"] == "no-store"
|
||||
assert res.headers["x-robots-tag"] == "noindex"
|
||||
assert "/embed/umami.js" in res.text
|
||||
assert await _views() == {"evil.example": 1}
|
||||
|
||||
|
||||
@@ -257,6 +280,7 @@ async def test_self_preview_not_counted(offline):
|
||||
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 "utm_campaign=preview" in _card(res.text)["link"]
|
||||
assert "/embed/umami.js" not in res.text
|
||||
assert await _views() == {}
|
||||
|
||||
|
||||
|
||||
@@ -184,6 +184,24 @@ curl -s -H "X-Admin-Key: $ADMIN_API_KEY" https://weather.o2o.kr/v1/admin/widget/
|
||||
- 보는 곳: GA4 보고서 → 획득 → 트래픽 획득. 측정기준을 '세션 소스/매체'로 두면 `widget / embed`, '세션 캠페인'으로 바꾸면 사이트별로 나옵니다.
|
||||
- 사용 방법 페이지의 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` 가 확인).
|
||||
- umami 스크립트는 외부(`analytics.webforai.kr/script.js`)에서 직접 부르지 않고 날씨각에 복사해 둔 `frontend/public/embed/umami.js` 를 씁니다(날씨각 웹 `index.html` 도 같음). 기록은 `data-host-url` 의 umami 서버로 갑니다. 외부 스크립트가 바뀌거나 그 서버가 뚫려도 날씨각과 위젯을 붙인 사이트에서 다른 코드가 돌지 않게 하려는 것입니다(무결성 확인 SRI 대신. umami 서버가 다른 사이트의 파일 확인 요청을 허락하지 않아 SRI 를 쓸 수 없다).
|
||||
- umami 서버를 업그레이드한 뒤 기록이 안 쌓이면: `https://analytics.webforai.kr/script.js` 를 다시 받아 `umami.js` 맨 위 주석만 남기고 덮어씁니다. 이 파일은 린트에서 뺐습니다(`frontend/.oxlintrc.json`).
|
||||
|
||||
---
|
||||
|
||||
## 5. 붙이는 쪽에 안내할 것
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"ignorePatterns": ["public/embed/umami.js"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
|
||||
+3
-2
@@ -10,8 +10,9 @@
|
||||
|
||||
gtag('config', 'G-D378J4X373', { platform: '%MODE%' === 'toss' ? 'toss' : /NalssigakApp\//.test(navigator.userAgent) ? 'android_app' : 'web' });
|
||||
</script>
|
||||
<!-- 유입 추적 (analytics.webforai.kr) — weather.o2o.kr 에서만 보낸다 -->
|
||||
<script defer src="https://analytics.webforai.kr/script.js"
|
||||
<!-- 유입 추적 (analytics.webforai.kr) — weather.o2o.kr 에서만 보낸다. 스크립트는 날씨각에 복사해 둔 것을 쓰고(외부 스크립트를 직접 실행하지 않게) 기록만 umami 서버로 보낸다 -->
|
||||
<script defer src="/embed/umami.js"
|
||||
data-host-url="https://analytics.webforai.kr"
|
||||
data-website-id="b2244cf7-9b43-49c0-b1c0-acfaaab95ddb"
|
||||
data-domains="weather.o2o.kr,www.weather.o2o.kr"
|
||||
data-exclude-search="true"
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
/* umami 방문 통계 스크립트 — https://analytics.webforai.kr/script.js 를 2026-11-26 그대로 복사한 것.
|
||||
외부 스크립트를 날씨각 페이지에서 직접 실행하지 않으려고(무결성 확인 대신) 날씨각에서 준다. 기록은 data-host-url 의 umami 서버로 간다.
|
||||
umami 서버를 업그레이드해 기록이 안 되면 같은 주소에서 다시 받아 덮어쓴다(이 주석은 남긴다). 손으로 고치지 않는다. */
|
||||
!function(){"use strict";function e(e,t=2e3){return e.slice(0,t).replace(/https?:\/\/[^\s)]+/g,e=>{try{const t=e.match(/:\d+:\d+$/)?.[0]||"",n=new URL(t?e.slice(0,-t.length):e);return`${n.origin}${n.pathname}${t}`}catch{return"[url]"}}).replace(/[\w.+-]+@[\w.-]+\.[a-z]{2,}/gi,"[email]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]+\b/g,"[token]").replace(/\b(password|secret|token|authorization|api[_-]?key)\s*[:=]\s*[^\s,;]+/gi,"$1=[redacted]").slice(0,t)}function t(t){try{return e(new URL(t,"https://localhost").pathname,500)}catch{return"/"}}function n(t={}){return Object.fromEntries(Object.entries(t).slice(0,20).filter(([e])=>!/password|secret|token|authorization|cookie|email|api.?key/i.test(e)).map(([t,n])=>[e(t,50),e(String(n),200)]))}function a(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function r(r){const i=new WeakMap,o=[];let s=!1,c=!1,l=0,d=0,f=0;async function u(u,m={},p=!0){try{if(!r.enabled||c||r.disabled()||o.length>=20)return;const h=Date.now();if(h<l)return;const y=Math.floor(h/6e4);if(d!==y&&(d=y,f=0),f>=20)return;if(u&&"object"==typeof u){if(h-(i.get(u)||0)<1e3)return;i.set(u,h)}f++;const g=r.context(),b=r.cache(),v=u&&"object"==typeof u?u:null,w="string"==typeof v?.message?v.message:"string"==typeof u?u:"Non-Error exception",T={version:1,website:g.website,eventId:a(),timestamp:h,name:e("string"==typeof v?.name?v.name:"Error",200)||"Error",message:e(w),stack:e("string"==typeof v?.stack?v.stack:"",16e3),handled:p,url:t(g.url),id:g.id,salt:g.salt,screen:g.screen,language:g.language,release:e(m.release||r.release,100),environment:e(m.environment||r.environment,50),tags:n(m.tags),...m.fingerprint?.length?{fingerprint:m.fingerprint.slice(0,5).map(t=>e(t,200))}:{}};let S;c=!0;try{S=r.beforeSend(T)}finally{c=!1}const k=await S;if(!k||r.disabled())return;o.push({payload:{...k,website:T.website,eventId:T.eventId,timestamp:h,version:1},cache:b}),async function(){if(!s){s=!0;try{for(;o.length;){const e=o.shift();if(!e||r.disabled())continue;const t=JSON.stringify({type:"error",payload:e.payload});if(!((new TextEncoder).encode(t).byteLength>48e3))for(let n=0;n<3&&!r.disabled();n++){try{const n=await fetch(r.endpoint,{method:"POST",keepalive:!0,credentials:"omit",body:t,headers:{"Content-Type":"application/json",...e.cache?{"x-umami-cache":e.cache}:{}}});if(n.ok){const t=await n.json();t.cache&&r.cache()===e.cache&&r.context().id===e.payload.id&&r.updateCache(t.cache);break}if(429===n.status){o.length=0;const e=Number(n.headers.get("Retry-After"))||60;l=Date.now()+1e3*Math.max(1,Math.min(e,300));break}if(n.status<500)break}catch{}n<2&&await new Promise(e=>setTimeout(e,1e3*2**n))}}}finally{s=!1}}}().catch(()=>{})}catch{}}return r.enabled&&(window.addEventListener("error",e=>{e.message&&u(e.error||{name:"Error",message:e.message,stack:e.filename?`at ${e.filename}:${e.lineno}:${e.colno}`:""},{},!1)}),window.addEventListener("unhandledrejection",e=>{u(e.reason,{},!1)})),{captureException:(e,t)=>u(e,t)}}(e=>{const{screen:{width:t,height:n},navigator:{language:a,doNotTrack:i,msDoNotTrack:o},location:s,document:c,history:l,top:d,doNotTrack:f}=e,{currentScript:u,referrer:m}=c,p=e.umamiConfig||{};if(!u&&!p.websiteId)return;const{hostname:h,href:y,origin:g}=s;let b;try{b=y.startsWith("data:")?void 0:e.localStorage}catch{}const v="data-",w="false",T="true",S=u?u.getAttribute.bind(u):()=>null,k=e=>{const t=S(`${v}${e}`);if(null!=t)return t;const n=p[(e=>e.replace(/-([a-z])/g,e=>e[1].toUpperCase()))(e)];return null==n||"function"==typeof n?null:Array.isArray(n)?n.join(","):String(n)},$=()=>{const t=k("before-send"),n=t?e[t]:p.beforeSend;return"function"==typeof n?n:void 0},x=k("website-id"),E=k("host-url"),j=k("distinct-id")||void 0,M=k("tag")||void 0,I=k("salt")||void 0,U=k("salt-rotation"),L=k("auto-track")!==w,O=k("do-not-track")===T,A=k("exclude-search")===T,D=k("exclude-hash")===T,C=k("domains")||"",N=k("fetch-credentials")||"omit",R=k("performance")===T,P=k("auto-pageview")!==w,z=C.split(",").map(e=>e.trim()),_=E||""||(u?u.src.split("/").slice(0,-1).join("/"):"");if(!u&&!_)return;const J=`${_.replace(/\/$/,"")}/api/send`,K=`${t}x${n}`,W=/data-umami-event-([\w-_]+)/,B=`${v}umami-event`,V=300,q=e=>{if(!e)return e;try{const t=new URL(e,s.href);return A&&(t.search=""),D&&(t.hash=""),t.toString()}catch{return e}},F=()=>{if(I)return I;const e={hourly:13,daily:10,weekly:10,monthly:7}[U];if(!e)return;const t=new Date;return"weekly"===U&&t.setUTCDate(t.getUTCDate()-t.getUTCDay()),t.toISOString().slice(0,e)},G=()=>{return{website:x,screen:K,language:a,title:c.title,hostname:h,url:re,referrer:(e=ie,e===g||e?.startsWith(`${g}/`)?e.slice(g.length):e),tag:M,id:ce||void 0,salt:F()};var e},H=(e,t,n)=>{n&&("function"==typeof ae&&ae(),ie=re,re=q(n),re!==ie&&P&&setTimeout(Z,VLine truncated
|
||||
@@ -37,7 +37,7 @@
|
||||
<p>회원 정보는 회원 탈퇴 시까지 보관하며, 탈퇴 요청을 받으면 지체 없이 파기합니다. 접속 기록은 「통신비밀보호법」에 따라 3개월간 보관합니다.</p>
|
||||
|
||||
<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>
|
||||
<p>보유 기간이 끝나거나 목적이 달성된 개인정보는 지체 없이 복구할 수 없는 방법으로 삭제합니다.</p>
|
||||
|
||||
Reference in new issue
Block a user